opencode-workflow-guard 1.20.1 → 1.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -126,6 +126,60 @@ function todoTaskLabel(todo: TodoItem): string {
126
126
  return String(todo.content ?? "").trim();
127
127
  }
128
128
 
129
+ /**
130
+ * A task key's distinct word tokens, lowercased.
131
+ *
132
+ * Refinement is judged on these tokens. A reworded task keeps every token of
133
+ * its predecessor and adds at least one. Punctuation and repeated words carry
134
+ * no weight, so only a real addition widens the set.
135
+ */
136
+ export function todoTaskTokens(key: string): Set<string> {
137
+ return new Set(key.toLowerCase().match(/[a-z0-9][a-z0-9'_-]*/g) ?? []);
138
+ }
139
+
140
+ /**
141
+ * True when `successor` is `predecessor` plus wording: every distinct token of
142
+ * the predecessor survives and the successor carries more. That is the same
143
+ * work item sharpened, not a different task. Two distinct tokens is the floor,
144
+ * so a one-word task always needs an exact match.
145
+ */
146
+ export function isTodoRefinement(predecessor: string, successor: string): boolean {
147
+ const before = todoTaskTokens(predecessor);
148
+ const after = todoTaskTokens(successor);
149
+ if (before.size < 2 || after.size <= before.size) return false;
150
+ for (const token of before) if (!after.has(token)) return false;
151
+ return true;
152
+ }
153
+
154
+ /**
155
+ * The active successor that carries a removed task's wording, or undefined.
156
+ *
157
+ * `available` bounds each successor to one predecessor, so two removed tasks
158
+ * cannot both hide behind one retained task. The caller spends the claim.
159
+ */
160
+ function findTodoRefinementSuccessor(
161
+ predecessorKey: string,
162
+ successors: TodoItem[],
163
+ available: Map<string, number>,
164
+ ): TodoItem | undefined {
165
+ if (todoTaskTokens(predecessorKey).size < 2) return undefined;
166
+ for (const todo of successors) {
167
+ const key = todoTaskKey(todo);
168
+ if (!key || (available.get(key) ?? 0) <= 0) continue;
169
+ if (!isTodoRefinement(predecessorKey, key)) continue;
170
+ return todo;
171
+ }
172
+ return undefined;
173
+ }
174
+
175
+ /** A removed active task and the active successor that carries its wording. */
176
+ export interface TodoRefinement {
177
+ from: string;
178
+ to: string;
179
+ fromKey: string;
180
+ toKey: string;
181
+ }
182
+
129
183
  /**
130
184
  * Record when each active task entered its current active window, in the
131
185
  * session's mutation count. Completion evidence is judged against this.
@@ -138,11 +192,22 @@ export function recordTodoTaskStarts(
138
192
  previousTodos: TodoItem[] | undefined,
139
193
  nextTodos: TodoItem[],
140
194
  mutationCount: number,
195
+ refinements: TodoRefinement[] = [],
141
196
  ): void {
142
197
  const previouslyActive = new Set<string>();
143
198
  for (const todo of previousTodos ?? []) {
144
199
  if (ACTIVE_TODO_STATUSES.has(String(todo.status ?? ""))) previouslyActive.add(todoTaskKey(todo));
145
200
  }
201
+ // A reworded task is the same work item, so it keeps the mutations already
202
+ // recorded for its predecessor instead of starting a fresh window. The
203
+ // pairing comes from the accepted lifecycle verdict, so one predecessor's
204
+ // window can move at most once and cannot be guessed twice.
205
+ const carried = new Map<string, number>();
206
+ for (const refinement of refinements) {
207
+ if (!starts.has(refinement.fromKey)) continue;
208
+ if (previouslyActive.has(refinement.toKey) || starts.has(refinement.toKey)) continue;
209
+ carried.set(refinement.toKey, starts.get(refinement.fromKey)!);
210
+ }
146
211
  const live = new Set<string>();
147
212
  for (const todo of nextTodos) {
148
213
  const key = todoTaskKey(todo);
@@ -152,7 +217,7 @@ export function recordTodoTaskStarts(
152
217
  // A task keeps its original window across rewrites and status
153
218
  // changes within the active set. A task returning to active after
154
219
  // finishing starts a fresh window.
155
- if (!previouslyActive.has(key) || !starts.has(key)) starts.set(key, mutationCount);
220
+ if (!previouslyActive.has(key) || !starts.has(key)) starts.set(key, carried.get(key) ?? mutationCount);
156
221
  }
157
222
  }
158
223
  // Finished or dropped tasks close their window; a later task with the
@@ -184,6 +249,7 @@ export function unverifiedTodoCompletions(
184
249
  nextTodos: TodoItem[],
185
250
  starts: Map<string, number>,
186
251
  mutationCount: number,
252
+ refinements: TodoRefinement[] = [],
187
253
  ): string[] {
188
254
  // Each prior occurrence can absorb at most one new item of the same key. A
189
255
  // prior `completed` occurrence absorbs a new `completed` item silently; any
@@ -198,6 +264,12 @@ export function unverifiedTodoCompletions(
198
264
  absorbCompleted.set(key, (absorbCompleted.get(key) ?? 0) + 1);
199
265
  }
200
266
  }
267
+ // Completion evidence is judged before the window map moves, so a reworded
268
+ // task reads its predecessor's start from the same accepted pairing.
269
+ const inheritedStarts = new Map<string, number>();
270
+ for (const refinement of refinements) {
271
+ if (starts.has(refinement.fromKey)) inheritedStarts.set(refinement.toKey, starts.get(refinement.fromKey)!);
272
+ }
201
273
 
202
274
  const claimed: Array<{ task: string; start: number }> = [];
203
275
  for (const todo of nextTodos) {
@@ -215,7 +287,8 @@ export function unverifiedTodoCompletions(
215
287
  const remaining = absorbable.get(key) ?? 0;
216
288
  if (remaining > 0) absorbable.set(key, remaining - 1);
217
289
  if (isReadOnlyTodo(todo)) continue;
218
- claimed.push({ task: todoTaskLabel(todo), start: starts.get(key) ?? 0 });
290
+ const start = starts.get(key) ?? inheritedStarts.get(key) ?? 0;
291
+ claimed.push({ task: todoTaskLabel(todo), start });
219
292
  }
220
293
 
221
294
  if (claimed.length === 0) return [];
@@ -309,64 +382,97 @@ export async function todoEvidenceReport(sessionID: string | undefined): Promise
309
382
  };
310
383
  }
311
384
 
312
- export function validateTodoLifecycle(
385
+ export interface TodoLifecycleVerdict {
386
+ error?: string;
387
+ refinements: TodoRefinement[];
388
+ }
389
+
390
+ /**
391
+ * The full lifecycle verdict: what would block the write, and which removed
392
+ * active tasks were accepted as refinements. `validateTodoLifecycle` keeps the
393
+ * string-only shape for callers that only need the gate.
394
+ */
395
+ export function inspectTodoLifecycle(
313
396
  newTodos: TodoItem[],
314
397
  existingTodos: TodoItem[] | undefined,
315
- ): string | undefined {
398
+ ): TodoLifecycleVerdict {
399
+ const refinements: TodoLifecycleVerdict["refinements"] = [];
316
400
  // Rule: No silent task deletion while active work remains
317
401
  // (single-focus rule removed: multiple tasks may be in_progress to allow
318
402
  // concurrent subagent work on different tasks)
319
- if (existingTodos && existingTodos.length > 0) {
320
- const activeExisting = existingTodos.filter((t) => {
321
- const s = String(t.status ?? "");
322
- return s === "pending" || s === "in_progress";
323
- });
324
- if (activeExisting.length > 0) {
325
- const activeNew = newTodos.filter((t) => ACTIVE_TODO_STATUSES.has(String(t.status ?? "")));
326
- const reviewObligation = /\b(?:secondary\s+review|re-?review|reviewer|(?:run|perform|request|obtain|complete)\s+(?:an?\s+)?review)\b/i;
327
- const remediationAction = /\b(?:address|fix|resolve|remediate)\b/i;
328
- const reviewReference = /\b(?:secondary\s+review|re-?review|reviewer|review)\b/i;
329
- const remediationSubject = /\b(?:findings?|feedback|comments?|issues?)\b/i;
330
- const isReviewObligation = (content: string) => reviewObligation.test(content) && !(remediationAction.test(content) && reviewReference.test(content) && remediationSubject.test(content));
331
- const newContentCounts = new Map<string, number>();
332
- for (const todo of newTodos) {
333
- const content = todoTaskKey(todo);
334
- newContentCounts.set(content, (newContentCounts.get(content) ?? 0) + 1);
335
- }
336
- const retainedReviewCounts = new Map<string, number>();
337
- for (const todo of activeNew) {
338
- const content = todoTaskKey(todo);
339
- retainedReviewCounts.set(content, (retainedReviewCounts.get(content) ?? 0) + 1);
340
- }
341
- let retainedReviewObligations = 0;
342
- for (const todo of activeExisting) {
343
- const content = todoTaskKey(todo);
344
- const remaining = retainedReviewCounts.get(content) ?? 0;
345
- if (remaining > 0 && isReviewObligation(content)) {
346
- retainedReviewCounts.set(content, remaining - 1);
347
- retainedReviewObligations++;
348
- }
403
+ if (!existingTodos || existingTodos.length === 0) return { refinements };
404
+ const activeExisting = existingTodos.filter((t) => {
405
+ const s = String(t.status ?? "");
406
+ return s === "pending" || s === "in_progress";
407
+ });
408
+ if (activeExisting.length === 0) return { refinements };
409
+ const activeNew = newTodos.filter((t) => ACTIVE_TODO_STATUSES.has(String(t.status ?? "")));
410
+ const reviewObligation = /\b(?:secondary\s+review|re-?review|reviewer|(?:run|perform|request|obtain|complete)\s+(?:an?\s+)?review)\b/i;
411
+ const remediationAction = /\b(?:address|fix|resolve|remediate)\b/i;
412
+ const reviewReference = /\b(?:secondary\s+review|re-?review|reviewer|review)\b/i;
413
+ const remediationSubject = /\b(?:findings?|feedback|comments?|issues?)\b/i;
414
+ const isReviewObligation = (content: string) => reviewObligation.test(content) && !(remediationAction.test(content) && reviewReference.test(content) && remediationSubject.test(content));
415
+ const newContentCounts = new Map<string, number>();
416
+ for (const todo of newTodos) {
417
+ const content = todoTaskKey(todo);
418
+ newContentCounts.set(content, (newContentCounts.get(content) ?? 0) + 1);
419
+ }
420
+ // Each active occurrence can absorb one predecessor. An exact-text match
421
+ // spends its own occurrence above, so it cannot also hide reworded work.
422
+ const successorCounts = new Map<string, number>();
423
+ for (const todo of activeNew) {
424
+ const content = todoTaskKey(todo);
425
+ if (content) successorCounts.set(content, (successorCounts.get(content) ?? 0) + 1);
426
+ }
427
+ const retainedReviewCounts = new Map<string, number>();
428
+ for (const todo of activeNew) {
429
+ const content = todoTaskKey(todo);
430
+ retainedReviewCounts.set(content, (retainedReviewCounts.get(content) ?? 0) + 1);
431
+ }
432
+ let retainedReviewObligations = 0;
433
+ for (const todo of activeExisting) {
434
+ const content = todoTaskKey(todo);
435
+ const remaining = retainedReviewCounts.get(content) ?? 0;
436
+ if (remaining > 0 && isReviewObligation(content)) {
437
+ retainedReviewCounts.set(content, remaining - 1);
438
+ retainedReviewObligations++;
439
+ }
440
+ }
441
+ let replacementReviewObligations = activeNew.filter((t) => isReviewObligation(todoTaskKey(t))).length - retainedReviewObligations;
442
+ const missing = activeExisting.find((todo) => {
443
+ const content = todoTaskKey(todo);
444
+ const remaining = newContentCounts.get(content) ?? 0;
445
+ if (remaining === 0) {
446
+ if (isReviewObligation(content) && replacementReviewObligations > 0) {
447
+ replacementReviewObligations--;
448
+ return false;
349
449
  }
350
- let replacementReviewObligations = activeNew.filter((t) => isReviewObligation(todoTaskKey(t))).length - retainedReviewObligations;
351
- const missing = activeExisting.find((todo) => {
352
- const content = todoTaskKey(todo);
353
- const remaining = newContentCounts.get(content) ?? 0;
354
- if (remaining === 0 && isReviewObligation(content) && replacementReviewObligations > 0) {
355
- replacementReviewObligations--;
356
- return false;
357
- }
358
- if (remaining === 0) return true;
359
- newContentCounts.set(content, remaining - 1);
450
+ const successor = findTodoRefinementSuccessor(content, activeNew, successorCounts);
451
+ if (successor) {
452
+ const successorKey = todoTaskKey(successor);
453
+ successorCounts.set(successorKey, (successorCounts.get(successorKey) ?? 0) - 1);
454
+ refinements.push({ from: todoTaskLabel(todo), to: todoTaskLabel(successor), fromKey: content, toKey: successorKey });
360
455
  return false;
361
- });
362
- if (missing) {
363
- return (
364
- `Blocked todowrite: active task '${String(missing.content ?? "")}' was removed ` +
365
- "without being marked completed or cancelled. Tasks cannot silently disappear."
366
- );
367
456
  }
457
+ return true;
368
458
  }
369
- }
459
+ newContentCounts.set(content, remaining - 1);
460
+ const availableSuccessors = successorCounts.get(content) ?? 0;
461
+ if (availableSuccessors > 0) successorCounts.set(content, availableSuccessors - 1);
462
+ return false;
463
+ });
464
+ if (!missing) return { refinements };
465
+ return {
466
+ refinements,
467
+ error:
468
+ `Blocked todowrite: active task '${String(missing.content ?? "")}' was removed ` +
469
+ "without being marked completed or cancelled. Tasks cannot silently disappear.",
470
+ };
471
+ }
370
472
 
371
- return undefined;
473
+ export function validateTodoLifecycle(
474
+ newTodos: TodoItem[],
475
+ existingTodos: TodoItem[] | undefined,
476
+ ): string | undefined {
477
+ return inspectTodoLifecycle(newTodos, existingTodos).error;
372
478
  }
@@ -325,6 +325,7 @@ import {
325
325
  findWorktreeForBranch,
326
326
  parseGitInvocation,
327
327
  prSourceBranch,
328
+ purgesMergedRemoteBranches,
328
329
  } from "./policies/git.ts";
329
330
 
330
331
  export {
@@ -335,6 +336,7 @@ export {
335
336
  findWorktreeForBranch,
336
337
  parseGitInvocation,
337
338
  prSourceBranch,
339
+ purgesMergedRemoteBranches,
338
340
  };
339
341
 
340
342
  import {
@@ -401,6 +403,7 @@ export { isResearchTool, liveDocsGatingReason };
401
403
 
402
404
  export { sendDesktopNotification } from "./policies/shell-safety.ts";
403
405
  export { checkInteractiveTtyCommand, checkPackageHygiene, escapeAppleScriptString };
406
+ export { shellHasSudoWrapper } from "./lib/shell.ts";
404
407
 
405
408
  function logObservation(client: unknown, message: string): void {
406
409
  try {
package/test/test.mts CHANGED
@@ -89,6 +89,7 @@ import {
89
89
  stripJsonComments,
90
90
  extractInterpreterPayload,
91
91
  isBranchAlreadyMergedOrClosed,
92
+ purgesMergedRemoteBranches,
92
93
  checkMergeConflicts,
93
94
  checkBranchBaseIsUpToDate,
94
95
  findWorktreeForBranch,
@@ -110,6 +111,7 @@ import {
110
111
  getSubagentMutationBudget,
111
112
  isReadOnlyRole,
112
113
  checkInteractiveTtyCommand,
114
+ shellHasSudoWrapper,
113
115
  checkPackageHygiene,
114
116
  delegationSpawnIn,
115
117
  sendDesktopNotification,
@@ -153,7 +155,7 @@ import { WorkflowGuardTui, WorkflowGuardTuiV2, formatBadge, readProjectOption, r
153
155
  import { scanSessionTodos, toolPartName, detectTodoCapability, recordedTodoCapability, recordTodoCapability, reportTodoGateFailOpen, resetTodoCapabilityForTesting } from "../src/lib/v2-todo.ts";
154
156
  import { buildPolicyPosture, renderPolicyPosture } from "../src/lib/policy-posture.ts";
155
157
  import { pluginKeyFor, preparePluginUpdate } from "../src/lib/config-writer.mjs";
156
- import { effectiveTodosWithOwner, isReadOnlyTodo, readOnlyTodoCompletions, recordTodoTaskStarts, todoEvidenceReport, unverifiedTodoCompletions, validateTodoLifecycle } from "../src/policies/todo.ts";
158
+ import { effectiveTodosWithOwner, inspectTodoLifecycle, isReadOnlyTodo, readOnlyTodoCompletions, recordTodoTaskStarts, todoEvidenceReport, unverifiedTodoCompletions, validateTodoLifecycle } from "../src/policies/todo.ts";
157
159
  import {
158
160
  LiveDocsResearchFloor,
159
161
  clearLiveDocsFloor,
@@ -412,6 +414,58 @@ check("completion evidence: a task that is only the marker has no identity and i
412
414
  check("lifecycle: appending the read-only marker to a planned task is not a silent deletion", !validateTodoLifecycle([item("Review the diff [read-only]", "completed")], [item("Review the diff", "in_progress")]));
413
415
  check("lifecycle: appending the marker to a still-active task retains it", !validateTodoLifecycle([item("Review the diff [read-only]", "in_progress")], [item("Review the diff", "in_progress")]));
414
416
 
417
+ // A sharpened task is the same work item, not a dropped one. A removed active
418
+ // task whose tokens all survive in an active successor is a refinement. The
419
+ // three shapes below are lifted from the audit journal's todo_lifecycle reasons.
420
+ check("lifecycle: added wording in a reworded task is a refinement", !validateTodoLifecycle([item("Verify the doc change, pass review, and open its PR", "in_progress")], [item("Verify the doc change and open its PR", "in_progress")]));
421
+ check("lifecycle: a reworded PR task with a new preposition is a refinement", !validateTodoLifecycle([item("Push the branch, open PR for #245 with Fixes #245", "in_progress")], [item("Push the branch, open PR #245 with Fixes #245", "in_progress")]));
422
+ check("lifecycle: a prefixed clause on an existing task is a refinement", !validateTodoLifecycle([item("Re-run review, record verdict, open PR for issue #42 and clean up the branch", "in_progress")], [item("Open PR for issue #42 and clean up the branch", "in_progress")]));
423
+ // The strict boundary still holds: no token superset means no refinement.
424
+ check("lifecycle: an unrelated equal-length replacement still blocks", !!validateTodoLifecycle([item("Run the test suite", "in_progress")], [item("Write the release notes", "in_progress")]));
425
+ check("lifecycle: a removed task with no successor still blocks", !!validateTodoLifecycle([item("other work", "in_progress")], [item("Write the release notes", "in_progress")]));
426
+ check("lifecycle: a one-word reword stays strict", !!validateTodoLifecycle([item("tests", "in_progress")], [item("tests please", "in_progress")]));
427
+ check("lifecycle: one successor cannot absorb two removed tasks", !!validateTodoLifecycle([item("deploy the service", "in_progress")], [item("write the fix, then deploy the service", "in_progress"), item("deploy the service", "in_progress")]));
428
+
429
+ // A refinement keeps the predecessor's mutation window, so recorded work still
430
+ // vouches for the reworded task. The pairing is the lifecycle verdict's, so the
431
+ // window carry and the completion gate cannot disagree about it.
432
+ const refinePrev = [item("Verify the doc change and open its PR", "in_progress")];
433
+ const refineNext = [item("Verify the doc change, pass review, and open its PR", "in_progress")];
434
+ const refinePairing = inspectTodoLifecycle(refineNext, refinePrev).refinements;
435
+ check("lifecycle: the refinement verdict names its predecessor and successor", refinePairing.length === 1 && refinePairing[0]!.from === "Verify the doc change and open its PR" && refinePairing[0]!.to === "Verify the doc change, pass review, and open its PR");
436
+ const refineStarts = new Map<string, number>();
437
+ recordTodoTaskStarts(refineStarts, undefined, refinePrev, 0);
438
+ recordTodoTaskStarts(refineStarts, refinePrev, refineNext, 3, refinePairing);
439
+ check("refinement: the reworded task inherits the predecessor's window", refineStarts.get("Verify the doc change, pass review, and open its PR") === 0 && !refineStarts.has("Verify the doc change and open its PR"));
440
+ const refinedComplete = [item("Verify the doc change, pass review, and open its PR", "completed")];
441
+ check("refinement: the carried window vouches for the refined completion", unverifiedTodoCompletions(refinePrev, refinedComplete, refineStarts, 1, refinePairing).length === 0);
442
+ const preCarry = new Map([["Verify the doc change and open its PR", 2]]);
443
+ check("refinement: completion evidence sees the inherited window before the map moves", unverifiedTodoCompletions(refinePrev, refinedComplete, preCarry, 3, refinePairing).length === 0);
444
+ check("refinement: a carried window still needs a mutation inside it", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, preCarry, 2, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
445
+ const lateCarry = new Map([["Verify the doc change and open its PR", 5]]);
446
+ check("refinement: mutations before the inherited window never count", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, lateCarry, 5, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
447
+ check("refinement: a reword with no recorded work does not complete freely", JSON.stringify(unverifiedTodoCompletions(refinePrev, refinedComplete, new Map(), 0, refinePairing)) === JSON.stringify(["Verify the doc change, pass review, and open its PR"]));
448
+
449
+ // One predecessor cannot carry its window to two successors. The verdict pairs
450
+ // it once, and the window map follows that pairing rather than guessing again.
451
+ const splitPrev = [item("add the retry loop", "in_progress")];
452
+ const splitNext = [item("add the retry loop for uploads", "in_progress"), item("add the retry loop for downloads", "in_progress")];
453
+ const splitPairing = inspectTodoLifecycle(splitNext, splitPrev).refinements;
454
+ check("lifecycle: one predecessor pairs with one successor", splitPairing.length === 1 && splitPairing[0]!.toKey === "add the retry loop for uploads");
455
+ const splitStarts = new Map([["add the retry loop", 4]]);
456
+ recordTodoTaskStarts(splitStarts, splitPrev, splitNext, 9, splitPairing);
457
+ check("refinement: one predecessor's window carries to one successor only", splitStarts.get("add the retry loop for uploads") === 4 && splitStarts.get("add the retry loop for downloads") === 9);
458
+
459
+ // Two predecessors and two successors pair one-to-one, so neither window is
460
+ // guessed from the other. Each successor is matched by its own tokens.
461
+ const pairPrev = [item("write the parser", "in_progress"), item("run the parser tests", "in_progress")];
462
+ const pairNext = [item("write the parser and add fixtures", "in_progress"), item("run the parser tests and triage failures", "in_progress")];
463
+ const pairVerdict = inspectTodoLifecycle(pairNext, pairPrev).refinements;
464
+ check("lifecycle: two reworded tasks pair with two distinct successors", pairVerdict.length === 2 && new Set(pairVerdict.map((r) => r.fromKey)).size === 2 && new Set(pairVerdict.map((r) => r.toKey)).size === 2);
465
+ const pairStarts = new Map([["write the parser", 1], ["run the parser tests", 6]]);
466
+ recordTodoTaskStarts(pairStarts, pairPrev, pairNext, 8, pairVerdict);
467
+ check("refinement: each predecessor's window moves to its own successor", pairStarts.get("write the parser and add fixtures") === 1 && pairStarts.get("run the parser tests and triage failures") === 6);
468
+
415
469
  // Marker escape, and the transitions that are not new claims.
416
470
  check("completion evidence: the read-only marker is recognized", isReadOnlyTodo(item("Review the diff [read-only]", "completed")) && !isReadOnlyTodo(item("Review the diff", "completed")));
417
471
  check("completion evidence: a marked read-only task completes with no mutation", unverifiedTodoCompletions([item("Review the diff [read-only]", "in_progress")], [item("Review the diff [read-only]", "completed")], new Map(), 0).length === 0);
@@ -448,6 +502,15 @@ const auditBeforeBlocked = getRecentAuditEntries(50).filter((entry) => entry.rea
448
502
  await call("todowrite", { todos: [item("real work [read-only]", "completed"), item("brand new", "completed")] }, { sessionID: "s-evidence-audit-order" });
449
503
  check("a blocked todowrite does not journal a read-only completion", getRecentAuditEntries(50).filter((entry) => entry.reason === "todo_completed_read_only").length === auditBeforeBlocked);
450
504
 
505
+ // End to end: reworded work passes the lifecycle gate and leaves a trail, while
506
+ // a genuine removal is still refused.
507
+ todo("s-refine", item("Verify the doc change and open its PR", "in_progress"));
508
+ check("dispatcher allows a reworded active task", !(await call("todowrite", { todos: [item("Verify the doc change, pass review, and open its PR", "in_progress")] }, { sessionID: "s-refine" })));
509
+ const refineAudit = getRecentAuditEntries(50).filter((entry) => entry.reason === "todo_refined");
510
+ check("dispatcher journals the refinement", refineAudit.length > 0 && JSON.stringify((refineAudit.at(-1)?.input as { refinements?: unknown })?.refinements) === JSON.stringify([{ from: "Verify the doc change and open its PR", to: "Verify the doc change, pass review, and open its PR" }]));
511
+ todo("s-refine-drop", item("Write the release notes", "in_progress"));
512
+ check("dispatcher still blocks a genuine task removal", blocked(await call("todowrite", { todos: [item("Publish the release", "in_progress")] }, { sessionID: "s-refine-drop" })));
513
+
451
514
  // guard_status surfaces the requirement before it bites.
452
515
  todo("s-evidence-report", item("write the fix", "in_progress"), item("Review the diff [read-only]", "in_progress"), item("done already", "completed"));
453
516
  const evidenceReport = await todoEvidenceReport("s-evidence-report");
@@ -888,6 +951,69 @@ setWorkspaceRoot(ffLocalRepo);
888
951
  check("on main: pull --ff-only from a local upstream branch stays blocked", blocked(await shell("git pull --ff-only")));
889
952
  check("on main: merge --ff-only from the local upstream stays blocked", blocked(await shell("git merge --ff-only")));
890
953
  rmSync(ffLocalBase, { recursive: true, force: true });
954
+ // The cleanup a merged PR requires used to be impossible for the agent: both
955
+ // halves were blocked whenever the checkout sat on the protected branch that
956
+ // received the merge. A merged-only delete publishes no commit, so it is
957
+ // exempt, and every form that could drop unmerged commits stays blocked.
958
+ const cleanupBase = mkdtempSync(join(tmpdir(), "wg-cleanup-"));
959
+ const cleanupRemote = join(cleanupBase, "remote.git");
960
+ const cleanupRepo = join(cleanupBase, "repo");
961
+ spawnSync("git", ["init", "--bare", "-b", "main", cleanupRemote]);
962
+ spawnSync("git", ["init", "-b", "main", cleanupRepo]);
963
+ writeFileSync(join(cleanupRepo, "a.txt"), "a\n");
964
+ ffGit("-C", cleanupRepo, "add", "a.txt");
965
+ ffGit("-C", cleanupRepo, "commit", "-m", "init");
966
+ ffGit("-C", cleanupRepo, "remote", "add", "origin", cleanupRemote);
967
+ ffGit("-C", cleanupRepo, "push", "-u", "origin", "main");
968
+ ffGit("-C", cleanupRepo, "branch", "feat/merged");
969
+ ffGit("-C", cleanupRepo, "push", "origin", "feat/merged");
970
+ ffGit("-C", cleanupRepo, "switch", "-c", "feat/unmerged");
971
+ writeFileSync(join(cleanupRepo, "b.txt"), "b\n");
972
+ ffGit("-C", cleanupRepo, "add", "b.txt");
973
+ ffGit("-C", cleanupRepo, "commit", "-m", "unmerged work");
974
+ ffGit("-C", cleanupRepo, "switch", "main");
975
+ ffGit("-C", cleanupRepo, "fetch", "origin");
976
+ setWorkspaceRoot(cleanupRepo);
977
+ check("on main: branch -d of a merged branch allowed", !blocked(await shell("git branch -d feat/merged")));
978
+ check("on main: branch --delete of a merged branch allowed", !blocked(await shell("git branch --delete feat/merged")));
979
+ check("on main: branch -D stays blocked", blocked(await shell("git branch -D feat/merged")));
980
+ check("on main: branch -d --force stays blocked", blocked(await shell("git branch -d --force feat/merged")));
981
+ check("on main: branch -d of a protected name stays blocked", blocked(await shell("git branch -d main")));
982
+ check("on main: branch --delete of a protected name stays blocked", blocked(await shell("git branch --delete main")));
983
+ check("on main: branch --delete --force stays blocked", blocked(await shell("git branch --delete --force feat/merged")));
984
+ check("on main: branch -fd stays blocked", blocked(await shell("git branch -fd feat/merged")));
985
+ check("on main: branch -rd of a merged branch allowed", !blocked(await shell("git branch -rd feat/merged")));
986
+ check("on main: branch -d with no branch named stays blocked", blocked(await shell("git branch -d")));
987
+ check("on main: ordinary push still blocked from the protected checkout", blocked(await shell("git push origin feat/merged")));
988
+ check("on main: delete of a merged remote branch allowed", !blocked(await shell("git push origin --delete feat/merged")));
989
+ check("on main: :refs/heads delete of a merged remote branch allowed", !blocked(await shell("git push origin :refs/heads/feat/merged")));
990
+ check("on main: delete of an unmerged remote branch blocked", blocked(await shell("git push origin --delete feat/unmerged")));
991
+ check("on main: :refspec delete of an unmerged remote branch blocked", blocked(await shell("git push origin :feat/unmerged")));
992
+ check("on main: delete of a protected remote branch blocked", blocked(await shell("git push origin --delete main")));
993
+ check("on main: push --prune stays blocked", blocked(await shell("git push origin --prune")));
994
+ check("on main: push --mirror stays blocked", blocked(await shell("git push --mirror origin")));
995
+ check("purge helper rejects a plain refspec", !purgesMergedRemoteBranches("git push origin feat/merged", cleanupRepo));
996
+ check("purge helper accepts a merged delete", purgesMergedRemoteBranches("git push origin --delete feat/merged", cleanupRepo));
997
+ check("purge helper rejects a tag refspec", !purgesMergedRemoteBranches("git push origin :refs/tags/feat/merged", cleanupRepo));
998
+ // A tag that shares the branch namespace must not satisfy the merged check.
999
+ // The helper names refs/heads and refs/remotes/origin explicitly, so the tag
1000
+ // alone resolves to nothing and the deletion stays blocked.
1001
+ ffGit("-C", cleanupRepo, "tag", "feat/onlytag", "main");
1002
+ check("purge helper rejects a tag short name with no branch of that name", !purgesMergedRemoteBranches("git push origin :feat/onlytag", cleanupRepo));
1003
+ check("on main: delete of a tag short name with no branch stays blocked", blocked(await shell("git push origin --delete feat/onlytag")));
1004
+ ffGit("-C", cleanupRepo, "branch", "-D", "feat/merged");
1005
+ check("on main: delete of a merged branch whose local ref is gone allowed", !blocked(await shell("git push origin --delete feat/merged")));
1006
+ // A configured protected name is protected here too, so the cleanup
1007
+ // exemption cannot become a way around `protectedBranches`.
1008
+ mkdirSync(join(cleanupRepo, ".opencode"), { recursive: true });
1009
+ writeFileSync(join(cleanupRepo, ".opencode", "workflow-guard.json"), JSON.stringify({ protectedBranches: ["feat/merged"] }));
1010
+ reloadProjectConfig(cleanupRepo);
1011
+ check("on main: branch -d of a configured protected branch blocked", blocked(await shell("git branch -d feat/merged")));
1012
+ check("on main: delete of a configured protected remote branch blocked", blocked(await shell("git push origin --delete feat/merged")));
1013
+ // The exemption must not become a way around the destination-side rule that
1014
+ // protects a configured branch from ordinary pushes.
1015
+ check("on main: ordinary push to a configured protected branch blocked", blocked(await shell("git push origin feat/merged")));
1016
+ rmSync(cleanupBase, { recursive: true, force: true });
891
1017
  setWorkspaceRoot(repo);
892
1018
  check("on main: git checkout path mutation blocked", blocked(await shell("git checkout -- tracked.txt")));
893
1019
  check("on main: git checkout path mutation without separator blocked", blocked(await shell("git checkout tracked.txt")));
@@ -5890,6 +6016,33 @@ check("checkInteractiveTtyCommand permits npm init --yes", !checkInteractiveTtyC
5890
6016
  check("checkInteractiveTtyCommand detects apt-get install without -y", checkInteractiveTtyCommand("apt-get install curl").isInteractive);
5891
6017
  check("checkInteractiveTtyCommand permits apt-get install -y", !checkInteractiveTtyCommand("apt-get install -y curl").isInteractive);
5892
6018
  check("checkInteractiveTtyCommand permits regular non-interactive command", !checkInteractiveTtyCommand("ls -la && git status").isInteractive);
6019
+ // Command position, not raw text: a pattern word in an argument is data.
6020
+ check("checkInteractiveTtyCommand permits sudo inside a grep pattern", !checkInteractiveTtyCommand(`grep -rn "sudo" docs/`).isInteractive);
6021
+ check("checkInteractiveTtyCommand permits an exact grep for sudo", !checkInteractiveTtyCommand("grep -n sudo file.txt").isInteractive);
6022
+ check("checkInteractiveTtyCommand permits sudo in a piped grep pattern", !checkInteractiveTtyCommand("journalctl --user -u x -n 20 --no-pager 2>&1 | grep -i sudo").isInteractive);
6023
+ check("checkInteractiveTtyCommand permits an interactive rebase pattern in a grep pattern", !checkInteractiveTtyCommand(`grep -n "git rebase -i" test/test.mts`).isInteractive);
6024
+ check("checkInteractiveTtyCommand permits npm init as grep data", !checkInteractiveTtyCommand(`grep -n "npm init" README.md`).isInteractive);
6025
+ check("checkInteractiveTtyCommand permits an editor name in a printf string", !checkInteractiveTtyCommand(`printf "%s\\n" "vim is not installed"`).isInteractive);
6026
+ check("checkInteractiveTtyCommand permits git log grep for interactive rebase", !checkInteractiveTtyCommand(`git log --grep="rebase -i"`).isInteractive);
6027
+ check("checkInteractiveTtyCommand permits a command name fed to a filter", !checkInteractiveTtyCommand(`echo "apt-get install curl" | cat`).isInteractive);
6028
+ // The same commands still block at command position.
6029
+ check("checkInteractiveTtyCommand still detects a chained editor", checkInteractiveTtyCommand("cd /repo && nano notes.txt").isInteractive);
6030
+ check("checkInteractiveTtyCommand still detects a shell -c editor", checkInteractiveTtyCommand("sh -c 'vim notes.txt'").isInteractive);
6031
+ check("checkInteractiveTtyCommand still detects eval npm init", checkInteractiveTtyCommand("eval 'npm init'").isInteractive);
6032
+ check("checkInteractiveTtyCommand still detects a wrapped sudo", checkInteractiveTtyCommand("env FOO=1 sudo ls").isInteractive);
6033
+ check("checkInteractiveTtyCommand still detects sudo before an editor", checkInteractiveTtyCommand("sudo vim notes.txt").isInteractive);
6034
+ check("checkInteractiveTtyCommand still detects a wrapped sudo before an editor", checkInteractiveTtyCommand("env A=1 sudo vim notes.txt").isInteractive);
6035
+ check("checkInteractiveTtyCommand still detects a timeout-wrapped sudo", checkInteractiveTtyCommand("timeout 5 sudo ls").isInteractive);
6036
+ check("checkInteractiveTtyCommand still detects sudo as a loop body", checkInteractiveTtyCommand("while true; do sudo ls; done").isInteractive);
6037
+ check("checkInteractiveTtyCommand still detects sudo after command", checkInteractiveTtyCommand("command sudo ls").isInteractive);
6038
+ check("checkInteractiveTtyCommand still detects git add -p", checkInteractiveTtyCommand("git add -p").isInteractive);
6039
+ check("checkInteractiveTtyCommand still detects yum install without -y", checkInteractiveTtyCommand("yum install curl").isInteractive);
6040
+ check("checkInteractiveTtyCommand still detects an apt install in a then body", checkInteractiveTtyCommand("if true; then apt-get install curl; fi").isInteractive);
6041
+ check("checkInteractiveTtyCommand still detects an apt install in a nested shell", checkInteractiveTtyCommand("bash -lc 'apt-get install curl'").isInteractive);
6042
+ check("checkInteractiveTtyCommand still detects busybox vi", checkInteractiveTtyCommand("busybox vi notes.txt").isInteractive);
6043
+ check("shellHasSudoWrapper reports a bare sudo", shellHasSudoWrapper("sudo ls"));
6044
+ check("shellHasSudoWrapper reports a sudo behind env", shellHasSudoWrapper("env FOO=1 sudo ls"));
6045
+ check("shellHasSudoWrapper ignores sudo as an argument", !shellHasSudoWrapper("grep -n sudo file.txt"));
5893
6046
 
5894
6047
  check("shell tool blocks nano", blocked(await shell("nano README.md")));
5895
6048
  check("shell tool blocks less", blocked(await shell("less package.json")));
@@ -8155,9 +8308,43 @@ const ocJson = "open" + "code.json";
8155
8308
  const ocJsonc = "open" + "code.jsonc";
8156
8309
  setWorkspaceRoot(root);
8157
8310
 
8158
- // Legacy (no live roots configured): the copy SOURCE under a config path alone
8159
- // blocks the command — the F3 false positive, pinned as current behavior.
8160
- check("legacy: cp FROM a .config/opencode source is blocked without live roots", blocked(await call("bash", { command: `cp ${livePlane}/agent/x.md ./draft.md` }, { sessionID: "s-active" })));
8311
+ // Legacy (no live roots configured): a copy-like verb reads its sources and
8312
+ // writes only its destination, so a guarded SOURCE alone is a read. This is the
8313
+ // F3 false positive, now allowed in both modes.
8314
+ const legacyCpFrom = (command: string) => call("bash", { command }, { sessionID: "s-active" });
8315
+ check("legacy: cp FROM a .config/opencode source is allowed without live roots", !blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ./draft.md`)));
8316
+ check("legacy: cp FROM a .config/opencode source with a redirect is allowed", !blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ./draft.md 2>/dev/null`)));
8317
+ check("legacy: a multi-source cp with one guarded source is allowed", !blocked(await legacyCpFrom(`cp ./notes.md ${livePlane}/agent/x.md ./draft.md`)));
8318
+ check("legacy: ln -s FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`ln -s ${livePlane}/agent/x.md ./draft-link.md`)));
8319
+ check("legacy: cp -s FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`cp -s ${livePlane}/agent/x.md ./draft-link.md`)));
8320
+ // A hard link is a second writable name for the guarded inode, so it stays a
8321
+ // mutation of the guarded file even when the link lands in the workspace.
8322
+ check("legacy: a hard link FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`ln ${livePlane}/agent/x.md ./hard-link.md`)));
8323
+ check("legacy: cp -l FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp -l ${livePlane}/agent/x.md ./hard-link.md`)));
8324
+ check("legacy: cp --link FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp --link ${livePlane}/agent/x.md ./hard-link.md`)));
8325
+ // The true positives hold: a guarded destination is still a mutation.
8326
+ check("legacy: cp INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md`)));
8327
+ check("legacy: cp with a guarded source and destination is still blocked", blocked(await legacyCpFrom(`cp ${livePlane}/agent/x.md ${livePlane}/agent/y.md`)));
8328
+ check("legacy: cp INTO a guarded path with a redirect is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md 2>/dev/null`)));
8329
+ check("legacy: cp -t a guarded directory is still blocked", blocked(await legacyCpFrom(`cp -t ${livePlane}/agent ./draft.md`)));
8330
+ check("legacy: cp --target-directory=a guarded directory is still blocked", blocked(await legacyCpFrom(`cp --target-directory=${livePlane}/agent ./draft.md`)));
8331
+ check("legacy: a multi-source cp into a guarded directory is still blocked", blocked(await legacyCpFrom(`cp ./a.md ./b.md ${livePlane}/agent`)));
8332
+ check("legacy: a wrapped cp into a guarded path is still blocked", blocked(await legacyCpFrom(`env FOO=1 cp ./draft.md ${livePlane}/agent/x.md`)));
8333
+ check("legacy: command-prefixed cp into a guarded path is still blocked", blocked(await legacyCpFrom(`command cp ./draft.md ${livePlane}/agent/x.md`)));
8334
+ check("legacy: fd duplication after a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md ${livePlane}/agent/x.md 2>&1`)));
8335
+ check("legacy: fd duplication before a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md 2>&1 ${livePlane}/agent/x.md`)));
8336
+ check("legacy: a discarded redirect before a guarded cp destination is still blocked", blocked(await legacyCpFrom(`cp ./draft.md >/dev/null 2>&1 ${livePlane}/agent/x.md`)));
8337
+ check("legacy: fd duplication does not mask a guarded redirect", blocked(await legacyCpFrom(`echo x 2>&1 > ${livePlane}/agent/x.md`)));
8338
+ check("legacy: fd duplication with no guarded path is allowed", !blocked(await legacyCpFrom(`cp ./draft.md ./copy.md 2>&1`)));
8339
+ check("legacy: ln -sfn FROM a .config/opencode source is allowed", !blocked(await legacyCpFrom(`ln -sfn ${livePlane}/agent/x.md ./draft-link.md`)));
8340
+ check("legacy: install -d -t a guarded directory is still blocked", blocked(await legacyCpFrom(`install -d -t ${livePlane}/plugins ./build`)));
8341
+ check("legacy: ln INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`ln -s ./draft-link.md ${livePlane}/agent/x.md`)));
8342
+ check("legacy: install -d a guarded directory is still blocked", blocked(await legacyCpFrom(`install -d ${livePlane}/plugins`)));
8343
+ check("legacy: install -d a workspace directory is allowed", !blocked(await legacyCpFrom(`install -d ./build/out`)));
8344
+ // mv removes its source, so a guarded source stays a mutation.
8345
+ check("legacy: mv FROM a .config/opencode path is still blocked", blocked(await legacyCpFrom(`mv ${livePlane}/agent/x.md ./draft.md`)));
8346
+ check("legacy: tee INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`echo x | tee ${livePlane}/agent/x.md`)));
8347
+ check("legacy: a redirect INTO a .config/opencode path is still blocked", blocked(await legacyCpFrom(`echo x > ${livePlane}/agent/x.md`)));
8161
8348
 
8162
8349
  // Declare the live control plane via project config, then reload.
8163
8350
  writeFileSync(join(lcpRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ liveControlPlanePaths: [livePlane] }));