opencode-workflow-guard 1.20.0 → 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.
@@ -33,6 +33,11 @@ export const SETTINGS_TAMPER_PATTERNS: RegExp[] = [
33
33
  // still executes the verb.
34
34
  const PATH_PATTERNS = SETTINGS_TAMPER_PATTERNS.slice(0, 4);
35
35
  const VERB_PATTERNS = SETTINGS_TAMPER_PATTERNS.slice(4);
36
+ // Patterns 1 and 3 match a redirect into a guarded path; patterns 0 and 2
37
+ // match a mutating verb whose operands include one. A redirect writes its
38
+ // target whatever verb carries it, so legacy mode judges it before it
39
+ // discounts any copy source.
40
+ const REDIRECT_PATH_PATTERNS = [PATH_PATTERNS[1]!, PATH_PATTERNS[3]!];
36
41
 
37
42
  export function normalizeShellEvasion(text: string): string {
38
43
  return decodeShellEscapes(text)
@@ -58,22 +63,109 @@ export function isCollaborationInvocation(segment: string): boolean {
58
63
  return COLLABORATION_INVOCATION_PATTERNS.some((re) => re.test(segment));
59
64
  }
60
65
 
66
+ const GUARDED_OPERAND_RE = new RegExp(`(?:${C_LIST}|${U_LIST})`, "i");
67
+
68
+ // Copy-like verbs read their sources and write only their destination. Legacy
69
+ // mode therefore judges the destination operand, so a guarded source is a read
70
+ // rather than a mutation. Every other mutating verb touches each operand it
71
+ // names, and a copy whose destination cannot be identified stays with that
72
+ // fail-closed set.
73
+ const COPY_INVOCATION_RE = /(?:^|[\s;&|])(?:cp|ln|install)\s+([^|;&]+)/gi;
74
+
75
+ // A redirect span is not a copy operand. Dropping it here keeps `cp src dst 2>
76
+ // log` from reading the log path as the destination.
77
+ const REDIRECT_SPAN_RE = /(?:^|\s)(?:&|\d*)?(?:>>?|&>)\s*\S*/g;
78
+
79
+ function classifyCopyInvocation(invocation: string): { safe: boolean; tamper: boolean } {
80
+ const args = invocation
81
+ .replace(REDIRECT_SPAN_RE, " ")
82
+ .trim()
83
+ .split(/\s+/)
84
+ .filter(Boolean);
85
+ const verb = (args.shift() ?? "").toLowerCase();
86
+ const operands: string[] = [];
87
+ let targetDir: string | undefined;
88
+ for (let index = 0; index < args.length; index++) {
89
+ const token = args[index]!;
90
+ if (token === "-t" || token === "--target-directory") {
91
+ targetDir = args[++index];
92
+ continue;
93
+ }
94
+ const longAttached = /^--target-directory=(.*)$/.exec(token);
95
+ if (longAttached) {
96
+ targetDir = longAttached[1];
97
+ continue;
98
+ }
99
+ const shortAttached = /^-t(.+)$/.exec(token);
100
+ if (shortAttached) {
101
+ targetDir = shortAttached[1];
102
+ continue;
103
+ }
104
+ if (token.startsWith("-")) continue;
105
+ operands.push(token);
106
+ }
107
+ const guarded = (token: string | undefined) => token !== undefined && GUARDED_OPERAND_RE.test(token);
108
+ // `install -d` treats every argument as a directory name, so all operands
109
+ // and any target directory are targets rather than sources.
110
+ if (verb === "install" && args.some((arg) => /^-[a-zA-Z]*d[a-zA-Z0-9]*$/.test(arg))) {
111
+ return { safe: false, tamper: operands.some(guarded) || guarded(targetDir) };
112
+ }
113
+ // A hard link is a second writable name for the source inode, so a later
114
+ // write to the workspace link would mutate the guarded file. Only a
115
+ // symbolic link keeps the guarded path behind a resolution the guard can
116
+ // follow, so `ln -s` and `cp -s` are reads while `ln`, `cp -l`, and
117
+ // `cp --link` stay on the fail-closed any-operand match. A bundled short
118
+ // cluster is classified by its letters: `s` is ln's symbolic-link flag and
119
+ // `l` is cp's link flag, so `-sfn` is symbolic and `-al` is a hard link.
120
+ // GNU rejects cp's `-l` together with `-s`, and the fail-closed branch wins
121
+ // there.
122
+ const shortFlag = (letter: string) => new RegExp(`^-[a-zA-Z]*${letter}[a-zA-Z]*$`);
123
+ const hardLink =
124
+ verb === "ln"
125
+ ? !args.some((arg) => arg === "--symbolic" || shortFlag("s").test(arg))
126
+ : verb === "cp" && args.some((arg) => arg === "--link" || shortFlag("l").test(arg));
127
+ if (hardLink) return { safe: false, tamper: operands.some(guarded) };
128
+ const destination = targetDir ?? (operands.length >= 2 ? operands[operands.length - 1] : undefined);
129
+ if (destination === undefined) return { safe: false, tamper: false };
130
+ if (guarded(destination)) return { safe: false, tamper: true };
131
+ return { safe: true, tamper: false };
132
+ }
133
+
134
+ function legacyPathTamper(residue: string): boolean {
135
+ if (REDIRECT_PATH_PATTERNS.some((re) => re.test(residue))) return true;
136
+ let tamper = false;
137
+ const rest = residue.replace(COPY_INVOCATION_RE, (match) => {
138
+ const verdict = classifyCopyInvocation(match);
139
+ if (verdict.tamper) tamper = true;
140
+ return verdict.safe ? " " : match;
141
+ });
142
+ if (tamper) return true;
143
+ return PATH_PATTERNS.some((re) => re.test(rest));
144
+ }
145
+
61
146
  export function isSettingsTamper(command: string, liveControlPlaneRoots?: readonly string[]): boolean {
62
147
  // When the host declares its live control-plane roots, path-shaped tamper is
63
148
  // decided by the mutation TARGET's runtime location (`isProtectedPath`), not
64
149
  // by matching any operand's raw text. That stops a copy/move SOURCE under a
65
150
  // config path from being flagged while the destination is a sanctioned draft
66
151
  // (finding F3). The opencode CLI verb patterns still apply. Callers that scan
67
- // written content (edit payloads) pass no roots and keep the legacy
68
- // fail-closed path matching.
152
+ // written content (edit payloads) pass no roots, so they keep the legacy
153
+ // matching: every mutating verb touches each operand, while a copy-like verb
154
+ // is judged by its destination only and fails closed when it has none.
69
155
  const factMode = liveControlPlaneRoots !== undefined && liveControlPlaneRoots.length > 0;
70
- return command.split(/[\n|;&]+/).some((s) => {
156
+ // `2>&1` and `2>&-` duplicate or close a file descriptor. They never name a
157
+ // write target, but their `&` would split the command and strand the
158
+ // operand after them in a fragment with no verb. Drop them before
159
+ // segmenting. A word after `>&` that is not a descriptor stays, because
160
+ // bash reads it as a file redirect.
161
+ const normalized = command.replace(/\d*>&(?:\d+(?![\w.])|-)/g, " ");
162
+ return normalized.split(/[\n|;&]+/).some((s) => {
71
163
  if (isCollaborationInvocation(s)) return false;
72
164
  const flattened = normalizeGlobPathEvasion(normalizeShellEvasion(s));
73
165
  if (VERB_PATTERNS.some((re) => re.test(flattened))) return true;
74
166
  if (factMode) return false;
75
167
  const residue = normalizeGlobPathEvasion(normalizeShellEvasion(prepareRedirectResidue(s)));
76
- return PATH_PATTERNS.some((re) => re.test(residue));
168
+ return legacyPathTamper(residue);
77
169
  });
78
170
  }
79
171
 
@@ -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 {