worktrust 0.10.37 → 0.11.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.
Files changed (43) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +59 -2
  3. package/SECURITY.md +25 -0
  4. package/chat-exports.mjs +20 -20
  5. package/engine-release.json +1 -1
  6. package/export-facts.mjs +71 -0
  7. package/log-session.mjs +15 -15
  8. package/package-release.json +1 -1
  9. package/package.json +36 -2
  10. package/remote-adapter-claude-code.mjs +111 -0
  11. package/remote-adapter-codex.mjs +119 -0
  12. package/remote-approval-bridge.mjs +122 -0
  13. package/remote-approvals.mjs +124 -0
  14. package/remote-attachments.mjs +129 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +325 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +205 -0
  22. package/remote-inventory.mjs +132 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-pairing.mjs +104 -0
  25. package/remote-pipeline-config.mjs +177 -0
  26. package/remote-pipeline-parsers.mjs +121 -0
  27. package/remote-pipeline.mjs +234 -0
  28. package/remote-policy.mjs +199 -0
  29. package/remote-preview.mjs +146 -0
  30. package/remote-projects.mjs +87 -0
  31. package/remote-protocol.mjs +3881 -0
  32. package/remote-qr.mjs +175 -0
  33. package/remote-release-plans.mjs +88 -0
  34. package/remote-releases.mjs +297 -0
  35. package/remote-run.mjs +174 -0
  36. package/remote-service.mjs +101 -0
  37. package/remote-session-list.mjs +25 -0
  38. package/remote-sessions.mjs +348 -0
  39. package/remote-steered.mjs +114 -0
  40. package/remote-steering.mjs +97 -0
  41. package/remote-store.mjs +123 -0
  42. package/remote-transport.mjs +88 -0
  43. package/worktrust.mjs +13 -6
@@ -0,0 +1,177 @@
1
+ /**
2
+ * THE PERSON'S PIPELINE FILE, READ AND HELD TO AN ALLOWLIST (owner, 2026-11-07; docs/remote-agents/PROTOCOL.md "Pipelines").
3
+ *
4
+ * A project's stages live in `.worktrust/pipeline.json`, which the PERSON writes and reviews at the keyboard
5
+ * (`worktrust remote pipeline review <folder>` prints every stage and command and pins a hash of the file and of the
6
+ * package.json scripts it names). The daemon runs a pipeline only while that hash still holds: an agent (or anyone) that
7
+ * edits the file or a named script after the review makes the pipeline `unreviewed` until the person looks again.
8
+ *
9
+ * A stage's `run` is one of five forms, split on single spaces, no quoting, no shell, every token from a safe character
10
+ * set and no `..` segment:
11
+ * pnpm <script> | pnpm run <script> | npm run <script> a script the project's package.json names, always run as
12
+ * `<pnpm|npm> run <script>` (never a package manager built-in such
13
+ * as install, add or publish)
14
+ * node scripts/<file>.(mjs|js|cjs) [args] a file inside the project's scripts folder
15
+ * semgrep [scan] <flags> [target] a local scan; `semgrep ci` (which uploads) is refused
16
+ * zap-baseline.py <flags> against a loopback target only (http://localhost, 127.0.0.1)
17
+ * A stage of kind deploy or publish has no `run`: it is a step at the desk, never run by the daemon. A stage whose script
18
+ * or file is named like a deploy (deploy, publish, ship, push, promote, rollout, upload) is refused as well, whatever its
19
+ * kind: those stay in the ship scripts at the computer (owner rule). Pure: the caller passes the file's text and the
20
+ * package.json scripts.
21
+ */
22
+ import { createHash } from "node:crypto";
23
+ import * as P from "./remote-protocol.mjs";
24
+
25
+ export const PIPELINE_FILE = ".worktrust/pipeline.json";
26
+ export const MAX_CONFIG_BYTES = 65_536;
27
+ const TOP_KEYS = new Set(["version", "run_after_tasks", "path_prepend", "stages"]);
28
+ const STAGE_KEYS = new Set(["id", "label", "kind", "run", "parser", "report", "timeout_min", "fail_on"]);
29
+ const STAGE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
30
+ const SAFE_TOKEN = /^[A-Za-z0-9@%+=:,./_-]+$/;
31
+ const SCRIPT_NAME = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,99}$/;
32
+ const NODE_FILE = /^scripts\/[A-Za-z0-9._/-]+\.(mjs|js|cjs)$/;
33
+ const REPORT = /^[A-Za-z0-9._/-]+\.(json|xml)$/;
34
+ const DEPLOY_WORDS = /(^|[:._/-])(deploy|deployment|publish|ship|push|promote|rollout|upload)([:._/-]|$)/i;
35
+ /**
36
+ * A deploy or a publish in a script's TEXT (review 2026-11-07, P2-3): a deploy tool in command position, a package
37
+ * manager's publish or deploy, a git push, a GitHub release. Applied to the named script and its pre/post hooks.
38
+ */
39
+ const DEPLOY_TEXT = /(^|&&|\|\||[;|(]|\bnpx\s+|\bdlx\s+)\s*(vercel|netlify|fly|flyctl|firebase|heroku|wrangler|serverless|sls|kubectl|helm|terraform|pulumi|eas|railway|render)(\s|$)|\b(npm|pnpm|yarn|bun)\s+(run\s+)?(publish|deploy)\b|\bgit\s+push\b|\bgh\s+release\b/;
40
+ const SEVERITIES = ["high", "medium", "low", "none"];
41
+ const SEMGREP_FLAGS = new Set(["--json", "--metrics=off", "--error", "--quiet", "-q", "--no-git-ignore", "--disable-version-check", "--oss-only"]);
42
+ /** A rules source semgrep reads: a registry pack by name, or a file inside the project; never a URL or `auto` (P3-10). */
43
+ const SEMGREP_CONFIG = /^(p\/[a-z0-9][a-z0-9_-]{0,63}|[A-Za-z0-9._/-]+\.(ya?ml))$/;
44
+ const SEMGREP_VALUED = new Set(["--config", "--exclude", "--include", "--severity", "--timeout", "--jobs", "--max-target-bytes"]);
45
+ const ZAP_FLAGS = new Set(["-I", "-j", "-a", "-s", "-d"]);
46
+ const ZAP_VALUED = new Set(["-t", "-J", "-x", "-m", "-T"]); // no -c (a rules file) or -z (raw ZAP options): the list stays this short
47
+ const LOOPBACK = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?(\/[A-Za-z0-9._~/%-]*)?$/;
48
+
49
+ const refuse = (detail) => ({ ok: false, detail });
50
+ const relativeOk = (p) => typeof p === "string" && !p.startsWith("/") && !p.split("/").some((s) => s === ".." || s === "") && SAFE_TOKEN.test(p);
51
+
52
+ /**
53
+ * One stage's command as argv, or why not. `scripts` is package.json's scripts object (or null). Run time calls this
54
+ * again on every stage, so a config read earlier cannot smuggle a command past a later check.
55
+ */
56
+ export function allowCommand(run, scripts) {
57
+ if (typeof run !== "string" || run.length === 0 || run.length > 500) return refuse("run: not a command line");
58
+ const tokens = run.split(" ");
59
+ if (tokens.some((t) => t === "" || !SAFE_TOKEN.test(t) || t.split("/").includes(".."))) return refuse("run: only plain words, single spaces, no shell characters, no ..");
60
+ const [head, ...rest] = tokens;
61
+ const scriptOf = (name) => {
62
+ if (!SCRIPT_NAME.test(name ?? "")) return refuse("run: not a script name");
63
+ if (!scripts || typeof scripts[name] !== "string") return refuse(`run: package.json names no script ${name}`);
64
+ if (DEPLOY_WORDS.test(name)) return refuse(`run: ${name} is a deploy or publish; it stays at your desk`);
65
+ for (const hook of [name, `pre${name}`, `post${name}`]) if (typeof scripts[hook] === "string" && DEPLOY_TEXT.test(scripts[hook])) return refuse(`run: the script ${hook} deploys or publishes; it stays at your desk`);
66
+ return null;
67
+ };
68
+ if (head === "pnpm" || head === "npm") {
69
+ const name = rest[0] === "run" ? rest[1] : head === "pnpm" ? rest[0] : undefined;
70
+ const used = rest[0] === "run" ? 2 : 1;
71
+ if (name === undefined || rest.length !== used) return refuse(`run: ${head} takes exactly one script${head === "npm" ? " (npm run <script>)" : ""}`);
72
+ const bad = scriptOf(name);
73
+ return bad ?? { ok: true, file: head, args: ["run", name], form: "script", script: name };
74
+ }
75
+ if (head === "node") {
76
+ const [file, ...args] = rest;
77
+ if (!NODE_FILE.test(file ?? "")) return refuse("run: node runs a file under scripts/ only");
78
+ if (DEPLOY_WORDS.test(file)) return refuse(`run: ${file} is a deploy or publish; it stays at your desk`);
79
+ if (args.some((a) => a.startsWith("--") && /^--(eval|require|import|loader|inspect)/.test(a))) return refuse("run: no node flags");
80
+ return { ok: true, file: "node", args: [file, ...args], form: "node", script: file };
81
+ }
82
+ if (head === "semgrep") {
83
+ const args = rest[0] === "scan" ? rest.slice(1) : rest;
84
+ if (rest[0] === "ci" || rest[0] === "login" || rest[0] === "publish") return refuse("run: semgrep scans locally only");
85
+ for (let i = 0; i < args.length; i += 1) {
86
+ const a = args[i];
87
+ const [flag, value] = a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, null];
88
+ if (SEMGREP_FLAGS.has(a)) continue;
89
+ if (SEMGREP_VALUED.has(flag)) {
90
+ const v = value ?? args[++i];
91
+ if (!v || v.startsWith("-")) return refuse(`run: ${flag} needs a value`);
92
+ if (flag === "--config" && !(SEMGREP_CONFIG.test(v) && (v.startsWith("p/") || relativeOk(v)))) return refuse("run: --config is a registry pack (p/<name>) or a rules file in the project");
93
+ continue;
94
+ }
95
+ if (i === args.length - 1 && !a.startsWith("-") && relativeOk(a)) continue; // the target folder
96
+ return refuse(`run: semgrep ${a} is not on the list`);
97
+ }
98
+ if (!args.includes("--metrics=off")) return refuse("run: semgrep runs with --metrics=off");
99
+ return { ok: true, file: "semgrep", args: rest[0] === "scan" ? rest : ["scan", ...rest], form: "semgrep", script: null };
100
+ }
101
+ if (head === "zap-baseline.py") {
102
+ let target = null;
103
+ for (let i = 0; i < rest.length; i += 1) {
104
+ const a = rest[i];
105
+ if (ZAP_FLAGS.has(a)) continue;
106
+ if (!ZAP_VALUED.has(a)) return refuse(`run: zap-baseline.py ${a} is not on the list`);
107
+ const v = rest[++i];
108
+ if (!v) return refuse(`run: ${a} needs a value`);
109
+ if (a === "-t") target = v;
110
+ if ((a === "-J" || a === "-x") && !relativeOk(v)) return refuse(`run: ${a} writes or reads inside the project only`);
111
+ }
112
+ if (!target || !LOOPBACK.test(target)) return refuse("run: ZAP scans a loopback target only (http://localhost or 127.0.0.1)");
113
+ return { ok: true, file: "zap-baseline.py", args: rest, form: "zap", script: null };
114
+ }
115
+ return refuse(`run: ${head} is not on the allowlist (pnpm, npm run, node scripts/…, semgrep, zap-baseline.py)`);
116
+ }
117
+
118
+ /** The file's text and package.json's scripts → { ok, config } with every stage checked, or the first refusal. */
119
+ export function parsePipelineConfig(text, scripts) {
120
+ if (typeof text !== "string" || Buffer.byteLength(text) > MAX_CONFIG_BYTES) return refuse("the file is missing or larger than 64 KB");
121
+ let raw;
122
+ try { raw = JSON.parse(text); } catch { return refuse("the file is not JSON"); }
123
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return refuse("the file is not an object");
124
+ const extra = Object.keys(raw).find((k) => !TOP_KEYS.has(k));
125
+ if (extra) return refuse(`unknown key ${extra}`);
126
+ if (raw.version !== 1) return refuse("version must be 1");
127
+ if (raw.run_after_tasks !== undefined && typeof raw.run_after_tasks !== "boolean") return refuse("run_after_tasks is true or false");
128
+ const prepend = raw.path_prepend ?? [];
129
+ if (!Array.isArray(prepend) || prepend.length > 8 || prepend.some((d) => typeof d !== "string" || !d.startsWith("/") || !SAFE_TOKEN.test(d) || d.split("/").includes(".."))) return refuse("path_prepend is a list of absolute folders");
130
+ if (!Array.isArray(raw.stages) || raw.stages.length === 0 || raw.stages.length > P.MAX_PIPELINE_STAGES) return refuse(`stages: 1 to ${P.MAX_PIPELINE_STAGES}`);
131
+ const ids = new Set();
132
+ const stages = [];
133
+ for (const [n, s] of raw.stages.entries()) {
134
+ const at = `stages[${n}]`;
135
+ if (!s || typeof s !== "object" || Array.isArray(s)) return refuse(`${at}: not an object`);
136
+ const unknown = Object.keys(s).find((k) => !STAGE_KEYS.has(k));
137
+ if (unknown) return refuse(`${at}: unknown key ${unknown}`);
138
+ if (!STAGE_ID.test(s.id ?? "") || ids.has(s.id)) return refuse(`${at}.id: [a-z0-9_-], once`);
139
+ ids.add(s.id);
140
+ if (typeof s.label !== "string" || s.label.trim() === "" || s.label.length > 200) return refuse(`${at}.label: 1 to 200 characters`);
141
+ if (!P.STAGE_KINDS.includes(s.kind)) return refuse(`${at}.kind: one of ${P.STAGE_KINDS.join(", ")}`);
142
+ const desk = P.DESK_STAGE_KINDS.has(s.kind);
143
+ if (desk) {
144
+ if (Object.keys(s).some((k) => !["id", "label", "kind"].includes(k))) return refuse(`${at}: a ${s.kind} stage is a step at your desk; it has no run`);
145
+ stages.push({ id: s.id, label: s.label, kind: s.kind, desk: true });
146
+ continue;
147
+ }
148
+ const parser = s.parser ?? "none";
149
+ if (!P.PIPELINE_PARSERS.includes(parser)) return refuse(`${at}.parser: one of ${P.PIPELINE_PARSERS.join(", ")}`);
150
+ const cmd = allowCommand(s.run, scripts);
151
+ if (!cmd.ok) return refuse(`${at}.${cmd.detail}`);
152
+ if (s.report !== undefined && !(typeof s.report === "string" && REPORT.test(s.report) && relativeOk(s.report))) return refuse(`${at}.report: a .json or .xml file inside the project`);
153
+ const timeout = s.timeout_min ?? 30;
154
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 120) return refuse(`${at}.timeout_min: 1 to 120`);
155
+ const failOn = s.fail_on ?? (parser === "semgrep_json" || parser === "zap_json" ? "high" : "none");
156
+ if (!SEVERITIES.includes(failOn)) return refuse(`${at}.fail_on: high, medium, low or none`);
157
+ stages.push({ id: s.id, label: s.label, kind: s.kind, desk: false, run: s.run, parser, report: s.report ?? null, timeout_ms: timeout * 60_000, fail_on: failOn });
158
+ }
159
+ return { ok: true, config: { run_after_tasks: raw.run_after_tasks ?? true, path_prepend: prepend, stages } };
160
+ }
161
+
162
+ /** The project files a `node scripts/<file>` stage runs, so their bytes are part of what the person reviewed. */
163
+ export function namedFiles(text, scripts) {
164
+ const parsed = parsePipelineConfig(text, scripts);
165
+ return parsed.ok ? [...new Set(parsed.config.stages.flatMap((s) => { const c = s.desk ? null : allowCommand(s.run, scripts); return c?.form === "node" ? [c.script] : []; }))] : [];
166
+ }
167
+
168
+ /**
169
+ * What the person reviewed (review 2026-11-07, P2-1/P2-2): the file's bytes, package.json's WHOLE scripts object (so a new
170
+ * pre or post hook is a change), the project's .npmrc (script-shell, node-options), and the bytes of every file a
171
+ * `node scripts/<file>` stage runs. `extras` is { npmrc: text | null, files: { path: text | null } } from the project.
172
+ * A changed byte in any of them is a new pipeline that needs a new review.
173
+ */
174
+ export function reviewHash(text, scripts, extras = { npmrc: null, files: {} }) {
175
+ const files = Object.fromEntries(namedFiles(text, scripts).map((f) => [f, createHash("sha256").update(extras.files?.[f] ?? "\u0000absent").digest("hex")]));
176
+ return createHash("sha256").update(P.canonicalJson({ file: text, scripts: scripts ?? null, npmrc: extras.npmrc ?? null, files })).digest("hex");
177
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * WHAT A STAGE'S TOOL REPORTED, COUNTED (owner, 2026-11-07: "400 / 500 tests" only when a tool said so). Pure functions
3
+ * over a tool's own report text. Each returns `{ measured?, findings? }` with only what it could read: a report that does
4
+ * not parse gives `{}`, never a guess and never a zero. `measured` is { done, total, failed, unit }: tests that ran over
5
+ * the tests there are (done = passed + failed + skipped), failed among them. `findings` is { high, medium, low } from a
6
+ * scanner. Tested against recorded fixtures in scripts/fixtures/remote/pipeline/.
7
+ *
8
+ * tap TAP 13/14 (node --test --test-reporter=tap, tape, …): the `# tests/pass/fail` summary when present,
9
+ * else the top-level `ok`/`not ok` lines over the plan `1..N`; `createTapCounter` counts while it streams
10
+ * node_test the node test runner's spec summary (ℹ tests / pass / fail / skipped / todo / cancelled)
11
+ * junit_xml <testsuites tests failures errors skipped>, else the sum of its <testsuite> elements
12
+ * vitest_json Vitest's json reporter (Jest's shape): numTotalTests, numFailedTests …
13
+ * jest_json the same fields from Jest
14
+ * semgrep_json results[].extra.severity ERROR / WARNING / INFO → high / medium / low; paths.scanned as files
15
+ * zap_json site[].alerts[].riskcode 3 / 2 / 1 → high / medium / low (0, informational, is not a finding)
16
+ */
17
+ const int = (v) => (typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : null);
18
+ const measured = (total, failed, unit = "tests") => (Number.isSafeInteger(total) && total > 0 && Number.isSafeInteger(failed) && failed >= 0 && failed <= total ? { measured: { done: total, total, failed, unit } } : {});
19
+
20
+ function jsonOf(text) {
21
+ try { return JSON.parse(text); } catch { /* a reporter may print around its JSON */ }
22
+ const from = text.indexOf("{"), to = text.lastIndexOf("}");
23
+ if (from < 0 || to <= from) return null;
24
+ try { return JSON.parse(text.slice(from, to + 1)); } catch { return null; }
25
+ }
26
+
27
+ export function parseTap(text) {
28
+ const summary = {};
29
+ for (const m of text.matchAll(/^#\s+(tests|pass|fail|skipped|todo|cancelled)\s+(\d+)\s*$/gm)) summary[m[1]] = Number(m[2]);
30
+ if (summary.tests !== undefined) return measured(summary.tests, (summary.fail ?? 0) + (summary.cancelled ?? 0));
31
+ let ok = 0, notOk = 0, plan = null;
32
+ for (const line of text.split("\n")) {
33
+ if (/^ok\s+\d+/.test(line)) ok += 1;
34
+ else if (/^not ok\s+\d+/.test(line)) notOk += 1;
35
+ else if (/^1\.\.(\d+)\s*$/.test(line)) plan = Number(/^1\.\.(\d+)/.exec(line)[1]);
36
+ }
37
+ if (plan === null || ok + notOk !== plan) return {}; // a cut stream: the denominator is not known
38
+ return measured(plan, notOk);
39
+ }
40
+
41
+ /** While TAP streams: tests seen so far, and the plan once a producer printed it first. */
42
+ export function createTapCounter() {
43
+ let carry = "", ok = 0, notOk = 0, plan = null;
44
+ return {
45
+ feed(chunk) {
46
+ const lines = (carry + chunk).split("\n");
47
+ carry = lines.pop() ?? "";
48
+ for (const line of lines) {
49
+ if (/^ok\s+\d+/.test(line)) ok += 1;
50
+ else if (/^not ok\s+\d+/.test(line)) notOk += 1;
51
+ else if (/^1\.\.(\d+)\s*$/.test(line)) plan = Number(/^1\.\.(\d+)/.exec(line)[1]);
52
+ }
53
+ },
54
+ /** A measured count only with a plan that covers what was seen; else nothing (no bar from a guess). */
55
+ now: () => (plan !== null && plan > 0 && ok + notOk <= plan ? { done: ok + notOk, total: plan, failed: notOk, unit: "tests" } : null),
56
+ };
57
+ }
58
+
59
+ export function parseNodeTest(text) {
60
+ const s = {};
61
+ for (const m of text.matchAll(/^\s*(?:ℹ|#)\s+(tests|pass|fail|skipped|todo|cancelled)\s+(\d+)\s*$/gm)) s[m[1]] = Number(m[2]);
62
+ return s.tests === undefined ? {} : measured(s.tests, (s.fail ?? 0) + (s.cancelled ?? 0));
63
+ }
64
+
65
+ const attrs = (tag) => Object.fromEntries([...tag.matchAll(/\s([a-z]+)="([^"]*)"/gi)].map((m) => [m[1].toLowerCase(), m[2]]));
66
+ export function parseJunitXml(text) {
67
+ const root = /<testsuites\b[^>]*>/i.exec(text)?.[0];
68
+ const a = root ? attrs(root) : null;
69
+ if (a && int(a.tests) !== null) return measured(int(a.tests), (int(a.failures) ?? 0) + (int(a.errors) ?? 0));
70
+ let tests = 0, failed = 0, seen = 0;
71
+ for (const m of text.matchAll(/<testsuite\b[^>]*>/gi)) {
72
+ const s = attrs(m[0]);
73
+ if (int(s.tests) === null) return {};
74
+ seen += 1; tests += int(s.tests); failed += (int(s.failures) ?? 0) + (int(s.errors) ?? 0);
75
+ }
76
+ return seen === 0 ? {} : measured(tests, failed);
77
+ }
78
+
79
+ export function parseJestJson(text) {
80
+ const j = jsonOf(text);
81
+ if (!j || int(j.numTotalTests) === null || int(j.numFailedTests) === null) return {};
82
+ return measured(int(j.numTotalTests), int(j.numFailedTests));
83
+ }
84
+
85
+ export function parseSemgrepJson(text) {
86
+ const j = jsonOf(text);
87
+ if (!j || !Array.isArray(j.results)) return {};
88
+ const findings = { high: 0, medium: 0, low: 0 };
89
+ for (const r of j.results) {
90
+ const sev = String(r?.extra?.severity ?? "").toUpperCase();
91
+ if (sev === "ERROR" || sev === "CRITICAL" || sev === "HIGH") findings.high += 1;
92
+ else if (sev === "WARNING" || sev === "MEDIUM") findings.medium += 1;
93
+ else findings.low += 1;
94
+ }
95
+ const scanned = Array.isArray(j.paths?.scanned) ? j.paths.scanned.length : 0;
96
+ return { findings, ...(scanned > 0 ? { measured: { done: scanned, total: scanned, failed: 0, unit: "files" } } : {}) };
97
+ }
98
+
99
+ export function parseZapJson(text) {
100
+ const j = jsonOf(text);
101
+ if (!j || !Array.isArray(j.site)) return {};
102
+ const findings = { high: 0, medium: 0, low: 0 };
103
+ for (const site of j.site) for (const alert of Array.isArray(site?.alerts) ? site.alerts : []) {
104
+ const risk = int(alert?.riskcode);
105
+ if (risk === 3) findings.high += 1; else if (risk === 2) findings.medium += 1; else if (risk === 1) findings.low += 1;
106
+ }
107
+ return { findings };
108
+ }
109
+
110
+ export const PARSERS = { tap: parseTap, node_test: parseNodeTest, junit_xml: parseJunitXml, vitest_json: parseJestJson, jest_json: parseJestJson, semgrep_json: parseSemgrepJson, zap_json: parseZapJson };
111
+
112
+ /** The parser's reading of a report, `{}` for `none` or an unknown parser. */
113
+ export const readReport = (parser, text) => (typeof text === "string" && Object.hasOwn(PARSERS, parser) ? PARSERS[parser](text) : {});
114
+
115
+ /** A scanner stage fails on a finding at or above its threshold; `none` never fails on findings. */
116
+ export function findingsFail(findings, failOn) {
117
+ if (!findings || failOn === "none") return false;
118
+ if (failOn === "high") return findings.high > 0;
119
+ if (failOn === "medium") return findings.high + findings.medium > 0;
120
+ return findings.high + findings.medium + findings.low > 0;
121
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * A RELEASE'S PIPELINE, RUN ON THE COMPUTER (owner, 2026-11-07; docs/remote-agents/PROTOCOL.md "Pipelines").
3
+ *
4
+ * The phone starts or cancels a pipeline the computer already has: the stages of the project's reviewed
5
+ * `.worktrust/pipeline.json` (remote-pipeline-config.mjs). Stages run one after another, each command checked against the
6
+ * allowlist again right before it runs and spawned without a shell, in its own process group (so a cancel or a timeout
7
+ * ends everything it started), with the person's environment minus every WORKTRUST_ variable and stdin closed. Output goes
8
+ * to a local log (~/.worktrust/remote/pipelines/<run>/<stage>.log, mode 0600) for the person to read at the desk, and
9
+ * never to the phone: the phone gets the stage's state and what its parser read. A deploy or publish stage is never run:
10
+ * it is `at_desk`.
11
+ *
12
+ * At most once, as with commands: a run is journaled before its first stage starts, and a run a stopped daemon left
13
+ * running is closed `failed` / `interrupted` by the next daemon and never run again. Each run is marked in the steered
14
+ * ledger as non-agent work (`steered: "pipeline"`), which the hour readers skip: a pipeline is never Passport hours.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, constants } from "node:fs";
18
+ import { join, sep } from "node:path";
19
+ import * as P from "./remote-protocol.mjs";
20
+ import { allowCommand, namedFiles, parsePipelineConfig, PIPELINE_FILE, reviewHash } from "./remote-pipeline-config.mjs";
21
+ import { createTapCounter, findingsFail, readReport } from "./remote-pipeline-parsers.mjs";
22
+ import { createCoalescer } from "./remote-sessions.mjs";
23
+
24
+ const MAX_KEEP = 256 * 1024; // the tail of stdout a parser reads when the stage names no report file
25
+ const MAX_REPORT = 16 * 1024 * 1024;
26
+ export const MAX_PIPELINES = 2;
27
+ const HISTORY = 40;
28
+
29
+ const inside = (root, path) => path === root || path.startsWith(root + sep);
30
+
31
+ /** A project file read safely: inside the project after every symlink, not a symlink itself, bounded. */
32
+ export function readProjectFile(projectPath, relative, max) {
33
+ try {
34
+ const root = realpathSync(projectPath);
35
+ const file = join(root, relative);
36
+ if (!existsSync(file) || lstatSync(file).isSymbolicLink() || !inside(root, realpathSync(file))) return null;
37
+ const text = readFileSync(file);
38
+ return text.length > max ? null : text.toString("utf8");
39
+ } catch { return null; }
40
+ }
41
+
42
+ const scriptsOf = (projectPath) => { try { return JSON.parse(readProjectFile(projectPath, "package.json", 1_048_576) ?? "null")?.scripts ?? null; } catch { return null; } };
43
+
44
+ /** The project-side inputs of reviewHash: its .npmrc and the files its node stages run. */
45
+ export function reviewExtras(projectPath, text, scripts) {
46
+ return { npmrc: readProjectFile(projectPath, ".npmrc", 65_536), files: Object.fromEntries(namedFiles(text, scripts).map((f) => [f, readProjectFile(projectPath, f, 4 * 1024 * 1024)])) };
47
+ }
48
+
49
+ /** The hash `worktrust remote pipeline review` pins, read from the project as it stands now. */
50
+ export function projectReviewHash(project) {
51
+ const text = readProjectFile(project.path, PIPELINE_FILE, 65_536);
52
+ if (text === null) return null;
53
+ const scripts = scriptsOf(project.path);
54
+ return reviewHash(text, scripts, reviewExtras(project.path, text, scripts));
55
+ }
56
+
57
+ /** absent | unreviewed | reviewed, and the parsed config when it may run. */
58
+ export function pipelineState(project, reviews) {
59
+ const text = readProjectFile(project.path, PIPELINE_FILE, 65_536);
60
+ if (text === null) return { state: "absent", config: null };
61
+ const scripts = scriptsOf(project.path);
62
+ const parsed = parsePipelineConfig(text, scripts);
63
+ if (!parsed.ok) return { state: "unreviewed", config: null, detail: parsed.detail };
64
+ const hash = reviewHash(text, scripts, reviewExtras(project.path, text, scripts));
65
+ return reviews[project.project_id]?.sha256 === hash ? { state: "reviewed", config: parsed.config, scripts, hash } : { state: "unreviewed", config: null };
66
+ }
67
+
68
+ export function createPipelines(ctx) {
69
+ // ctx: { journal, now, random, emit, projects(), reviews(), log, logDir, markLedger(record), env(prepend), onEnded(run), spawnImpl? }
70
+ const runs = new Map(); // live runs: id -> { body, child, cancelled }
71
+ const go = ctx.spawnImpl ?? spawn;
72
+ const coalesce = createCoalescer({ now: ctx.now });
73
+
74
+ const history = (projectId, stageId) => ctx.journal.pipelines().filter((p) => p.project_id === projectId && p.state === "passed").slice(-HISTORY)
75
+ .flatMap((p) => (stageId === null ? [(p.ended_at - p.started_at) / 1000] : p.stages.filter((s) => s.stage_id === stageId && s.state === "passed" && s.duration_ms !== undefined).map((s) => s.duration_ms / 1000)));
76
+ const etaFor = (durations, startedAt) => { const e = P.etaForDisplay(P.etaFromHistory(durations, Math.max(0, (ctx.now() - startedAt) / 1000))); return e.kind === "estimate" ? e : undefined; };
77
+
78
+ /** History's estimate where etaForDisplay keeps one, on live stages and a live run only; every other ETA dropped. */
79
+ function withEtas(body) {
80
+ const final = P.isFinalPipelineState(body.state);
81
+ const stages = body.stages.map((s) => {
82
+ const { eta: _drop, ...rest } = s;
83
+ if (final || (s.state !== "running" && s.state !== "queued")) return rest;
84
+ const eta = etaFor(history(body.project_id, s.stage_id), s.started_at ?? ctx.now());
85
+ return eta ? { ...rest, eta } : rest;
86
+ });
87
+ const { eta: _old, ...top } = body;
88
+ const eta = final ? undefined : etaFor(history(body.project_id, null), body.started_at);
89
+ return { ...top, stages, ...(eta ? { eta } : {}) };
90
+ }
91
+
92
+ /** Journal first, then the phone; a live count is coalesced to one per two seconds per run. */
93
+ function publish(run, { live = false } = {}) {
94
+ run.body = withEtas(run.body);
95
+ const shaped = P.validateEventBody("pipeline.updated", run.body);
96
+ if (!shaped.ok) { ctx.log("pipeline_refused", { detail: shaped.code }); return false; }
97
+ ctx.journal.recordPipeline(run.body);
98
+ const send = () => ctx.emit(null, "pipeline.updated", run.body);
99
+ if (live) coalesce.offer(run.body.pipeline_run_id, send); else coalesce.now(run.body.pipeline_run_id, send);
100
+ return true;
101
+ }
102
+
103
+ /** A stage an earlier daemon left running: its process group is ended when its command line is still that stage's. */
104
+ function reap(runId) {
105
+ const held = ctx.journal.pipelinePid?.(runId);
106
+ if (!held || process.platform === "win32" || !Number.isSafeInteger(held.pid) || held.pid <= 1) return false;
107
+ const command = ctx.commandOf?.(held.pid) ?? ""; // `ps` lives in remote-run.mjs: this file spawns stages only
108
+ if (!command.includes(held.file)) return false;
109
+ try { (ctx.kill ?? process.kill.bind(process))(-held.pid, "SIGTERM"); return true; } catch { return false; }
110
+ }
111
+
112
+ const setStage = (run, id, patch) => { run.body = { ...run.body, stages: run.body.stages.map((s) => (s.stage_id === id ? { ...s, ...patch } : s)) }; };
113
+
114
+ function finish(run, state, reason) {
115
+ run.body = { ...run.body, state, reason, ended_at: Math.max(ctx.now(), run.body.started_at),
116
+ stages: run.body.stages.map((s) => (s.state === "queued" || s.state === "running" ? { ...s, state: "skipped" } : s)) };
117
+ publish(run);
118
+ ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: run.body.pipeline_run_id, release_id: run.body.release_id, project_id: run.body.project_id, started_at: run.body.started_at, ended_at: run.body.ended_at });
119
+ runs.delete(run.body.pipeline_run_id);
120
+ ctx.onEnded?.(run.body);
121
+ }
122
+
123
+ function runStage(run, stage, project, config) {
124
+ return new Promise((resolve) => {
125
+ const argv = allowCommand(stage.run, scriptsOf(project.path)); // again, at run time
126
+ if (!argv.ok) { resolve({ state: "failed" }); return; }
127
+ const started = ctx.now();
128
+ setStage(run, stage.id, { state: "running", started_at: started });
129
+ publish(run);
130
+ const dir = join(ctx.logDir, run.body.pipeline_run_id);
131
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
132
+ const log = openSync(join(dir, `${stage.id}.log`), constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0), 0o600);
133
+ let tail = "";
134
+ const tap = stage.parser === "tap" ? createTapCounter() : null;
135
+ const child = go(argv.file, argv.args, { cwd: project.path, env: ctx.env(config.path_prepend), shell: false, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
136
+ run.child = child;
137
+ if (Number.isSafeInteger(child.pid)) ctx.journal.recordPipelinePid(run.body.pipeline_run_id, { pid: child.pid, file: argv.file }); // a later daemon ends it (P2-4)
138
+ const take = (chunk, out) => {
139
+ const text = chunk.toString("utf8");
140
+ try { writeSync(log, text); } catch { /* the log is the person's convenience */ }
141
+ if (!out) return;
142
+ tail = (tail + text).slice(-MAX_KEEP);
143
+ if (tap) { tap.feed(text); const m = tap.now(); if (m) { setStage(run, stage.id, { measured: m }); publish(run, { live: true }); } }
144
+ };
145
+ child.stdout?.on("data", (c) => take(c, true));
146
+ child.stderr?.on("data", (c) => take(c, false));
147
+ const timer = setTimeout(() => { run.timedOut = true; kill(child); }, stage.timeout_ms);
148
+ timer.unref?.();
149
+ const done = (code) => {
150
+ clearTimeout(timer);
151
+ try { closeSync(log); } catch { /* closed */ }
152
+ run.child = null;
153
+ const report = stage.report ? readProjectFile(project.path, stage.report, MAX_REPORT) : tail;
154
+ const read = readReport(stage.parser, report ?? "");
155
+ const exitOk = stage.parser === "zap_json" ? code === 0 || code === 1 || code === 2 : code === 0;
156
+ const failed = !exitOk || run.cancelled || run.timedOut || (read.measured?.unit === "tests" && read.measured.failed > 0) || findingsFail(read.findings, stage.fail_on);
157
+ const { measured: _live, ...rest } = run.body.stages.find((s) => s.stage_id === stage.id);
158
+ const result = { ...rest, ...(read.measured ? { measured: read.measured } : {}), ...(read.findings ? { findings: read.findings } : {}) };
159
+ const state = run.cancelled ? "skipped" : failed ? "failed" : "passed";
160
+ run.body = { ...run.body, stages: run.body.stages.map((s) => (s.stage_id === stage.id ? { ...result, state, duration_ms: Math.max(0, ctx.now() - started) } : s)) };
161
+ resolve({ state });
162
+ };
163
+ child.on("error", () => done(-1));
164
+ child.on("close", (code) => done(code ?? -1));
165
+ });
166
+ }
167
+
168
+ const kill = (child) => { try { if (process.platform !== "win32" && child.pid) process.kill(-child.pid, "SIGTERM"); else child.kill("SIGTERM"); } catch { try { child.kill("SIGTERM"); } catch { /* gone */ } } };
169
+
170
+ async function drive(run, project, config, hash) {
171
+ for (const stage of config.stages) {
172
+ if (stage.desk) continue;
173
+ if (run.cancelled) break;
174
+ // Reviewed still? An earlier stage, a task or the desk may have changed the file, a script or a stage's code (P3-5).
175
+ if (pipelineState(project, ctx.reviews()).hash !== hash) return finish(run, "failed", "unreviewed");
176
+ const { state } = await runStage(run, stage, project, config);
177
+ if (state === "failed") return finish(run, "failed", run.timedOut ? "timeout" : "stage_failed");
178
+ publish(run);
179
+ }
180
+ if (run.cancelled) return finish(run, "cancelled", "cancelled");
181
+ finish(run, "passed", null);
182
+ }
183
+
184
+ return {
185
+ state: (project) => pipelineState(project, ctx.reviews()).state,
186
+ runsAfterTasks: (project) => pipelineState(project, ctx.reviews()).config?.run_after_tasks === true,
187
+ /** → { ok: true, run } or { ok: false, reason } with a protocol reject reason. Never a desk stage. */
188
+ start({ release_id, project_id }) {
189
+ const project = ctx.projects().find((p) => p.project_id === project_id);
190
+ if (!project) return { ok: false, reason: "not_found" };
191
+ const found = pipelineState(project, ctx.reviews());
192
+ if (found.state === "absent") return { ok: false, reason: "not_found" };
193
+ if (found.state !== "reviewed") return { ok: false, reason: "unreviewed" };
194
+ if ([...runs.values()].some((r) => r.body.project_id === project_id) || runs.size >= MAX_PIPELINES) return { ok: false, reason: "busy" };
195
+ const body = { pipeline_run_id: P.mintId("plr", ctx.random), release_id, project_id, state: "running", reason: null, started_at: ctx.now(), ended_at: null,
196
+ stages: found.config.stages.map((s) => ({ stage_id: s.id, label: s.label, kind: s.kind, state: s.desk ? "at_desk" : "queued" })) };
197
+ const run = { body, child: null, cancelled: false, timedOut: false };
198
+ if (!publish(run)) return { ok: false, reason: "unsupported" }; // journaled before the first stage runs, or nothing runs
199
+ runs.set(body.pipeline_run_id, run);
200
+ ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: body.pipeline_run_id, release_id, project_id, started_at: body.started_at, ended_at: null });
201
+ // The first stage starts on the next turn of the loop, after the caller saved the release as verifying (P3-6).
202
+ run.done = new Promise((resolve) => setImmediate(resolve)).then(() => drive(run, project, found.config, found.hash))
203
+ .catch((e) => { ctx.log("pipeline_failed", { name: e?.name ?? "Error" }); if (runs.has(body.pipeline_run_id)) finish(run, "failed", "stage_failed"); });
204
+ return { ok: true, run: body };
205
+ },
206
+ cancel(runId) {
207
+ const run = runs.get(runId);
208
+ if (!run) return false;
209
+ run.cancelled = true;
210
+ if (run.child) kill(run.child);
211
+ return true;
212
+ },
213
+ /** Runs an earlier daemon left open: failed, interrupted, never run again. */
214
+ recover() {
215
+ let closed = 0;
216
+ for (const p of ctx.journal.pipelines()) {
217
+ if (P.isFinalPipelineState(p.state) || runs.has(p.pipeline_run_id)) continue;
218
+ reap(p.pipeline_run_id);
219
+ const ended = Math.max(ctx.now(), p.started_at);
220
+ const body = { ...p, state: "failed", reason: "interrupted", ended_at: ended, stages: p.stages.map((s) => { const { eta: _e, ...r } = s; return s.state === "running" ? { ...r, state: "failed", duration_ms: Math.max(0, ended - (s.started_at ?? ended)) } : s.state === "queued" ? { ...r, state: "skipped" } : r; }) };
221
+ const { eta: _top, ...clean } = body;
222
+ ctx.journal.recordPipeline(clean);
223
+ ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: p.pipeline_run_id, release_id: p.release_id, project_id: p.project_id, started_at: p.started_at, ended_at: ended });
224
+ ctx.emit(null, "pipeline.updated", clean);
225
+ ctx.onEnded?.(clean);
226
+ closed += 1;
227
+ }
228
+ return closed;
229
+ },
230
+ running: () => [...runs.keys()],
231
+ get: (runId) => runs.get(runId)?.body ?? ctx.journal.pipelines().find((p) => p.pipeline_run_id === runId) ?? null,
232
+ async stopAll() { for (const run of runs.values()) { run.cancelled = true; if (run.child) kill(run.child); } await Promise.all([...runs.values()].map((r) => r.done)); },
233
+ };
234
+ }