fix(#4594): one canonical dispatch-identity owner — the emitted format and the parser that reads it back (#4693)

* fix(#4594): give dispatch identity one owner for the emitted format and its parser

The isolation guards decided whether a run-scoped sentinel applied to a
dispatch by regex-scraping model-authored prose. The scrape returned values in
a different namespace from the ones the sentinel records, so the comparison
could never succeed:

  sentinel  { phase: "03", plan: "03-02-hardening" }   <- $PHASE_NUMBER / $plan_id
  prose     "Execute plan 02 of phase 03-auth."
  scraped   { phase: "03-auth.", plan: "02" }          <- greedy (\S+), both wrong

#4594 reports only the phase half. Measured against a real phase-plan-index
run, plans[].id is phase-prefixed, plan-numbered AND slugged, while the prose
carries a bare in-phase plan number — so the plan field mismatches too, and the
Claude path is dead rather than latent. A fresh sentinel was therefore
discarded on every executor dispatch and every legitimate ISOLATION=none
degrade was denied, leaving the work unrun.

hooks/lib/dispatch-identity.js is now the single owner of both halves. The two
prompt-body producers emit a canonical marker carrying the same shell values
the sentinel records, so producer and consumer agree by construction. The prose
frame stays as a fallback, bounded by the phase-token grammar ADR-2121 owns and
deliberately reporting no plan — an absent identifier means "cannot compare"
and is safe; a wrong one is a false mismatch and is not.

The prose sentence itself is byte-identical: the executor agent reads it too,
so the marker is purely additive (Hyrum's Law).

An inapplicable sentinel is now named in the guards' deny reason instead of
being dropped silently — the silence is why this survived three producers and
two consumers unnoticed. Interpolated values come from a sentinel file and from
prompt text, so both are length-bounded and stripped of control characters.

ADR-4630 locks the seam and maps the epic's three phases.

Refs #4630
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#4594): resolve eight review findings across the dispatch-identity seam

Three orthogonal review engines ran on 43418af144 — the code-review skill's
Standards and Spec axes, and an isolated adversarial security pass — plus a
self-review of the committed diff. Every finding is fixed here; none deferred.

F1 (major, reproduced). A keyless or unknown-key-only marker — the literal
"[gsd:dispatch]" or "[gsd:dispatch run=..]" — matched the marker grammar and
returned source:'marker' with both fields null, suppressing the prose fallback
entirely. Any prompt text containing that literal silently disabled identity
narrowing, so a fresh sentinel applied to a dispatch it was never scoped to,
defeating #3045 SECURITY F2. Prompt text is attacker-influenceable. A marker
that yields neither recognized key is no longer a marker: the scan continues to
later markers, then later texts, then prose. Forward-compatible tolerance of
unknown keys is unchanged.

F2/F3 (major). The first cut duplicated sanitizeForReason,
describeSentinelDiscard and REASON_INTERPOLATION_MAX_LEN byte-for-byte across
both guards — the exact defect class this epic exists to delete, and with no
cold-load justification, since both hooks already require hooks/lib/. They now
live in hooks/lib/isolation-deny-reason.js, and buildSentinelDiscard lives in
isolation-sentinel.js beside the comparison it mirrors, returning the nested
{sentinel:{phase,plan}, dispatch:{phase,plan}} shape instead of a bespoke
four-field bag that renamed the pairs already flowing through the seam.

F4 (hard violation). The visibility test asserted on the deny reason's prose.
CONTRIBUTING.md prohibits raw text matching on hook output, which is why every
deny carries a stable reason_code. The discard is now a structured
sentinel_discarded field on each hook's stdout JSON, and the test asserts that;
the sentence stays for the operator but is no longer the contract.

F5 (hard violation). The 64-character truncation limit had no boundary
coverage. 63/64/65 are now exercised against the single consolidated helper.

F6 (minor). sanitizeForReason stripped C0/C1 controls but not U+2028/U+2029 or
the bidi overrides, so a crafted value could still reflow or reverse the
message. Both classes are stripped, with a test each.

F7 (major). The producer/template parity test was vacuous — it rendered a
marker and re-parsed its own output, and would have passed with both templates
deleted. It now reads the two workflow templates, extracts each marker line,
substitutes the measured values and asserts the owner's parser returns them.
Proven red by deleting one template's marker line before being proven green.

F8 (doc). ADR-4630 and the design notes claimed the marker is guaranteed on the
orchestrator-worktree path because that prompt is built in shell. It is not:
executor-isolation-dispatch.md:131 says plainly that those are template
placeholders, not shell variables, so {plan_id} is model-substituted there too.
A false guarantee in a design lock is worse than a stated limit. Both documents
now say the marker is model-substituted on both paths and that the prose
fallback is the real floor everywhere. The "3 workflow templates" count was
also wrong — 3 prose sites across 2 files, 2 of which carry the marker.

Refs #4630
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#4594): refresh the compact-content baseline and acknowledge execute-phase.md growth

Refs #4630.

The dispatch-identity marker and its substitution note grew
gsd-core/workflows/execute-phase.md by 525 bytes (91846 -> 92371), which drifts
two real-tree guards that lint:ci does not run:

- tests/benchmark-compact-content.test.cjs asserts the committed baseline is
  "up to date"; the split for execute-phase.md moved off 25827 -> 25952 and on
  23576 -> 23701, taking its compaction reduction 8.72% -> 8.67%. Baseline
  regenerated with scripts/benchmark-compact-content.cjs --write.
- tests/emitted-attribution.test.cjs requires a growth acknowledgment trailer
  for any emitted file that grows, keyed on the bare filename. Added below.

The growth is two additions and no rewrites: the [gsd:dispatch ...] marker line
inside the Agent() prompt's <objective>, and the note telling the orchestrator
to substitute {plan_id} with the plan's id verbatim. Both are load-bearing --
the marker is what lets a guard hook match a dispatch to the sentinel the
per-plan gate wrote, and without the note the orchestrator has no instruction
telling it the value must not be paraphrased.

Emitted-Drift-Ack-Growth: execute-phase.md — adds the canonical [gsd:dispatch] identity marker and its {plan_id} substitution note, which the isolation guards compare verbatim against the run-scoped sentinel (#4594)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#4594): set changeset fragment pr to 4693

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-09-13 15:36:08 -04:00
committed by GitHub
parent a155ff4fb6
commit c0b2a05d2f
27 changed files with 1226 additions and 59 deletions

View File

@@ -63,8 +63,8 @@
const fs = require('fs');
const path = require('path');
const os = require('os');
const { readSentinel, VALID_ISOLATION, extractDispatchIdentifiers, sentinelAppliesToDispatch } = require('./lib/isolation-sentinel.js');
const { REASON_CODE } = require('./lib/isolation-deny-reason.js');
const { readSentinel, VALID_ISOLATION, extractDispatchIdentifiers, sentinelAppliesToDispatch, buildSentinelDiscard } = require('./lib/isolation-sentinel.js');
const { REASON_CODE, describeSentinelDiscard } = require('./lib/isolation-deny-reason.js');
const { HOOK_ON_CRASH, allow, deny, crash } = require('./lib/hook-exit.js');
// Required at module top, alongside the other ./lib requires — NOT behind
@@ -385,16 +385,20 @@ function resolveIsolationState(cwd, { clock = Date, dispatchIds = null } = {}) {
projectExists = false;
}
if (!projectExists) {
return { gsdProject: false, isolation: null, harnessFlag: null, error: null };
return { gsdProject: false, isolation: null, harnessFlag: null, error: null, sentinelDiscarded: null };
}
const sentinel = readSentinel(cwd, { clock });
if (sentinel.present && !sentinel.stale && sentinelAppliesToDispatch(sentinel, dispatchIds)) {
// Hoisted so the "sentinel was present/fresh but did not apply" case below
// (#4594 row 15 — Postel's-Law finding) can distinguish itself from
// "absent"/"stale" without re-deriving applicability.
const applies = sentinelAppliesToDispatch(sentinel, dispatchIds);
if (sentinel.present && !sentinel.stale && applies) {
if (sentinel.isolation !== 'harness-worktree') {
return { gsdProject: true, isolation: sentinel.isolation, harnessFlag: null, error: null };
return { gsdProject: true, isolation: sentinel.isolation, harnessFlag: null, error: null, sentinelDiscarded: null };
}
if (sentinel.harnessFlag) {
return { gsdProject: true, isolation: 'harness-worktree', harnessFlag: sentinel.harnessFlag, error: null };
return { gsdProject: true, isolation: 'harness-worktree', harnessFlag: sentinel.harnessFlag, error: null, sentinelDiscarded: null };
}
// #3045 BLOCKER 2 fix: the sentinel already PROVED this dispatch requires
// isolation (it resolved harness-worktree) but carries no usable flag —
@@ -423,6 +427,7 @@ function resolveIsolationState(cwd, { clock = Date, dispatchIds = null } = {}) {
'dispatch-isolation sentinel resolved "harness-worktree" but recorded no harness_flag — ' +
'cannot verify what parameter the dispatch must carry.'
),
sentinelDiscarded: null,
};
}
@@ -430,11 +435,19 @@ function resolveIsolationState(cwd, { clock = Date, dispatchIds = null } = {}) {
// conservative fallback (#3045 finding — must still cover fail-closed case
// (a): a project that opted out of worktrees entirely via
// workflow.use_worktrees).
//
// #4594 row 15: a PRESENT, FRESH sentinel that simply does not apply to
// THIS dispatch (identifiers disagree) is a distinct case from "absent" or
// "stale" — record what was discarded so evaluateDispatch can name it in a
// block reason instead of silently falling through to a registry-resolution
// message that never mentions the sentinel existed.
const sentinelDiscarded = buildSentinelDiscard(sentinel, dispatchIds);
try {
const { isolation, harnessFlag } = resolveRegistryIsolation(cwd, configPath);
return { gsdProject: true, isolation, harnessFlag, error: null };
return { gsdProject: true, isolation, harnessFlag, error: null, sentinelDiscarded };
} catch (err) {
return { gsdProject: true, isolation: null, harnessFlag: null, error: err };
return { gsdProject: true, isolation: null, harnessFlag: null, error: err, sentinelDiscarded };
}
}
@@ -464,10 +477,16 @@ function evaluateDispatch(data, { clock = Date } = {}) {
}
const cwd = data.cwd || process.cwd();
// #3045 SECURITY F2: best-effort plan/phase extraction from this
// dispatch's own description text, so a fresh sentinel that disagrees
// with THIS dispatch is treated as inapplicable rather than trusted.
const dispatchIds = extractDispatchIdentifiers(toolInput.description);
// #3045 SECURITY F2 / #4594: best-effort plan/phase extraction from this
// dispatch's own text, so a fresh sentinel that disagrees with THIS
// dispatch is treated as inapplicable rather than trusted. PROMPT FIRST:
// `description` is short, model-authored free text that only carries usable
// identity when the model happens to reproduce the dispatch template
// verbatim, while the canonical `[gsd:dispatch phase="…" plan="…"]` marker
// (or, failing that, the prose fallback) lives in the prompt body itself —
// `description` is kept only as a fallback for a marker/prose match that
// exists solely in it.
const dispatchIds = extractDispatchIdentifiers(toolInput.prompt, toolInput.description);
const state = resolveIsolationState(cwd, { clock, dispatchIds });
if (!state.gsdProject) return { action: 'allow' };
@@ -493,7 +512,8 @@ function evaluateDispatch(data, { clock = Date } = {}) {
`required — a guard that cannot verify must not answer "safe" (#3050). Retry once the ` +
`project configuration is readable.`;
const reasonCode = isBuildFailure ? REASON_CODE.RUNTIME_BUILD_FAILED : REASON_CODE.CONFIG_UNREADABLE;
return { action: 'block', reason, reasonCode };
const fullReason = state.sentinelDiscarded ? reason + describeSentinelDiscard(state.sentinelDiscarded) : reason;
return { action: 'block', reason: fullReason, reasonCode, sentinelDiscarded: state.sentinelDiscarded };
}
if (state.isolation !== 'harness-worktree') return { action: 'allow' };
@@ -503,13 +523,14 @@ function evaluateDispatch(data, { clock = Date } = {}) {
if (toolInput[parsed.param] === parsed.value) return { action: 'allow' };
const reason =
let reason =
`Agent isolation guard: this project's dispatch isolation resolves to "harness-worktree", ` +
`but the Agent() dispatch for subagent_type="${subagentType}" is missing ` +
`${parsed.param}="${parsed.value}". Add ${parsed.param}="${parsed.value}" to the Agent() ` +
`call so the executor runs in an isolated worktree instead of the primary checkout ` +
`(gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md).`;
return { action: 'block', reason, reasonCode: REASON_CODE.HARNESS_FLAG_MISSING };
if (state.sentinelDiscarded) reason += describeSentinelDiscard(state.sentinelDiscarded);
return { action: 'block', reason, reasonCode: REASON_CODE.HARNESS_FLAG_MISSING, sentinelDiscarded: state.sentinelDiscarded };
}
/* istanbul ignore next -- stdin adapter, exercised via spawnSync in tests */
@@ -524,7 +545,12 @@ function main() {
const data = JSON.parse(input);
const decision = evaluateDispatch(data);
if (decision.action === 'block') {
const out = { decision: 'block', reason: decision.reason, reason_code: decision.reasonCode };
const out = {
decision: 'block',
reason: decision.reason,
reason_code: decision.reasonCode,
sentinel_discarded: decision.sentinelDiscarded ?? null,
};
// Kimi feeds stderr (not stdout) back to the model on exit 2.
deny(out, decision.reason);
}

View File

@@ -62,8 +62,8 @@ const { allow } = require('./lib/hook-exit.js');
// hooks/lib/cursor-workspace.js. Staged next to these scripts by
// writeCursorHooksJson so the require always resolves post-install.
const { resolveStatePath } = require('./lib/cursor-workspace.js');
const { readSentinel, VALID_ISOLATION, extractDispatchIdentifiers, sentinelAppliesToDispatch } = require('./lib/isolation-sentinel.js');
const { REASON_CODE } = require('./lib/isolation-deny-reason.js');
const { readSentinel, VALID_ISOLATION, extractDispatchIdentifiers, sentinelAppliesToDispatch, buildSentinelDiscard } = require('./lib/isolation-sentinel.js');
const { REASON_CODE, describeSentinelDiscard } = require('./lib/isolation-deny-reason.js');
// #3582: gsd-core/bin/lib/*.cjs (runtime-homes.cjs, worktree-safety.cjs,
// runtime-name-policy.cjs, capability-registry.cjs — required below, inside
// resolveIsolationEvidence and resolveFallbackIsolation) are tsc build
@@ -491,18 +491,25 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`Refusing to allow this subagent to spawn until the runtime library is built — a guard ` +
`that cannot verify must not answer "safe" (#3050).`,
reasonCode: REASON_CODE.RUNTIME_BUILD_FAILED,
sentinelDiscarded: null,
};
}
// #3045 BLOCKER fix: a fresh sentinel is authoritative for THIS dispatch's
// actual resolved isolation — see the doc comment above.
// #3045 SECURITY F2: a fresh sentinel that names a DIFFERENT plan/phase
// than this dispatch is not applicable to it — fall through to the
// conservative fallback exactly as a stale sentinel would.
// Hoisted (readSentinel never throws) so the "present, fresh, but did not
// apply" case (#4594 row 15) can be reported on every deny path below
// instead of silently discarded.
const sentinel = readSentinel(root, { clock });
const applies = sentinelAppliesToDispatch(sentinel, dispatchIds);
const sentinelDiscarded = buildSentinelDiscard(sentinel, dispatchIds);
let declaredIsolation;
try {
// #3045 BLOCKER fix: a fresh sentinel is authoritative for THIS
// dispatch's actual resolved isolation — see the doc comment above.
// #3045 SECURITY F2: a fresh sentinel that names a DIFFERENT
// plan/phase than this dispatch is not applicable to it — fall through
// to the conservative fallback exactly as a stale sentinel would.
const sentinel = readSentinel(root, { clock });
declaredIsolation = (sentinel.present && !sentinel.stale && sentinelAppliesToDispatch(sentinel, dispatchIds))
declaredIsolation = (sentinel.present && !sentinel.stale && applies)
? sentinel.isolation
: resolveFallbackIsolation(root, configPath);
} catch {
@@ -513,8 +520,10 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`dispatch-isolation configuration ('.planning/config.json' exists under "${root}"). ` +
`Refusing to allow this subagent to spawn without being able to verify whether ` +
`isolation is required — a guard that cannot verify must not answer "safe" (#3050). ` +
`Retry once the project configuration is readable.`,
`Retry once the project configuration is readable.` +
(sentinelDiscarded ? describeSentinelDiscard(sentinelDiscarded) : ''),
reasonCode: REASON_CODE.CONFIG_UNREADABLE,
sentinelDiscarded,
};
}
@@ -530,8 +539,10 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`GSD subagent isolation guard: this project's dispatch isolation resolves to ` +
`"harness-worktree", but the subagentStart payload for this dispatch carries no usable ` +
`subagent_type. Refusing to allow it to spawn without being able to confirm whether it ` +
`is a GSD executor — a guard that cannot verify must not answer "safe" (#3050).`,
`is a GSD executor — a guard that cannot verify must not answer "safe" (#3050).` +
(sentinelDiscarded ? describeSentinelDiscard(sentinelDiscarded) : ''),
reasonCode: REASON_CODE.NO_SUBAGENT_TYPE,
sentinelDiscarded,
};
}
@@ -547,8 +558,10 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`"harness-worktree", but whether "${root}" is running in an isolated Cursor worktree ` +
`could not be determined (git did not respond). Refusing to allow subagent_type=` +
`"${subagentType}" to spawn without being able to verify isolation — a guard that ` +
`cannot verify must not answer "safe" (#3050). Retry once git is responsive.`,
`cannot verify must not answer "safe" (#3050). Retry once git is responsive.` +
(sentinelDiscarded ? describeSentinelDiscard(sentinelDiscarded) : ''),
reasonCode: REASON_CODE.CANNOT_DETERMINE_ISOLATION,
sentinelDiscarded,
};
}
@@ -560,8 +573,10 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`which is not an isolated Cursor worktree — it would edit the user's primary checkout ` +
`directly, with no consent and no warning. Start an isolated session first (the ` +
`"--worktree" CLI flag or the "/worktree" chat command; Cursor manages these worktrees ` +
`under "~/.cursor/worktrees/") and retry.`,
`under "~/.cursor/worktrees/") and retry.` +
(sentinelDiscarded ? describeSentinelDiscard(sentinelDiscarded) : ''),
reasonCode: REASON_CODE.NOT_ISOLATED_WORKTREE,
sentinelDiscarded,
};
}
@@ -611,7 +626,12 @@ function main() {
decision = { action: 'allow' };
}
if (decision.action === 'deny') {
const out = { permission: 'deny', user_message: decision.reason, reason_code: decision.reasonCode };
const out = {
permission: 'deny',
user_message: decision.reason,
reason_code: decision.reasonCode,
sentinel_discarded: decision.sentinelDiscarded ?? null,
};
if (additionalContext !== null) out.additional_context = additionalContext;
process.stdout.write(JSON.stringify(out));
return;

View File

@@ -0,0 +1,187 @@
'use strict';
// hooks/lib/dispatch-identity.js — the ONE canonical owner of the
// `[gsd:dispatch phase="…" plan="…"]` marker format and its prose fallback
// (#4594, epic #4630 Phase 1). See
// `.gsd/phase/fix-4594-dispatch-identity-seam/40-design.md` for the full
// rationale (behavior table, negative space, rejected alternatives).
//
// COLD-LOAD CONSTRAINT (load-bearing, not a style choice): this module MUST
// require NOTHING — no `fs`, no `path`, and above all nothing under
// `gsd-core/bin/lib/` or `ensure-runtime-build`. The guard hooks that consume
// this module must load on a raw plugin-marketplace install where the
// compiled lib is absent and the self-healing build seam has not run — a
// hook that dies at module load is worse than one carrying a mirror. See
// `tests/dispatch-identity.test.cjs`'s "cold tree load" test, which asserts
// this by monkeypatching `Module._load` to throw on exactly those paths.
// DISPATCH_PHASE_TOKEN_SOURCE is a DELIBERATE MIRROR of
// `CASE_FLEXIBLE_PHASE_NUMBER_TOKEN_SOURCE` in `src/phase-id.cts`
// (ADR-2121 owns the phase-token grammar; `gsd-core/bin/lib/phase-id.cjs` is
// its compiled form). It cannot be an `require()`-based import: importing the
// compiled lib here would violate the cold-load constraint above (either a
// direct dependency on `gsd-core/bin/lib/` or a forced self-heal via
// `ensure-runtime-build`), which is exactly the failure mode this module
// exists to avoid for the guard hooks that consume it.
//
// Because this is a hand-copied mirror and not a shared reference, a
// hand-edited grammar change on one side that is not mirrored on the other
// does NOT fail loudly — both sides remain independently valid regex
// sources, so the failure mode is a silent, invisible non-match (a dispatch
// whose phase token the two owners now parse differently), never a thrown
// error. `tests/dispatch-identity.test.cjs`'s "templates: prose token source
// matches the case-flexible phase-id grammar" test pins this string equal to
// the compiled source at test time specifically to turn that silent drift
// into a loud, in-CI failure.
const DISPATCH_PHASE_TOKEN_SOURCE = '\\d+[A-Za-z]?(?:\\.\\d+)*';
// Bounded marker grammar: `[gsd:dispatch key="value" key2="value2"]`.
// - Key names bounded to {1,31} — no key we emit or expect is anywhere near
// that long; this is purely a backstop against pathological input.
// - Values bounded to {0,200} and forbidden from containing `"`, `]`, or any
// control character that could either close the marker early or forge a
// sibling key — enforced structurally by the negated character class, not
// by a separate validation pass.
// Global flag so `findMarker` can scan forward through a large prompt.
const MARKER_RE = /\[gsd:dispatch((?:\s+[A-Za-z][A-Za-z0-9_-]{0,31}="[^"\]\r\n]{0,200}")*)\s*\]/g;
const MARKER_KV_RE = /([A-Za-z][A-Za-z0-9_-]{0,31})="([^"\]\r\n]{0,200})"/g;
// Prose fallback frame: `execute plan <token> of phase <PHASE TOKEN>`.
// - Case-insensitive, `\s+` throughout so CRLF (and any run of whitespace)
// parses identically to LF.
// - The plan token is bounded (`\S{1,80}`) but its VALUE is deliberately
// discarded by the caller (see `parseDispatchIdentity` below) — captured
// only so the phase token can be anchored correctly after it.
// - The phase token is bounded by `DISPATCH_PHASE_TOKEN_SOURCE`, replacing
// the old greedy `(\S+)`, so a directory-name suffix (`-auth`) or a
// sentence-terminating period is never swept into the token.
const PROSE_RE = new RegExp(
`execute\\s+plan\\s+(\\S{1,80})\\s+of\\s+phase\\s+(${DISPATCH_PHASE_TOKEN_SOURCE})`,
'i',
);
/**
* Render the `[gsd:dispatch phase="…" plan="…"]` marker for a producer to
* embed verbatim in a dispatch description/prompt. Never throws.
*
* Emits only keys whose value is a non-empty string not containing `"`, `]`,
* `\r`, or `\n` — such a value is UNUSABLE and that key is omitted entirely,
* because embedding it could close the marker early and forge a second,
* attacker-controlled field. Key order is always `phase` then `plan`.
* Returns `''` when neither key is usable (nothing worth emitting).
*/
function renderDispatchIdentityMarker(input) {
const value = input && typeof input === 'object' ? input : {};
const parts = [];
for (const key of ['phase', 'plan']) {
const v = value[key];
if (typeof v === 'string' && v.length > 0 && !/["\]\r\n]/.test(v)) {
parts.push(`${key}="${v}"`);
}
}
if (parts.length === 0) return '';
return `[gsd:dispatch ${parts.join(' ')}]`;
}
function emptyResult() {
return { phase: null, plan: null, source: null };
}
/**
* Scan `texts` in order for the first well-formed marker that yields at
* least one recognized key (`phase` and/or `plan`). Returns `{ phase, plan }`
* (one of the two possibly null, never both) or `null` if no QUALIFYING
* marker was found in any text. Unrecognized keys inside a marker are
* ignored (forward compatibility — a later `run=`/`wave=` key must not break
* a deployed parser).
*
* #4594 F1 fix: a marker that matches `MARKER_RE` but carries neither
* `phase=` nor `plan=` (e.g. only unrecognized keys, or an empty kv block)
* is NOT treated as "found" — it is skipped and scanning continues (later
* markers in the same text, then subsequent texts), falling through to the
* prose fallback if nothing qualifying turns up. Without this, prompt text
* that merely CONTAINS the literal marker syntax with no usable identifiers
* silently suppressed the prose fallback entirely, since the old
* implementation returned on the first syntactic match regardless of
* content.
*/
function findMarker(texts) {
for (const text of texts) {
if (typeof text !== 'string' || text.length === 0) continue;
MARKER_RE.lastIndex = 0;
let match;
while ((match = MARKER_RE.exec(text)) !== null) {
const kvBlock = match[1] || '';
let phase = null;
let plan = null;
MARKER_KV_RE.lastIndex = 0;
let kv;
while ((kv = MARKER_KV_RE.exec(kvBlock)) !== null) {
const [, key, val] = kv;
if (key === 'phase' && phase === null) phase = val;
else if (key === 'plan' && plan === null) plan = val;
}
if (phase === null && plan === null) continue;
return { phase, plan };
}
}
return null;
}
/**
* Scan `texts` in order for the first `execute plan <token> of phase
* <PHASE TOKEN>` frame. Returns `{ phase }` or `null`.
*
* The prose fallback returns `plan: null` DELIBERATELY (enforced by the
* caller, not here): the prose plan token (e.g. `02`) is a bare in-phase
* plan number, a different namespace from the sentinel's `plan_id` (e.g.
* `03-02-hardening`, which is phase-prefixed AND slugged). Reporting the
* prose plan token as the parsed `plan` is exactly the false-mismatch bug
* this module exists to fix — an absent value is honestly "cannot compare",
* while a wrong value silently forges a mismatch on every dispatch. Do not
* "fix" this by threading the plan token through — that was the bug.
*/
function findProse(texts) {
for (const text of texts) {
if (typeof text !== 'string' || text.length === 0) continue;
const match = PROSE_RE.exec(text);
if (match) {
return { phase: match[2] };
}
}
return null;
}
/**
* Parse dispatch identity out of one or more texts (a short description, a
* full prompt body, etc). Never throws for any input type; non-string
* entries are skipped.
*
* Pass 1: scan all texts in order for a well-formed marker; the first one
* wins outright (marker beats prose even if prose appears earlier in the
* same text — see the design doc's row 8).
* Pass 2 (only if no marker was found anywhere): scan all texts in order for
* the prose frame; the first match wins. `plan` is always `null` from this
* path (see `findProse`'s doc comment).
*
* Returns `{ phase, plan, source }` where `source` is `'marker' | 'prose' |
* null`.
*/
function parseDispatchIdentity(...texts) {
const marker = findMarker(texts);
if (marker) {
return { phase: marker.phase, plan: marker.plan, source: 'marker' };
}
const prose = findProse(texts);
if (prose) {
return { phase: prose.phase, plan: null, source: 'prose' };
}
return emptyResult();
}
module.exports = {
DISPATCH_PHASE_TOKEN_SOURCE,
renderDispatchIdentityMarker,
parseDispatchIdentity,
};

View File

@@ -36,4 +36,56 @@ const REASON_CODE = Object.freeze({
NOT_ISOLATED_WORKTREE: 'not_isolated_worktree',
});
module.exports = { REASON_CODE };
// #4594 row 15 / F2: values interpolated into a deny reason (sentinel/dispatch
// phase and plan) come from a sentinel file on disk and, transitively, from
// model-authored prompt text, neither of which is trusted — bound length and
// strip control characters/newlines so a crafted value cannot forge extra
// lines or otherwise inject content into the guard's stdout/stderr message
// (same discipline as escaping an untrusted token before embedding it in a
// message, e.g. phase-plan-index's `depends_on` warning).
//
// Originally duplicated byte-for-byte in hooks/gsd-agent-isolation-guard.js
// and hooks/gsd-cursor-subagent-start.js (#4594 F2 review finding) — both
// hooks already require this dependency-free module, so there is no
// cold-load justification for the duplication the way there is for
// hooks/lib/dispatch-identity.js's grammar mirror. Moved here as the single
// owner; both hooks now import it.
const REASON_INTERPOLATION_MAX_LEN = 64;
// F6: also strip Unicode line/paragraph separators (U+2028/U+2029) and the
// bidi-override/isolate control characters (U+202A-U+202E, U+2066-U+2069) —
// none of these are in `[\x00-\x1f\x7f]`, so a crafted sentinel or dispatch
// value carrying them could still visually reflow the deny message onto a
// new line or reverse/hide part of it despite the ASCII control-char strip.
const REASON_UNSAFE_CHARS_RE = new RegExp(
// eslint-disable-next-line no-control-regex -- deliberately stripping control chars/newlines
'[\\x00-\\x1f\\x7f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]',
'g',
);
function sanitizeForReason(value) {
if (typeof value !== 'string' || value.length === 0) return '(none)';
const stripped = value.replace(REASON_UNSAFE_CHARS_RE, '');
return stripped.length > REASON_INTERPOLATION_MAX_LEN
? `${stripped.slice(0, REASON_INTERPOLATION_MAX_LEN)}…`
: stripped;
}
function describeSentinelDiscard(sentinelDiscarded) {
const sentinelPhase = sanitizeForReason(sentinelDiscarded.sentinel.phase);
const sentinelPlan = sanitizeForReason(sentinelDiscarded.sentinel.plan);
const dispatchPhase = sanitizeForReason(sentinelDiscarded.dispatch.phase);
const dispatchPlan = sanitizeForReason(sentinelDiscarded.dispatch.plan);
return (
` A fresh dispatch-isolation sentinel was present but did not apply to this dispatch ` +
`(sentinel phase="${sentinelPhase}" plan="${sentinelPlan}"; dispatch phase="${dispatchPhase}" ` +
`plan="${dispatchPlan}"), so it was not consulted.`
);
}
module.exports = {
REASON_CODE,
REASON_INTERPOLATION_MAX_LEN,
sanitizeForReason,
describeSentinelDiscard,
};

View File

@@ -56,6 +56,7 @@
const fs = require('fs');
const path = require('path');
const { parseDispatchIdentity } = require('./dispatch-identity.js');
// Isolation modes ADR-1239 declares (mirrors gsd-tools.cjs
// routeDispatchIsolation / routeRecordDispatchIsolation).
@@ -223,26 +224,40 @@ function readSentinel(cwd, { clock = Date } = {}) {
}
/**
* #3045 SECURITY F2: extract the `{plan, phase}` a specific Agent()/Task()
* dispatch is FOR, from the one place that data is reliably embedded today —
* the dispatch prompt/description text (`execute-phase.md`'s Agent() block
* uses the literal shape `description="Execute plan {plan_number} of phase
* {phase_number}"`, and the prompt body's `<objective>` repeats "Execute plan
* {plan_number} of phase {phase_number}-{phase_name}." verbatim — the SAME
* text the orchestrator-worktree EXECUTOR_PROMPT template and Cursor's `task`
* field carry, since Cursor dispatches the same prompt content). There is no
* structured per-dispatch kwarg carrying plan/phase identifiers today (#3045
* would need a larger dispatch-protocol change to add one) — this is
* therefore a best-effort, NOT a guaranteed, extraction: a dispatch whose
* text doesn't match the expected shape returns `{ plan: null, phase: null }`
* and the caller must NOT treat that as a mismatch (see
* `sentinelAppliesToDispatch`).
* #3045 SECURITY F2 / #4594: extract the `{plan, phase}` a specific
* Agent()/Task() dispatch is FOR. Variadic — accepts any number of text
* sources (short description, full prompt body, etc) and delegates to
* `hooks/lib/dispatch-identity.js::parseDispatchIdentity`, the one canonical
* owner of both the `[gsd:dispatch phase="…" plan="…"]` marker format and its
* prose fallback (see `.gsd/phase/fix-4594-dispatch-identity-seam/40-design.md`).
*
* MARKER-FIRST CONTRACT: producers embed a structured marker carrying the
* exact shell values the sentinel itself records (`$PHASE_NUMBER`,
* `$plan_id`), so producer and consumer agree by construction, independent
* of how the prose reads or whether a model paraphrases the dispatch
* sentence. Only when no marker is found anywhere in the supplied texts does
* this fall back to scanning for the prose frame "execute plan <token> of
* phase <PHASE TOKEN>".
*
* The prose fallback is now CORRECT-OR-ABSENT rather than possibly-wrong:
* the phase token is bounded by the same grammar `src/phase-id.cts` owns
* (ADR-2121), so a directory-name slug or trailing punctuation can no longer
* leak into the phase value, and the prose plan token is never reported at
* all (it lives in a different namespace than the sentinel's phase-prefixed,
* slugged `plan_id` — reporting it was the #4594 false-mismatch bug).
*
* This is still a best-effort, NOT a guaranteed, extraction: a dispatch that
* carries neither a marker nor a matching prose frame in ANY supplied text
* returns `{ plan: null, phase: null }`, and the caller MUST NEVER treat
* that as a mismatch — see `sentinelAppliesToDispatch`, whose whole
* contract depends on "missing" and "wrong" being distinguishable.
*
* Returns only the two-field `{ plan, phase }` shape existing callers
* depend on — `parseDispatchIdentity`'s `source` field is discarded here.
*/
function extractDispatchIdentifiers(text) {
if (typeof text !== 'string' || text.length === 0) return { plan: null, phase: null };
const m = /execute\s+plan\s+(\S+)\s+of\s+phase\s+(\S+)/i.exec(text);
if (!m) return { plan: null, phase: null };
return { plan: m[1], phase: m[2] };
function extractDispatchIdentifiers(...texts) {
const { phase, plan } = parseDispatchIdentity(...texts);
return { plan, phase };
}
/**
@@ -265,6 +280,29 @@ function sentinelAppliesToDispatch(sentinel, dispatchIds) {
return true;
}
/**
* #4594 F3: build the structured "a fresh sentinel was present but did not
* apply to this dispatch" descriptor, mirroring the exact comparison
* `sentinelAppliesToDispatch` performs. Returns `null` when the sentinel is
* absent, stale, malformed, or DOES apply — i.e. exactly when there is
* nothing to report as discarded. Otherwise returns the nested
* `{ sentinel: {phase, plan}, dispatch: {phase, plan} }` shape, reusing the
* `{phase, plan}` pair already flowing through this module end to end rather
* than renaming its fields into an ad hoc `sentinelPhase`/`dispatchPlan` bag
* (previously rebuilt identically at two call sites in the guard hooks).
*/
function buildSentinelDiscard(sentinel, dispatchIds) {
if (!sentinel || !sentinel.present || sentinel.stale) return null;
if (sentinelAppliesToDispatch(sentinel, dispatchIds)) return null;
return {
sentinel: { phase: sentinel.phase ?? null, plan: sentinel.plan ?? null },
dispatch: {
phase: dispatchIds ? (dispatchIds.phase ?? null) : null,
plan: dispatchIds ? (dispatchIds.plan ?? null) : null,
},
};
}
module.exports = {
VALID_ISOLATION,
SENTINEL_RELATIVE_PATH,
@@ -274,4 +312,5 @@ module.exports = {
readSentinel,
extractDispatchIdentifiers,
sentinelAppliesToDispatch,
buildSentinelDiscard,
};