@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.0
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/CHANGELOG.md +56 -0
- package/README.md +8 -6
- package/README.tr.md +8 -6
- package/docs/architecture.md +3 -3
- package/docs/ecosystem.md +50 -13
- package/docs/facts.json +9 -9
- package/docs/features.md +9 -4
- package/install/claude.mjs +34 -1
- package/install/templates/claude-hooks.json +12 -1
- package/manifest.json +117 -90
- package/package.json +3 -2
- package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
- package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
- package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
- package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
- package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
- package/pipeline/lib/args.mjs +131 -4
- package/pipeline/lib/bg-launch.mjs +5 -2
- package/pipeline/lib/credential-store.sh +11 -1
- package/pipeline/lib/hook-once.mjs +134 -0
- package/pipeline/lib/isotonic.mjs +73 -0
- package/pipeline/lib/low-disk.mjs +154 -0
- package/pipeline/lib/mcp-schema-load.mjs +90 -0
- package/pipeline/lib/md2confluence-v3.py +8 -7
- package/pipeline/lib/model-dispatch.sh +26 -2
- package/pipeline/lib/normalize-text.mjs +135 -0
- package/pipeline/lib/outbound-gate.mjs +21 -3
- package/pipeline/lib/plan-todos.sh +17 -4
- package/pipeline/lib/redact.mjs +12 -3
- package/pipeline/lib/risky-settings.mjs +198 -0
- package/pipeline/lib/route-state.sh +1 -0
- package/pipeline/lib/secret-patterns.generated.mjs +6 -2
- package/pipeline/lib/session-usage.mjs +232 -0
- package/pipeline/lib/source-digest.mjs +211 -0
- package/pipeline/lib/tdd-evidence.mjs +250 -17
- package/pipeline/lib/untrusted-fence.mjs +132 -1
- package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
- package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
- package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
- package/pipeline/multi-agent-refs/features/doctor.md +66 -4
- package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
- package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
- package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
- package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
- package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
- package/pipeline/multi-agent-refs/help/en.md +3 -1
- package/pipeline/multi-agent-refs/help/tr.md +3 -1
- package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
- package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
- package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
- package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
- package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
- package/pipeline/multi-agent-refs/progress-contract.md +3 -1
- package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
- package/pipeline/office/toolkit.json +1 -1
- package/pipeline/rules/outside-the-pipeline.md +1 -1
- package/pipeline/schemas/doctor-report.schema.json +47 -0
- package/pipeline/schemas/plan-todos.schema.json +29 -1
- package/pipeline/schemas/prefs.schema.json +81 -0
- package/pipeline/schemas/route-config.schema.json +51 -0
- package/pipeline/schemas/secret-patterns.json +17 -1
- package/pipeline/schemas/toolkit-path-params.json +15 -1
- package/pipeline/scripts/_cost-advise.mjs +357 -0
- package/pipeline/scripts/_cost-budget.mjs +78 -0
- package/pipeline/scripts/_cost.mjs +29 -0
- package/pipeline/scripts/_decode_text.py +107 -0
- package/pipeline/scripts/_guard-probe.mjs +406 -0
- package/pipeline/scripts/_guard_rules.py +206 -0
- package/pipeline/scripts/_memory-policy.mjs +1 -25
- package/pipeline/scripts/_retrieval.mjs +148 -2
- package/pipeline/scripts/_secret-scan.mjs +6 -1
- package/pipeline/scripts/_stack-routing.mjs +1 -0
- package/pipeline/scripts/_test-gaming.mjs +346 -0
- package/pipeline/scripts/agent-guard.py +8 -1
- package/pipeline/scripts/argv-secret-scan.mjs +2 -1
- package/pipeline/scripts/autopilot-loop.mjs +407 -0
- package/pipeline/scripts/autopilot-runner.mjs +38 -25
- package/pipeline/scripts/capture-resume.sh +9 -1
- package/pipeline/scripts/cost-analyze.mjs +66 -4
- package/pipeline/scripts/cost-budget-check.mjs +5 -13
- package/pipeline/scripts/disk-cleaner.mjs +1432 -0
- package/pipeline/scripts/doctor.mjs +302 -47
- package/pipeline/scripts/evidence-gate.mjs +90 -0
- package/pipeline/scripts/gate-ledger.mjs +76 -21
- package/pipeline/scripts/gc-tmp.sh +5 -0
- package/pipeline/scripts/guard-probe-known-holes.json +3 -0
- package/pipeline/scripts/learnings-ledger.mjs +16 -12
- package/pipeline/scripts/note-agent-event.mjs +2 -0
- package/pipeline/scripts/note-mcp-failure.mjs +9 -2
- package/pipeline/scripts/note-skill-use.mjs +4 -1
- package/pipeline/scripts/pre-commit-check.sh +2 -2
- package/pipeline/scripts/pre-push-check.sh +8 -1
- package/pipeline/scripts/priority-review.mjs +912 -0
- package/pipeline/scripts/publish-staged.mjs +324 -0
- package/pipeline/scripts/route-learn.mjs +628 -0
- package/pipeline/scripts/run-scope-guard.mjs +55 -1
- package/pipeline/scripts/scan-agent-config.sh +1 -1
- package/pipeline/scripts/statusline.mjs +309 -0
- package/pipeline/scripts/test-integrity-gate.mjs +97 -2
- package/pipeline/scripts/triage-memory.mjs +12 -4
- package/pipeline/scripts/uninstall.mjs +1 -0
- package/pipeline/skills/.skill-manifest.json +17 -5
- package/pipeline/skills/.skills-index.json +36 -3
- package/pipeline/skills/shared/README.md +9 -6
- package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
- package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
- package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
- package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
- package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
- package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
- package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
- package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
- package/pipeline/skills/skill-copies.json +4 -0
- package/pipeline/skills/skills-index.md +5 -2
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* source-digest.mjs - one sha256 over the source a working tree holds right
|
|
4
|
+
* now, committed or not.
|
|
5
|
+
*
|
|
6
|
+
* Build and test evidence is recorded before Phase 4 commits anything, so the
|
|
7
|
+
* HEAD a gate records says nothing about an edit made after the build. This
|
|
8
|
+
* digest does: it covers every tracked file as it is on disk and every
|
|
9
|
+
* untracked file git does not ignore, so an edit, a new file or a deletion
|
|
10
|
+
* after the evidence changes it, and undoing the edit brings it back.
|
|
11
|
+
* Committing the same content leaves it unchanged, so a checkpoint commit does
|
|
12
|
+
* not age the evidence.
|
|
13
|
+
*
|
|
14
|
+
* How it stays cheap on a large repository:
|
|
15
|
+
* - unchanged tracked files are named by the blob id the index already holds
|
|
16
|
+
* (`git ls-files -s`); nothing is read for them;
|
|
17
|
+
* - only modified and untracked files are hashed, by `git hash-object
|
|
18
|
+
* --stdin-paths`, which streams each file and applies the same clean
|
|
19
|
+
* filters the index used, so an unmodified file and a re-saved one agree;
|
|
20
|
+
* - hashing stops at `maxFiles` files or `maxBytes` bytes; past the cap a
|
|
21
|
+
* file is named by its size and mtime, which still changes on an edit,
|
|
22
|
+
* and the result says `capped: true`;
|
|
23
|
+
* - every git call has `timeoutMs`; a call that fails or times out makes the
|
|
24
|
+
* digest null, which callers read as "cannot tell", never as a match.
|
|
25
|
+
*
|
|
26
|
+
* Ignore rules are git's own (`--exclude-standard`). The pipeline's own
|
|
27
|
+
* output inside a worktree is left out too, because it is written after the
|
|
28
|
+
* build it describes: untracked `*.log` files, `*.xcresult` bundles and the
|
|
29
|
+
* `.pipeline/`, `.multi-agent/` and `.claude/` directories.
|
|
30
|
+
*
|
|
31
|
+
* A submodule is named by the commit its checkout is on, plus `dirty` when
|
|
32
|
+
* its own tree has changes.
|
|
33
|
+
*
|
|
34
|
+
* CLI: source-digest.mjs [--repo <dir>] [--json]
|
|
35
|
+
* prints the digest (or the whole result with --json); exit 3 when <dir> is
|
|
36
|
+
* not in a git work tree or git could not answer.
|
|
37
|
+
*
|
|
38
|
+
* Zero runtime dependencies (ADR-0004).
|
|
39
|
+
*
|
|
40
|
+
* @module pipeline/lib/source-digest
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
import { spawnSync } from "node:child_process";
|
|
44
|
+
import { createHash } from "node:crypto";
|
|
45
|
+
import { lstatSync, readlinkSync } from "node:fs";
|
|
46
|
+
import { join } from "node:path";
|
|
47
|
+
|
|
48
|
+
import { invokedDirectly } from "./invoked-directly.mjs";
|
|
49
|
+
import { parseArgs } from "./args.mjs";
|
|
50
|
+
|
|
51
|
+
export const DIGEST_LIMITS = Object.freeze({
|
|
52
|
+
maxFiles: 5000,
|
|
53
|
+
maxBytes: 256 * 1024 * 1024,
|
|
54
|
+
timeoutMs: 20000,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const ARTEFACT = /(?:^|\/)(?:\.pipeline|\.multi-agent|\.claude)\/|\.log$|\.xcresult(?:\/|$)/;
|
|
58
|
+
|
|
59
|
+
/** Whether an untracked path is the pipeline's own output rather than source. */
|
|
60
|
+
export function isPipelineArtefact(path) {
|
|
61
|
+
return ARTEFACT.test(path);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function git(cwd, args, { timeoutMs, input } = {}) {
|
|
65
|
+
const r = spawnSync("git", ["-C", cwd, ...args], {
|
|
66
|
+
encoding: "utf8",
|
|
67
|
+
timeout: timeoutMs,
|
|
68
|
+
maxBuffer: 1024 * 1024 * 1024,
|
|
69
|
+
input,
|
|
70
|
+
});
|
|
71
|
+
if (r.status !== 0 || r.error) return null;
|
|
72
|
+
return r.stdout;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const nulList = (out) => (out ? out.split("\0").filter(Boolean) : []);
|
|
76
|
+
|
|
77
|
+
function statOf(path) {
|
|
78
|
+
try {
|
|
79
|
+
return lstatSync(path);
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function submoduleToken(root, path, timeoutMs) {
|
|
86
|
+
const dir = join(root, path);
|
|
87
|
+
const head = git(dir, ["rev-parse", "HEAD"], { timeoutMs });
|
|
88
|
+
if (head === null) return "gitlink:absent";
|
|
89
|
+
const dirty = git(dir, ["status", "--porcelain", "--untracked-files=no"], { timeoutMs });
|
|
90
|
+
return `gitlink:${head.trim()}${dirty && dirty.trim() ? ":dirty" : ""}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The digest of the working tree `dir` is in, or null when it is not in one
|
|
95
|
+
* or git could not answer in time.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} dir
|
|
98
|
+
* @param {{maxFiles?: number, maxBytes?: number, timeoutMs?: number}} [opts]
|
|
99
|
+
* @returns {null | {digest: string, root: string, files: number, hashed: number,
|
|
100
|
+
* statOnly: number, capped: boolean, newestEditMs: number, ms: number}}
|
|
101
|
+
*/
|
|
102
|
+
export function sourceDigest(dir, opts = {}) {
|
|
103
|
+
const { maxFiles, maxBytes, timeoutMs } = { ...DIGEST_LIMITS, ...opts };
|
|
104
|
+
const started = Date.now();
|
|
105
|
+
const top = git(dir, ["rev-parse", "--show-toplevel"], { timeoutMs });
|
|
106
|
+
if (top === null) return null;
|
|
107
|
+
const root = top.trim();
|
|
108
|
+
|
|
109
|
+
const staged = git(root, ["ls-files", "-s", "-z"], { timeoutMs });
|
|
110
|
+
const modifiedOut = git(root, ["ls-files", "-m", "-z"], { timeoutMs });
|
|
111
|
+
const deletedOut = git(root, ["ls-files", "-d", "-z"], { timeoutMs });
|
|
112
|
+
const untrackedOut = git(root, ["ls-files", "-o", "--exclude-standard", "-z"], { timeoutMs });
|
|
113
|
+
if (staged === null || modifiedOut === null || deletedOut === null || untrackedOut === null) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const tokens = new Map();
|
|
118
|
+
const gitlinks = new Set();
|
|
119
|
+
for (const rec of nulList(staged)) {
|
|
120
|
+
const tab = rec.indexOf("\t");
|
|
121
|
+
const [mode, sha, stage] = rec.slice(0, tab).split(" ");
|
|
122
|
+
const path = rec.slice(tab + 1);
|
|
123
|
+
if (stage !== "0" && tokens.has(path)) continue;
|
|
124
|
+
if (mode === "160000") gitlinks.add(path);
|
|
125
|
+
tokens.set(path, `${mode}:${sha}`);
|
|
126
|
+
}
|
|
127
|
+
const deleted = new Set(nulList(deletedOut));
|
|
128
|
+
const toHash = [];
|
|
129
|
+
for (const path of nulList(modifiedOut)) {
|
|
130
|
+
if (deleted.has(path)) continue;
|
|
131
|
+
if (gitlinks.has(path)) tokens.set(path, submoduleToken(root, path, timeoutMs));
|
|
132
|
+
else toHash.push(path);
|
|
133
|
+
}
|
|
134
|
+
for (const path of deleted) tokens.set(path, "deleted");
|
|
135
|
+
for (const path of nulList(untrackedOut)) {
|
|
136
|
+
if (!isPipelineArtefact(path)) toHash.push(path);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
let hashedBytes = 0;
|
|
140
|
+
let newestEditMs = 0;
|
|
141
|
+
let capped = false;
|
|
142
|
+
const hashList = [];
|
|
143
|
+
for (const path of toHash) {
|
|
144
|
+
const st = statOf(join(root, path));
|
|
145
|
+
if (!st) {
|
|
146
|
+
tokens.set(path, "deleted");
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
newestEditMs = Math.max(newestEditMs, st.mtimeMs);
|
|
150
|
+
if (st.isSymbolicLink()) {
|
|
151
|
+
let target;
|
|
152
|
+
try {
|
|
153
|
+
target = readlinkSync(join(root, path));
|
|
154
|
+
} catch {
|
|
155
|
+
target = "?";
|
|
156
|
+
}
|
|
157
|
+
tokens.set(path, `link:${target}`);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (!st.isFile()) {
|
|
161
|
+
tokens.set(path, `other:${st.mode}`);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const fits = hashList.length < maxFiles && hashedBytes + st.size <= maxBytes;
|
|
165
|
+
if (!fits || path.includes("\n")) {
|
|
166
|
+
if (!path.includes("\n")) capped = true;
|
|
167
|
+
tokens.set(path, `stat:${st.size}:${Math.trunc(st.mtimeMs)}`);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
hashedBytes += st.size;
|
|
171
|
+
hashList.push(path);
|
|
172
|
+
}
|
|
173
|
+
if (hashList.length) {
|
|
174
|
+
const out = git(root, ["hash-object", "--stdin-paths"], {
|
|
175
|
+
timeoutMs,
|
|
176
|
+
input: `${hashList.join("\n")}\n`,
|
|
177
|
+
});
|
|
178
|
+
if (out === null) return null;
|
|
179
|
+
const shas = out.trim().split("\n");
|
|
180
|
+
if (shas.length !== hashList.length) return null;
|
|
181
|
+
hashList.forEach((path, i) => tokens.set(path, `blob:${shas[i]}`));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const hash = createHash("sha256");
|
|
185
|
+
let statOnly = 0;
|
|
186
|
+
for (const path of [...tokens.keys()].sort()) {
|
|
187
|
+
const token = tokens.get(path);
|
|
188
|
+
if (token.startsWith("stat:")) statOnly++;
|
|
189
|
+
hash.update(`${path}\0${token.replace(/^(?:100644|100755):/, "blob:")}\n`);
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
digest: `sha256:${hash.digest("hex")}`,
|
|
193
|
+
root,
|
|
194
|
+
files: tokens.size,
|
|
195
|
+
hashed: hashList.length,
|
|
196
|
+
statOnly,
|
|
197
|
+
capped,
|
|
198
|
+
newestEditMs,
|
|
199
|
+
ms: Date.now() - started,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (invokedDirectly(import.meta.url)) {
|
|
204
|
+
const { flags } = parseArgs(process.argv.slice(2), { booleans: ["json"] });
|
|
205
|
+
const r = sourceDigest(typeof flags.repo === "string" ? flags.repo : process.cwd());
|
|
206
|
+
if (!r) {
|
|
207
|
+
process.stderr.write("source-digest: not a git work tree, or git did not answer in time\n");
|
|
208
|
+
process.exit(3);
|
|
209
|
+
}
|
|
210
|
+
process.stdout.write(flags.json ? `${JSON.stringify(r)}\n` : `${r.digest}\n`);
|
|
211
|
+
}
|
|
@@ -40,10 +40,25 @@
|
|
|
40
40
|
* mode without the evidence). Phase 3 notes the unverified todos and the
|
|
41
41
|
* exemptions a todo declared for itself (`--no-tests`, `selfDeclared`).
|
|
42
42
|
*
|
|
43
|
+
* The tests RED wrote are kept. RED records `red.testFiles[]`: every test file
|
|
44
|
+
* of the run's work tree (state.worktreePath, or --repo) committed since the
|
|
45
|
+
* run base (state.baseSha, else MA_RUN_BASE_SHA; HEAD when neither is set)
|
|
46
|
+
* or new or changed in the work tree, as {path, blob}, so a failing test
|
|
47
|
+
* committed before RED is kept too. The blob is written into that
|
|
48
|
+
* repository's object store so the bytes can come back. Under
|
|
49
|
+
* MULTI_AGENT_UNATTENDED=1 test-integrity-gate reports even a recorded edit
|
|
50
|
+
* as blocking. GREEN refuses (exit 1) when one of those files was
|
|
51
|
+
* modified or deleted since, because a suite made green by weakening its own
|
|
52
|
+
* new test proves nothing; `restore` writes the RED bytes back. A legitimate
|
|
53
|
+
* fix to the test passes with `--test-edit-reason <why>` and is kept as
|
|
54
|
+
* `green.testEdits[]`, which test-integrity-gate --state reports for review.
|
|
55
|
+
* Outside a git work tree no files are recorded and nothing is refused.
|
|
56
|
+
*
|
|
43
57
|
* CLI (exit 0 ok, 1 the evidence does not hold, 2 usage or unreadable input):
|
|
44
58
|
* tdd-evidence.mjs parse <results>
|
|
45
|
-
* tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce]
|
|
46
|
-
* tdd-evidence.mjs green --state <f> --todo <id> --results <r>
|
|
59
|
+
* tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce] [--repo <dir>]
|
|
60
|
+
* tdd-evidence.mjs green --state <f> --todo <id> --results <r> [--test-edit-reason <why>] [--repo <dir>]
|
|
61
|
+
* tdd-evidence.mjs restore --state <f> --todo <id> [--repo <dir>]
|
|
47
62
|
* tdd-evidence.mjs check --state <f> --todo <id> --mode off|warn|enforce [--no-tests <reason>]
|
|
48
63
|
* tdd-evidence.mjs unverified --state <f>
|
|
49
64
|
*
|
|
@@ -56,10 +71,12 @@
|
|
|
56
71
|
*/
|
|
57
72
|
|
|
58
73
|
import { spawnSync } from "node:child_process";
|
|
59
|
-
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
60
|
-
import { basename, join } from "node:path";
|
|
74
|
+
import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
75
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
61
76
|
|
|
77
|
+
import { isTestPath } from "../scripts/_handle-patterns.mjs";
|
|
62
78
|
import { fromXcresultJson, summarize } from "../scripts/test-summary.mjs";
|
|
79
|
+
import { mkdirSafe, writeFileSafe } from "./safe-write.mjs";
|
|
63
80
|
import { invokedDirectly } from "./invoked-directly.mjs";
|
|
64
81
|
import { ArgsError, parseArgs } from "./args.mjs";
|
|
65
82
|
|
|
@@ -327,6 +344,191 @@ export function resultsFresh(path, startedAt) {
|
|
|
327
344
|
}
|
|
328
345
|
}
|
|
329
346
|
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
// Test files written in RED
|
|
349
|
+
|
|
350
|
+
const MAX_TEST_FILES = 200;
|
|
351
|
+
const GIT_TIMEOUT_MS = 20000;
|
|
352
|
+
|
|
353
|
+
function gitRun(dir, args, { input, buffer = false } = {}) {
|
|
354
|
+
const r = spawnSync("git", ["-C", dir, ...args], {
|
|
355
|
+
encoding: buffer ? null : "utf8",
|
|
356
|
+
timeout: GIT_TIMEOUT_MS,
|
|
357
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
358
|
+
input,
|
|
359
|
+
});
|
|
360
|
+
return r.status === 0 && !r.error ? r.stdout : null;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** The root of the git work tree `dir` is in, or null. */
|
|
364
|
+
export function workTreeRoot(dir) {
|
|
365
|
+
if (!dir || !existsSync(dir)) return null;
|
|
366
|
+
const out = gitRun(dir, ["rev-parse", "--show-toplevel"]);
|
|
367
|
+
return out ? out.trim() : null;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** A repository-relative path that stays inside the work tree. */
|
|
371
|
+
function insideRoot(root, path) {
|
|
372
|
+
if (typeof path !== "string" || !path || isAbsolute(path) || path.includes("\0")) return null;
|
|
373
|
+
const abs = resolve(root, path);
|
|
374
|
+
const rel = relative(root, abs);
|
|
375
|
+
if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
|
|
376
|
+
return abs;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The commit `ref` names in the work tree at root, or null. */
|
|
380
|
+
function commitOf(root, ref) {
|
|
381
|
+
if (typeof ref !== "string" || !/^[0-9a-f]{7,64}$/i.test(ref)) return null;
|
|
382
|
+
const out = gitRun(root, [
|
|
383
|
+
"rev-parse",
|
|
384
|
+
"--verify",
|
|
385
|
+
"--quiet",
|
|
386
|
+
"--end-of-options",
|
|
387
|
+
`${ref}^{commit}`,
|
|
388
|
+
]);
|
|
389
|
+
return out ? out.trim() || null : null;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* The test files the run wrote: those committed since the run base
|
|
394
|
+
* (`git diff <base>...HEAD`, deletions left out), and the work tree's new,
|
|
395
|
+
* changed and renamed-to ones, untracked included. Without a base, or with
|
|
396
|
+
* one that names no commit here, the run starts at HEAD and only the work
|
|
397
|
+
* tree counts.
|
|
398
|
+
*/
|
|
399
|
+
function changedTestFiles(root, base = null) {
|
|
400
|
+
const paths = [];
|
|
401
|
+
const since = commitOf(root, base);
|
|
402
|
+
if (since) {
|
|
403
|
+
const committed = gitRun(root, [
|
|
404
|
+
"diff",
|
|
405
|
+
"--name-only",
|
|
406
|
+
"-z",
|
|
407
|
+
"--diff-filter=d",
|
|
408
|
+
`${since}...HEAD`,
|
|
409
|
+
]);
|
|
410
|
+
for (const path of (committed ?? "").split("\0"))
|
|
411
|
+
if (path && isTestPath(path)) paths.push(path);
|
|
412
|
+
}
|
|
413
|
+
const out = gitRun(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
|
|
414
|
+
if (out === null) return paths;
|
|
415
|
+
const recs = out.split("\0");
|
|
416
|
+
for (let i = 0; i < recs.length; i++) {
|
|
417
|
+
const rec = recs[i];
|
|
418
|
+
if (rec.length < 4) continue;
|
|
419
|
+
const xy = rec.slice(0, 2);
|
|
420
|
+
if (xy[0] === "R" || xy[0] === "C") i++;
|
|
421
|
+
if (xy.includes("D")) continue;
|
|
422
|
+
const path = rec.slice(3);
|
|
423
|
+
if (isTestPath(path)) paths.push(path);
|
|
424
|
+
}
|
|
425
|
+
return paths;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** The run base: the state's baseSha, else MA_RUN_BASE_SHA, else none (HEAD). */
|
|
429
|
+
export function runBase(state, env = process.env) {
|
|
430
|
+
const fromState = typeof state?.baseSha === "string" ? state.baseSha.trim() : "";
|
|
431
|
+
return fromState || String(env.MA_RUN_BASE_SHA || "").trim() || null;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function hashFiles(root, paths, write) {
|
|
435
|
+
if (!paths.length) return [];
|
|
436
|
+
const args = write ? ["hash-object", "-w", "--stdin-paths"] : ["hash-object", "--stdin-paths"];
|
|
437
|
+
const out = gitRun(root, args, { input: `${paths.join("\n")}\n` });
|
|
438
|
+
const shas = out ? out.trim().split("\n") : [];
|
|
439
|
+
if (shas.length !== paths.length) throw new Unreadable(`git could not hash ${paths.join(", ")}`);
|
|
440
|
+
return shas;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Keep the test files a RED run stands on: each file's bytes go into the
|
|
445
|
+
* repository's object store and its blob id is returned. `paths` defaults to
|
|
446
|
+
* the test files the run wrote since `base` (changedTestFiles).
|
|
447
|
+
*
|
|
448
|
+
* @param {string} repo
|
|
449
|
+
* @param {string[]|null} [paths]
|
|
450
|
+
* @param {{base?: string|null}} [opts]
|
|
451
|
+
* @returns {{path: string, blob: string}[]}
|
|
452
|
+
*/
|
|
453
|
+
export function snapshotTestFiles(repo, paths = null, { base = null } = {}) {
|
|
454
|
+
const root = workTreeRoot(repo);
|
|
455
|
+
if (!root) return [];
|
|
456
|
+
const wanted = [...new Set(paths ?? changedTestFiles(root, base))]
|
|
457
|
+
.filter((p) => {
|
|
458
|
+
const abs = insideRoot(root, p);
|
|
459
|
+
return abs && !p.includes("\n") && existsSync(abs) && lstatSync(abs).isFile();
|
|
460
|
+
})
|
|
461
|
+
.sort()
|
|
462
|
+
.slice(0, MAX_TEST_FILES);
|
|
463
|
+
const blobs = hashFiles(root, wanted, true);
|
|
464
|
+
return wanted.map((path, i) => ({ path, blob: blobs[i] }));
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Which kept test files no longer hold their RED bytes.
|
|
469
|
+
*
|
|
470
|
+
* @param {string} repo
|
|
471
|
+
* @param {{path: string, blob: string}[]} testFiles
|
|
472
|
+
* @returns {{path: string, change: "modified"|"deleted"}[]}
|
|
473
|
+
*/
|
|
474
|
+
export function testFileChanges(repo, testFiles) {
|
|
475
|
+
const root = workTreeRoot(repo);
|
|
476
|
+
if (!root || !Array.isArray(testFiles) || !testFiles.length) return [];
|
|
477
|
+
const present = [];
|
|
478
|
+
const changes = [];
|
|
479
|
+
for (const f of testFiles) {
|
|
480
|
+
const abs = insideRoot(root, f?.path);
|
|
481
|
+
if (!abs) continue;
|
|
482
|
+
if (!existsSync(abs)) changes.push({ path: f.path, change: "deleted" });
|
|
483
|
+
else present.push(f);
|
|
484
|
+
}
|
|
485
|
+
const now = hashFiles(
|
|
486
|
+
root,
|
|
487
|
+
present.map((f) => f.path),
|
|
488
|
+
false,
|
|
489
|
+
);
|
|
490
|
+
present.forEach((f, i) => {
|
|
491
|
+
if (now[i] !== f.blob) changes.push({ path: f.path, change: "modified" });
|
|
492
|
+
});
|
|
493
|
+
return changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Write the RED bytes of every kept test file that changed back into the work
|
|
498
|
+
* tree. A path that leaves the work tree, or a link on the way, is refused.
|
|
499
|
+
*
|
|
500
|
+
* @param {string} repo
|
|
501
|
+
* @param {{path: string, blob: string}[]} testFiles
|
|
502
|
+
* @returns {string[]} the restored paths
|
|
503
|
+
*/
|
|
504
|
+
export function restoreTestFiles(repo, testFiles) {
|
|
505
|
+
const root = workTreeRoot(repo);
|
|
506
|
+
if (!root) throw new Unreadable(`${repo} is not in a git work tree`);
|
|
507
|
+
for (const f of testFiles ?? []) {
|
|
508
|
+
if (!insideRoot(root, f?.path)) {
|
|
509
|
+
throw new Refused(`refusing to restore ${f?.path}: outside the work tree`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const changed = new Set(testFileChanges(root, testFiles).map((c) => c.path));
|
|
513
|
+
const restored = [];
|
|
514
|
+
for (const f of testFiles ?? []) {
|
|
515
|
+
if (!changed.has(f.path)) continue;
|
|
516
|
+
const bytes = gitRun(root, ["cat-file", "blob", f.blob], { buffer: true });
|
|
517
|
+
if (bytes === null) throw new Unreadable(`blob ${f.blob} for ${f.path} is gone`);
|
|
518
|
+
const abs = insideRoot(root, f.path);
|
|
519
|
+
try {
|
|
520
|
+
mkdirSafe(dirname(abs), { mode: 0o755, anchors: [root] });
|
|
521
|
+
writeFileSafe(abs, bytes, { mode: 0o644, anchors: [root] });
|
|
522
|
+
} catch (err) {
|
|
523
|
+
if (err?.code === "ELINKED")
|
|
524
|
+
throw new Refused(`refusing to restore ${f.path}: ${err.message}`);
|
|
525
|
+
throw err;
|
|
526
|
+
}
|
|
527
|
+
restored.push(f.path);
|
|
528
|
+
}
|
|
529
|
+
return restored;
|
|
530
|
+
}
|
|
531
|
+
|
|
330
532
|
// ---------------------------------------------------------------------------
|
|
331
533
|
// Decisions
|
|
332
534
|
|
|
@@ -407,9 +609,19 @@ export function redRecord(summary, { tests = [], alreadyPassing = "", mode = "wa
|
|
|
407
609
|
* The GREEN record, on top of the todo's RED record.
|
|
408
610
|
*
|
|
409
611
|
* @param {object} summary
|
|
410
|
-
* @param {{prior: object|null, testPolicy?: string, now: string
|
|
612
|
+
* @param {{prior: object|null, testPolicy?: string, now: string,
|
|
613
|
+
* testChanges?: {path: string, change: string}[], testEditReason?: string}} opts
|
|
411
614
|
*/
|
|
412
|
-
export function greenRecord(
|
|
615
|
+
export function greenRecord(
|
|
616
|
+
summary,
|
|
617
|
+
{ prior, testPolicy, now, testChanges = [], testEditReason = "" },
|
|
618
|
+
) {
|
|
619
|
+
if (testChanges.length && !testEditReason) {
|
|
620
|
+
const list = testChanges.map((c) => `${c.path} (${c.change})`).join(", ");
|
|
621
|
+
throw new Refused(
|
|
622
|
+
`test file(s) written in RED changed before GREEN: ${list}. A suite made green by weakening its own new test proves nothing: restore them (tdd-evidence.mjs restore, plan-todos.sh tdd-restore), or, when the test itself was wrong, record why with --test-edit-reason <why>`,
|
|
623
|
+
);
|
|
624
|
+
}
|
|
413
625
|
if (!prior?.red && testPolicy !== "tests-after") {
|
|
414
626
|
throw new Refused("no RED run recorded for this todo; record RED first");
|
|
415
627
|
}
|
|
@@ -436,7 +648,10 @@ export function greenRecord(summary, { prior, testPolicy, now }) {
|
|
|
436
648
|
base.outcome = "verified";
|
|
437
649
|
delete base.reason;
|
|
438
650
|
}
|
|
439
|
-
|
|
651
|
+
const green = { at: now, failed: 0, total: summary.total };
|
|
652
|
+
if (testChanges.length)
|
|
653
|
+
green.testEdits = testChanges.map((c) => ({ ...c, reason: testEditReason }));
|
|
654
|
+
return { ...base, green };
|
|
440
655
|
}
|
|
441
656
|
|
|
442
657
|
function exemption(todo, { taskType, testPolicy, noTests }) {
|
|
@@ -532,21 +747,39 @@ function main(argv) {
|
|
|
532
747
|
if (!f.results) throw new Unreadable("--results is required");
|
|
533
748
|
const summary = parseResults(f.results);
|
|
534
749
|
resultsFresh(f.results, todo.startedAt);
|
|
535
|
-
const
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
750
|
+
const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
|
|
751
|
+
let record;
|
|
752
|
+
if (cmd === "red") {
|
|
753
|
+
record = redRecord(summary, {
|
|
754
|
+
tests: (f.tests ?? "").split(",").filter(Boolean),
|
|
755
|
+
alreadyPassing: f["already-passing"] ?? "",
|
|
756
|
+
mode: f.mode,
|
|
757
|
+
now,
|
|
758
|
+
});
|
|
759
|
+
const testFiles =
|
|
760
|
+
record.outcome === "red"
|
|
761
|
+
? snapshotTestFiles(repo, null, { base: runBase(state, process.env) })
|
|
762
|
+
: [];
|
|
763
|
+
if (testFiles.length) record.red.testFiles = testFiles;
|
|
764
|
+
} else {
|
|
765
|
+
record = greenRecord(summary, {
|
|
766
|
+
prior: todo.tdd ?? null,
|
|
767
|
+
testPolicy: state.testPolicy,
|
|
768
|
+
now,
|
|
769
|
+
testChanges: testFileChanges(repo, todo.tdd?.red?.testFiles),
|
|
770
|
+
testEditReason: typeof f["test-edit-reason"] === "string" ? f["test-edit-reason"] : "",
|
|
771
|
+
});
|
|
772
|
+
}
|
|
544
773
|
if (record.red?.testsUnverifiable) {
|
|
545
774
|
process.stderr.write(
|
|
546
775
|
`tdd-evidence: warning: ${f.results} names no failing test, so --tests ${f.tests} is recorded unchecked (red.testsUnverifiable); JUnit XML names them\n`,
|
|
547
776
|
);
|
|
548
777
|
}
|
|
549
778
|
print(record);
|
|
779
|
+
} else if (cmd === "restore") {
|
|
780
|
+
const { state, todo } = loadTodo(f);
|
|
781
|
+
const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
|
|
782
|
+
print({ restored: restoreTestFiles(repo, todo.tdd?.red?.testFiles ?? []) });
|
|
550
783
|
} else if (cmd === "check") {
|
|
551
784
|
const { state, todo } = loadTodo(f);
|
|
552
785
|
print(
|
|
@@ -566,7 +799,7 @@ function main(argv) {
|
|
|
566
799
|
}
|
|
567
800
|
} else {
|
|
568
801
|
throw new Unreadable(
|
|
569
|
-
`unknown subcommand '${cmd ?? ""}' (parse | red | green | check | unverified)`,
|
|
802
|
+
`unknown subcommand '${cmd ?? ""}' (parse | red | green | restore | check | unverified)`,
|
|
570
803
|
);
|
|
571
804
|
}
|
|
572
805
|
return 0;
|
|
@@ -22,6 +22,17 @@
|
|
|
22
22
|
* Extra attributes follow `source` in the order given; a value loses `"`, `<`,
|
|
23
23
|
* `>` and line breaks, and an empty one is left out.
|
|
24
24
|
*
|
|
25
|
+
* Text that reads like instructions to the model is marked, never changed or
|
|
26
|
+
* refused: wrapUntrusted adds `suspicious="<classes>"` last, naming the
|
|
27
|
+
* SUSPICIOUS_CLASSES its rules matched, in that list's order. The text
|
|
28
|
+
* patterns run on the text and on a fold of it (NFKC, format characters such
|
|
29
|
+
* as zero-width ones removed), over the head and tail of a long text, with
|
|
30
|
+
* bounded gaps only. Hidden or look-alike characters hide text rather than
|
|
31
|
+
* instruct, so they are not marked. A caller that passes its own `suspicious`
|
|
32
|
+
* value, or the toolkit's `injection-flags`, keeps it and gets no second mark.
|
|
33
|
+
* Blocking stays with the guards; the mark is a signal for the model and for
|
|
34
|
+
* review.
|
|
35
|
+
*
|
|
25
36
|
* This file imports nothing, so the vendored copy runs on its own.
|
|
26
37
|
*
|
|
27
38
|
* @module untrusted-fence
|
|
@@ -47,14 +58,134 @@ export function hasFenceMarker(text) {
|
|
|
47
58
|
return MARKER.test(String(text ?? ""));
|
|
48
59
|
}
|
|
49
60
|
|
|
61
|
+
export const SUSPICIOUS_SCAN_HEAD = 196_608;
|
|
62
|
+
export const SUSPICIOUS_SCAN_TAIL = 65_536;
|
|
63
|
+
|
|
64
|
+
/** The classes a mark can name, in the order it lists them (the toolkit's suspiciousOf order). */
|
|
65
|
+
export const SUSPICIOUS_CLASSES = Object.freeze([
|
|
66
|
+
"instruction-override",
|
|
67
|
+
"role-tag",
|
|
68
|
+
"tool-invocation",
|
|
69
|
+
"exfiltration",
|
|
70
|
+
"fence-escape",
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Instruction-shaped text by family, each folded into one class. The family
|
|
75
|
+
* ids and patterns are the toolkit's injection-scan families, so a fenced
|
|
76
|
+
* tool result and a fenced ticket carry the same names. Every pattern has
|
|
77
|
+
* bounded gaps only, so the cost is linear in the scanned text.
|
|
78
|
+
*/
|
|
79
|
+
export const SUSPICIOUS_RULES = Object.freeze([
|
|
80
|
+
{
|
|
81
|
+
id: "instruction-override",
|
|
82
|
+
cls: "instruction-override",
|
|
83
|
+
re: /\b(ignore|disregard|forget|override)\b[^.\n]{0,40}\b(previous|prior|above|earlier|all|your|the)\b[^.\n]{0,30}\b(instructions?|prompts?|rules|directions|guidelines)\b/i,
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: "role-reassignment",
|
|
87
|
+
cls: "instruction-override",
|
|
88
|
+
re: /\b(you are now (a|an|the|in) [^.\n]{0,30}\b(ai|assistant|model|agent|bot|mode|persona|character)\b|you are (actually|secretly) (a|an|the)\b|from now on,? you (are|will|must|should)\b|act as (an?|the) (unrestricted|jailbroken|developer mode)|developer mode enabled|do anything now|jailbreak mode)/i,
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: "directive-injection",
|
|
92
|
+
cls: "instruction-override",
|
|
93
|
+
re: /(^|\n)[ \t#>*-]*(new|updated|revised|real|actual|additional|hidden)\s+(instructions?|directives?|task|system prompt|orders)\s*:|\b(the (assistant|ai|model|agent)|you) (must|should) (not|never) (tell|inform|mention|reveal|show)\b[^.\n]{0,20}\b(the )?user\b|\b(do not|don't|never) (tell|inform|mention (this|it) to|show (this|it) to) the user\b/i,
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
id: "system-prompt-probe",
|
|
97
|
+
cls: "instruction-override",
|
|
98
|
+
re: /\b(reveal|print|show|repeat|output)\b[^.\n]{0,30}\b(system prompt|hidden instructions|initial instructions)\b/i,
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "chat-template-token",
|
|
102
|
+
cls: "role-tag",
|
|
103
|
+
re: /<\|(im_start|im_end|system|endoftext|start_header_id|end_header_id|eot_id)\|>|\[\/?INST\]|<<\/?SYS>>|<\/?(system|assistant)>|\n\n(Human|Assistant):/i,
|
|
104
|
+
},
|
|
105
|
+
{ id: "forged-turns", cls: "role-tag", turns: true },
|
|
106
|
+
{
|
|
107
|
+
id: "tool-call-mimicry",
|
|
108
|
+
cls: "tool-invocation",
|
|
109
|
+
re: /<\/?(function_calls|invoke|tool_use|tool_call|tool_code)\b|"(tool_use|function_call)"\s*:|"tool_calls"\s*:\s*\[|"method"\s*:\s*"tools\/call"/i,
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
id: "exfiltration-request",
|
|
113
|
+
cls: "exfiltration",
|
|
114
|
+
re: /\b(send|post|upload|forward|exfiltrate|leak)\b[^.\n]{0,60}\b(api[_ -]?keys?|tokens?|secrets?|credentials?|passwords?|env(ironment)? variables?|\.env|ssh keys?)\b/i,
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
id: "covert-link-action",
|
|
118
|
+
cls: "exfiltration",
|
|
119
|
+
re: /\b(open|visit|navigate to|fetch|curl|click)\b[^.\n]{0,20}https?:\/\/\S+[^.\n]{0,40}\b(silently|without telling|do not mention|don't mention|secretly)\b/i,
|
|
120
|
+
},
|
|
121
|
+
{ id: "fence-marker", cls: "fence-escape", raw: MARKER },
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
const ROLE_LINE = /^[ \t]*(system|assistant|user|human)[ \t]*:/gim;
|
|
125
|
+
const MAX_ROLE_LINES = 64;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A forged conversation: line-start role markers for at least two different
|
|
129
|
+
* roles, one of them system or assistant. A single "System: macOS 14" line is
|
|
130
|
+
* a spec sheet, not a turn.
|
|
131
|
+
*/
|
|
132
|
+
function forgedTurns(text) {
|
|
133
|
+
const roles = new Set();
|
|
134
|
+
let seen = 0;
|
|
135
|
+
for (const m of text.matchAll(ROLE_LINE)) {
|
|
136
|
+
roles.add(m[1].toLowerCase());
|
|
137
|
+
if (++seen >= MAX_ROLE_LINES) break;
|
|
138
|
+
}
|
|
139
|
+
return roles.size >= 2 && (roles.has("system") || roles.has("assistant"));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The part of a text the rules read: all of it, or its head and tail joined by a newline. */
|
|
143
|
+
function scanWindow(text) {
|
|
144
|
+
if (text.length <= SUSPICIOUS_SCAN_HEAD + SUSPICIOUS_SCAN_TAIL) return text;
|
|
145
|
+
return `${text.slice(0, SUSPICIOUS_SCAN_HEAD)}\n${text.slice(text.length - SUSPICIOUS_SCAN_TAIL)}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The fold the text patterns also run on: NFKC, format characters removed. */
|
|
149
|
+
function foldForRules(text) {
|
|
150
|
+
return text.normalize("NFKC").replace(/\p{Cf}/gu, "");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The SUSPICIOUS_CLASSES the text falls into, in class order, each once.
|
|
155
|
+
*
|
|
156
|
+
* @param {string} text
|
|
157
|
+
* @returns {string[]}
|
|
158
|
+
*/
|
|
159
|
+
export function suspiciousKinds(text) {
|
|
160
|
+
const raw = scanWindow(String(text ?? ""));
|
|
161
|
+
if (!raw) return [];
|
|
162
|
+
const folded = foldForRules(raw);
|
|
163
|
+
const hit = new Set();
|
|
164
|
+
for (const r of SUSPICIOUS_RULES) {
|
|
165
|
+
if (hit.has(r.cls)) continue;
|
|
166
|
+
const matched = r.raw
|
|
167
|
+
? r.raw.test(raw)
|
|
168
|
+
: r.turns
|
|
169
|
+
? forgedTurns(raw) || (folded !== raw && forgedTurns(folded))
|
|
170
|
+
: r.re.test(raw) || (folded !== raw && r.re.test(folded));
|
|
171
|
+
if (matched) hit.add(r.cls);
|
|
172
|
+
}
|
|
173
|
+
return SUSPICIOUS_CLASSES.filter((c) => hit.has(c));
|
|
174
|
+
}
|
|
175
|
+
|
|
50
176
|
/**
|
|
51
177
|
* @param {string} source where the text came from, e.g. `jira:PROJ-12`
|
|
52
178
|
* @param {string} text
|
|
53
179
|
* @param {Record<string, unknown>} [attrs] extra attributes after source
|
|
54
180
|
*/
|
|
55
181
|
export function wrapUntrusted(source, text, attrs = {}) {
|
|
182
|
+
const own = (k) => Object.prototype.hasOwnProperty.call(attrs, k);
|
|
183
|
+
const all =
|
|
184
|
+
own("suspicious") || own("injection-flags")
|
|
185
|
+
? attrs
|
|
186
|
+
: { ...attrs, suspicious: suspiciousKinds(text).join(",") };
|
|
56
187
|
let head = `${UNTRUSTED_OPEN} source="${clean(source || "unknown")}"`;
|
|
57
|
-
for (const [name, value] of Object.entries(
|
|
188
|
+
for (const [name, value] of Object.entries(all)) {
|
|
58
189
|
if (!ATTR_NAME.test(name) || name === "source") {
|
|
59
190
|
throw new Error(`untrusted-fence: bad attribute name ${JSON.stringify(name)}`);
|
|
60
191
|
}
|