* test(#3706): failing-first coverage for OpenCode variant emission and frontmatter escaping * fix(#3706): emit the resolved reasoning effort as OpenCode's variant key `query resolve-execution` resolved an effort level for every agent, but the OpenCode bake wrote only `model:` — the effort never reached the generated agent, so subagents ran at whatever the runtime defaulted the model to. This is the effort-side twin of the model-side defect fixed in #3705. The key is written only when an `effort` block is actually configured. `resolveInstallTimeEffort` always returns a level (the catalog default is `high`), so gating on its return value would stamp `variant: high` into every existing OpenCode install — and OpenCode resolves a variant name against a `variants` map in the user's `opencode.jsonc`, so a value nobody declared is not a safe default. Gating on `readGsdEffectiveEffortConfig` keeps installs that never asked for effort routing byte-identical. Kilo does not receive the key: `EFFORT_ARGV` declares surfaces for claude, opencode and codex and has no kilo entry. This is deliberately asymmetric with the model side, where #2794 J8 requires the two runtimes to resolve alike. Both frontmatter sinks now route through `frontmatterScalar`, which quotes and escapes any value that is not a plain scalar. The raw interpolation predates this change, but it was already shown by execution during the #3705 security review to let a config value containing a newline inject additional top-level keys (`tools:`, `permission:`) into a generated agent file. This change adds a second write to that sink, so it is closed here rather than doubled. * fix(#3706): quote frontmatter values YAML would not read back verbatim Self-review of the predicate added in the previous commit. Treating /^[A-Za-z0-9._:/@+-]+$/ as 'safe to emit bare' answers the wrong question: a value can match it and still not round-trip. - A leading '@' is a YAML *reserved* indicator and may not open a plain scalar at all, so a scoped ID like '@org/model' emitted bare is a parse error, not an ambiguity — the whole agent file becomes unreadable. - 'no' / 'y' / 'off' / 'null' resolve to booleans and null, so a variant with one of those names would match no entry in the user's variants map. - '12:30' resolves to 750 under YAML 1.1 sexagesimal, and ':' is legal mid-identifier here, so the form is reachable rather than contrived. Real model IDs pass every clause and stay bare, so already-generated files remain byte-identical. * fix(#3706): route variant through the declared effort seam and cover the live path Addresses six findings from the isolated review, all confirmed by execution. The tests were the serious one: they required `../bin/install.js` while the fix landed in src/, which compiles to gsd-core/bin/lib/. They exercised a different copy of the converter than the one the bake actually uses, so the whole suite was green-by-construction against unchanged code and the remote run failed all 13. Every case now runs against BOTH copies from one table, which doubles as the parity assertion the generative-fix note in runtime-artifact-conversion.cts asks for, and bin/install.js carries the mirrored change. Emission no longer hand-rolls the value. It goes through `renderEffortArgv`, the declared OpenCode effort seam (EFFORT_ARGV.opencode: its own supported set and clamp). That is what rejects a level that is not a wire value — above all `inherit`, which per #3533 (10d) means "omit the key and follow the host default" and was previously written literally, naming a variant that cannot resolve. Reachable two ways, both now pinned: an agent_overrides entry and a routing_tier_defaults entry. A bare effort.default does NOT reach a tiered agent (the #3531 tier ladder answers first), so a test written against `default` alone asserts nothing — that is pinned too. The plain-scalar decision moved into frontmatter.cts beside `scalarNeedsDoubleQuoting` rather than sitting next to it as a second, weaker predicate. `agentScalarNeedsDoubleQuoting` is a documented superset: it adds a trailing `:` (read as a nested mapping key, which fails the whole frontmatter), boolean/null words, and numeric-looking values including YAML 1.1 sexagesimal. Docs now state the cascade plainly: the gate is on effort being configured at all, not on the individual agent being named, so every generated OpenCode agent gets a variant line once any effort block exists. * test(#3706): assert the two frontmatterScalar copies cannot diverge A hand-picked adversarial corpus plus a fast-check property over YAML-significant strings, both run against bin/install.js and the live src copy. Verified the property can actually fail: mutating one copy's quoting rule is killed well inside the run budget. * fix(#3706): close the review findings — predicate, seam, and dead mirror Third review round; every item below was confirmed by execution. The scalar predicate was wrong in two families, both found by a round-trip property test rather than by reading. Basing it on scalarNeedsDoubleQuoting dropped the "first character must be alphanumeric" clause, so `~`, `.inf`, `.nan`, `+1`, `-0` and `.5` went out bare and came back as null/floats/ints; and that base predicate only inspects the FIRST character, so an embedded `: ` (a nested mapping, i.e. a parse error) or ` #` (a comment, i.e. silent truncation) also passed. Dates round out the set: `2026-08-25` opens alphanumeric, survives every other clause, and YAML resolves it to a Date. The property now asserts the contract directly over generated values instead of trusting an enumerated character list. The bin/install.js mirror is gone. Its premise was false — install.js already requires bin/lib at :65 — and it was unreachable besides: install.js's convertClaudeToOpencodeFrontmatter has no `isAgent: true` call site, because its agents path resolves converters from the compiled module. It was a third copy of the YAML rules serving a test rather than a caller, so the file is back to origin/next and the tests target the live copy only. Effort clamping moved to `clampEffortForHost`, which renderEffortArgv now delegates to. The layout was calling renderEffortArgv with a hardcoded 'argv' to borrow its clamp, which read as if the frontmatter key were gated on the invocation-time axis. It is not: claude declares effortSurface "argv" and independently bakes an effort: key. One capability table, one clamp, two channels that no longer pretend to be each other. Also corrects an earlier claim of mine: adding EFFORT_RENDERING.opencode would NOT have made `effort sync` write the wrong key, because it guards on the runtime name before it ever renders. The seam choice stands on other grounds. `effort sync` still skips OpenCode, but its stated reason claimed OpenCode "does not use effort: frontmatter", which this change makes false — so the message now says what is actually true. * docs(#3706): restate the changeset around the round-trip contract * fix(#3706): restore the changeset fragment belonging to #3809 An earlier commit in this branch picked the first file in .changeset/ by glob order instead of the fragment created for this issue, and overwrote agile-geese-squeak.md (PR 3815 / #3809) with this change's body. Restored verbatim from origin/next; this change's text now lives in its own patient-cranes-parade.md, where it was created. * feat(#3706): maintain the OpenCode variant key from effort sync Install bakes the resolved effort into OpenCode agent frontmatter as `variant:`, so `effort sync` has to maintain it or a config change only takes effect on reinstall — and its skip message claimed OpenCode does not use frontmatter effort at all, which this issue made false. cmdEffortSyncOpencode mirrors the codex branch: resolve per agent, clamp through the declared OpenCode capability, then write, strip, or skip. A null target means the key must not exist, which covers both "no effort configured" and "resolved to inherit or to an unsupported level" — the same states under which install writes nothing, so sync and install agree by construction. The frontmatter line-editors are key-parameterised rather than copied: setEffortFrontmatter / removeEffortFrontmatter are now thin wrappers over the same internals the variant path uses, and a test pins that the claude `effort:` behavior did not move. The child-process test harness fixes both HOME and USERPROFILE, so the hermetic-config assertions cannot pass vacuously on Windows. * fix(#3706): scope the frontmatter line editors to the matched block Found by the security review of the sync path, reported as correctness rather than vulnerability, and reproduced against pre-fix code before being fixed. Both editors matched the frontmatter with a regex that can match a block after a preamble, then derived the EOL and the opening-fence length from the START OF THE FILE. On a CRLF document with a preamble those disagree, the offsets shift by one byte, and the reassembled document comes back with a mangled fence (`---\rname: x`). Both now take the EOL from the matched block. `setFrontmatterKeyLine` additionally did a whole-file `/m` replace when the key already existed, gated only on the key being present in the frontmatter body — so a preamble line starting with the same key was rewritten instead of the frontmatter one. It now replaces inside the frontmatter span only, which is the hazard `removeFrontmatterKeyLine` already documented and guarded against. Neither is reachable from an install-written `gsd-*.md` (those begin at byte 0 with `---`), and both predate this change — but the editors are in this diff because #3706 key-parameterised them, so they are fixed here rather than left for the next caller to trip over. Three regression tests, each confirmed to fail against the pre-fix build. * fix(#3706): treat a present-but-empty key as present, and pin the real seam Fourth review round. The MAJOR one: both sync branches read the current value with `(.+?)`, which needs at least one character, so a key present with an EMPTY value read as "key absent". When the target was also null the code concluded "already correct" and skipped — leaving the key in the file, where it reads back as YAML `null`: exactly the unresolvable-variant state this change exists to prevent. Whitespace decided whether it fired, since `variant: ` matched and `variant:` did not. Presence and value are now separate questions at both the opencode and the claude branch. The OpenCode writer now follows the codex branch rather than the claude one: tmp file plus retryRenameSync with orphan cleanup, and a write failure skips that agent and is reported instead of aborting the sweep. Same granularity, same transient-Windows-lock exposure, so the hardened sibling was the right precedent. Also: the generic line-editors escape their interpolated key, the JSDoc stranded by the clampEffortForHost extraction is back on renderEffortArgv, and a cast that declared a nullable function as non-nullable is corrected. Tests close the gaps the review listed — empty value (both spellings), CRLF round-trip through write and strip, the symlink guard, a body line starting `variant:`, a file with no frontmatter, and the YAML classes that actually broke the predicate. The new layout-seam test drives the real stage() path and was verified to FAIL when `variant` is removed from the converter call; a seam test that survives cutting the seam is worse than none. * fix(#3706): clear the round-five review findings No blockers or majors this round; the repo's review gate is zero-tolerance, so the minors are cleared too. A duplicated key was only half-stripped: the strip regex had no `g` flag, so a frontmatter carrying the key twice lost one occurrence, reported success, and left the "a null target means the key must not exist" invariant false on disk — converging only on a second run. Such a document is already invalid YAML, so this is robustness rather than a live corruption path, but a successful sync has to leave the invariant true. A run in which every write failed still summarised as `ok`, so a caller could not tell "nothing to do" from "everything failed". The OpenCode branch now reports `failed` when any write failed. The write-failure path was also the newest code in the change with no coverage at all; it now has a test that injects the failure by monkeypatching the write, per CLAUDE.md §4, rather than by chmod — mode bits do not bite under root in CI. `CodexEffortSyncWriteFailure` is renamed `EffortSyncWriteFailure` now that two branches share it. Removed a guard on the claude concrete path that was provably unreachable — no member of EFFORT_SET renders null there, so it read as protection that did not exist. The claude inherit path's presence check is load-bearing and untouched. Three stale statements corrected: the OpenCode result shape matches codex's, not claude's, now that it emits write_failures; the `thread()` test helper now calls `clampEffortForHost` so it genuinely mirrors the layout instead of merely claiming to; and a test helper restored `USERPROFILE` by assignment, writing the literal string "undefined" into the environment on POSIX — it deletes now. * fix(#3706): converge the set path, degrade on unreadable files, preserve mode Rounds five and six of review. No blockers or majors; the review gate is zero-tolerance, so the minors are cleared too. `setFrontmatterKeyLine` was the mirror of a defect already fixed in its sibling: `remove` was made global, `set` was not, so on a frontmatter carrying the key twice it rewrote the first and left a stale second. Last-wins YAML readers honour the stale value while the sync's own first-occurrence read reports "in sync" — permanently non-converging. It now collapses to exactly one occurrence, in the position of the first, so ordinary single-occurrence documents stay byte-identical (verified across seven shapes before and after). An unreadable agent file used to throw and abort the entire sweep, while a failed WRITE in the same loop degraded into a report. The OpenCode branch now reports read failures alongside write failures; the claude branch degrades to a skip without a new result field, because its shape is long-standing and widely consumed and one bad file aborting the sweep is the actual defect. The tmp+rename publish dropped the original file's mode — a plain writeFileSync preserves it, a rename does not — so a 0600 agent came back 0644. Both the OpenCode and the codex branch now carry the original's permission bits across the publish, masked with 0o7777: the raw stat mode includes the file-type bits, and POSIX leaves those unspecified for chmod. Linux is the only OS the remote matrix runs, so relying on Darwin's tolerance would have been untestable here. Also documents the `from` contract on EffortSyncChange (null means the key was absent, '' means present with an empty value — a distinction earlier rounds introduced and then collapsed in the output), adds OpenCode to the docs paragraph enumerating where the key is omitted under inherit, and records in a comment that the 'failed' summary reaches only raw mode and does not change the exit code, which is a CLI-contract change affecting all three branches and is deliberately not made here. * fix(#3706): guard the codex read, close the tmp permission window, rename the failure type Round seven, plus one thing I found myself. `cmdEffortSyncCodex` still had an unguarded `fs.readFileSync` — a read fault on one agent exited 1 and aborted the whole sweep. The claude and opencode branches were both guarded earlier this round and codex was missed, with the unguarded read sitting ten lines above the chmod block the previous commit did edit. It now reports read failures the way the OpenCode branch does, and a read failure flips its summary to `failed` — which write failures did not do there either, so both are corrected for consistency. The tmp file was created at the default mode and only tightened afterwards, so a 0600 agent's contents sat in a 0644 file for the length of the publish. I measured the window rather than assuming it, then closed it by passing the mode at creation. The chmod after the write is deliberately RETAINED and commented: the `mode` option only applies when the file is actually created, so a leftover tmp from an earlier crashed run would be truncated and reused at its old mode, and the chmod is what corrects that. `EffortSyncWriteFailure` is renamed `EffortSyncFileFailure` — it was typing a `read_failures` array, the same naming-lie the `Codex…` prefix had last round. Also pins the codex mode preservation with a test. It only writes on a path that genuinely rewrites the file, so the fixture is an Anthropic-flavoured model pin the sync strips, and the test asserts the content changed before checking the mode — otherwise it would pass on a sync that did nothing. * fix(#3706): guard the claude writes and share one escaping rule The security sign-off caught a comment of mine that was factually wrong: the new claude read guard said the failure is folded in "like the write path in this same loop does", and there was no write guard in that loop. Rather than correct the sentence, both claude write sites are now guarded the way the read is — a failed file is skipped, the sweep continues, and the raw summary token flips to `failed`. The JSON shape stays frozen deliberately, because it is long-standing and widely consumed; the token is the channel that can carry the signal without a compatibility risk, which is the reviewer's own suggestion. That makes all three branches consistent: reads and writes guarded everywhere, per-file failures degrade instead of aborting, and every branch reports `failed` rather than `ok` when something did not sync. `setFrontmatterKeyLine` interpolated its value raw while the install-side writer quoted through the shared helpers — two writers of the same frontmatter key disagreeing on escaping, the divergence class this repo requires closed. They now share one rule. Verified no churn: all six effort levels are plain scalars and emit byte-identically, with claude's documented minimal-to-low clamp the only difference in the table, exactly as before. * fix(#3706): publish claude agent writes atomically too Both reviewers found this independently, and it is data loss rather than a reporting gap. The claude branch wrote in place, so `fs.writeFileSync`'s O_TRUNC meant a post-open fault left the agent file truncated or half-written: an injected ENOSPC produced an empty file, and under `ulimit -f` a 60000-byte agent came back as 512 bytes of wrong content. The guard added earlier this round then counted that destroyed file as `skipped`, which in JSON mode is indistinguishable from "already in sync" — so a caller would have read the sweep as clean while an agent on disk was corrupt. It now publishes the way the codex and opencode branches already do: write to a tmp file created at the original's masked mode, chmod, then retryRenameSync, with the tmp unlinked and the agent skipped on any failure. The corrupting case is gone rather than merely reported, which matters because this branch deliberately takes no new result key. I had claimed all three branches were consistent after the previous commit. That was true for degradation and reporting and not for atomicity; the reviewer caught the overclaim. It is true now. Also sorts the claude file list, which the other two branches already did — readdir order is platform-dependent, so leaving it unsorted made the reported `changes` ordering differ across machines for identical inputs. * chore(#3706): backfill the changeset PR number pr:0 placeholder replaced with the real PR now that gh api returned it. * test(#3706): kill the frontmatter mutants this change introduced CI's Stryker frontmatter shard scored 60.58 against a break floor of 62. The cause is documented in the lane's own config, from #1882: this PR added a multi-clause predicate to frontmatter.cts and exported the escaper, but the tests constraining them live in tests/runtime-converters.test.cjs, which that shard does not run — so every mutant in the new code was uncovered there even though the behaviour is tested elsewhere. The fix is assertions that kill real mutants, per the repo's own instruction, not a lowered floor and not a Stryker disable: scripts/mutation-matrix.cjs is untouched. Each clause of agentScalarNeedsDoubleQuoting now has a true case AND a near-miss that must answer the opposite way, so flipping the clause fails a specific named test — alnum-first against `a-b`, trailing `:` against `foo:bar`, embedded `: ` against `a:b`, embedded ` #` against `a#b`, the word list against `yes1`/`nullish`, the numeric forms against `1a`/`0xzz`, the timestamp against `2026-08-25x`, plus the case-insensitive spellings that pin the `i` flag. escapeDoubleQuoted is pinned on exact output, including a case constructed so that escaping in the wrong ORDER yields a different string. Two of my expectations were wrong and are asserted as the code actually behaves: `12:99` is NOT quoted, because the sexagesimal alternative never range-checks minutes and so does not match — which is right, since YAML would not read it as sexagesimal either; and `20260825` is quoted by the numeric clause rather than the timestamp one, being a bare integer. * chore(#3706): ratchet the frontmatter mutation floor to 65 The lane measured 66.67 on PR 3867 after the mutant-killing unit tests landed — above its pre-change 63.35 baseline, not merely recovered. Step 3 of this file's own HOW TO UPDATE procedure says to set minScore = floor(measured) - 1 in the same diff, so 62 becomes 65 and the improvement is locked in rather than left free to slide back. The ledger of measured scores now records the new measurement, why the shard broke in the first place (logic added to frontmatter.cts whose only tests lived in a file this lane does not run — the same trap the #1882 note describes), and one discrepancy: step 3 also says to update "the matching RATCHET_BASELINE entry", but no such declaration exists in this file. The name appears only in that comment, so minScore and the ledger are all there is to update. * fix(#3706): update RATCHET_BASELINE alongside the raised floor The ratchet test caught the previous commit: it raised COVERED['frontmatter'] .minScore to 65 without updating the baseline that mirrors it, which is exactly the mismatch that guard exists to make visible in review. I had claimed RATCHET_BASELINE did not exist. It does — in tests/mutation-matrix-ratchet.test.cjs, not in scripts/mutation-matrix.cjs, which is the only file I searched before concluding it was a stale reference. The ledger comment is corrected to say where it lives and to record that the guard caught the error rather than leaving my wrong claim on the record. * docs(#3706): put the mutation ledger entries back under their own dates The 2026-08-25 measurement was spliced into the middle of the 2026-06-14 list, so adr-parser, config-schema, active-workstream-store and core-utils ended up sitting under the wrong heading and misattributing their measurement dates. That ledger is what a future change reads to calibrate a floor, so a wrong date there is not cosmetic. Each measurement is now under the date it was taken. Also drops the first-person account of my own mistake from the entry — the factual half (where RATCHET_BASELINE lives, and that it is updated in the same diff) is what a reader needs; the confession is not. --------- Co-authored-by: sim <sim@local>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,8 @@ const {
|
||||
noOpObjectListSetError,
|
||||
parseMustHavesBlock,
|
||||
FRONTMATTER_SCHEMAS,
|
||||
agentScalarNeedsDoubleQuoting,
|
||||
escapeDoubleQuoted,
|
||||
} = require('../gsd-core/bin/lib/frontmatter.cjs');
|
||||
|
||||
// ─── extractFrontmatter ───────────────────────────────────────────────────────
|
||||
@@ -1512,3 +1514,236 @@ describe('stripFrontmatter', () => {
|
||||
assert.strictEqual(stripFrontmatter(''), '');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── agentScalarNeedsDoubleQuoting (#3706) ────────────────────────────────────
|
||||
//
|
||||
// Mutant-killing discipline: every boolean clause gets a true case AND a
|
||||
// near-miss false case one edit away, so flipping any operator/character
|
||||
// class in the source changes at least one assertion here.
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: delegates to scalarNeedsDoubleQuoting', () => {
|
||||
test('empty string needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(''), true);
|
||||
});
|
||||
test('embedded double quote needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a"b'), true);
|
||||
});
|
||||
test('embedded backslash needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a\\b'), true);
|
||||
});
|
||||
test('embedded control char needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a\u0001b'), true);
|
||||
});
|
||||
test('leading whitespace needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(' abc'), true);
|
||||
});
|
||||
test('trailing whitespace needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('abc '), true);
|
||||
});
|
||||
for (const c of ['#', '&', '*', '!', '|', '>', '%', '@', '`', '[', ']', '{', '}', ',', "'"]) {
|
||||
test(`leading indicator "${c}" needs quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(`${c}foo`), true);
|
||||
});
|
||||
}
|
||||
test('near-miss: plain word does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('plainword'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: first character must be alphanumeric', () => {
|
||||
for (const v of ['~', '.inf', '.nan', '+1', '-1', '-0', '.5']) {
|
||||
test(`non-alphanumeric first char "${v}" needs quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), true);
|
||||
});
|
||||
}
|
||||
test('near-miss: alphanumeric-first with internal hyphen does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a-b'), false);
|
||||
});
|
||||
test('near-miss: digit-first non-numeric word does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('0abc'), false);
|
||||
});
|
||||
test('near-miss: alphanumeric-first with trailing hyphen does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('x-'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: trailing colon', () => {
|
||||
test('a bare trailing colon needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('foo:'), true);
|
||||
});
|
||||
test('near-miss: colon followed by more text does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('foo:bar'), false);
|
||||
});
|
||||
test('near-miss: single-char key:value shape does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a:b'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: embedded ": " (colon + whitespace)', () => {
|
||||
test('colon followed by space needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a: b'), true);
|
||||
});
|
||||
test('colon followed by tab needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a:\tb'), true);
|
||||
});
|
||||
test('near-miss: colon with no following whitespace does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a:b'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: embedded " #" (whitespace + hash)', () => {
|
||||
test('space followed by hash needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a #b'), true);
|
||||
});
|
||||
test('tab followed by hash needs quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a\t#b'), true);
|
||||
});
|
||||
test('near-miss: hash with no preceding whitespace does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a#b'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: boolean/null words (case-insensitive)', () => {
|
||||
for (const v of ['y', 'n', 'yes', 'no', 'true', 'false', 'on', 'off', 'null']) {
|
||||
test(`lowercase word "${v}" needs quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), true);
|
||||
});
|
||||
}
|
||||
for (const v of ['YES', 'No', 'TRUE', 'Null']) {
|
||||
test(`mixed-case word "${v}" needs quoting (case-insensitivity)`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), true);
|
||||
});
|
||||
}
|
||||
test('near-miss: "yes1" is not an exact word match', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('yes1'), false);
|
||||
});
|
||||
test('near-miss: "nope" is not an exact word match', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('nope'), false);
|
||||
});
|
||||
test('near-miss: "nullish" is not an exact word match', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('nullish'), false);
|
||||
});
|
||||
test('near-miss: "onward" is not an exact word match', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('onward'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: numeric-looking values', () => {
|
||||
for (const v of [
|
||||
'1', '123', '1.5', '1.', '1e5', '1E5', '1e+5', '1e-5', '1_000',
|
||||
'0x1F', '0b101', '0o17', '0X1f', '12:30', '1:2:3', '12:30.5',
|
||||
]) {
|
||||
test(`numeric form "${v}" needs quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), true);
|
||||
});
|
||||
}
|
||||
test('near-miss: "1a" (digit then letter) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('1a'), false);
|
||||
});
|
||||
test('near-miss: "a1" (letter then digit) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('a1'), false);
|
||||
});
|
||||
test('near-miss: "x1e5" (non-digit first char) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('x1e5'), false);
|
||||
});
|
||||
test('near-miss: "0xzz" (invalid hex digits) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('0xzz'), false);
|
||||
});
|
||||
// Verified against the real implementation: the sexagesimal group only
|
||||
// consumes a leading [0-5]? then one mandatory digit per ":" segment, so
|
||||
// "12:99" cannot fully match YAML_NUMERIC_RE (the second "9" is left over)
|
||||
// and no other clause fires either. The code does NOT reject an
|
||||
// out-of-range (60-99) minute-like group — pinned here as actual behavior,
|
||||
// not the originally assumed "false because minutes must be 0-59".
|
||||
test('"12:99" does not need quoting (sexagesimal regex cannot consume the trailing digit)', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('12:99'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: YAML timestamp', () => {
|
||||
for (const v of [
|
||||
'2026-08-25', '2026-8-5', '2026-08-25T10:00:00Z', '2026-08-25 10:00:00',
|
||||
]) {
|
||||
test(`timestamp form "${v}" needs quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), true);
|
||||
});
|
||||
}
|
||||
test('near-miss: "2026-08" (missing day) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('2026-08'), false);
|
||||
});
|
||||
// Verified against the real implementation: this string never reaches the
|
||||
// timestamp clause at all — the pure-digit numeric clause (YAML_NUMERIC_RE's
|
||||
// first alternative matches any \d[\d_]* string) fires first and returns
|
||||
// true. So "20260825" IS true, but for a different reason than "looks like
|
||||
// a date"; it does not exercise YAML_TIMESTAMP_RE.
|
||||
test('"20260825" (no hyphens) needs quoting via the numeric clause, not the timestamp clause', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('20260825'), true);
|
||||
});
|
||||
// This is the case that actually pins YAML_TIMESTAMP_RE's trailing
|
||||
// `(?:[Tt ].*)?$` anchor: the numeric clause cannot match (hyphens present,
|
||||
// no colon), so only the timestamp regex is left to decide, and it rejects
|
||||
// trailing text that isn't introduced by "T"/"t"/" ".
|
||||
test('"2026-08-25x" (trailing junk not preceded by T/t/space) does not need quoting', () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting('2026-08-25x'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agentScalarNeedsDoubleQuoting: real-world values that must stay unquoted', () => {
|
||||
for (const v of [
|
||||
'sonnet', 'synthetic/hf:zai-org/GLM-5.2', 'gpt-5.6-luna', 'claude-opus-5',
|
||||
'high', 'xhigh', 'minimal', 'a.b', 'GLM-5.2',
|
||||
]) {
|
||||
test(`"${v}" does not need quoting`, () => {
|
||||
assert.equal(agentScalarNeedsDoubleQuoting(v), false);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── escapeDoubleQuoted (#1779 / #3497) ────────────────────────────────────────
|
||||
|
||||
describe('escapeDoubleQuoted: exact output strings', () => {
|
||||
test('backslash is escaped before the quote it precedes (ordering matters)', () => {
|
||||
// Input: a, \, ", b. If the quote were escaped BEFORE the backslash, the
|
||||
// backslash added in front of the quote would then itself get doubled by
|
||||
// a subsequent backslash pass, producing a different (wrong) string. The
|
||||
// real order (backslash first, then quote) yields exactly 3 backslashes
|
||||
// followed by the quote.
|
||||
const input = 'a' + '\\' + '"' + 'b';
|
||||
const expected = 'a' + '\\'.repeat(3) + '"' + 'b';
|
||||
assert.equal(escapeDoubleQuoted(input), expected);
|
||||
});
|
||||
|
||||
test('double quote alone', () => {
|
||||
assert.equal(escapeDoubleQuoted('"'), '\\"');
|
||||
});
|
||||
|
||||
test('newline alone', () => {
|
||||
assert.equal(escapeDoubleQuoted('\n'), '\\n');
|
||||
});
|
||||
|
||||
test('tab alone', () => {
|
||||
assert.equal(escapeDoubleQuoted('\t'), '\\t');
|
||||
});
|
||||
|
||||
test('carriage return alone', () => {
|
||||
assert.equal(escapeDoubleQuoted('\r'), '\\r');
|
||||
});
|
||||
|
||||
test('a C0 control char (0x01) becomes lowercase zero-padded \\xHH', () => {
|
||||
assert.equal(escapeDoubleQuoted('\u0001'), '\\x01');
|
||||
});
|
||||
|
||||
test('DEL (0x7f) becomes \\x7f', () => {
|
||||
assert.equal(escapeDoubleQuoted('\u007f'), '\\x7f');
|
||||
});
|
||||
|
||||
test('plain string with no specials is returned unchanged', () => {
|
||||
assert.equal(escapeDoubleQuoted('plain'), 'plain');
|
||||
});
|
||||
|
||||
test('combined input exercising every escape in one pass', () => {
|
||||
const input = 'a\\b"c\nd\te\rf\u0001g\u007fh';
|
||||
const expected = 'a\\\\b\\"c\\nd\\te\\rf\\x01g\\x7fh';
|
||||
assert.equal(escapeDoubleQuoted(input), expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -194,7 +194,7 @@ const RATCHET_BASELINE = {
|
||||
'context-utilization': 80,
|
||||
'context-composer': 66, // #2929: extracted from prompt-budget; same floor as prompt-budget
|
||||
'prompt-budget': 66, // CI 68.33% 2026-06-14; was 90 (timeout-inflated local)
|
||||
'frontmatter': 62,
|
||||
'frontmatter': 65, // #3706: raised from 62; measured 66.67 on PR 3867
|
||||
'adr-parser': 68,
|
||||
'config-schema': 52, // CI 54.55% 2026-06-14; was 68 (timeout-inflated local)
|
||||
'active-workstream-store': 80,
|
||||
|
||||
@@ -2208,3 +2208,374 @@ describe('bug-2876: skill+agent converters emit YAML-quoted description', () =>
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── #3706: OpenCode subagent effort (variant) + frontmatter escaping ────────
|
||||
//
|
||||
// `query resolve-execution` reported an effort (high/xhigh) that never reached
|
||||
// OpenCode: the bake wrote `model:` and nothing else, so every subagent ran at
|
||||
// whatever opencode.jsonc defaults the model to. The effort-side twin of #3705.
|
||||
//
|
||||
// bin/install.js has its own copy of these converters, but no `isAgent: true`
|
||||
// call site: its agents install path runs through the compiled bin/lib module,
|
||||
// not through its own copy. The live copy in src/runtime-artifact-conversion.cts
|
||||
// (compiled to gsd-core/bin/lib/runtime-artifact-conversion.cjs) is therefore
|
||||
// the one the bake actually uses, and the one under test here.
|
||||
const liveConversion = require('../gsd-core/bin/lib/runtime-artifact-conversion.cjs');
|
||||
|
||||
const OPENCODE_CONVERTERS = [['src (live bake)', liveConversion.convertClaudeToOpencodeFrontmatter]];
|
||||
const KILO_CONVERTERS = [['src (live bake)', liveConversion.convertClaudeToKiloFrontmatter]];
|
||||
|
||||
describe('#3706: OpenCode agent variant (resolved effort)', () => {
|
||||
const AGENT = ['---', 'name: gsd-executor', 'description: x', 'model: sonnet', '---', '', 'Body.'].join('\n');
|
||||
const hasKey = (out, key) => new RegExp(`^${key}:`, 'm').test(out);
|
||||
|
||||
for (const [label, convert] of OPENCODE_CONVERTERS) {
|
||||
test(`[${label}] emits variant alongside model`, () => {
|
||||
const out = convert(AGENT, {
|
||||
isAgent: true, modelOverride: 'synthetic/hf:zai-org/GLM-5.2', variant: 'high',
|
||||
});
|
||||
assert.match(out, /^model: synthetic\/hf:zai-org\/GLM-5\.2$/m);
|
||||
assert.match(out, /^variant: high$/m);
|
||||
});
|
||||
|
||||
test(`[${label}] carries whatever level was resolved, not a fixed one`, () => {
|
||||
assert.match(convert(AGENT, { isAgent: true, variant: 'xhigh' }), /^variant: xhigh$/m);
|
||||
});
|
||||
|
||||
test(`[${label}] omits the key entirely when no variant is supplied`, () => {
|
||||
// The control that keeps every existing install byte-identical.
|
||||
const out = convert(AGENT, { isAgent: true, modelOverride: 'M' });
|
||||
assert.ok(!hasKey(out, 'variant'), `expected no variant key, got:\n${out}`);
|
||||
assert.match(out, /^model: M$/m, 'the model side is unaffected');
|
||||
});
|
||||
|
||||
test(`[${label}] commands get neither model nor variant`, () => {
|
||||
const out = convert(AGENT, { isAgent: false, modelOverride: 'M', variant: 'high' });
|
||||
assert.ok(!hasKey(out, 'variant'));
|
||||
assert.ok(!hasKey(out, 'model'));
|
||||
});
|
||||
|
||||
test(`[${label}] adding a variant perturbs no other line`, () => {
|
||||
const withV = convert(AGENT, { isAgent: true, modelOverride: 'M', variant: 'high' });
|
||||
const without = convert(AGENT, { isAgent: true, modelOverride: 'M' });
|
||||
assert.match(withV, /^mode: subagent$/m);
|
||||
assert.deepEqual(
|
||||
withV.split('\n').filter((l) => !/^variant:/.test(l)),
|
||||
without.split('\n'),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [label, convert] of KILO_CONVERTERS) {
|
||||
test(`[${label}] Kilo does NOT emit variant even when one is passed`, () => {
|
||||
// The asymmetry, pinned. EFFORT_ARGV declares surfaces for claude/opencode/
|
||||
// codex and has no kilo entry — unlike the model side, where #2794 J8
|
||||
// requires the two runtimes to resolve identically.
|
||||
const out = convert(AGENT, { isAgent: true, modelOverride: 'M', variant: 'high' });
|
||||
assert.ok(!hasKey(out, 'variant'), `kilo has no declared effort surface; got:\n${out}`);
|
||||
assert.match(out, /^model: M$/m, 'but the model override still applies');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── #3706: config-supplied values cannot inject frontmatter keys ────────────
|
||||
//
|
||||
// `model:` and now `variant:` both interpolate values read from
|
||||
// .planning/config.json / ~/.gsd/defaults.json. Raw interpolation let a value
|
||||
// containing a newline inject additional TOP-LEVEL keys — proven by execution
|
||||
// during the #3705 security review. The sink predates #3706; this change adds a
|
||||
// SECOND write to it, so it is closed here rather than doubled.
|
||||
describe('#3706: frontmatter values are escaped, not interpolated raw', () => {
|
||||
const AGENT = ['---', 'name: gsd-executor', 'description: x', '---', '', 'Body.'].join('\n');
|
||||
|
||||
for (const [label, convert] of OPENCODE_CONVERTERS) {
|
||||
test(`[${label}] a newline-bearing model value cannot add top-level keys`, () => {
|
||||
const out = convert(AGENT, {
|
||||
isAgent: true, modelOverride: 'sonnet\ntools: ["*"]\npermission: bypass',
|
||||
});
|
||||
assert.ok(!/^tools:/m.test(out), `injected a tools key:\n${out}`);
|
||||
assert.ok(!/^permission: bypass$/m.test(out), `injected a permission key:\n${out}`);
|
||||
assert.match(out, /^model: "/m, 'the value is quoted');
|
||||
});
|
||||
|
||||
test(`[${label}] a newline-bearing variant value cannot add top-level keys`, () => {
|
||||
const out = convert(AGENT, { isAgent: true, variant: 'high\nevil: yes' });
|
||||
assert.ok(!/^evil:/m.test(out), `injected a key:\n${out}`);
|
||||
assert.match(out, /^variant: "/m);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [label, convert] of KILO_CONVERTERS) {
|
||||
test(`[${label}] Kilo model values are escaped too — the same sink exists there`, () => {
|
||||
const out = convert(AGENT, { isAgent: true, modelOverride: 'sonnet\ntools: ["*"]' });
|
||||
assert.ok(!/^tools:/m.test(out), `injected a tools key:\n${out}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── #3706: values that look plain but do not round-trip ────────────────────
|
||||
//
|
||||
// Matching /^[A-Za-z0-9._:\/@+-]+$/ is not the same question as "does YAML read
|
||||
// this back as the exact string that went in". Each row below is wrong when
|
||||
// emitted bare; the last is the control that keeps real installs unchanged.
|
||||
describe('#3706: YAML-ambiguous scalars are quoted, not emitted bare', () => {
|
||||
const AGENT = ['---', 'name: gsd-executor', 'description: x', '---', '', 'Body.'].join('\n');
|
||||
|
||||
const QUOTED = [
|
||||
// A PARSE ERROR bare, not merely ambiguous: '@' is a YAML reserved
|
||||
// indicator and may not open a plain scalar, so the whole agent file
|
||||
// becomes unreadable.
|
||||
'@org/model',
|
||||
// A trailing ':' reads as a nested mapping key — "bad indentation of a
|
||||
// mapping entry" kills the frontmatter.
|
||||
'foo:',
|
||||
// YAML 1.1 resolves these to booleans/null, so a variant named 'no'
|
||||
// arrives as `false` and matches no entry in the user's variants map.
|
||||
'no', 'yes', 'true', 'off', 'y', 'n', 'null',
|
||||
// '12:30' resolves to the integer 750; ':' is legal mid-identifier here,
|
||||
// so the form is reachable rather than contrived.
|
||||
'12:30', '0755', '1.5', '0x1f',
|
||||
// #3706 hardening: '(.+?)' in the value regex needs one character before
|
||||
// this fix, so an empty/whitespace-only value read as "key absent" rather
|
||||
// than "key present, value empty" — these are the YAML-ambiguous classes
|
||||
// that predicate missed once presence and value became distinct questions.
|
||||
'~', '.inf', '.Inf', '.nan', '+1', '-1', '-0', '+1.5', '.5', '0x1F',
|
||||
'2026-08-25', '2026-08-25T10:00:00Z', 'a: b', 'a #b',
|
||||
];
|
||||
// The whole point of the predicate: no churn for anybody's existing files.
|
||||
const BARE = ['sonnet', 'synthetic/hf:zai-org/GLM-5.2', 'gpt-5.6-luna', 'claude-opus-5', 'x-', 'a.b', 'GLM-5.2'];
|
||||
|
||||
for (const [label, convert] of OPENCODE_CONVERTERS) {
|
||||
const modelLine = (v) =>
|
||||
(convert(AGENT, { isAgent: true, modelOverride: v })
|
||||
.split('\n').find((l) => l.startsWith('model:')) ?? '');
|
||||
|
||||
for (const v of QUOTED) {
|
||||
test(`[${label}] quotes ${JSON.stringify(v)}`, () => {
|
||||
assert.equal(modelLine(v), `model: "${v}"`);
|
||||
});
|
||||
}
|
||||
for (const v of BARE) {
|
||||
test(`[${label}] leaves ${JSON.stringify(v)} bare`, () => {
|
||||
assert.equal(modelLine(v), `model: ${v}`);
|
||||
});
|
||||
}
|
||||
test(`[${label}] the same predicate governs variant, not just model`, () => {
|
||||
assert.match(convert(AGENT, { isAgent: true, variant: 'no' }), /^variant: "no"$/m);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── #3706: the threading seam — where the bug actually was ─────────────────
|
||||
//
|
||||
// Every test above exercises a converter directly. #3706 broke one layer up, in
|
||||
// runtime-artifact-layout's convertedAgentsKind: the converter had no variant to
|
||||
// write because nothing resolved or passed one. A converter-only suite goes green
|
||||
// while the value still never arrives, so the resolve→render chain is pinned here.
|
||||
describe('#3706: install-time effort resolves and renders for OpenCode', () => {
|
||||
const effortResolver = require('../gsd-core/bin/lib/install-effort-resolver.cjs');
|
||||
const catalog = require('../gsd-core/bin/lib/model-catalog.cjs');
|
||||
|
||||
// Exactly the composition the layout performs per agent.
|
||||
const thread = (effortCfg, agentName) => {
|
||||
const universal = effortCfg ? effortResolver.resolveInstallTimeEffort(effortCfg, agentName) : null;
|
||||
return universal ? catalog.clampEffortForHost('opencode', universal) : null;
|
||||
};
|
||||
|
||||
test('no effort config at all yields no variant', () => {
|
||||
// The gate. resolveInstallTimeEffort ALWAYS returns a level ('high' from the
|
||||
// catalog default) even for a null config, so gating on its return value
|
||||
// would stamp `variant:` into every existing OpenCode install.
|
||||
assert.equal(effortResolver.resolveInstallTimeEffort(null, 'gsd-executor'), 'high');
|
||||
assert.equal(thread(null, 'gsd-executor'), null);
|
||||
});
|
||||
|
||||
test('a configured agent override reaches the emitted value', () => {
|
||||
assert.equal(thread({ agent_overrides: { 'gsd-executor': 'xhigh' } }, 'gsd-executor'), 'xhigh');
|
||||
});
|
||||
|
||||
test('a configured default reaches an agent with no catalog tier', () => {
|
||||
// effort.default is only consulted for agents the tier ladder does not
|
||||
// answer for; see the tiered-agent test below for the other half.
|
||||
assert.equal(thread({ default: 'low' }, 'not-a-catalog-agent'), 'low');
|
||||
});
|
||||
|
||||
test("'inherit' is never emitted as a literal", () => {
|
||||
// #3533 (10d): inherit means "omit the key and follow the host default" and
|
||||
// is not a wire level on ANY runtime. It IS a member of EFFORT_SET, so the
|
||||
// resolver returns it verbatim — the declared render seam is what drops it.
|
||||
// Writing `variant: inherit` would name a variant that cannot resolve.
|
||||
for (const cfg of [
|
||||
{ agent_overrides: { 'gsd-executor': 'inherit' } },
|
||||
{ routing_tier_defaults: { light: 'inherit', standard: 'inherit', heavy: 'inherit' } },
|
||||
]) {
|
||||
assert.equal(effortResolver.resolveInstallTimeEffort(cfg, 'gsd-executor'), 'inherit');
|
||||
assert.equal(thread(cfg, 'gsd-executor'), null, `should omit for ${JSON.stringify(cfg)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('a bare effort.default does NOT reach a tiered agent', () => {
|
||||
// Not obvious, and it is why the `inherit` case above goes through
|
||||
// agent_overrides instead: for an agent WITH a catalog tier the manifest
|
||||
// tier ladder (#3531) answers before effort.default is ever consulted, so
|
||||
// `default: 'inherit'` leaves a tiered agent at its tier value. Pinned
|
||||
// because a test written against `default` alone would assert nothing.
|
||||
assert.equal(effortResolver.resolveInstallTimeEffort({ default: 'inherit' }, 'gsd-executor'), 'high');
|
||||
assert.equal(thread({ default: 'inherit' }, 'gsd-executor'), 'high');
|
||||
});
|
||||
|
||||
test('a level OpenCode does not accept is dropped, not emitted', () => {
|
||||
// 'ultra' is a real EFFORT_SET member that OpenCode's declared supported set
|
||||
// does not contain. Omitting beats naming a variant that cannot resolve.
|
||||
assert.equal(catalog.renderEffortArgv('opencode', 'ultra', 'argv').value, null);
|
||||
});
|
||||
|
||||
test('the full universal ladder OpenCode does accept passes through', () => {
|
||||
for (const lvl of ['minimal', 'low', 'medium', 'high', 'xhigh', 'max']) {
|
||||
assert.equal(catalog.renderEffortArgv('opencode', lvl, 'argv').value, lvl);
|
||||
}
|
||||
});
|
||||
|
||||
test('an empty model override omits the key rather than writing an empty value', () => {
|
||||
// Found by the property below, which originally asserted a round-trip for
|
||||
// every generated string and failed on "". An empty override is falsy, so
|
||||
// no `model:` line is written at all — that is the #2256/J7 contract (omit
|
||||
// the key, never `model: ""`), so the property is scoped to non-empty
|
||||
// values and the empty case is pinned here instead of being generated away.
|
||||
const out = liveConversion.convertClaudeToOpencodeFrontmatter(
|
||||
['---', 'name: x', 'description: y', '---', '', 'Body.'].join('\n'),
|
||||
{ isAgent: true, modelOverride: '' },
|
||||
);
|
||||
assert.ok(!/^model:/m.test(out), `expected no model key, got:\n${out}`);
|
||||
});
|
||||
|
||||
test('every emitted model line parses back to the exact value', () => {
|
||||
// The real contract, stated directly: whatever a user puts in config, the
|
||||
// generated frontmatter must read back as that same string. A per-character
|
||||
// rule list is only a means to this end, and this is what catches the case
|
||||
// nobody thought to enumerate.
|
||||
const fc = require('fast-check');
|
||||
const yaml = require('js-yaml');
|
||||
const chars = ':@-_./"\\ \n\t#&*!|>%`{}[],?~+abcXY019';
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string({ unit: fc.constantFrom(...chars.split('')), minLength: 1 }),
|
||||
(value) => {
|
||||
const out = liveConversion.convertClaudeToOpencodeFrontmatter(
|
||||
['---', 'name: x', 'description: y', '---', '', 'Body.'].join('\n'),
|
||||
{ isAgent: true, modelOverride: value },
|
||||
);
|
||||
const fmBody = /^---\r?\n([\s\S]*?)^---\r?$/m.exec(out)[1];
|
||||
return yaml.load(fmBody).model === value;
|
||||
},
|
||||
),
|
||||
{ numRuns: 2000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── #3706: the layout seam actually threads the variant ─────────────────────
|
||||
//
|
||||
// Every test above calls a converter directly. Direct-converter tests all
|
||||
// still pass if a future edit drops `variant` from the `rawConverter(...)`
|
||||
// call inside runtime-artifact-layout.cts's convertedAgentsKind, or flips its
|
||||
// `converterName ===` gate — this drives the REAL staging path
|
||||
// (resolveRuntimeArtifactLayout -> the OpenCode 'agents' kind's stage()) so
|
||||
// that regression cannot hide behind converter-only coverage.
|
||||
describe('#3706: the layout seam actually threads the variant', () => {
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
const { resolveRuntimeArtifactLayout } = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
|
||||
// Fixture layout mirrors the .gsd-source marker convention
|
||||
// (findAgentsSourceRoot): the marker at <configDir>/.gsd-source points to
|
||||
// <configDir>/commands/gsd, and agents/ is resolved as its sibling.
|
||||
function makeConfigDirFixture(agentContent) {
|
||||
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3706-seam-configdir-'));
|
||||
const commandsDir = path.join(configDir, 'commands', 'gsd');
|
||||
const agentsDir = path.join(configDir, 'agents');
|
||||
fs.mkdirSync(commandsDir, { recursive: true });
|
||||
fs.mkdirSync(agentsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(configDir, '.gsd-source'), commandsDir + '\n', 'utf8');
|
||||
fs.writeFileSync(path.join(agentsDir, 'gsd-executor.md'), agentContent, 'utf8');
|
||||
return configDir;
|
||||
}
|
||||
|
||||
function makeProjectRootWithEffort(effort) {
|
||||
const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3706-seam-project-'));
|
||||
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectRoot, '.planning', 'config.json'),
|
||||
JSON.stringify({ effort }),
|
||||
'utf8',
|
||||
);
|
||||
return projectRoot;
|
||||
}
|
||||
|
||||
// resolveInstallTimeEffort also merges ~/.gsd/defaults.json (os.homedir()),
|
||||
// so HOME/USERPROFILE are pinned to an empty temp dir for the duration of
|
||||
// each stage() call to keep the assertion hermetic against the real
|
||||
// developer machine's home directory.
|
||||
function stageWithFakeHome(agentKind, resolvedProfile, agentCtx) {
|
||||
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3706-seam-home-'));
|
||||
const realHome = process.env.HOME;
|
||||
const realUserProfile = process.env.USERPROFILE;
|
||||
process.env.HOME = fakeHome;
|
||||
process.env.USERPROFILE = fakeHome;
|
||||
try {
|
||||
return agentKind.stage(resolvedProfile, agentCtx);
|
||||
} finally {
|
||||
// On POSIX, USERPROFILE (and potentially HOME) is unset before this
|
||||
// helper runs — `process.env.X = undefined` would coerce to the
|
||||
// literal string "undefined" and leak that into the environment for
|
||||
// the rest of the test process. Restore by deletion when the saved
|
||||
// value was genuinely absent.
|
||||
if (realHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = realHome;
|
||||
if (realUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = realUserProfile;
|
||||
cleanup(fakeHome);
|
||||
}
|
||||
}
|
||||
|
||||
const AGENT_SOURCE = ['---', 'name: gsd-executor', 'description: x', '---', '', 'Body.'].join('\n');
|
||||
const resolvedProfile = { name: 'full', skills: '*', agents: new Set() };
|
||||
|
||||
test('a configured effort reaches the real OpenCode agents kind staging output', () => {
|
||||
const configDir = makeConfigDirFixture(AGENT_SOURCE);
|
||||
const projectRoot = makeProjectRootWithEffort({ agent_overrides: { 'gsd-executor': 'xhigh' } });
|
||||
try {
|
||||
const layout = resolveRuntimeArtifactLayout('opencode', configDir, 'global');
|
||||
const agentKind = layout.kinds.find((k) => k.kind === 'agents');
|
||||
assert.ok(agentKind, 'opencode global layout must include an agents kind');
|
||||
|
||||
const agentCtx = { runtime: 'opencode', pathPrefix: '', attribution: null, targetDir: projectRoot };
|
||||
const stagedDir = stageWithFakeHome(agentKind, resolvedProfile, agentCtx);
|
||||
const stagedContent = fs.readFileSync(path.join(stagedDir, 'gsd-executor.md'), 'utf8');
|
||||
assert.match(stagedContent, /^variant: xhigh$/m, `expected variant: xhigh in staged output:\n${stagedContent}`);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(projectRoot);
|
||||
}
|
||||
});
|
||||
|
||||
test('no effort config at all reaches the real staging output with no variant key', () => {
|
||||
const configDir = makeConfigDirFixture(AGENT_SOURCE);
|
||||
const noConfigRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3706-seam-noconfig-'));
|
||||
try {
|
||||
const layout = resolveRuntimeArtifactLayout('opencode', configDir, 'global');
|
||||
const agentKind = layout.kinds.find((k) => k.kind === 'agents');
|
||||
|
||||
const agentCtx = { runtime: 'opencode', pathPrefix: '', attribution: null, targetDir: noConfigRoot };
|
||||
const stagedDir = stageWithFakeHome(agentKind, resolvedProfile, agentCtx);
|
||||
const stagedContent = fs.readFileSync(path.join(stagedDir, 'gsd-executor.md'), 'utf8');
|
||||
assert.doesNotMatch(stagedContent, /^variant:/m, `expected no variant key in staged output:\n${stagedContent}`);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(noConfigRoot);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user