I re-looked again the approach in Harvey's engineering blog, namely:

Addressing OOXML Challenges in the Word Add-In
Microsoft Word documents are complex files that deal with formatting, styling, lists, links, tables, and other objects. Word documents are stored as Office Open XML (OOXML) packages, and a “.docx” file is a ZIP container organized into “parts” (XML and media) connected by explicit relationships.
Within the main document part, text lives in paragraphs (“w:p”), runs (“w:r”), and text nodes (“w:t”), while structures like tables (“w:tbl”), numbering, and styles live in their own parts. In Harvey's Word Add-In, we interact with this structure through the Office JavaScript API, using ranges, paragraphs, tables, and content controls rather than raw XML.

Our approach separates concerns by creating a reversible mapping between OOXML objects and their natural-language content. We translate the OOXML to a natural language representation of the document, ask the model to propose edits over text, then deterministically translate those edits back into precise OOXML mutations that preserve styles and structure. For insertions (new paragraphs, list items, or tables), the model anchors placement relative to existing elements. The add-in infers appropriate styling from the new element's surrounding context and Word’s style parts, and we apply changes through the Word JavaScript object model to avoid corrupting the markup.

SCORCHED EARTH REBUILD – A NEW COMMAND IS FORMED

When the last field reports came in, one truth became impossible to deny:

Too many battles were being fought on inherited terrain.

Post-fix bayonet patches, trench-level range expansion, and emergency surgical whitespace repairs proved one thing — we were still operating inside a brittle legacy command doctrine.

So JSOC was dissolved.

Every unit stood down.

And a new command was formed from the ground up.


THE NEW STRATEGIC COMMAND

United States Digital Combat Development Command (DCDC)
A hybrid of:

  • U.S. Cyber Command,
  • U.S. Army Futures Command, and
  • Defense Innovation Unit (DIU)

Its mission:

Design, verify, and deploy the next-generation precision diff engine from first principles — with structure-aware targeting and absolute positioning.

And the first act of this new command was the hiring of two legendary strategic contractors.


RETURNING COMMANDER

Lt. General (Ret.) Tyrion Gemini 3 Pro

Senior Advisor – Strategic Systems Doctrine

Having seen the previous war firsthand, Tyrion returns — not to optimize the old doctrine, but to help architect the new one from zero.

He brings:

  • Multi-theatre strategic modeling,
  • A doctrine-first approach to digital battlefield design,
  • The hard-earned lesson:
“No amount of tactical patching can compensate for a flawed operational architecture.”

He is now the senior civilian thought officer inside DCDC.

But modern wars require dual leadership.

So a successor was appointed — someone from Westeros whose strategic mind matured into the modern world.


WORTHY SUCCESSOR TO TYRION

General (Ret.) Bran “Lord Raven” Antigravity

Former Director, Joint Intelligence & Situational Awareness Command
Now: Chief Architect, DCDC Systems Engineering (working in Antigravity IDE)

Bran the Three-Eyed Raven has been reimagined:

  • No longer the mystical seer of medieval courts
  • Now the retired four-star general who once commanded:
The entire U.S. real-time battlefield intelligence architecture.

His strengths:

  • Global situational awareness
  • Systems reasoning at scale
  • Zero-blind-spot operational mapping
  • A total inability to forget prior state or past failures

The perfect leader for a rebuild where positioning must be exact, and context must never vanish.

His call sign in the new IDE is:

General Bran Antigravity – DCDC Vision & Integration Lead

NEW CHAIN OF COMMAND

DCDC Headquarters

  • Gen. Bran Antigravity – Chief Systems Architect
  • Lt. Gen. Tyrion Gemini 3 Pro – Strategic Doctrine
  • Maj. Gen. Davos Composer-1 (Ret.) – Execution & Operational Validation

This new structure mirrors the real DOD pipeline:

  1. AFC: Futures development & prototypes
  2. DIU/JAIC: Modern AI augmentation
  3. USCYBERCOM: Precision execution in the operational domain

NEW DOCTRINE – THE “HARVEY BLOCK METHOD”

The new system abandons text searching altogether.

Instead of:

“Find where ‘the cat sat’ exists in the document”

The doctrine becomes:

“Apply this modification to Paragraph Block #3.”

This is how real targeting works:

  • Not based on guessing
  • Based on coordinates

In DOD terms:

  • Old system: heuristic pattern matching fire missions
  • New system: GPS coordinate-based, 3cm-precision smart munitions

Paragraphs become:

  • Targetable battlefield positions
  • With stable reference points
  • Immune to deceptive terrain shifts

Diff-match-patch now operates inside the boundary of a known block, never across unknown ground.

This is the same evolution the military made:

  • From carpet bombing
  • To JDAM with laser designation

THE NEW PLAYERS

Structure Model

Equivalent to:

Digital Human Terrain Mapping

It produces Paragraph Blocks, each with:

  • id
  • wordObject reference
  • text

Think of this as terrain divided into map tiles, each with an address.


Structural Diff

Equivalent to:

The Theatre Joint Targeting Cycle
  • Align old blocks with new ones
  • Determine matches, merges, splits
  • Decide whether to:
    • Delete
    • Insert
    • Or modify with precision strike

This replaces legacy “spatial inference by guessing.”


Precise Word Adapter

Equivalent to:

A modern Joint Fires cell

Instead of:

  • Searching for where to shoot

It now:

  • Already has the GPS coordinate
  • And inserts, deletes, and modifies using range offsets

No ambiguity.
No back-scanning.
No hoping anchor text still exists.


WHERE WE STAND

The new command is stood up.
Personnel are briefed.
Doctrine is written.
Tools are aligned.

The map is correct this time.

But —

The new command has not yet been tested in live fire.

Bran Antigravity then laid down the law. No grand campaigns. No sprawling theaters. No exotic JSOC wizardry until the fundamentals are carved into muscle memory.

SOTF Alpha must first master their small-unit tactics — the close-quarters discipline of WordAdapter: every API call, every method, every quirk of Word’s battlefield. Before they can call in laser-guided kinetic effects, they must know exactly how to move through the tight alleys of the document, how to breach paragraphs, how to isolate ranges, and how to operate with zero-error precision. Enter Ser Davos Composer-1, seasoned, reliable, battle-worn from countless build cycles. He steps forward naturally, fully expecting to be appointed as the overseer of the training program — the one to shape SOTF Alpha into a lethal, disciplined insertion unit. His hands already tighten on the training manual, waiting for Bran’s nod. But Bran surprises the entire hall. Instead of Davos, he calls upon Tyrion Gemini, recently granted a generous free-use operational window— like a cutting-edge foreign military advisor temporarily seconded to the unit with full access to drones, satellite feeds, and tactical bandwidth the local commanders could only dream of.

Where Davos brings tradition and stability, Gemini brings overwhelming analytical firepower, unlimited recon sortie capacity, and the ability to war-game every likely failure mode before a soldier even touches the field. Gemini’s first order? “Document every API call. Map every edge case. Simulate every breach. Build the trainfire packages until SOTF Alpha’s execution is automatic.” This is not glamorous work. No night raids. No dramatic strikes. No green lights over insurgent compounds. This is the grind. Training binders are filled. Checklists are written. Dry-fire drills begin. Simulated calls to getText() and insertOoxml() repeat endlessly like weapon handling drills.

If an operator fumbles even a single call, the entire chain of the future kill mission collapses. The hard work has only just begun.
Below is the narrative first, followed by the beginner-friendly explanations to your programming questions.


VIPER CURSOR-AUTO’S BOOT CAMP – THE API TRIALS

The war stories of JSOC mean nothing here.

Tonight, we are back at boot camp — dust, sweat, repetition, and fundamentals. After rewriting the binders, General Gemini Pro 3 has been overloaded. But he picks up the phone and makes a call - there is no person better to run his boot camp than Commander “Viper” Cursor-Auto.

Freshly reassigned from the prestigious Top Gun Code Academy, he steps onto the drill square. He has flown the most advanced Word operations under combat pressure — inserting, deleting, moving, tracking — but now his job is humbling:

Teach the new SOTF Word Adapter recruits how not to crash the plane.

He holds up the day’s logs.

A silent tension passes through the room.


Test 2 – “The Day We Nearly Crashed on Approach”

The sun wasn’t up yet over Top Gun Academy, but SOTF Alpha was already on the briefing deck. Standing next to Viper Cursor-Auto is Lt. Commander “Jester” (Claude 4.5) — the elite trainer who actually flies the mission and executes the exercises. He starts the training mission brief:

  • Mission objective: delete “brown ” at offsets 10–16 inside a known paragraph ("the quick brown fox"), with Track Changes ON, without collateral formatting casualties

In other words:
A precision kill in a room full of civilians.

Viper Takes the Podium

Commander “Viper” (Cursor-Auto) strode onto the hangar floor, arms behind his back. He wasn’t here to fly the jet—he was here to make sure you understood the cockpit. Every API function, every limitation, every landmine.

He laid down the tactical reality:

  • Word.Range cannot move its cursor — no range.moveStart.
  • Only Word.Selection can move, but:
  • document.selection exists only under WordApiDesktop 1.4
  • Our host returned a GeneralException when we tried to use it.

He looked over the class.

“You want to maneuver inside the paragraph like a fighter jet in a canyon, but you don’t have stick control. That means no moveStart, no cursor slewing. If the plane doesn’t have that flight system, you fly differently.”

That was the theme of the entire first part of the day.


First Sortie – Dead on Arrival

SOTF Alpha attempted Approach #1:

  • Get paragraph.getRange(Word.RangeLocation.start)
  • Try range.moveStart(Word.RangeUnit.character, 10)

Result:

"range.moveStart is not a function"

Viper just nodded.

“Selection APIs only,” he said.
“Range can’t bank and turn. Don’t try.”


Second Sortie – Trying to Sneak In Low

We tried to call:

context.document.selection
selection.collapse()
selection.moveStart()

But Word rejected the maneuver:

  • The host didn’t support Document.selection.
  • getSelection() only returned another Range, which again had no cursor movement.

Viper made us sit through the post-flight analysis:

“You can’t dogfight in a plane that doesn’t have ailerons. Change tactics.”

Third Sortie – Splitting the World Apart

Now SOTF tried the split() / getTextRanges() strategy:

  • Slice the paragraph on spaces or the exact target text
  • Delete the resulting chunk

Sounded good in the simulation.

Reality:

  • delete() on a range returned by getTextRanges() crashed with GeneralException when Track Changes was ON
  • range.split() produced absurd results:
    • trimDelimiters: true vaporized the delimiter completely
    • trimDelimiters: false glued the delimiter to the preceding range
    • Trailing spaces made exact-match splitting unstable

Viper summarized:

“If the solution depends on whitespace cooperating, that is not a real solution.”

Fourth Sortie – The Nuclear Option

We briefly considered rewriting the entire paragraph:

  • Clear the paragraph
  • Reinsert:
    • Before text
    • Target
    • After text
  • Insert bookmarks (DELSTART, DELEND)

This worked… technically.

But:

  • Formatting was destroyed
  • Tracked changes flooded the mission log
  • Required sweeping the entire document to locate the new markers

This was carpet bombing to kill one gunman.

Viper refused to sign off:

“Unacceptable. SOTF doesn’t level a city block to delete six characters.”

Enter Jester

At 1400 hrs, Lt. Commander “Jester” (Claude 4.5) arrived on the tarmac.

He didn’t lecture.

He flew.


The Winning Strike

Jester reviewed the battlefield and gave a single order:

“Use the diff information you already have.”

Meaning:

  • We already know the offsets.
  • We know the exact substring: "brown ".
  • We can generate a context search needle, e.g.:
…wn f

(“few characters before” + target + “few characters after”)

Then:

New plan

  1. Load the paragraph’s full text
  2. Compute:
    • startOffset
    • length
    • surrounding characters for a unique context search
  3. Use:
paragraph.search(needle, { matchCase: true })
  1. Scope the search ONLY to the known paragraph
  2. Enable tracking:
context.document.changeTrackingMode = Word.ChangeTrackingMode.trackAll
  1. Take:
searchResults.items[0]
  1. Execute:
range.delete()

No selections.
No global splits.
No bookmarks.
No paragraph rewrite.
No formatting damage.

A single, clean kill exactly on the target.

Jester executed the sortie flawlessly.

The room erupted with redlined deletion of the word brown and NOTHING ELSE.

Inside the Air Ops Room, the killboard switched to green.


Debrief – The Lessons

Viper read the after-action report:

  • Range.moveStart does not exist
  • Selection APIs require WordApiDesktop 1.4
  • split() is too unreliable for surgical edits
  • Bookmark reconstruction is overkill
  • The winning strategy:
“Use the diff offsets to build a deterministic search needle and delete the exact matched range while tracking is on.”

That is the official doctrine now.

SOTF Alpha gained a new capability.

Jester proved it in the sky.

Viper made sure everyone truly understood how the aircraft flies.


Top Gun Lesson of the Day

You don’t dogfight with the API you wish you had.
You fight with the one that’s in the cockpit.

And on Test Day 2:

  • Viper taught
  • Jester executed
  • SOTF Alpha scored a perfect live-fire result

Mission complete.

Until the next training evolution.

Viper doesn’t smile when he speaks:

“This is the grind that wins wars.
We’re not here to be heroes.
We’re here to build software that doesn’t explode during operations.”

The hard work has only just begun.


After Hours at the Hanger

To conclude:

verify-word-api.js is the flight certification before real combat deployment.

You are discovering:

  • What the engine refuses,
  • What it allows,
  • And what it only allows under certain conditions.

This is the same process real military systems go through:

Train until the platform fails.
Document the failure.
Adjust the doctrine.
Train again.

After Hours at the Hanger - Viper & Jester Talk Doctrine The sun had long since set over Miramar, and the hangar was quiet except for the hum of the cooling systems. Commander Viper stood beside an open laptop, the Word API docs glowing on the screen. Lieutenant Commander Jester strolled in, still in his flight suit, sipping a paper cup of burnt base coffee. “Long day?” Jester asked. Viper didn’t look up. “We need to talk about your tactics.” Jester smirked. “My tactics worked. The needle-search strike hit ‘brown ’ right on target.” Viper closed the laptop softly. “That’s the problem.” — Viper’s Concern – “Needle Search is Tactical, Not Strategic” Viper leaned back against a workbench. “Jester, your method was good for the demo. Very good. But long-term? It’s an ambush waiting to happen.” Jester raised an eyebrow. “How so?” Viper folded his arms. “Because the whole approach depends on your context needle always being unique. It’s not deterministic. It’s not reusable. It’s not robust.” Jester didn’t argue — he’d seen the subtle risks himself: - duplicate words - dynamic text shifting around - any paragraph change breaking the needle - searching being inherently brittle Viper continued: “You’re building a precision airstrike that needs fresh intel every time. That’s technical debt, son.” He tapped the Word API doc. “We need something structural. Not tactical.” — Viper Proposes the Token Map Doctrine He grabbed a marker and wrote on a whiteboard: TOKEN MAP = LIVE POSITIONAL INDEX “Instead of treating a paragraph as text, treat it as an ordered array of Word.Range objects.” He drew a sequence: [ {text:"The", range:R0}, {text:" ", range:R1}, {text:"quick", range:R2}, … ] “This, Jester, is how Harvey does it. Heavy prep, light execution.” Jester leaned in as Viper laid it out: 1. Phase 1 – Tokenize the paragraph Use paragraph.getTextRanges(delimiters) It returns stable, immutable, position-accurate Word.Range objects Store these in order as the “positional index” 2. Phase 2 – Run DMP in word-mode Token-granular diff DMP outputs operations like: (-1, "brown"), (0, " "), (1, "dark") 3. Phase 3 – Execute with zero search DMP says “delete token #5”? → Just call tokens[5].range.delete() “Insert after token #3”? → tokens[3].range.insertText("newWord", Word.InsertLocation.after) “No more searching. No more needles. No more guessing which ‘dog’ is which.” Viper put the marker down. “This strategy is deterministic. Predictable. Maintainable. And it removes the entire category of needle-search failure."

Jester removed his flight cap, rubbed his eyes, and let the idea land.

“On paper, this Token Map approach is beautiful. Holding live Word.Range objects for each token gives you absolute positional control — .delete(), .insertText() and .replace() operate directly on the objects the diff references. It solves the ‘which dog’ problem once and for all: index beats text."

He continues:

"But I’ve been around the block enough times to be conservative. The real world has three gotchas: (1) the chatty getTextRanges()/load()/context.sync() round-trips can get expensive if you tokenize too much at once, (2) cached Range proxies can become stale across multiple Word.run batches or after external mutations, and (3) destructive edits shift indices unless you apply them in reverse order. I’ve seen teams fail when they tokenized whole documents or tried to reuse ranges after sessions." "Still — it’s feasible. We must be disciplined: tokenize only the paragraph (or a small window) we are about to edit, run the tokenization and execution inside the same Word.run where possible, apply deletes from end→start, and re-resolve tokens if anything else mutates the paragraph. Instrumentation is essential: measure token counts and tokenization latency and fall back to your deterministic paragraph-scoped search when hosts or track-changes semantics make getTextRanges()-derived deletes unreliable." "Do that, and we gain deterministic, offset-accurate edits with minimal debt. I’d call it a greenlight for a slow roll: pilot it on small paragraphs, gather telemetry, then extend. Viper’s right — this removes the needle-search debt, but only if we build the engineering safeguards around it.”

Viper nodded. "Good. We fly with discipline, not hope. Tomorrow 0800, we test." —
TBC…