fix(continue): run the arg-parser, find the master prompt at the repo root, and let the consistency check read the state file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-10-23 15:05:19 +02:00
commit f32baf50ad
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
6 changed files with 204 additions and 20 deletions

View file

@ -74,7 +74,7 @@ Execute these phases in order. Do not skip phases.
Run the arg-parser via Bash:
```
node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekreview "$@"
node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekreview -- "$@"
```
Pull the structured flags from its JSON output. Reject unknown flags. If

View file

@ -29,9 +29,15 @@ See **Handover 7** in `docs/HANDOVER-CONTRACTS.md` for the full schema.
## Phase 0 — `--help` handling
Parse `$ARGUMENTS` with `parseArgs($ARGUMENTS, 'trekcontinue')` from
`lib/parsers/arg-parser.mjs`. Dispatch the usage block ONLY when one of these
two conditions equals exactly true (no substring search, no "contains" check):
Parse `$ARGUMENTS` with the shared arg-parser. Run first, exactly like this:
```bash
node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekcontinue -- $ARGUMENTS
```
Read `flags` and `positional` from the JSON it prints. Dispatch the usage
block ONLY when one of these two conditions equals exactly true (no substring
search, no "contains" check):
- `flags['--help'] === true`, OR
- `positional[0] === '-h'` (single-dash short form — the parser keeps it as
@ -75,7 +81,7 @@ Typical flow:
## Phase 0.5 — Cleanup mode dispatch
After `parseArgs` has resolved `$ARGUMENTS`, check the parsed `flags`
After the parser has printed its parse of `$ARGUMENTS`, check the parsed `flags`
object directly (NOT a string contains-check on raw `$ARGUMENTS` — that
substring pattern was the root cause of Bug 1).
@ -174,23 +180,28 @@ locations; this phase refuses ambiguity before validating the state file.
After resolving the project directory and state-file path, look for two
`NEXT-SESSION-PROMPT.local.md` candidates:
a. `<plugin-root>/NEXT-SESSION-PROMPT.local.md` — operator-managed master file
a. `NEXT-SESSION-PROMPT.local.md` at the repo root (`git rev-parse --show-toplevel`) —
operator-managed master file, written by the operator or an external producer, never by Voyage
b. `<project-dir>/NEXT-SESSION-PROMPT.local.md` — producer-written sibling
**If both exist:**
- Read both via the **Read tool** (NOT Bash — same anti-substitution rule
as Phase 2).
- Invoke the consistency validator with both paths emitted as concrete
literal tokens (no template substitution at the Bash boundary):
- Invoke the consistency validator with the paths emitted as concrete
literal tokens (no template substitution at the Bash boundary). When the
project's `.session-state.local.json` exists, pass it with `--state-file`
(else run the same line without the option):
```
node ${CLAUDE_PLUGIN_ROOT}/lib/validators/next-session-prompt-validator.mjs --json --consistency <RESOLVED-PATH-A> <RESOLVED-PATH-B>
node ${CLAUDE_PLUGIN_ROOT}/lib/validators/next-session-prompt-validator.mjs --json --consistency <RESOLVED-PATH-A> <RESOLVED-PATH-B> --state-file <RESOLVED-PATH-STATE>
```
Replace `<RESOLVED-PATH-A>` and `<RESOLVED-PATH-B>` with the two concrete
filesystem paths you have in your working context. The validator emits
`{valid, errors, warnings}` JSON on stdout.
filesystem paths you have in your working context, and
`<RESOLVED-PATH-STATE>` with the concrete path of the project's
`.session-state.local.json`. The validator emits `{valid, errors, warnings}`
JSON on stdout.
- **If `valid: false`** (typically `NEXT_SESSION_PROMPT_PRODUCER_MISMATCH`):
print the structured `errors[]` (each `[code] message` on its own line),

View file

@ -1309,7 +1309,7 @@ but do not block.
**Also write sibling `NEXT-SESSION-PROMPT.local.md`** with frontmatter
(`produced_by: trekexecute`, `produced_at: <ISO-8601>`,
`status: stopped`) — same combined ESM pattern as Phase 8 — so Phase 1.5
of `/trekcontinue` can compare project-dir and plugin-root candidates.
of `/trekcontinue` can compare project-dir and repo-root candidates.
If the entry condition **passes**:
```
@ -2773,7 +2773,7 @@ to stderr but do NOT block — Phase 8 must always reach the final report.
contract — see `docs/HANDOVER-CONTRACTS.md` § Handover 7 Lifecycle) in the
project directory. The frontmatter MUST contain `produced_by: trekexecute`
and `produced_at: <ISO-8601>` so `/trekcontinue` Phase 1.5 can detect
producer drift between project-dir and plugin-root candidates. Use a single
producer drift between project-dir and repo-root candidates. Use a single
ESM inline block so state-file + prompt-file writes succeed or fail together:
```bash

View file

@ -153,11 +153,25 @@ export function validateNextSessionPromptConsistency(a, b, opts = {}) {
if (isMain(import.meta.url)) {
const args = process.argv.slice(2);
const positionals = args.filter(a => !a.startsWith('--'));
const wantJson = args.includes('--json');
const consistency = args.includes('--consistency');
const stateIdx = args.indexOf('--state-file');
const stateFile = stateIdx >= 0 ? args[stateIdx + 1] : null;
// The valued flag (--state-file) consumes its value before positionals are
// collected, so the state file is never counted as a third path.
const positionals = [];
let wantJson = false;
let consistency = false;
let stateFile = null;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--state-file') {
const v = args[++i];
if (v === undefined || v.startsWith('--')) {
process.stderr.write('next-session-prompt-validator: --state-file needs a value\n');
process.exit(2);
}
stateFile = v;
} else if (a === '--json') wantJson = true;
else if (a === '--consistency') consistency = true;
else if (!a.startsWith('--')) positionals.push(a);
}
function emit(r) {
if (wantJson) {
@ -194,7 +208,8 @@ if (isMain(import.meta.url)) {
{ state: stateObj },
);
emit({
valid: r.valid && ra.valid !== false,
// Valid only when the pair is consistent AND A and B are each valid.
valid: r.valid && ra.valid !== false && rb.valid !== false,
errors: [...(ra.errors || []), ...(rb.errors || []), ...r.errors],
warnings: [...(ra.warnings || []), ...(rb.warnings || []), ...r.warnings],
});

View file

@ -1112,3 +1112,90 @@ test('keep: commands/trekreview.md carries no disable-model-invocation field (/t
assert.ok(fm.ok, fm.error);
assert.equal(fm.fields['disable-model-invocation'], undefined);
});
// --- #66 / #102 ----------------------------------------------------------------------
// #66: /trekcontinue's Phase 0 told the session to call parseArgs($ARGUMENTS, ...)
// as a function, which no Bash line runs; it now runs the arg-parser CLI and
// reads its JSON. agents/review-orchestrator.md ran the parser without `--`, so
// the CLI parsed nothing.
// #102: Phase 1.5 looked for the master file at "<plugin-root>", where nothing
// writes it; the master file is at the repo root. The consistency call now
// passes the state file, so the state-anchored staleness check runs.
const CONTINUE = 'commands/trekcontinue.md';
const CONTINUE_PARSER_LINE = 'node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekcontinue -- $ARGUMENTS';
const CONSISTENCY_LINE = 'node ${CLAUDE_PLUGIN_ROOT}/lib/validators/next-session-prompt-validator.mjs --json --consistency <RESOLVED-PATH-A> <RESOLVED-PATH-B> --state-file <RESOLVED-PATH-STATE>';
/** The Phase 0 parser line run through bash() with `args` in place of $ARGUMENTS. */
function runContinueParser(cmd, args) {
return bash(cmd.split('$ARGUMENTS').join(args), ROOT);
}
test('[#66] /trekcontinue Phase 0 has no parseArgs($ARGUMENTS call, and its parser line run with --help sets the help flag', () => {
const phase0 = section(read(CONTINUE), '## Phase 0 — `--help` handling');
assert.doesNotMatch(phase0, /parseArgs\(\$ARGUMENTS/, 'Phase 0 still calls parseArgs($ARGUMENTS, ...) as a function');
const cmd = line(phase0, 'parsers/arg-parser.mjs');
assert.equal(cmd, CONTINUE_PARSER_LINE, 'the Phase 0 parser line is not the trekcontinue parser call on $ARGUMENTS');
const block = phase0.split('\n```bash\n').slice(1).map((b) => b.split('\n```')[0]).find((b) => b.includes(cmd));
assert.ok(block, 'the parser line is not in a runtime ```bash block');
assert.match(flat(phase0), /Run first, exactly like this:/);
assert.match(flat(phase0), /Read `flags` and `positional` from the JSON it prints/);
assert.match(flat(phase0), /`flags\['--help'\] === true`/, 'Phase 0 does not dispatch on the parsed --help flag');
assert.match(flat(phase0), /`positional\[0\] === '-h'`/, 'Phase 0 does not dispatch on a lone -h as the first positional');
const help = runContinueParser(cmd, '--help');
assert.equal(help.status, 0, help.stdout + help.stderr);
assert.equal(JSON.parse(help.stdout).flags['--help'], true, 'the parser line run with --help does not set the help flag');
const dir = runContinueParser(cmd, '.claude/projects/demo');
assert.equal(dir.status, 0, dir.stdout + dir.stderr);
const r = JSON.parse(dir.stdout);
assert.equal(r.flags['--help'], undefined, 'a project dir set the --help flag');
assert.deepEqual(r.positional, ['.claude/projects/demo']);
const h = runContinueParser(cmd, '-h');
assert.equal(h.status, 0, h.stdout + h.stderr);
assert.equal(JSON.parse(h.stdout).positional[0], '-h');
const p05 = flat(section(read(CONTINUE), '## Phase 0.5 — Cleanup mode dispatch'));
assert.doesNotMatch(p05, /After `parseArgs` has resolved/);
assert.match(p05, /After the parser has printed/);
});
test('[#66] sibling: agents/review-orchestrator.md passes the arguments to the parser after --', () => {
const p1 = section(read('agents/review-orchestrator.md'), '### Phase 1 — Parse mode and validate input');
const cmd = line(p1, 'parsers/arg-parser.mjs');
assert.equal(cmd, 'node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekreview -- "$@"');
const r = bash(`set -- --project .claude/projects/demo; ${cmd}`, ROOT);
assert.equal(r.status, 0, r.stdout + r.stderr);
assert.equal(JSON.parse(r.stdout).flags['--project'], '.claude/projects/demo', 'the parser did not see --project');
});
test('[#102] /trekcontinue Phase 1.5 finds the master file at the repo root and passes the state file to the consistency call', () => {
assert.doesNotMatch(read(CONTINUE), /<plugin-root>/, 'commands/trekcontinue.md still names <plugin-root>');
const p15 = section(read(CONTINUE), '## Phase 1.5 — Frontmatter consistency check');
assert.ok(flat(p15).includes('a. `NEXT-SESSION-PROMPT.local.md` at the repo root (`git rev-parse --show-toplevel`) — operator-managed master file, written by the operator or an external producer, never by Voyage'),
'candidate a is not the repo-root master file');
const cmd = line(p15, 'validators/next-session-prompt-validator.mjs');
assert.equal(cmd, CONSISTENCY_LINE, 'the consistency call does not pass --state-file <RESOLVED-PATH-STATE>');
assert.match(flat(p15), /When the project's `\.session-state\.local\.json` exists, pass it with `--state-file` \(else run the same line without the option\)/);
assert.match(flat(p15), /`<RESOLVED-PATH-STATE>` with the concrete path of the project's `\.session-state\.local\.json`/);
// The line, with the tokens filled in, runs the state-anchored check.
const dir = mkdtempSync(join(tmpdir(), 'v-102-'));
try {
const a = join(dir, 'a.md');
const b = join(dir, 'b.md');
const s = join(dir, '.session-state.local.json');
writeFileSync(a, '---\nproduced_by: graceful-handoff\nproduced_at: 2026-05-03T10:00:00.000Z\n---\n\nbody\n');
writeFileSync(b, '---\nproduced_by: trekexecute\nproduced_at: 2026-05-04T16:05:00.000Z\n---\n\nbody\n');
writeFileSync(s, JSON.stringify({ schema_version: 1, updated_at: '2026-05-04T16:00:00.000Z' }));
const filled = cmd.replace('<RESOLVED-PATH-A>', a).replace('<RESOLVED-PATH-B>', b).replace('<RESOLVED-PATH-STATE>', s);
const r = bash(filled, ROOT);
assert.equal(r.status, 0, r.stdout + r.stderr);
assert.ok(JSON.parse(r.stdout).warnings.some((w) => w.code === 'NEXT_SESSION_PROMPT_STALE_IGNORED'));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('[#102] sibling: commands/trekexecute.md names project-dir and repo-root candidates, never plugin-root candidates', () => {
const text = flat(read(EXEC));
assert.doesNotMatch(text, /plugin-root candidates/);
assert.equal((text.match(/project-dir and repo-root candidates/g) || []).length, 2);
});

View file

@ -8,7 +8,8 @@ import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { execFileSync, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
validateNextSessionPromptContent,
@ -133,3 +134,73 @@ test('CLI shim — consistency mode flags producer mismatch', () => {
rmSync(dir, { recursive: true, force: true });
}
});
// --- #102: the consistency call reads the state file -----------------------
// The CLI counted the --state-file value as a third positional and exited 2,
// so the state-anchored staleness check never ran from the command line; and
// an invalid B still gave valid: true. These tests use spawnSync so they reach
// an assertion on exit 2 too.
const CLI = fileURLToPath(new URL('../../lib/validators/next-session-prompt-validator.mjs', import.meta.url));
function runCli(args) {
return spawnSync(process.execPath, [CLI, ...args], { encoding: 'utf-8' });
}
/** A stale master (older than the state's updated_at) and a fresh sibling by another producer. */
function stalePair(dir) {
const a = join(dir, 'a.md');
const b = join(dir, 'b.md');
const s = join(dir, '.session-state.local.json');
writeFileSync(a, frontmatter('graceful-handoff', '2026-05-03T10:00:00.000Z'));
writeFileSync(b, frontmatter('trekexecute', '2026-05-04T16:05:00.000Z'));
writeFileSync(s, JSON.stringify({ schema_version: 1, updated_at: '2026-05-04T16:00:00.000Z' }));
return { a, b, s };
}
test('[#102] CLI --json --consistency a b --state-file s: the state-anchored case exits 0 with a STALE_IGNORED warning', () => {
const dir = mkdtempSync(join(tmpdir(), 'nspv-cli-'));
try {
const { a, b, s } = stalePair(dir);
const r = runCli(['--json', '--consistency', a, b, '--state-file', s]);
assert.equal(r.status, 0, `exit ${r.status}: ${r.stdout}${r.stderr}`);
const parsed = JSON.parse(r.stdout);
assert.equal(parsed.valid, true, JSON.stringify(parsed.errors));
assert.ok(parsed.warnings.find((w) => w.code === 'NEXT_SESSION_PROMPT_STALE_IGNORED'),
'the stale candidate was not ignored');
assert.equal(parsed.errors.find((e) => e.code === 'NEXT_SESSION_PROMPT_PRODUCER_MISMATCH'), undefined);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('control: the same pair without --state-file is a producer mismatch (exit 1)', () => {
const dir = mkdtempSync(join(tmpdir(), 'nspv-cli-'));
try {
const { a, b } = stalePair(dir);
const r = runCli(['--json', '--consistency', a, b]);
assert.equal(r.status, 1, `exit ${r.status}: ${r.stdout}${r.stderr}`);
const parsed = JSON.parse(r.stdout);
assert.equal(parsed.valid, false);
assert.ok(parsed.errors.find((e) => e.code === 'NEXT_SESSION_PROMPT_PRODUCER_MISMATCH'));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('[#102] sibling: rb.valid counts: an invalid B makes the consistency result invalid (exit 1)', () => {
const dir = mkdtempSync(join(tmpdir(), 'nspv-cli-'));
try {
const a = join(dir, 'a.md');
const b = join(dir, 'b.md');
writeFileSync(a, frontmatter('trekexecute', '2026-05-04T16:00:00.000Z'));
writeFileSync(b, '---\nproduced_by: trekexecute\n---\n\n# B, no produced_at\n');
const r = runCli(['--json', '--consistency', a, b]);
assert.equal(r.status, 1, `an invalid B still passed: exit ${r.status}: ${r.stdout}${r.stderr}`);
const parsed = JSON.parse(r.stdout);
assert.equal(parsed.valid, false);
assert.ok(parsed.errors.find((e) => e.code === 'NEXT_SESSION_PROMPT_MISSING_FIELD' && /produced_at/.test(e.message)));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});