fix(#3003): opt-in mechanism for intentional deletions in worktree.cleanup-wave (#3757)

* test(#3003): failing-first suite for declared deletions in cleanup-wave

Binds the guard's opt-in before it exists, so the suite is RED against next.

The rows that carry the weight are the over-authorization set: a directory
declaration must not authorize its children, a glob declaration must authorize
nothing, and a declaration must not act as a string prefix of another path.
Each of those BLOCKS, and each would PASS under a prefix, glob, or startsWith
matcher — which is how a path list quietly degrades into the boolean opt-in
#3003 explicitly rejected. The glob row matters most: declaredScopePrefix
already returns null ("matches everything") for a glob-leading pattern, correct
for the advisory it serves and catastrophic for a gate.

Also pinned: a failed deletion check blocks on its own reason rather than being
filtered into a pass; the block detail names only the undeclared residue so the
operator is not misdirected by paths that were fine; an entry with no
declaration blocks exactly as before; junk and non-array declarations do not
authorize; and a blocked entry still isolates rather than aborting the wave
(#2852, which must stay fixed).

Two advisory rows cover an interaction found while designing: git diff
--name-only includes deleted paths, so without unioning the declaration into
the #2596 scope check, authorizing a deletion would raise
SCOPE_OUT_OF_DECLARED against the very path just authorized.

A seeded property states the whole invariant the three over-authorization rows
sample: a deletion merges iff its normalized path is in the declared set.

* feat(#3003): declared deletions opt-in for the cleanup-wave guard

The deletions guard blocked the merge-back of any executor branch whose diff
removed a file, with no way to say a removal was intended. A plan that folded
one test file into a sibling could not be merged by the tool meant to merge it,
forcing a manual --no-ff outside the tool -- strictly less safe than what the
guard protects against.

A plan now declares removals in its own frontmatter (files_deleted), and that
list rides the same path files_modified already travels: plan-document parse ->
phase plan JSON -> the per-plan worktree gate -> record-agent/create
--deletions -> declared_deletions on the manifest entry -> the guard. The guard
blocks only the deletions NOT in that list.

A path list rather than a boolean, per the pinned decision: a boolean disarms
the guard for the whole entry, so an unexpected deletion riding along with a
declared one would pass unnoticed. Matching is exact after the module's shared
normalizer -- never a prefix, never a glob. Both would let one declaration
authorize a whole set, which is the mass-deletion accident the guard exists to
catch. That also means declaredScopePrefix is deliberately NOT reused here: it
returns null ("matches everything") for a glob-leading pattern, which is right
for the advisory it serves and would silently disarm a gate.

The block detail now carries only the undeclared residue, so an operator is not
sent looking at paths that were fine. A failed deletion check still blocks on
its own reason and is never filtered into a pass. A blocked entry still
isolates rather than aborting the wave (#2852).

The #2596 scope advisory unions the declaration into its declared set --
git diff --name-only includes deleted paths, so without that, authorizing a
deletion would immediately warn that the same path was out of declared scope.

Optional and additive throughout: files_deleted is absent from
PLAN_REQUIRED_FIELDS, a manifest entry without declared_deletions keeps the
original unconditional block, and omitting --deletions leaves the on-disk entry
shape untouched.

Supersedes the spent #2856 emitted-drift ack entry for execute-phase.md, the
same supersede that entry performed on #3370 and #3370 on #3324.

* fix(#3003): wire --deletions on every dispatch surface, not just one

Review found the feature inert on two of three dispatch paths. execute-phase.md
(harness inline) passed --deletions, but the orchestrator-worktree path
(executor-isolation-dispatch.md, worktree.create) and the Fleet-parallel batch
path (capabilities/claude-orchestration/fragments/execute-wave-pre.md,
worktree.record-agent) still passed only --files. A plan declaring
files_deleted would have merged on one path and been blocked on the other two
-- the exact bug #3003 exists to fix, left unfixed where most of the isolation
actually runs.

Worse, per-plan-worktree-gate.md already claimed --deletions was passed 'on the
same worktree.record-agent / worktree.create calls', which was false for both
untouched sites. A doc asserting coverage that does not exist is how a gap
survives review.

All four surfaces now pass the flag, verified by sweeping every .md under
gsd-core/, capabilities/, commands/, skills/ and agents/ that invokes
worktree.record-agent or worktree.create: each one that passes --files now also
passes --deletions. The isolation-dispatch note explains why this flag, unlike
--files, is not advisory -- omitting it does not skip a check, it blocks a
merge the plan declared.

Regenerates capability-registry.cjs, which the fragment edit made stale.

Neither newly-grown file needs an emitted-drift ack: executor-isolation-dispatch.md
sits under workflows/execute-phase/steps/ and execute-wave-pre.md under
capabilities/, both outside currentSizes()'s non-recursive scan of
gsd-core/workflows/ and agents/.

* docs(#3003): document files_deleted where a plan author will actually find it

The feature's entire user surface is one plan-frontmatter field, and the
canonical reference for that frontmatter -- docs/reference/plan-md.md, the table
that documents every other key -- never mentioned it. A field nobody can
discover ships as a field nobody uses. Adds the files_deleted row and an example
entry in all five locales (en, ja-JP, zh-CN, ko-KR, pt-BR), stating the property
that makes the opt-in safe: matching is exact per path after separator
normalization, with no globs and no directory prefixes, so a declaration can
never authorize more than it literally lists, and omitting the field keeps the
guard's original unconditional block.

Also corrects two claims in the scope-conformance how-to that this change made
false. Its opening paragraph described the recorded declared scope as
files_modified alone; declared_deletions is now unioned into that comparison.
Its "Renames are not detected specially" bullet asserted the deletions guard
blocks any entry whose diff contains a deletion, full stop -- which was the
whole point of #3003 and is no longer true. Reworked to say what now decides a
rename's fate: declare the old path in files_deleted and both halves become
ordinary paths for the advisory check, which is also why the old path needs no
separate files_modified entry.

Documentation that describes the pre-change behavior of the thing being changed
is worse than no documentation, because a reader trusts it.

* fix(#3003): close every review finding on the declared-deletions opt-in

Two independent isolated reviewers, correctness and security. Neither found a
blocker; both found real defects, and the directive treats a finding at any
severity as blocking. All of them are fixed here.

MAJOR -- the submodule worktree gate could not see a deletion-only plan.
per-plan-worktree-gate.md intersected $SUBMODULE_PATHS against $PLAN_FILES
alone, while $PLAN_DELETIONS was extracted and then never used. Before
files_deleted existed, a path had to appear in files_modified to be planned at
all, so the gate saw it; the new field plus the new docs telling authors a
deleted path needs no files_modified entry opened a hole where a plan whose only
submodule touch is a removal kept worktree isolation on -- the exact case #2772
disabled it for. Both channels now feed the intersection. Note the posture is
deliberately the OPPOSITE of the cleanup-wave guard: there the channels stay
apart because a deletion AUTHORIZATION must never be inferred; here they merge
because a safety fallback must never MISS a touch.

MAJOR -- same-wave conflict detection could not see a deletion. The planner's
implicit-dependency rule compared files_modified only, so plan A editing
src/x.ts and plan B declaring files_deleted: [src/x.ts] scored as conflict-free
and ran in parallel: one branch removing what the other is writing, which is the
sharpest conflict there is. Overlap is now computed across both channels.

MINOR (both reviewers, one root cause) -- the advisory union gave one field two
matching rules. declared_deletions was unioned into the scope list handed to
planWaveScopeConformance, which reads it with prefix-and-glob semantics. So a
field that is exact-match-only at the gate silently became wider at the
advisory: ["*.md"], inert at the gate, yielded a null prefix meaning "matches
everything" and muted the advisory completely, and ["src"] muted all of src/.
The union also activated the advisory on plans that declared no modification
scope at all, warning on every modified path. Replaced with subtraction from the
findings, gated on files_modified alone. One field, one rule, everywhere.

MINOR -- core.quotepath made the feature silently inert for non-ASCII paths.
git emits "tests/\303\251.ts" C-escaped and quoted, which never equals the
declared plain path, so a correctly declared deletion of tests/é.ts would block
forever with nothing pointing at the encoding. Both diffs now pass
-c core.quotepath=false.

NIT -- flag() consumed a following flag as a value, so --deletions --files x
swallowed --files and dropped both. Now treated as a missing declaration, which
fails closed. Fixed at both call sites; the helper is duplicated verbatim in
cmdWorktreeRecordAgent and cmdWorktreeCreate and leaving one would reintroduce it.

TEST -- one test passed for the wrong reason. "a declared deletion is in scope
for the advisory" asserted only that warnings omit the deleted path; under a
full revert the entry blocks first, warnings come back empty, and the negative
assertion passes anyway. It now asserts the entry actually merged, which is the
load-bearing half. Four regressions added, one per fix above.

Docs corrected rather than extended. The rename bullet in the scope-conformance
how-to claimed a rename whose delete side is undeclared never reaches the
advisory. Verified false: git's rename detection is on by default, so a pure
rename is a single R entry that appears in no --diff-filter=D output and was
never gated, before or after #3003. Only a rename that edits enough to fall
below the similarity threshold decomposes into add+delete. The pre-existing
sentence made the same wrong claim; this restates it correctly instead of
sharpening the error. The localized plan-md.md reference edits are reverted:
the PR template requires docs content added here to be English, and the
translations already lag by three fields, so English-only is the repo's
standing posture, not an oversight.

Agent-file size caps respected: gsd-planner.md is XL-tier by bytes but carries a
separate 49152-LF-CHAR cap asserted by four suites, so its edit is deliberately
terse and lands at 49141 with 11 chars of headroom, with the rationale moved to
docs/reference/plan-md.md, which has no cap. gsd-plan-checker.md lands at 49107
bytes, 45 under the LARGE cap. Both acks merged into the existing fragments that
already name those paths, since two ack sources may never name the same path.

* fix(#3003): decode git's path quoting instead of changing the git argv

The previous commit's non-ASCII fix turned the remote suite red: 44 failures,
42 of them "unexpected git call: -c core.quotepath=false diff --diff-filter=D
--name-only ...". The suite's git mocks match on exact argv, so adding two
flags to the deletions diff and the advisory diff invalidated every existing
fixture in tests/worktree-safety.test.cjs. Rewriting dozens of fixtures to
accommodate one flag would be paying a large Hyrum's-law bill to fix a small
defect.

Both execGit calls are reverted to their original argv. The C-quoting is now
decoded in normalizeScopePath instead, via a new decodeGitQuotedPath helper.
That is the better fix on its own merits, not merely the cheaper one: the git
argv is untouched so no fixture moves, the decode lands on the ONE normalizer
already applied to both sides of the comparison so the declared and reported
paths cannot disagree, and it holds regardless of the user's own core.quotepath
setting rather than only when we remember to override it.

A value not wrapped in a leading AND trailing quote is returned completely
untouched, so the plain-ASCII path -- the overwhelmingly common case -- is
byte-identical to before. Escapes decode to BYTES collected into a Buffer and
UTF-8 decoded only at the end, because \303\251 is two bytes forming one
character and decoding them separately yields mojibake. Malformed input never
throws: a trailing lone backslash or a short octal escape degrades to the
literal character, since one bad path must not take down a cleanup wave.

Caught while reviewing the helper: the non-escape branch pushed a UTF-16 code
unit rather than UTF-8 bytes. Git always escapes non-ASCII so its own output was
fine, but this normalizer runs on the DECLARED side too, and an author may write
a quoted path holding a literal é -- pushing 0xE9 alone is invalid UTF-8, so the
declaration would decode to a replacement character and silently stop matching.
That is precisely the failure this change removes, reintroduced on the other
side of the comparison. Now converts whole code points, surrogate pairs intact.

The other 2 failures: tests/parallel-dependent-plans.test.cjs pins the exact
unbackticked substring "files_modified overlap" in gsd-planner.md, and rewording
that comment to "declared-scope overlap" deleted it. The comment is restored
verbatim and the files_deleted change rides in the pseudocode and the Rule
sentence instead. Recorded in the ack fragment so the next contributor does not
rediscover it the same way.

Four regression tests cover the decode through the public cleanup-wave seam
(the helper is module-private): a declared non-ASCII deletion merges against a
C-quoted git report, the symmetric case where the DECLARATION is the quoted
form, an undeclared non-ASCII deletion still blocks with the residue naming the
decoded path an operator can act on, and a path merely containing a quote is
left alone. Plain ASCII was already covered and is not duplicated.

* fix(#3003): revert the leading-dash flag guard, the review nit was wrong

The remote suite came back with 2 failures, down from 44, and both point at the
same thing: tests/worktree-safety.test.cjs:7045 already pins the opposite
contract, deliberately.

  test('a flag-shaped --files value is not re-parsed as a flag', ...)
    recordAgent(['--files', '--branch'])
    -> files_modified === ['--branch']
    -> branch === 'worktree-agent-a1'  ("the real --branch value must be untouched")

So consuming the next argv element positionally, whatever its shape, is the
tested intent of this parser, not an oversight. The security reviewer's nit
claimed --deletions --files x would "swallow --files and drop both". It does
not: each flag runs its own indexOf, so --deletions records the literal
'--files' while --files independently still resolves to x. And that literal is
a path git never reports as deleted, so it authorizes nothing -- already
fail-closed with no guard at all. The guard bought no safety and silently
changed --files behavior along the way, outside this issue's scope.

Reverted at both call sites, which are byte-identical again, along with the test
asserting the reverted behavior and the docs sentence describing it. The nit is
recorded as REJECTED in the review artifact with the reasoning above, rather
than as fixed -- a finding that turns out to be wrong should leave a trace of
why, or the next reviewer files it again.

docs/CLI-TOOLS.md now states the positional-read behavior plainly instead, so
the next person meets it as documented intent rather than rediscovering it
through a red suite.

* chore(#3003): backfill changeset pr number to 3757

* test(#3003): cover parsePlanDocument's filesDeleted branch to clear the mutation gate

CI's Stryker shard for plan-document failed at 73.28 against a break threshold
of 75: 170 killed, 62 survived, 232 total. Eight of those survivors are the
filesDeleted block this issue added to parsePlanDocument, which shipped with no
direct coverage at all -- the field was exercised end to end through the
cleanup-wave tests, but the parser itself was never called with a plan that
declares it, so every mutant in the block lived.

Four tests, each pinned to specific mutants rather than written for coverage
percentage:

- absent key yields exactly [] -- kills the array-literal seed
  (["Stryker was here"]) and the `fmDeleted = true` conditional, which would
  otherwise produce ["true"]
- a scalar underscore `files_deleted:` wraps into a one-element array -- kills
  `fmDeleted = false`, the `&&` logical-operator swap, the `fm[""]` string
  mutation on the first operand, the emptied if-block, and the ternary's
  non-array branch
- an array-valued hyphenated `files-deleted:` maps element-wise -- kills the
  `fm[""]` mutation on the SECOND operand (only reachable when the legacy
  hyphen alias is the one carrying the value) and the ternary's array branch
- an empty list yields [] -- boundary case, and a genuinely distinct one from
  the absent key: [] is truthy in JS so it ENTERS the if, and only
  Array.isArray's true branch mapping over nothing produces the same []

Threshold arithmetic: 174 of 232 are needed for 75%, and these take it to about
178, so the shard clears with margin rather than landing on the line.

Every expected value was confirmed by executing the built parser before being
asserted, not inferred from reading the source.

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-22 13:17:51 -04:00
committed by GitHub
parent 738f42f4fd
commit 2f86278b5e
21 changed files with 661 additions and 44 deletions

View File

@@ -593,6 +593,7 @@ interface RawPlan {
autonomous: boolean;
objective: string | null;
filesModified: string[];
filesDeleted: string[];
taskCount: number;
hasSummary: boolean;
/** #2830: true iff this plan's own SUMMARY declares `status: halted` (a designed stop). */
@@ -826,6 +827,7 @@ function cmdPhasePlanIndex(cwd: string, phase: string, raw: boolean): void {
autonomous: planDoc.autonomous,
objective: planDoc.objective,
filesModified: planDoc.filesModified,
filesDeleted: planDoc.filesDeleted,
agentHint: planDoc.agentHint,
taskCount: planDoc.taskCount,
hasSummary,
@@ -929,6 +931,7 @@ function cmdPhasePlanIndex(cwd: string, phase: string, raw: boolean): void {
autonomous: rawPlan.autonomous,
objective: rawPlan.objective,
files_modified: rawPlan.filesModified,
files_deleted: rawPlan.filesDeleted,
agent_hint: rawPlan.agentHint,
task_count: rawPlan.taskCount,
has_summary: rawPlan.hasSummary,

View File

@@ -79,6 +79,14 @@ interface PlanDocument {
agentHint: string | null;
/** Frontmatter `files_modified` / `files-modified`, normalised to an array. */
filesModified: string[];
/**
* #3003: frontmatter `files_deleted` / `files-deleted`, normalised to an array.
* Paths the plan declares it will REMOVE, so `worktree cleanup-wave`'s deletions
* guard can authorize exactly those and keep blocking anything undeclared.
* OPTIONAL — a plan that omits it declares nothing and keeps the guard's original
* unconditional block.
*/
filesDeleted: string[];
tasks: PlanTask[];
/**
* Legacy count. Invariant: `taskCount === tasks.length`, always. Exposed as
@@ -289,6 +297,13 @@ function parsePlanDocument(content: string, planPath = ''): PlanDocument {
filesModified = Array.isArray(fmFiles) ? fmFiles.map(String) : [String(fmFiles)];
}
let filesDeleted: string[] = [];
const fmDeleted = fm['files_deleted'] || fm['files-deleted'];
if (fmDeleted) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string -- FrontmatterValue scalar-to-string
filesDeleted = Array.isArray(fmDeleted) ? fmDeleted.map(String) : [String(fmDeleted)];
}
let agentHint: string | null = null;
const fmAgentHint = fm['agent_hint'];
if (fmAgentHint !== undefined) {
@@ -304,6 +319,7 @@ function parsePlanDocument(content: string, planPath = ''): PlanDocument {
autonomous,
agentHint,
filesModified,
filesDeleted,
tasks,
taskCount: tasks.length,
};

View File

@@ -486,6 +486,18 @@ interface CleanupManifestEntry {
allowed_bases?: string[];
/** #2596: the plan's declared `files_modified`, when the recorder supplied it. Absent = unknown, never "declares nothing". */
files_modified?: string[];
/**
* #3003: paths the PLAN declared it would delete. The deletions guard blocks only
* deletions NOT in this list. Absent = declares nothing, which keeps the guard's
* original unconditional block — never "authorizes everything".
*
* A path LIST, not a boolean, deliberately: a boolean would disarm the guard for the
* whole entry, so an unexpected deletion riding along with a declared one would pass
* unnoticed. Matching is EXACT after `normalizeScopePath`, never a prefix and never a
* glob — a directory prefix authorizes a mass deletion, which is the precise accident
* this guard exists to catch.
*/
declared_deletions?: string[];
}
function normalizeCleanupManifestEntry(entry: unknown): CleanupManifestEntry | null {
@@ -510,6 +522,12 @@ function normalizeCleanupManifestEntry(entry: unknown): CleanupManifestEntry | n
// would make an unrecorded plan look 100% out of scope.
const filesModified = (Array.isArray(e.files_modified) ? e.files_modified : [])
.filter((f): f is string => typeof f === 'string' && f.trim().length > 0);
// #3003: same liberal-in-what-we-accept rule as `files_modified` above — non-array,
// or non-string / empty elements, are dropped rather than coerced, and an EMPTY
// result omits the field entirely so "declares nothing" stays indistinguishable
// from "not recorded" (the guard's own absence-check already treats both as unknown).
const declaredDeletions = (Array.isArray(e.declared_deletions) ? e.declared_deletions : [])
.filter((f): f is string => typeof f === 'string' && f.trim().length > 0);
const normalized: CleanupManifestEntry = {
agent_id: typeof e.agent_id === 'string' ? e.agent_id : null,
worktree_path: worktreePath,
@@ -518,6 +536,7 @@ function normalizeCleanupManifestEntry(entry: unknown): CleanupManifestEntry | n
allowed_bases: allowedBases,
};
if (filesModified.length > 0) normalized.files_modified = filesModified;
if (declaredDeletions.length > 0) normalized.declared_deletions = declaredDeletions;
return normalized;
}
@@ -634,16 +653,78 @@ function repoRootStillMidMerge(execGit: ExecGitFn, repoRoot: string): boolean {
const SUMMARY_ARTIFACT_DIR = '.planning';
const SUMMARY_ARTIFACT_SUFFIX = 'SUMMARY.md';
/**
* Decode a git-quoted path. With `core.quotepath` left at its default (`true`)
* git wraps any path containing non-ASCII or special bytes in double quotes
* and C-escapes it — e.g. `tests/é.ts` is emitted as the literal
* `"tests/\303\251.ts"`. Both sides of the deletion/scope comparison
* (a declared path and a git-reported path) must agree on the same decoded
* shape, and decoding it here — rather than passing `-c core.quotepath=false`
* on the `execGit` call — keeps the git argv, and therefore every existing
* test fixture that asserts on exact argv, unchanged. It also works
* regardless of the user's own `core.quotepath` config.
*
* A value that is not wrapped in a leading and trailing `"` is returned
* completely untouched — this is the overwhelmingly common (plain ASCII)
* case and must not be altered in any way.
*
* Escapes decode to BYTES, collected into a Buffer and decoded as UTF-8 only
* at the end: `\303\251` is two bytes that together form one character (é),
* so decoding them one at a time would produce mojibake. Malformed input
* (a trailing lone backslash, or an octal escape with fewer than three
* digits) never throws — it degrades to treating the character literally, so
* a single bad path can never take down the whole cleanup wave.
*/
function decodeGitQuotedPath(raw: string): string {
if (raw.length < 2 || !raw.startsWith('"') || !raw.endsWith('"')) return raw;
const body = raw.slice(1, -1);
const bytes: number[] = [];
for (let i = 0; i < body.length; i++) {
const ch = body[i];
if (ch !== '\\' || i === body.length - 1) {
// UTF-8 bytes, not the code unit: a DECLARED path may be quoted while
// still holding a literal `é`, and pushing 0xE9 alone is invalid UTF-8.
// codePointAt keeps a surrogate pair together.
const codePoint = body.codePointAt(i);
const char = codePoint === undefined ? ch : String.fromCodePoint(codePoint);
bytes.push(...Buffer.from(char, 'utf8'));
i += char.length - 1;
continue;
}
const rest = body.slice(i + 1);
const octalMatch = /^([0-3][0-7][0-7])/.exec(rest);
if (octalMatch) {
bytes.push(parseInt(octalMatch[1], 8));
i += 3;
continue;
}
const next = body[i + 1];
const CONTROL_ESCAPES: Record<string, number> = {
a: 0x07, b: 0x08, f: 0x0c, n: 0x0a, r: 0x0d, t: 0x09, v: 0x0b,
'\\': 0x5c, '"': 0x22,
};
if (Object.prototype.hasOwnProperty.call(CONTROL_ESCAPES, next)) {
bytes.push(CONTROL_ESCAPES[next]);
} else {
bytes.push(next.charCodeAt(0));
}
i += 1;
}
return Buffer.from(bytes).toString('utf8');
}
/**
* Normalize one path for scope comparison. Applied to BOTH sides so a declared
* path and a git-reported path meet in the same shape: backslashes become
* slashes unconditionally (a backslash path is not a Windows-only input),
* a leading `./` and any trailing `/` are stripped. This is the single
* normalizer shared by the SUMMARY-artifact predicate and the scope advisory,
* so the two can never disagree about what `./a\b/` means.
* path and a git-reported path meet in the same shape: any git C-quoting is
* decoded first (order matters — the backslash-to-slash conversion below
* would destroy the escape sequences if it ran first), then backslashes
* become slashes unconditionally (a backslash path is not a Windows-only
* input), and a leading `./` and any trailing `/` are stripped. This is the
* single normalizer shared by the SUMMARY-artifact predicate and the scope
* advisory, so the two can never disagree about what `./a\b/` means.
*/
function normalizeScopePath(raw: string): string {
return String(raw || '')
return decodeGitQuotedPath(String(raw || '').trim())
.replace(/\\/g, '/')
.trim()
.replace(/^\.\//, '')
@@ -869,6 +950,42 @@ function planWaveScopeConformance(
return warnings;
}
/**
* #3003: split git's reported deletions into declared and undeclared.
*
* EXACT match after `normalizeScopePath` — the same normalizer both other path
* comparisons in this file use, so a declared path and a git-reported path meet in the
* same shape (`a\b` and `./a/b/` both become `a/b`).
*
* Deliberately NOT `declaredScopePrefix`. That helper returns `null` for a glob-leading
* pattern meaning "matches everything", which is right for the ADVISORY it serves — a
* false alarm there costs more than a miss — and exactly wrong for a GATE, where it would
* let `["*.ts"]` disarm the guard. A glob here is simply a literal path that matches
* nothing. Prefix matching is likewise refused: `["tests"]` must not authorize deleting
* everything under tests/.
*
* Pure — no git, no IO. Returns the undeclared residue in the order git reported it.
*/
function partitionDeclaredDeletions(deletedPaths: unknown, declared: unknown): string[] {
const allowed = new Set(
(Array.isArray(declared) ? declared : [])
.filter((p): p is string => typeof p === 'string')
.map((p) => normalizeScopePath(p))
.filter((p) => p.length > 0),
);
const undeclared: string[] = [];
const seen = new Set<string>();
for (const raw of Array.isArray(deletedPaths) ? deletedPaths : []) {
if (typeof raw !== 'string') continue;
const normalized = normalizeScopePath(raw);
if (!normalized || seen.has(normalized)) continue;
seen.add(normalized);
if (allowed.has(normalized)) continue;
undeclared.push(normalized);
}
return undeclared;
}
interface WaveCleanupEntryResult extends CleanupManifestEntry {
status: string;
reason: string | null;
@@ -950,13 +1067,20 @@ function executeWorktreeWaveCleanupPlan(plan: WaveCleanupPlan | null, deps: Work
continue; // #2852: isolate
}
if (deletions.stdout) {
// Unconditional: any deletion in this entry's branch blocks THIS entry. Whether
// that guard should have an opt-in for intentional deletions is a deferred
// product decision (issue #2852's own triage scoped it out — tracked in #3003);
// this fix only isolates the block to this one entry (#2852) instead of aborting
// the rest of the wave, same as every other block reason below.
blockEntry(result, 'branch_contains_deletions', deletions.stdout);
continue; // #2852: isolate
// #3003: a deletion the PLAN declared is authorized; anything else still blocks.
// Only a SUCCESSFUL check reaches here — a failed one blocked above on its own
// reason, so a broken check can never be filtered into a pass.
//
// The block detail carries ONLY the undeclared residue. Listing declared paths
// there would misdirect the operator toward paths that were fine.
const undeclaredDeletions = partitionDeclaredDeletions(
deletions.stdout.split('\n'),
entry.declared_deletions,
);
if (undeclaredDeletions.length > 0) {
blockEntry(result, 'branch_contains_deletions', undeclaredDeletions.join('\n'));
continue; // #2852: isolate
}
}
// #2596: advisory scope conformance — does the branch's ACTUAL committed
@@ -968,13 +1092,34 @@ function executeWorktreeWaveCleanupPlan(plan: WaveCleanupPlan | null, deps: Work
// ADVISORY ONLY. Unlike the deletions check above, a finding here does NOT
// call blockEntry and does NOT touch `ok` — the merge proceeds. Promotion
// to a hard gate is a separate, disclosed change.
if (Array.isArray(entry.files_modified) && entry.files_modified.length > 0) {
// #3003: a declared deletion is in scope by construction — `git diff --name-only`
// includes deleted paths, so without accounting for the declaration, authorizing a
// deletion would immediately warn that the same path is out of declared scope.
//
// It is SUBTRACTED from the findings rather than UNIONED into the declared scope,
// and the difference is not cosmetic. `planWaveScopeConformance` reads its scope
// list with prefix-and-glob semantics, so unioning would silently hand
// `declared_deletions` a second, WIDER matching rule than the gate gives it:
// `["*.md"]` (inert at the gate) would yield a null prefix meaning "matches
// everything" and mute the advisory entirely, and `["src"]` would mute all of
// `src/`. One field with two matching rules is a trap. Subtracting keeps the
// field exact-match-only on every surface it touches.
//
// Gating stays on `files_modified` alone for the same reason: a plan that declares
// only deletions has still declared no modification scope, so the advisory stays
// exactly as silent as it was before this change instead of warning on every
// modified path.
const declaredFiles = Array.isArray(entry.files_modified) ? entry.files_modified : [];
if (declaredFiles.length > 0) {
const scopeDiff = execGit(['diff', '--name-only', `HEAD...${entry.branch}`], { cwd: plan.repoRoot });
const scopeWarnings: WaveCleanupWarning[] = !gitResultOk(scopeDiff)
// A broken advisory must never become a gate: record that conformance
// is unknown rather than blocking (or, worse, silently passing).
? [{ code: WAVE_CLEANUP_WARNING.SCOPE_CHECK_UNAVAILABLE, branch: entry.branch, path: null }]
: planWaveScopeConformance((scopeDiff.stdout || '').split('\n'), entry.files_modified, entry.branch);
: planWaveScopeConformance((scopeDiff.stdout || '').split('\n'), declaredFiles, entry.branch)
// A path-less warning (SCOPE_CHECK_UNAVAILABLE) is never subtracted.
.filter((w) => w.path === null
|| partitionDeclaredDeletions([w.path], entry.declared_deletions).length > 0);
result.warnings.push(...scopeWarnings);
allWarnings.push(...scopeWarnings);
}
@@ -1117,6 +1262,7 @@ interface RecordAgentFields {
branch: string;
base: string;
files?: string;
deletions?: string;
}
/**
@@ -1184,12 +1330,16 @@ function planWorktreeRecordAgent(manifestRaw: string, fields: RecordAgentFields)
// 2. Shared validation: run the candidate through the reader's normalizer.
// If it returns null the reader would drop this entry on read — reject now.
const declaredScope = parseDeclaredScopeFlag(fields.files);
// #3003: reuse parseDeclaredScopeFlag — a blank/absent --deletions leaves the
// entry shape untouched, mirroring the --files rule directly above.
const declaredDeletions = parseDeclaredScopeFlag(fields.deletions);
const candidate = {
agent_id: agentId,
worktree_path: worktreePath,
branch,
expected_base: base,
...(declaredScope.length > 0 ? { files_modified: declaredScope } : {}),
...(declaredDeletions.length > 0 ? { declared_deletions: declaredDeletions } : {}),
};
const entry = normalizeCleanupManifestEntry(candidate);
if (!entry) {
@@ -1283,6 +1433,11 @@ function planWorktreeRecordAgent(manifestRaw: string, fields: RecordAgentFields)
if (entry.files_modified && entry.files_modified.length > 0) {
recorded.files_modified = entry.files_modified;
}
// #3003: same conservative rule as --files above — a blank --deletions
// leaves the entry shape untouched.
if (entry.declared_deletions && entry.declared_deletions.length > 0) {
recorded.declared_deletions = entry.declared_deletions;
}
worktrees.push(recorded);
return {
@@ -1311,7 +1466,7 @@ interface RecordAgentCmdResult {
/**
* CLI command: append a validated per-agent entry to a wave cleanup manifest.
*
* Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> [--files "<space-separated paths>"]
* Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> [--files "<space-separated paths>"] [--deletions "<space-separated paths>"]
*
* Fails loudly (non-zero exit + recovery hint on stderr) when a field is
* missing/garbled or the manifest is absent/malformed, rather than appending an
@@ -1320,14 +1475,15 @@ interface RecordAgentCmdResult {
function cmdWorktreeRecordAgent(cwd: string, args: string[] = [], deps: RecordAgentCmdDeps = {}): RecordAgentCmdResult {
const flag = (name: string): string => {
const i = args.indexOf(name);
return i >= 0 && i + 1 < args.length ? args[i + 1] : '';
if (i < 0 || i + 1 >= args.length) return '';
return args[i + 1];
};
const write = deps.write || ((s: string) => process.stdout.write(s));
const writeErr = deps.writeErr || ((s: string) => process.stderr.write(s));
const manifestPath = flag('--manifest');
if (!manifestPath) {
writeErr('Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> [--files "<space-separated paths>"]\n');
writeErr('Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> [--files "<space-separated paths>"] [--deletions "<space-separated paths>"]\n');
process.exitCode = 2;
return { ok: false, reason: 'usage', entry: null };
}
@@ -1351,6 +1507,7 @@ function cmdWorktreeRecordAgent(cwd: string, args: string[] = [], deps: RecordAg
branch: flag('--branch'),
base: flag('--base'),
files: flag('--files'),
deletions: flag('--deletions'),
});
if (!plan.ok || plan.manifest === null) {
@@ -1381,6 +1538,7 @@ interface WorktreeCreateFields {
branch: string;
base: string;
files?: string;
deletions?: string;
}
interface WorktreeCreatePlan {
@@ -1419,12 +1577,16 @@ function planWorktreeCreate(fields: WorktreeCreateFields): WorktreeCreatePlan {
}
const declaredScope = parseDeclaredScopeFlag(fields.files);
// #3003: reuse parseDeclaredScopeFlag — a blank/absent --deletions leaves the
// entry shape untouched, mirroring the --files rule directly above.
const declaredDeletions = parseDeclaredScopeFlag(fields.deletions);
const candidate = {
agent_id: agentId,
worktree_path: worktreePath,
branch,
expected_base: base,
...(declaredScope.length > 0 ? { files_modified: declaredScope } : {}),
...(declaredDeletions.length > 0 ? { declared_deletions: declaredDeletions } : {}),
};
const entry = normalizeCleanupManifestEntry(candidate);
if (!entry) {
@@ -1581,7 +1743,7 @@ interface WorktreeCreateCmdResult {
* validated manifest entry so the worktree is immediately manageable by
* `worktree cleanup-wave` / `worktree reap-orphans`.
*
* Usage: worktree create --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> --root <dir> [--files "<space-separated paths>"]
* Usage: worktree create --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> --root <dir> [--files "<space-separated paths>"] [--deletions "<space-separated paths>"]
*
* #2584 FIX 1 — ORDERING CONTRACT: every manifest read/parse/shape-validate/
* plan step runs BEFORE the git side effect (step 5). The ONLY manifest
@@ -1595,14 +1757,15 @@ interface WorktreeCreateCmdResult {
function cmdWorktreeCreate(cwd: string, args: string[] = [], deps: RecordAgentCmdDeps & WorktreeDeps = {}): WorktreeCreateCmdResult {
const flag = (name: string): string => {
const i = args.indexOf(name);
return i >= 0 && i + 1 < args.length ? args[i + 1] : '';
if (i < 0 || i + 1 >= args.length) return '';
return args[i + 1];
};
const write = deps.write || ((s: string) => process.stdout.write(s));
const writeErr = deps.writeErr || ((s: string) => process.stderr.write(s));
const manifestPath = flag('--manifest');
if (!manifestPath) {
writeErr('Usage: worktree create --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> --root <dir> [--files "<space-separated paths>"]\n');
writeErr('Usage: worktree create --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha> --root <dir> [--files "<space-separated paths>"] [--deletions "<space-separated paths>"]\n');
process.exitCode = 2;
return { ok: false, reason: 'usage' };
}
@@ -1667,6 +1830,7 @@ function cmdWorktreeCreate(cwd: string, args: string[] = [], deps: RecordAgentCm
branch: flag('--branch'),
base: flag('--base'),
files: flag('--files'),
deletions: flag('--deletions'),
});
if (!plan.ok || !plan.entry) {
@@ -1741,6 +1905,11 @@ function cmdWorktreeCreate(cwd: string, args: string[] = [], deps: RecordAgentCm
if (Array.isArray(plan.entry.files_modified) && plan.entry.files_modified.length > 0) {
recorded.files_modified = plan.entry.files_modified;
}
// #3003: same conservative rule as --files above — a blank --deletions
// leaves the entry shape untouched.
if (Array.isArray(plan.entry.declared_deletions) && plan.entry.declared_deletions.length > 0) {
recorded.declared_deletions = plan.entry.declared_deletions;
}
const dedupeKey = `${recorded.worktree_path}\0${recorded.branch}`;
const alreadyPresent = worktrees.some((existing) => {
const normalized = normalizeCleanupManifestEntry(existing);