Skip to content

build(xterm): restore the patch regeneration harness and gate it in CI - #15223

Merged
nwparker merged 2 commits into
mainfrom
nwparker/xterm-patch-harness
Aug 18, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/xterm-patch-harness

Conversation

@nwparker

@nwparker nwparker commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​470 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​469
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2053 $\color{#cf222e}{\Huge{\mathbf{−}}}$​41 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2012

docs/reference/ime-architecture.md says, inline: "Never hand-edit the bundles in the patch," and links to docs/reference/xterm-patch-regeneration.md.

That doc does not exist. Neither does the harness it describes.

What happened

Both landed in 29117bf7767 and were deleted by 17cfc968cf5 — "Revert the terminal IME composition-ownership change (#13282)" — on 2026-08-08. A functional revert that swept up a build tool, its 451-line test, the upstream pin, the source patch and a CI gate as collateral. The rule survived; its enforcement did not.

Every xterm patch since has had to hand-edit minified bundles to comply with the surrounding architecture: a47b9d1167d (#13284), 17ef6ccce68 (#14758), 453237cc57c (#15014). Not carelessness — everything resolves to lib/xterm.mjs at runtime and under vitest via the package module field, so a src-only edit is inert. It would leave tests passing while changing nothing.

The shipped bundles were not build output — measured, not asserted

Reading a 7 MB minified diff proves nothing, so this compares identifier multisets between the shipped bundle and a pristine build of the pinned commit. lib/xterm.mjs: 20 of 3,175 distinct tokens differ. lib/xterm.js: 25 of 2,937. Fifteen and eighteen of those respectively are one- and two-character minifier locals that shift because esbuild allocates names by frequency.

The rest are fingerprints of a human editing minified code:

tell shipped rebuilt
$rl, $hp, $tid — hand-written names a minifier never emits 2 each 0
const in an otherwise let-only esbuild bundle 8 0
!! where the source reads Boolean() — Boolean 2→3
escaped LRM vs the literal codepoint esbuild emits u200E 1 0
a {…; return} block esbuild collapses to void(…) void 402 403

No unexplained token remains. This PR replaces those bundles with genuine build output.

The old source patch could not be reused

This is the trap, and it is worse than "the file is stale."

The .src.patch at 29117bf7767 is 247 lines and describes the reverted composition-ownership architecture. Restoring it would not merely have dropped three accumulated fixes — it would have re-applied an abandoned design.

It is re-derived from the currently shipped patch instead, giving 1,005 lines. The derivation is a fixed point: bootstrapping sourceHunks(shipped) returns byte-identical to what the canonical --write path re-emits.

Proof the base is right — occurrence counts against freshly reinstalled node_modules:

_compositionRemainder      (#15014)   mjs=5  js=5
_deferPreeditResync        (#14758)   mjs=2  js=2
classList.toggle("active"  (#13284)   mjs=1  js=1
_claimImeKeydownCommit     (#12099)   mjs=0  js=0   <- correct, not in this base
_imeKeydownAwaitingCommit  (#12099)   mjs=0  js=0   <- correct

(Occurrence counts via grep -o … | wc -l. grep -c returns 1 regardless of hit count here, because the bundles are a single line.)

Two deliberate departures from the deleted version

Sourcemaps included, not deleted. The 08-08 policy deletes lib/*.map; terminal-ime-xterm-transaction-events.test.ts reads them and asserts the mapped Version.ts matches the runtime version. Restoring verbatim would have broken a live test. Costs ~5.8 MB of the patch.

The source-patch superset carve-out is gone. It existed to tolerate source hunks the shipped patch cannot name. That case is not live today, so rather than document a hypothetical the check is now strict equality — a hunk that cannot be named fails the run loudly instead of being carved out silently.

An inherited claim that was half wrong

The old doc asserted @xterm/addon-webgl and @xterm/addon-serialize reproduce byte for byte. Measured rather than repeated:

True — all four packages carry the same commit stamp (53a98a72…, including [email protected] despite the version skew), and both addons' ESM output and sourcemaps rebuild identical to the published tarballs.

False — both also publish a CJS lib/addon-*.js that the root package script never builds; upstream's webpack entry is core's Terminal.js alone. Folding either addon in today would emit a patch whose CJS stanza came from the current hand-edited bundle. That is a real blocker the old sentence concealed.

The gate

xterm_patch_sync runs the regenerator in --check mode, so a patch that does not match a rebuild of the pinned upstream now fails PR CI. Local cold run ~20 s.

-diff -text on the emitted patch is required, not cosmetic: pnpm hashes it byte-for-byte, so a CRLF checkout on Windows breaks pnpm install outright. -diff also suppresses an unreadable 7 MB diff — review the source patch under xterm-src/ instead.

Verification

regenerate-xterm-patches + pr-workflow-parallelism    45 passed (45)
config/scripts                            837 passed | 6 skipped (843)
terminal-pane                                       3640 passed (3640)
--check                          in sync (7364643 bytes)

The trim was proven byte-neutral by regenerating before and after and comparing hashes — both 7fd86b33ead4…, patch and source patch alike.

pr.yml is +31 / −0. #15211 landed as this branch's base, so its work was re-applied additively and verified intact: filter: blob:none on all four checkouts, the TypeScript incremental cache, the baseline Git build cache, and build:release:parallel. oxlint clean, max-lines ratchet OK, no suppression added.

Not verified

  • The CI job has not run on a real runner. Now verified on CI. xterm patch sync passed on this PR: in sync (7364643 bytes) — the same byte count as locally — in ~43 s cold, and the upstream cache saved its key. The run also confirms CI is --work-dir's only consumer, since the job invokes --check --work-dir="$WORK_DIR".
  • The addon CJS bundles are unreproduced, as above.
  • Windows and Linux untested for both the -diff -text attributes and the generator itself. macOS only.
  • regenerate-xterm-patches.mjs sits at 591 effective lines against the 600 **/*.mjs budget. Since suppressions are banned, the next addition needs a split rather than a bump.

Stacking

#15198 (the #12099 fix) rebases on top of this. Its patch conflict must be resolved by regenerating, not by --ours/--theirs or hand-merging — hand-resolving a 7 MB generated file reintroduces exactly the drift this removes.

docs/reference/ime-architecture.md says "Never hand-edit the bundles in
the patch" and links to docs/reference/xterm-patch-regeneration.md. That
doc does not exist, and neither does the harness it describes.

Both landed in 29117bf and were deleted by 17cfc96, a revert of
the composition-ownership change, which swept up a build tool and a CI
gate as collateral. The rule survived; its enforcement did not. Every
xterm patch since has had to hand-edit minified bundles to comply with
the surrounding architecture, because everything resolves to
lib/xterm.mjs at runtime and under vitest, so a src-only edit is inert.

The shipped bundles were therefore not the output of any build, and this
restores them to build output. Comparing identifier multisets against a
pristine build of the pinned commit finds hand-written names a minifier
never emits ($rl, $hp, $tid), const in an otherwise let-only esbuild
bundle, !! where the source reads Boolean(), an escaped LRM where esbuild
emits the literal, and a return block esbuild collapses to void(...).
Every remaining token difference is a minifier local reallocating.

The old source patch could not be reused. It described the reverted
composition-ownership architecture, so restoring it would have re-applied
an abandoned design on top of dropping three accumulated fixes. It is
re-derived from the shipped patch instead, and the derivation is a fixed
point.

Two deliberate departures from the deleted version. Sourcemaps are
included rather than deleted, because a live test reads lib/*.map and
asserts the mapped version matches the runtime version. The source-patch
superset carve-out is gone, so a source hunk the shipped patch cannot
name now fails loudly instead of being carved out silently.

The doc's claim that the webgl and serialize addons reproduce byte for
byte was half wrong. Their ESM output does reproduce at the pinned
commit, but both also publish CJS that the root package script never
builds, so folding either in needs a build step this harness lacks.
Recorded as a blocker rather than a confident sentence.

xterm_patch_sync runs the regenerator in --check mode, so a patch that
does not match a rebuild of the pinned upstream now fails PR CI.

The -diff -text attribute is required, not cosmetic: pnpm hashes the
patch byte-for-byte, so a CRLF checkout breaks the install outright.

Not verified: the CI job has not run on a real runner, the addon CJS
bundles are unreproduced, and the generator is untested on Windows and
Linux.
@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 55dc473d-f6d1-4837-810a-9e8de1d5192b

📥 Commits

Reviewing files that changed from the base of the PR and between 06bf1bc and 65d28b4.

📒 Files selected for processing (4)
  • .gitattributes
  • config/scripts/regenerate-xterm-patches.mjs
  • config/scripts/regenerate-xterm-patches.test.mjs
  • docs/reference/xterm-patch-regeneration.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • .gitattributes
  • config/scripts/regenerate-xterm-patches.test.mjs
  • docs/reference/xterm-patch-regeneration.md
  • config/scripts/regenerate-xterm-patches.mjs

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

Adds a pinned xterm.js regeneration manifest and CLI with source, bundle, toolchain, sourcemap, and lockfile validation. Updates browser composition handling with transaction-based IME reconciliation, cleanup, input routing, and mid-line rendering. Adds comprehensive regeneration tests. Integrates patch synchronization into pull-request verification and documents the regeneration process. Adds Git attributes and tracking rules for patch artifacts.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description gives detailed technical context and testing results, but it omits required template sections and does not provide a linked issue. Add the required template sections, including ELI5, What Changed, Why, Linked Issue, Visual Proof or N/A, Testing, AI Disclosure, Review, Notes, and Checklist.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: restoring the xterm patch regeneration harness and enforcing it in CI.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (4)
config/patches/xterm-upstream.json (1)

12-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Separate the toolchain documentation key from the version map.

assertToolchain iterates every key of manifest.toolchain and skips only the literal key why. If anyone adds a second prose key here (for example note), the generator resolves node_modules/note/package.json and fails with "Upstream install is missing note". Nest the pinned versions under their own object so prose and data cannot collide.

♻️ Proposed manifest shape
   "toolchain": {
     "why": "Pinned by the upstream package-lock at the commit above. The generator asserts these resolve as expected so a silent upstream resolution change surfaces as a toolchain error rather than a mystery patch diff.",
-    "esbuild": "0.28.1",
-    "webpack": "5.107.0",
-    "terser": "5.47.1",
-    "`@typescript/native-preview`": "7.0.0-dev.20260521.1"
+    "versions": {
+      "esbuild": "0.28.1",
+      "webpack": "5.107.0",
+      "terser": "5.47.1",
+      "`@typescript/native-preview`": "7.0.0-dev.20260521.1"
+    }
   },

assertToolchain then iterates manifest.toolchain.versions and drops the name === 'why' special case.

config/scripts/regenerate-xterm-patches.mjs (1)

488-505: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

diffFolders exists twice because the generator keeps it private. The generator's copy sets maxBuffer: 512 * 1024 * 1024 and rethrows when git writes to stderr; the test copy does neither, so the diff-based tests validate a second implementation instead of the shipped one.

  • config/scripts/regenerate-xterm-patches.mjs#L488-L505: add export to diffFolders.
  • config/scripts/regenerate-xterm-patches.test.mjs#L56-L71: delete the local diffFolders and import it from ./regenerate-xterm-patches.mjs.
config/scripts/regenerate-xterm-patches.test.mjs (1)

435-443: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert that the committed source patch contains source stanzas only.

sourceHunks(source) discards any stanza outside src/ before the comparison. A source patch that carried a lib/ stanza would pass this test, and git apply would then write a generated file during regeneration. The heavy xterm_patch_sync job compares full bytes, but the comment at lines 422-423 states that this test is meant to catch the desync cheaply.

💚 Proposed tightening
       const source = await readFile(path.join(REPO_ROOT, packageEntry.sourcePatch), 'utf8')
+      expect(sourceHunks(source)).toBe(source)
       expect(sourceHunks(source)).toBe(sourceHunks(patch))
       expect(generatedHunks(patch, packageEntry.generatedPaths)).not.toBe('')
config/patches/xterm-src/@[email protected] (1)

20-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share one source for the composition event names.

'xterm-composition-transaction-accepted' appears as a literal in CoreBrowserTerminal.ts and as XTERM_COMPOSITION_TRANSACTION_ACCEPTED_EVENT in CompositionHelper.ts. 'xterm-composition-transaction-settled' is inlined at line 748 while the other three names use constants. Export the constants from one module and import them in both files, so a rename cannot desynchronize the producer and the consumers.

Also applies to: 115-118, 746-751


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 939fc5bb-eda4-4489-bbe6-48277ccf47d4

📥 Commits

Reviewing files that changed from the base of the PR and between 13b10e0 and 06bf1bc.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • .gitattributes
  • .github/workflows/pr.yml
  • .gitignore
  • config/patches/@[email protected]
  • config/patches/xterm-src/@[email protected]
  • config/patches/xterm-upstream.json
  • config/scripts/pr-workflow-parallelism.test.mjs
  • config/scripts/regenerate-xterm-patches.mjs
  • config/scripts/regenerate-xterm-patches.test.mjs
  • docs/reference/xterm-patch-regeneration.md

Included review availability: Your plan includes up to 10 reviews per rolling hour; 5 remain after this review.

Comment on lines +556 to +568
+ const textareaInput = this._getPendingTextareaInput(pending, includeFollowingInput);
+ const observedInput = this._removeAlreadySentData(
+ pending.inputData || pending.keypressData,
+ pending.dataAlreadySent
+ );
+ // Why: with no textarea, end, input, or keypress evidence the composition
+ // was cancelled (e.g. Backspace over the whole preedit); stale
+ // compositionupdate data must not be replayed as committed text.
+ const input = this._mergeTextObservations(
+ textareaInput || pending.endData || (observedInput ? pending.compositionData : ''),
+ observedInput,
+ pending.keypressMayOverlapComposition
+ );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

pending.inputData || pending.keypressData drops one of two distinct observations.

inputData and keypressData can both be non-empty and hold different text. For IBus Hangul the preedit is withdrawn before compositionend, the committed syllable arrives through insertText, and the committing Space or Enter arrives through keypress. With ||, inputData wins and the committing key is lost. macOS hides this shape because terminal-ime-native-text-forwarder.ts suppresses insertText while a transaction is pending, and that forwarder is macOS-only.

Merge the two observations instead of selecting one.

Based on learnings: "CompositionHelper._sendPendingComposition must account for pending.inputData and pending.keypressData containing different text ... using pending.inputData || pending.keypressData then drops the committing Space or Enter."

🐛 Proposed fix to combine both observations
     const textareaInput = this._getPendingTextareaInput(pending, includeFollowingInput);
     const observedInput = this._removeAlreadySentData(
-      pending.inputData || pending.keypressData,
+      this._mergeTextObservations(
+        pending.inputData,
+        pending.keypressData,
+        pending.keypressMayOverlapComposition
+      ),
       pending.dataAlreadySent
     );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
+ const textareaInput = this._getPendingTextareaInput(pending, includeFollowingInput);
+ const observedInput = this._removeAlreadySentData(
+ pending.inputData || pending.keypressData,
+ pending.dataAlreadySent
+ );
+ // Why: with no textarea, end, input, or keypress evidence the composition
+ // was cancelled (e.g. Backspace over the whole preedit); stale
+ // compositionupdate data must not be replayed as committed text.
+ const input = this._mergeTextObservations(
+ textareaInput || pending.endData || (observedInput ? pending.compositionData : ''),
+ observedInput,
+ pending.keypressMayOverlapComposition
+ );
const textareaInput = this._getPendingTextareaInput(pending, includeFollowingInput);
const observedInput = this._removeAlreadySentData(
this._mergeTextObservations(
pending.inputData,
pending.keypressData,
pending.keypressMayOverlapComposition
),
pending.dataAlreadySent
);
// Why: with no textarea, end, input, or keypress evidence the composition
// was cancelled (e.g. Backspace over the whole preedit); stale
// compositionupdate data must not be replayed as committed text.
const input = this._mergeTextObservations(
textareaInput || pending.endData || (observedInput ? pending.compositionData : ''),
observedInput,
pending.keypressMayOverlapComposition
);

Source: Learnings

Comment on lines +717 to +738
+ private _endPendingCompositionSession(pending: IPendingComposition): void {
+ if (pending.sessionEnded) {
+ return;
+ }
+ pending.sessionEnded = true;
+ const input =
+ this._getPendingTextareaInput(pending) ||
+ pending.endData ||
+ pending.compositionData;
+ this._dispatchCompositionSessionEvent(new CustomEvent(
+ XTERM_COMPOSITION_SESSION_END_EVENT,
+ {
+ bubbles: true,
+ cancelable: true,
+ detail: {
+ id: pending.transactionId,
+ data: input,
+ dataPendingReconciliation: true
+ }
+ }
+ ));
+ }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find call sites and consumers of the pending-session-end path.
set -euo pipefail

# Producer: any call other than the definition inside the patch.
rg -n '_endPendingCompositionSession|sessionEnded' --glob '!**/node_modules/**'

# Consumers: anything reading the reconciliation flag or the session-end event.
rg -n 'dataPendingReconciliation|xterm-composition-session-end' --glob '!**/node_modules/**'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- matching symbols and event names ---'
rg -n -F -e '_endPendingCompositionSession' -e 'sessionEnded' -e 'dataPendingReconciliation' -e 'xterm-composition-session-end' . \
  --glob '!**/node_modules/**' || true

printf '%s\n' '--- patch context ---'
sed -n '680,770p' config/patches/xterm-src/@[email protected]
sed -n '520,585p' config/patches/xterm-src/@[email protected]

Repository: stablyai/orca

Length of output: 50372


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

p = Path("config/patches/xterm-src/@[email protected]")
terms = (
    "_endPendingCompositionSession",
    "sessionEnded",
    "dataPendingReconciliation",
    "xterm-composition-session-end",
)
for n, line in enumerate(p.read_text(errors="replace").splitlines(), 1):
    if any(term in line for term in terms):
        print(f"{n}: {line[:500]}")
PY

printf '%s\n' '--- nearby patch lines ---'
sed -n '700,755p' config/patches/xterm-src/@[email protected]
sed -n '540,580p' config/patches/xterm-src/@[email protected]

Repository: stablyai/orca

Length of output: 3874


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path("config/patches/xterm-src/@[email protected]")
lines = p.read_text(errors="replace").splitlines()
for start, end in ((430, 590), (680, 770), (770, 850)):
    print(f"--- patch lines {start}-{end} ---")
    for n in range(start, min(end, len(lines)) + 1):
        print(f"{n}: {lines[n-1][:700]}")
PY

printf '%s\n' '--- all references outside the vendored patch ---'
rg -n -F -e '_endPendingCompositionSession' -e 'dataPendingReconciliation' -e 'xterm-composition-session-end' . \
  --glob '!config/patches/xterm-src/@[email protected]' \
  --glob '!**/node_modules/**' || true

Repository: stablyai/orca

Length of output: 50372


Remove the unused _endPendingCompositionSession path

_endPendingCompositionSession has no call site. Therefore, pending.sessionEnded remains false, and this method never dispatches a dataPendingReconciliation: true event. Remove the unused method and the sessionEnded field, or add the intended call path.

Comment on lines +905 to +916
+ private _opaqueViewBackground(): string {
+ const value = this._optionsService.rawOptions.theme?.background?.trim();
+ if (!value) {
+ return '#000';
+ }
+ const channels = /^rgba?\(([^,()]+),([^,()]+),([^,()]+)(?:,[^()]+)?\)$/.exec(value);
+ if (channels) {
+ return `rgb(${channels[1]},${channels[2]},${channels[3]})`;
+ }
+ const opaqueHex = /^(#(?:[\da-f]{3}|[\da-f]{6}))[\da-f]{1,2}$/i.exec(value);
+ return opaqueHex ? opaqueHex[1] : value;
+ }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

_opaqueViewBackground keeps alpha for modern color syntax.

The regexes match only comma-separated rgb()/rgba() and hex with 1-2 alpha nibbles. Space-separated syntax such as rgb(0 0 0 / 50%), plus hsl(), hsla(), color(), and the keyword transparent, fall through unchanged. The overlay then stays see-through, and the cells that the rendered tail stands in for remain visible.

Composite the value over an opaque base, or reject any value that is not proven opaque and fall back to #000.

Comment on lines +235 to +242
function lockfileResolutionHashPattern(packageKey) {
const separator = packageKey.lastIndexOf('@')
const name = escapeRegExp(packageKey.slice(0, separator))
const version = escapeRegExp(packageKey.slice(separator + 1))
// Two spellings: `name@version(patch_hash=…)` in dependency keys, and a bare
// `: version(patch_hash=…)` under `version:` and in resolved dependency maps.
return new RegExp(`(?:${name}@|: )${version}\\(patch_hash=([0-9a-f]{64})\\)`, 'g')
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

The bare : version(patch_hash=…) branch can match a different patched package.

lockfileResolutionHashPattern matches on the version string alone in its second alternative. Today the two patched packages hold distinct versions (@xterm/[email protected] and [email protected]), so the collision is latent. If two patched packages ever share a version string, readLockfileResolutionHashes reports foreign hashes as stale and updateLockfilePatchHash rewrites the other package's hash, which corrupts pnpm-lock.yaml.

Add a fail-stop guard so ambiguity cannot pass silently, for example by asserting in regenerateXtermPatches that no two manifest.packages entries share a version, or by keying the resolution scan on the package name context.

Based on learnings from config/scripts/generate-skill-bundle-manifest.mjs: "do not allow duplicate appVersion mapping entries to silently rely on a first-write-wins … deterministically deduplicate or validate … (fail/stop generation if ambiguous)". The same fail-on-ambiguity rule applies to this hash mapping.

Source: Learnings

Comment on lines +366 to +379
function ensureDependencies(upstreamRoot, manifest) {
const lockfile = path.join(upstreamRoot, 'package-lock.json')
const stamp = path.join(upstreamRoot, 'node_modules', '.orca-xterm-install-stamp')
const want = `${manifest.upstream.commit}\n${statSync(lockfile).size}\n`
if (existsSync(stamp) && readFileSync(stamp, 'utf8') === want) {
return
}
run('npm', ['ci'], {
cwd: upstreamRoot,
env: { ...process.env, PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1', PUPPETEER_SKIP_DOWNLOAD: '1' }
})
assertToolchain(upstreamRoot, manifest)
writeFileSync(stamp, want)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Run assertToolchain on every invocation, not only after a fresh install.

ensureDependencies returns early when the stamp matches. The stamp records only manifest.upstream.commit and the upstream lockfile size, so a change to manifest.toolchain does not invalidate it. On a warm work directory the generator then builds without checking any pinned toolchain version, which is the exact silent-resolution-drift case the manifest toolchain.why text says this gate prevents. Any manual mutation of node_modules also goes unchecked.

Move the assertion out of the install branch.

🐛 Proposed fix
 function ensureDependencies(upstreamRoot, manifest) {
   const lockfile = path.join(upstreamRoot, 'package-lock.json')
   const stamp = path.join(upstreamRoot, 'node_modules', '.orca-xterm-install-stamp')
   const want = `${manifest.upstream.commit}\n${statSync(lockfile).size}\n`
-  if (existsSync(stamp) && readFileSync(stamp, 'utf8') === want) {
-    return
-  }
-  run('npm', ['ci'], {
-    cwd: upstreamRoot,
-    env: { ...process.env, PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1', PUPPETEER_SKIP_DOWNLOAD: '1' }
-  })
-  assertToolchain(upstreamRoot, manifest)
-  writeFileSync(stamp, want)
+  const installed = existsSync(stamp) && readFileSync(stamp, 'utf8') === want
+  if (!installed) {
+    run('npm', ['ci'], {
+      cwd: upstreamRoot,
+      env: { ...process.env, PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1', PUPPETEER_SKIP_DOWNLOAD: '1' }
+    })
+    writeFileSync(stamp, want)
+  }
+  assertToolchain(upstreamRoot, manifest)
 }

Comment on lines +531 to +537
function diffCheckoutSource(packageRoot) {
return run('git', [...CHECKOUT_DIFF_FLAGS, '--', 'src/'], {
cwd: packageRoot,
env: pnpmDiffEnvironment(),
maxBuffer: 64 * 1024 * 1024
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

git diff -- src/ omits files the source patch adds.

regeneratePackage applies the source patch with git apply at line 553. A patch stanza that creates a new file under src/ leaves that file untracked, so diffCheckoutSource does not report it. The folder diff at line 572 does report it, so assertSourceDerivationsAgree fails with the "disagree on a source file" message instead of the real cause. In --write mode the newly added file is dropped from the regenerated source patch.

Mark new paths as intent-to-add before the diff.

🐛 Proposed fix
 function diffCheckoutSource(packageRoot) {
+  // `git apply` leaves created files untracked, and `git diff` ignores those.
+  run('git', ['add', '--intent-to-add', '--', 'src/'], { cwd: packageRoot })
   return run('git', [...CHECKOUT_DIFF_FLAGS, '--', 'src/'], {
     cwd: packageRoot,
     env: pnpmDiffEnvironment(),
     maxBuffer: 64 * 1024 * 1024
   })
 }

Note that regeneratePackage already resets the checkout with git reset --hard before each apply, so the index change does not leak into the next package.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function diffCheckoutSource(packageRoot) {
return run('git', [...CHECKOUT_DIFF_FLAGS, '--', 'src/'], {
cwd: packageRoot,
env: pnpmDiffEnvironment(),
maxBuffer: 64 * 1024 * 1024
})
}
function diffCheckoutSource(packageRoot) {
// `git apply` leaves created files untracked, and `git diff` ignores those.
run('git', ['add', '--intent-to-add', '--', 'src/'], { cwd: packageRoot })
return run('git', [...CHECKOUT_DIFF_FLAGS, '--', 'src/'], {
cwd: packageRoot,
env: pnpmDiffEnvironment(),
maxBuffer: 64 * 1024 * 1024
})
}

Comment on lines +210 to +215
`xterm_patch_sync` in `.github/workflows/pr.yml` runs
`regenerate-xterm-patches.mjs --check` on every PR and is part of the `verify`
aggregate. It clones the pinned commit, installs upstream's toolchain, builds
twice, and byte-compares the result against the committed patch. Both builds and
the diff together are about eight seconds; `npm ci` for upstream's toolchain is
what the job actually spends its minutes on, and the cache key is the manifest.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target context ---'
sed -n '190,225p' docs/reference/xterm-patch-regeneration.md
printf '%s\n' '--- related statements about runner validation and timing ---'
rg -n -i -C 3 'real runner|runner|eight seconds|8 seconds|timing|xterm_patch_sync|regenerate-xterm-patches' . \
  -g '!node_modules' -g '!dist' -g '!build'
printf '%s\n' '--- workflow job definition ---'
rg -n -C 12 'xterm_patch_sync|regenerate-xterm-patches\.mjs|npm ci|cache' .github docs \
  -g '*.yml' -g '*.yaml' -g '*.md' -g '*.mjs' -g '*.json'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target document ---'
sed -n '1,230p' docs/reference/xterm-patch-regeneration.md
printf '%s\n' '--- focused xterm references ---'
rg -n -i -C 4 'real runner|runner validation|eight seconds|8 seconds|timing|xterm_patch_sync|regenerate-xterm-patches' \
  docs/reference/xterm-patch-regeneration.md .github/workflows/pr.yml \
  .github/pull_request_template.md 2>/dev/null || true
printf '%s\n' '--- repository status and recent change summary ---'
git status --short
git diff --stat

Repository: stablyai/orca

Length of output: 21306


Qualify the CI timing estimate until a runner validates it.

State that the approximately eight-second build-and-diff time is a local measurement, or update it after xterm_patch_sync runs on a real CI runner. The workflow definition does not establish CI timing.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~210-~210: The official name of this software platform is spelled with a capital “H”.
Context: ... ## CI Contract xterm_patch_sync in .github/workflows/pr.yml runs `regenerate-xter...

(GITHUB)

…paths

Readiness review on the restore found one blocking gap and two cheap
cleanups. None of them change the emitted patch, which is byte-identical
before and after.

The generator could not run on Windows at all. Three sites called npm
through execFileSync with shell:false, but npm ships as npm.cmd there,
execFile applies no PATHEXT, and since CVE-2024-27980 it refuses a .cmd
target without a shell. That matters because this harness arms a
blocking gate whose documented remedy is --write, so a Windows
contributor who tripped the gate had no remedy except hand-editing a 7MB
minified bundle, which is the practice the gate exists to abolish. Four
sibling scripts in config/scripts already handle this; the fix follows
them and lands in run(), so the manifest-driven build step is covered
too. git and tar are real executables in System32 and keep resolving
without a shell, which avoids quoting exposure on paths with spaces.

deleteGeneratedSourcemaps was unreachable, since the policy is include.
Deleting it left "delete" as a legal policy value that nothing honoured,
so a manifest asking for it would have silently shipped sourcemaps that
do not match the bundle. The enum is narrowed and an unrecognised policy
now throws rather than falling through.

generatedHunks moved into the test file rather than being dropped; its
partition assertion, that generated and source hunks reconstruct the
whole patch, is worth keeping.

The -text attribute now covers all five patch files. pnpm hashes each of
them byte-for-byte, so the CRLF hazard the xterm patch was protected
from applies equally to node-pty and the three addons. All five were
already LF in the object DB, so this pins existing behaviour. -diff
stays scoped to the xterm patch, since the others are readable.

The doc's claim that the addons reproduce byte for byte is now dated and
marked a one-off measurement rather than an invariant, because nothing
re-runs it.

Effective lines fall from 591 to 568 against the 600 budget. Still the
largest file in config/scripts, and adding a second package to the
manifest would need a split first.
@nwparker
nwparker merged commit 4975247 into main Aug 18, 2026
46 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
stablyai#15223)

* build(xterm): restore the patch regeneration harness and gate it in CI

docs/reference/ime-architecture.md says "Never hand-edit the bundles in
the patch" and links to docs/reference/xterm-patch-regeneration.md. That
doc does not exist, and neither does the harness it describes.

Both landed in 29117bf and were deleted by 17cfc96, a revert of
the composition-ownership change, which swept up a build tool and a CI
gate as collateral. The rule survived; its enforcement did not. Every
xterm patch since has had to hand-edit minified bundles to comply with
the surrounding architecture, because everything resolves to
lib/xterm.mjs at runtime and under vitest, so a src-only edit is inert.

The shipped bundles were therefore not the output of any build, and this
restores them to build output. Comparing identifier multisets against a
pristine build of the pinned commit finds hand-written names a minifier
never emits ($rl, $hp, $tid), const in an otherwise let-only esbuild
bundle, !! where the source reads Boolean(), an escaped LRM where esbuild
emits the literal, and a return block esbuild collapses to void(...).
Every remaining token difference is a minifier local reallocating.

The old source patch could not be reused. It described the reverted
composition-ownership architecture, so restoring it would have re-applied
an abandoned design on top of dropping three accumulated fixes. It is
re-derived from the shipped patch instead, and the derivation is a fixed
point.

Two deliberate departures from the deleted version. Sourcemaps are
included rather than deleted, because a live test reads lib/*.map and
asserts the mapped version matches the runtime version. The source-patch
superset carve-out is gone, so a source hunk the shipped patch cannot
name now fails loudly instead of being carved out silently.

The doc's claim that the webgl and serialize addons reproduce byte for
byte was half wrong. Their ESM output does reproduce at the pinned
commit, but both also publish CJS that the root package script never
builds, so folding either in needs a build step this harness lacks.
Recorded as a blocker rather than a confident sentence.

xterm_patch_sync runs the regenerator in --check mode, so a patch that
does not match a rebuild of the pinned upstream now fails PR CI.

The -diff -text attribute is required, not cosmetic: pnpm hashes the
patch byte-for-byte, so a CRLF checkout breaks the install outright.

Not verified: the CI job has not run on a real runner, the addon CJS
bundles are unreproduced, and the generator is untested on Windows and
Linux.

* build(xterm): make the regenerator runnable on Windows and drop dead paths

Readiness review on the restore found one blocking gap and two cheap
cleanups. None of them change the emitted patch, which is byte-identical
before and after.

The generator could not run on Windows at all. Three sites called npm
through execFileSync with shell:false, but npm ships as npm.cmd there,
execFile applies no PATHEXT, and since CVE-2024-27980 it refuses a .cmd
target without a shell. That matters because this harness arms a
blocking gate whose documented remedy is --write, so a Windows
contributor who tripped the gate had no remedy except hand-editing a 7MB
minified bundle, which is the practice the gate exists to abolish. Four
sibling scripts in config/scripts already handle this; the fix follows
them and lands in run(), so the manifest-driven build step is covered
too. git and tar are real executables in System32 and keep resolving
without a shell, which avoids quoting exposure on paths with spaces.

deleteGeneratedSourcemaps was unreachable, since the policy is include.
Deleting it left "delete" as a legal policy value that nothing honoured,
so a manifest asking for it would have silently shipped sourcemaps that
do not match the bundle. The enum is narrowed and an unrecognised policy
now throws rather than falling through.

generatedHunks moved into the test file rather than being dropped; its
partition assertion, that generated and source hunks reconstruct the
whole patch, is worth keeping.

The -text attribute now covers all five patch files. pnpm hashes each of
them byte-for-byte, so the CRLF hazard the xterm patch was protected
from applies equally to node-pty and the three addons. All five were
already LF in the object DB, so this pins existing behaviour. -diff
stays scoped to the xterm patch, since the others are readable.

The doc's claim that the addons reproduce byte for byte is now dated and
marked a one-off measurement rather than an invariant, because nothing
re-runs it.

Effective lines fall from 591 to 568 against the 600 budget. Still the
largest file in config/scripts, and adding a second package to the
manifest would need a split first.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
stablyai#15223)

* build(xterm): restore the patch regeneration harness and gate it in CI

docs/reference/ime-architecture.md says "Never hand-edit the bundles in
the patch" and links to docs/reference/xterm-patch-regeneration.md. That
doc does not exist, and neither does the harness it describes.

Both landed in 29117bf and were deleted by 17cfc96, a revert of
the composition-ownership change, which swept up a build tool and a CI
gate as collateral. The rule survived; its enforcement did not. Every
xterm patch since has had to hand-edit minified bundles to comply with
the surrounding architecture, because everything resolves to
lib/xterm.mjs at runtime and under vitest, so a src-only edit is inert.

The shipped bundles were therefore not the output of any build, and this
restores them to build output. Comparing identifier multisets against a
pristine build of the pinned commit finds hand-written names a minifier
never emits ($rl, $hp, $tid), const in an otherwise let-only esbuild
bundle, !! where the source reads Boolean(), an escaped LRM where esbuild
emits the literal, and a return block esbuild collapses to void(...).
Every remaining token difference is a minifier local reallocating.

The old source patch could not be reused. It described the reverted
composition-ownership architecture, so restoring it would have re-applied
an abandoned design on top of dropping three accumulated fixes. It is
re-derived from the shipped patch instead, and the derivation is a fixed
point.

Two deliberate departures from the deleted version. Sourcemaps are
included rather than deleted, because a live test reads lib/*.map and
asserts the mapped version matches the runtime version. The source-patch
superset carve-out is gone, so a source hunk the shipped patch cannot
name now fails loudly instead of being carved out silently.

The doc's claim that the webgl and serialize addons reproduce byte for
byte was half wrong. Their ESM output does reproduce at the pinned
commit, but both also publish CJS that the root package script never
builds, so folding either in needs a build step this harness lacks.
Recorded as a blocker rather than a confident sentence.

xterm_patch_sync runs the regenerator in --check mode, so a patch that
does not match a rebuild of the pinned upstream now fails PR CI.

The -diff -text attribute is required, not cosmetic: pnpm hashes the
patch byte-for-byte, so a CRLF checkout breaks the install outright.

Not verified: the CI job has not run on a real runner, the addon CJS
bundles are unreproduced, and the generator is untested on Windows and
Linux.

* build(xterm): make the regenerator runnable on Windows and drop dead paths

Readiness review on the restore found one blocking gap and two cheap
cleanups. None of them change the emitted patch, which is byte-identical
before and after.

The generator could not run on Windows at all. Three sites called npm
through execFileSync with shell:false, but npm ships as npm.cmd there,
execFile applies no PATHEXT, and since CVE-2024-27980 it refuses a .cmd
target without a shell. That matters because this harness arms a
blocking gate whose documented remedy is --write, so a Windows
contributor who tripped the gate had no remedy except hand-editing a 7MB
minified bundle, which is the practice the gate exists to abolish. Four
sibling scripts in config/scripts already handle this; the fix follows
them and lands in run(), so the manifest-driven build step is covered
too. git and tar are real executables in System32 and keep resolving
without a shell, which avoids quoting exposure on paths with spaces.

deleteGeneratedSourcemaps was unreachable, since the policy is include.
Deleting it left "delete" as a legal policy value that nothing honoured,
so a manifest asking for it would have silently shipped sourcemaps that
do not match the bundle. The enum is narrowed and an unrecognised policy
now throws rather than falling through.

generatedHunks moved into the test file rather than being dropped; its
partition assertion, that generated and source hunks reconstruct the
whole patch, is worth keeping.

The -text attribute now covers all five patch files. pnpm hashes each of
them byte-for-byte, so the CRLF hazard the xterm patch was protected
from applies equally to node-pty and the three addons. All five were
already LF in the object DB, so this pins existing behaviour. -diff
stays scoped to the xterm patch, since the others are readable.

The doc's claim that the addons reproduce byte for byte is now dated and
marked a one-off measurement rather than an invariant, because nothing
re-runs it.

Effective lines fall from 591 to 568 against the 600 budget. Still the
largest file in config/scripts, and adding a second package to the
manifest would need a split first.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#15223)

* build(xterm): restore the patch regeneration harness and gate it in CI

docs/reference/ime-architecture.md says "Never hand-edit the bundles in
the patch" and links to docs/reference/xterm-patch-regeneration.md. That
doc does not exist, and neither does the harness it describes.

Both landed in 29117bf and were deleted by 0b80276, a revert of
the composition-ownership change, which swept up a build tool and a CI
gate as collateral. The rule survived; its enforcement did not. Every
xterm patch since has had to hand-edit minified bundles to comply with
the surrounding architecture, because everything resolves to
lib/xterm.mjs at runtime and under vitest, so a src-only edit is inert.

The shipped bundles were therefore not the output of any build, and this
restores them to build output. Comparing identifier multisets against a
pristine build of the pinned commit finds hand-written names a minifier
never emits ($rl, $hp, $tid), const in an otherwise let-only esbuild
bundle, !! where the source reads Boolean(), an escaped LRM where esbuild
emits the literal, and a return block esbuild collapses to void(...).
Every remaining token difference is a minifier local reallocating.

The old source patch could not be reused. It described the reverted
composition-ownership architecture, so restoring it would have re-applied
an abandoned design on top of dropping three accumulated fixes. It is
re-derived from the shipped patch instead, and the derivation is a fixed
point.

Two deliberate departures from the deleted version. Sourcemaps are
included rather than deleted, because a live test reads lib/*.map and
asserts the mapped version matches the runtime version. The source-patch
superset carve-out is gone, so a source hunk the shipped patch cannot
name now fails loudly instead of being carved out silently.

The doc's claim that the webgl and serialize addons reproduce byte for
byte was half wrong. Their ESM output does reproduce at the pinned
commit, but both also publish CJS that the root package script never
builds, so folding either in needs a build step this harness lacks.
Recorded as a blocker rather than a confident sentence.

xterm_patch_sync runs the regenerator in --check mode, so a patch that
does not match a rebuild of the pinned upstream now fails PR CI.

The -diff -text attribute is required, not cosmetic: pnpm hashes the
patch byte-for-byte, so a CRLF checkout breaks the install outright.

Not verified: the CI job has not run on a real runner, the addon CJS
bundles are unreproduced, and the generator is untested on Windows and
Linux.

* build(xterm): make the regenerator runnable on Windows and drop dead paths

Readiness review on the restore found one blocking gap and two cheap
cleanups. None of them change the emitted patch, which is byte-identical
before and after.

The generator could not run on Windows at all. Three sites called npm
through execFileSync with shell:false, but npm ships as npm.cmd there,
execFile applies no PATHEXT, and since CVE-2024-27980 it refuses a .cmd
target without a shell. That matters because this harness arms a
blocking gate whose documented remedy is --write, so a Windows
contributor who tripped the gate had no remedy except hand-editing a 7MB
minified bundle, which is the practice the gate exists to abolish. Four
sibling scripts in config/scripts already handle this; the fix follows
them and lands in run(), so the manifest-driven build step is covered
too. git and tar are real executables in System32 and keep resolving
without a shell, which avoids quoting exposure on paths with spaces.

deleteGeneratedSourcemaps was unreachable, since the policy is include.
Deleting it left "delete" as a legal policy value that nothing honoured,
so a manifest asking for it would have silently shipped sourcemaps that
do not match the bundle. The enum is narrowed and an unrecognised policy
now throws rather than falling through.

generatedHunks moved into the test file rather than being dropped; its
partition assertion, that generated and source hunks reconstruct the
whole patch, is worth keeping.

The -text attribute now covers all five patch files. pnpm hashes each of
them byte-for-byte, so the CRLF hazard the xterm patch was protected
from applies equally to node-pty and the three addons. All five were
already LF in the object DB, so this pins existing behaviour. -diff
stays scoped to the xterm patch, since the others are readable.

The doc's claim that the addons reproduce byte for byte is now dated and
marked a one-off measurement rather than an invariant, because nothing
re-runs it.

Effective lines fall from 591 to 568 against the 600 budget. Still the
largest file in config/scripts, and adding a second package to the
manifest would need a split first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant