opencode-workflow-guard 1.20.1 → 1.20.4
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.
- package/README.md +1 -1
- package/docs/agents/ledger.md +523 -0
- package/docs/agents/lessons/20261120T134830Z-align-with-the-sibling-matcher.md +13 -0
- package/docs/agents/rsi-loop-playbook.md +77 -0
- package/docs/policies.md +11 -7
- package/docs/testing.md +2 -2
- package/docs/troubleshooting.md +2 -0
- package/package.json +5 -5
- package/src/lib/custom-tools.ts +1 -1
- package/src/lib/guard-api.ts +1 -0
- package/src/lib/guard-dispatcher.ts +38 -26
- package/src/lib/shell.ts +12 -3
- package/src/lib/state.ts +5 -2
- package/src/lib/types.ts +10 -0
- package/src/lib/v2-plugin.ts +2 -1
- package/src/lib/verify.ts +43 -5
- package/src/policies/completion.ts +7 -3
- package/src/policies/git.ts +82 -1
- package/src/policies/post-edit-validation.ts +7 -2
- package/src/policies/shell-safety.ts +50 -25
- package/src/policies/tamper.ts +96 -4
- package/src/policies/todo.ts +158 -52
- package/src/workflow-guard.ts +6 -1
- package/test/test.mts +277 -6
package/src/policies/git.ts
CHANGED
|
@@ -172,7 +172,7 @@ export function normalizeGitCommands(command: string): string {
|
|
|
172
172
|
}
|
|
173
173
|
|
|
174
174
|
export const GIT_WRITE_RE =
|
|
175
|
-
/\bgit\s+(add|rm|mv|commit|merge|rebase|cherry-pick|revert|stash\s+pop|apply|am|restore|reset|update-ref|filter-branch)\b|\bgit\s+tag\s+(?!--?list\b|-l\b)(?:[^|;&]*\s)?(?:-d\b|--delete\b)|\bgit\s+checkout\s+(?!-b\b)|\bgit\s+branch\s+(?:[^|;&]*\s)
|
|
175
|
+
/\bgit\s+(add|rm|mv|commit|merge|rebase|cherry-pick|revert|stash\s+pop|apply|am|restore|reset|update-ref|filter-branch)\b|\bgit\s+tag\s+(?!--?list\b|-l\b)(?:[^|;&]*\s)?(?:-d\b|--delete\b)|\bgit\s+checkout\s+(?!-b\b)|\bgit\s+branch\s+(?:[^|;&]*\s)?(?:-[A-Za-z]*[dDM][A-Za-z]*\b|--delete\b)/;
|
|
176
176
|
|
|
177
177
|
// `pull` is deliberately absent from GIT_WRITE_RE: pulling on a feature branch
|
|
178
178
|
// is how a stale base is refreshed, and that is not a write to protect. On a
|
|
@@ -243,6 +243,87 @@ export function isProtectedBranchFastForward(text: string, root: string): boolea
|
|
|
243
243
|
return ancestor.status === 0;
|
|
244
244
|
}
|
|
245
245
|
|
|
246
|
+
/**
|
|
247
|
+
* True when `text` deletes local branches with git's merged-only form,
|
|
248
|
+
* `git branch -d`. `-D` and `--force` stay blocked, because they can drop
|
|
249
|
+
* unmerged commits. `-d` cannot: the manual states the branch "must be fully
|
|
250
|
+
* merged" in its upstream, or in HEAD when no upstream is set, so git refuses
|
|
251
|
+
* the deletion itself and the protected-branch rule has nothing to protect.
|
|
252
|
+
*
|
|
253
|
+
* This is the local half of the cleanup a merged PR requires. It was blocked
|
|
254
|
+
* whenever the checkout sat on the protected branch that receives the merge,
|
|
255
|
+
* which left the operator as the only actor who could finish it.
|
|
256
|
+
*/
|
|
257
|
+
export function isMergedLocalBranchDeletion(text: string, root: string): boolean {
|
|
258
|
+
const tokens = unwrapShellWords(text);
|
|
259
|
+
if (tokens[0] !== "git" || tokens[1] !== "branch") return false;
|
|
260
|
+
const args = tokens.slice(2);
|
|
261
|
+
// Short flags arrive as clusters (`-d`, `-rd`, `-Df`). Read the letters
|
|
262
|
+
// once so the delete and force rules cannot disagree about a cluster.
|
|
263
|
+
const shortFlags = args.filter((arg) => /^-[A-Za-z]+$/.test(arg)).join("");
|
|
264
|
+
const deletes = args.includes("--delete") || shortFlags.includes("d") || shortFlags.includes("D");
|
|
265
|
+
if (!deletes) return false;
|
|
266
|
+
if (args.includes("--force") || /[Df]/.test(shortFlags)) return false;
|
|
267
|
+
const names = args.filter((arg) => !arg.startsWith("-"));
|
|
268
|
+
if (names.length === 0) return false;
|
|
269
|
+
const protectedBranches = getProtectedBranches(root);
|
|
270
|
+
return names.every((name) => !protectedBranches.has(name));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* True when `text` pushes nothing but deletions of remote branches that are
|
|
275
|
+
* already merged into the remote default: `git push <remote> --delete <branch>`
|
|
276
|
+
* or a `:<branch>` refspec.
|
|
277
|
+
*
|
|
278
|
+
* Deleting a merged branch's remote ref publishes no commit, so it is the other
|
|
279
|
+
* half of the cleanup a merged PR requires. The rules stay narrow. Every named
|
|
280
|
+
* branch must be an ancestor of the remote default, so an unmerged branch keeps
|
|
281
|
+
* its commits reachable. Protected names are refused. Options that delete more
|
|
282
|
+
* than the named refs (`--prune`, `--mirror`, `--force`) and any ordinary
|
|
283
|
+
* refspec keep the push blocked. The branch resolves through `refs/heads/`
|
|
284
|
+
* first, then `refs/remotes/origin/<branch>`, because deleting the local ref
|
|
285
|
+
* first is the normal order. Both namespaces are explicit, so a local branch
|
|
286
|
+
* whose remote ref is already gone stays blocked instead of guessing.
|
|
287
|
+
*/
|
|
288
|
+
export function purgesMergedRemoteBranches(text: string, root: string): boolean {
|
|
289
|
+
const tokens = unwrapShellWords(text);
|
|
290
|
+
if (tokens[0] !== "git" || tokens[1] !== "push") return false;
|
|
291
|
+
const args = tokens.slice(2);
|
|
292
|
+
const targets: string[] = [];
|
|
293
|
+
let deleteFlag = false;
|
|
294
|
+
let remoteSeen = false;
|
|
295
|
+
for (const arg of args) {
|
|
296
|
+
if (arg.startsWith("-")) {
|
|
297
|
+
if (arg === "-d" || arg === "--delete") {
|
|
298
|
+
deleteFlag = true;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
if (!remoteSeen && !arg.startsWith(":")) {
|
|
304
|
+
remoteSeen = true;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
const name = arg.startsWith(":") ? arg.slice(1) : deleteFlag ? arg : "";
|
|
308
|
+
if (!name) return false;
|
|
309
|
+
// A fully-qualified ref is only a branch refspec under refs/heads/.
|
|
310
|
+
// Deleting a tag, or any other namespace, stays blocked.
|
|
311
|
+
if (name.startsWith("refs/") && !name.startsWith("refs/heads/")) return false;
|
|
312
|
+
const branch = name.replace(/^refs\/heads\//, "");
|
|
313
|
+
if (!branch || getProtectedBranches(root).has(branch)) return false;
|
|
314
|
+
targets.push(branch);
|
|
315
|
+
}
|
|
316
|
+
if (targets.length === 0) return false;
|
|
317
|
+
return targets.every((branch) => {
|
|
318
|
+
// Name the ref namespaces explicitly. A bare short name also matches a
|
|
319
|
+
// tag of the same name, and a tag deletion is not branch cleanup.
|
|
320
|
+
const localRef = `refs/heads/${branch}`;
|
|
321
|
+
const ref = gitRefExists(localRef, root) ? localRef : `refs/remotes/origin/${branch}`;
|
|
322
|
+
if (!gitRefExists(ref, root)) return false;
|
|
323
|
+
return isBranchAlreadyMergedOrClosed(root, ref, false).merged;
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
246
327
|
/** The ref the current branch tracks, or undefined when it tracks nothing. */
|
|
247
328
|
function gitUpstreamRef(root: string): string | undefined {
|
|
248
329
|
const upstream = spawnSync("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], {
|
|
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
4
4
|
import { getProjectConfig } from "../lib/state.ts";
|
|
5
|
-
import { runVerify, snipVerifyOutput } from "../lib/verify.ts";
|
|
5
|
+
import { formatTimeoutLimit, runVerify, snipVerifyOutput } from "../lib/verify.ts";
|
|
6
6
|
import { extractPatchPaths } from "./boundary.ts";
|
|
7
7
|
|
|
8
8
|
export interface FileSnapshot {
|
|
@@ -69,7 +69,12 @@ export async function runPostEditValidators(root: string, before: FileSnapshot):
|
|
|
69
69
|
const timeoutMs = validator.timeoutMs ?? 30_000;
|
|
70
70
|
const result = await runVerify(validator.command, root, timeoutMs);
|
|
71
71
|
if (!result.passed) {
|
|
72
|
-
|
|
72
|
+
// A validator that never finished is not a failed validator. Say
|
|
73
|
+
// which one happened, or the agent debugs a check that never ran.
|
|
74
|
+
const outcome = result.timedOut === true
|
|
75
|
+
? `did not finish within ${formatTimeoutLimit(result.timeoutMs)}`
|
|
76
|
+
: "failed";
|
|
77
|
+
failures.push(`[workflow-guard] Post-edit validator ${outcome} for ${relativePath}: ${validator.command}\n${snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : "failed")}`);
|
|
73
78
|
}
|
|
74
79
|
}
|
|
75
80
|
return failures.length ? failures.join("\n\n") : undefined;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { basename } from "node:path";
|
|
3
|
-
import { splitShellSegments, unwrapShellWords } from "../lib/shell.ts";
|
|
3
|
+
import { shellHasSudoWrapper, splitShellSegments, TRANSPARENT_PREFIX, unwrapShellWords } from "../lib/shell.ts";
|
|
4
4
|
|
|
5
5
|
// AI agents frequently run dangerous package manager flags (e.g. npm audit fix --force,
|
|
6
6
|
// npm install -g, pip install --force-reinstall, agent-driven publish) that introduce
|
|
@@ -40,43 +40,40 @@ export function checkPackageHygiene(command: string): { isViolating: boolean; na
|
|
|
40
40
|
|
|
41
41
|
// AI agents running in non-interactive terminal subshells hang indefinitely when an
|
|
42
42
|
// interactive prompt (vim, nano, less, top, sudo, npm init without -y, apt without -y,
|
|
43
|
-
// git rebase -i) waits for TTY input.
|
|
44
|
-
//
|
|
45
|
-
//
|
|
43
|
+
// git rebase -i) waits for TTY input. Every one of those names is judged at command
|
|
44
|
+
// position, because the same word in an argument is data: `echo top`, a grep pattern
|
|
45
|
+
// like `grep -n 'sudo'`, or a printf string must not read as a hang. Process monitors
|
|
46
|
+
// and pagers already work that way; the patterns below follow the same rule.
|
|
46
47
|
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
regex: /\bsudo\b/i,
|
|
55
|
-
name: "sudo with password prompt",
|
|
56
|
-
advice: "Avoid sudo in agent sessions; run commands directly or request user execution.",
|
|
57
|
-
},
|
|
48
|
+
const INTERACTIVE_EDITORS = new Set(["nano", "vi", "vim", "emacs", "pico", "joe", "micro"]);
|
|
49
|
+
const EDITOR_ADVICE = "Use the edit, write, or apply_patch tools instead of interactive terminal editors.";
|
|
50
|
+
const SUDO_NAME = "sudo with password prompt";
|
|
51
|
+
const SUDO_ADVICE = "Avoid sudo in agent sessions; run commands directly or request user execution.";
|
|
52
|
+
|
|
53
|
+
// Anchored on the command word, so a `git rebase -i` inside a grep pattern stays data.
|
|
54
|
+
const INTERACTIVE_VERB_PATTERNS: Array<{ regex: RegExp; name: string; advice: string }> = [
|
|
58
55
|
{
|
|
59
|
-
regex:
|
|
56
|
+
regex: /^git\s+rebase\s+-[a-zA-Z]*i/i,
|
|
60
57
|
name: "git interactive rebase",
|
|
61
58
|
advice: "Use non-interactive git commands or explicit cherry-pick/merge sequences.",
|
|
62
59
|
},
|
|
63
60
|
{
|
|
64
|
-
regex:
|
|
61
|
+
regex: /^git\s+add\s+-[a-zA-Z]*p/i,
|
|
65
62
|
name: "git interactive patch",
|
|
66
63
|
advice: "Use git add <file> or git apply rather than interactive patch selection.",
|
|
67
64
|
},
|
|
68
65
|
{
|
|
69
|
-
regex:
|
|
66
|
+
regex: /^npm\s+init\b(?!\s+(?:-y|--yes|--force))\b/i,
|
|
70
67
|
name: "npm init without non-interactive flag",
|
|
71
68
|
advice: "Add -y or --yes flag: npm init -y",
|
|
72
69
|
},
|
|
73
70
|
{
|
|
74
|
-
regex:
|
|
71
|
+
regex: /^(?:apt|apt-get)\s+(?:install|remove|purge|upgrade|dist-upgrade)\b(?!\s+(?:-y|--yes|--assume-yes))\b/i,
|
|
75
72
|
name: "apt command without non-interactive flag",
|
|
76
73
|
advice: "Add -y flag to avoid interactive confirmation prompts (e.g. apt-get install -y <pkg>).",
|
|
77
74
|
},
|
|
78
75
|
{
|
|
79
|
-
regex:
|
|
76
|
+
regex: /^(?:yum|dnf)\s+(?:install|remove|upgrade)\b(?!\s+-y)\b/i,
|
|
80
77
|
name: "yum/dnf command without non-interactive flag",
|
|
81
78
|
advice: "Add -y flag to avoid interactive confirmation prompts (e.g. dnf install -y <pkg>).",
|
|
82
79
|
},
|
|
@@ -140,17 +137,45 @@ function containsPagerCommand(command: string, depth = 0): boolean {
|
|
|
140
137
|
return false;
|
|
141
138
|
}
|
|
142
139
|
|
|
140
|
+
function containsInteractivePattern(command: string, depth = 0): { name: string; advice: string } | undefined {
|
|
141
|
+
if (depth >= 16) return undefined;
|
|
142
|
+
for (const segment of splitShellSegments(command)) {
|
|
143
|
+
// Unwrapping strips `sudo` before the command word, so ask the unwrapper.
|
|
144
|
+
if (shellHasSudoWrapper(segment)) return { name: SUDO_NAME, advice: SUDO_ADVICE };
|
|
145
|
+
const words = unwrapShellWords(segment);
|
|
146
|
+
while (words.length > 0 && (words[0] === "--" || TRANSPARENT_PREFIX.has(words[0]!))) words.shift();
|
|
147
|
+
if (words[0] === "sudo") return { name: SUDO_NAME, advice: SUDO_ADVICE };
|
|
148
|
+
const executable = basename(words[0] ?? "").toLowerCase();
|
|
149
|
+
const busybox = executable === "busybox";
|
|
150
|
+
const candidate = busybox ? basename(words[1] ?? "").toLowerCase() : executable;
|
|
151
|
+
if (INTERACTIVE_EDITORS.has(candidate)) return { name: "interactive text editor", advice: EDITOR_ADVICE };
|
|
152
|
+
const commandText = words.slice(busybox ? 1 : 0).join(" ");
|
|
153
|
+
for (const { regex, name, advice } of INTERACTIVE_VERB_PATTERNS) {
|
|
154
|
+
if (regex.test(commandText)) return { name, advice };
|
|
155
|
+
}
|
|
156
|
+
if (executable === "eval" && words.length > 1) {
|
|
157
|
+
const nested = containsInteractivePattern(words.slice(1).join(" "), depth + 1);
|
|
158
|
+
if (nested) return nested;
|
|
159
|
+
}
|
|
160
|
+
if (/^(?:ba|z|da|k)?sh$/i.test(executable)) {
|
|
161
|
+
const commandFlag = words.findIndex((word, index) => index > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(word));
|
|
162
|
+
if (commandFlag >= 0 && words[commandFlag + 1]) {
|
|
163
|
+
const nested = containsInteractivePattern(words[commandFlag + 1]!, depth + 1);
|
|
164
|
+
if (nested) return nested;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
143
171
|
export function checkInteractiveTtyCommand(command: string): { isInteractive: boolean; name?: string; advice?: string } {
|
|
144
172
|
const monitor = checkProcessMonitorCommand(command);
|
|
145
173
|
if (monitor.isInteractive) return monitor;
|
|
146
174
|
if (containsPagerCommand(command)) {
|
|
147
175
|
return { isInteractive: true, name: "terminal pager", advice: PAGER_ADVICE };
|
|
148
176
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
return { isInteractive: true, name, advice };
|
|
152
|
-
}
|
|
153
|
-
}
|
|
177
|
+
const pattern = containsInteractivePattern(command);
|
|
178
|
+
if (pattern) return { isInteractive: true, ...pattern };
|
|
154
179
|
return { isInteractive: false };
|
|
155
180
|
}
|
|
156
181
|
|
package/src/policies/tamper.ts
CHANGED
|
@@ -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
|
|
68
|
-
//
|
|
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
|
-
|
|
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
|
|
168
|
+
return legacyPathTamper(residue);
|
|
77
169
|
});
|
|
78
170
|
}
|
|
79
171
|
|
package/src/policies/todo.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
-
):
|
|
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
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
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
|
-
|
|
473
|
+
export function validateTodoLifecycle(
|
|
474
|
+
newTodos: TodoItem[],
|
|
475
|
+
existingTodos: TodoItem[] | undefined,
|
|
476
|
+
): string | undefined {
|
|
477
|
+
return inspectTodoLifecycle(newTodos, existingTodos).error;
|
|
372
478
|
}
|