@mnaimfaizy/agent-kit 1.0.0-beta.1 → 1.0.0-beta.10

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/src/exec.mjs CHANGED
@@ -1,49 +1,238 @@
1
- // Runs `git` and `gh` as argument arrays, never through a shell, so no string
2
- // from a Consumer file or a GitHub response is ever parsed as shell syntax.
3
- // Every module takes a runner as a parameter; tests inject a fake one.
1
+ // Runs commands as argument arrays, never through a shell, so no string from a
2
+ // Consumer file or a GitHub response is ever parsed as shell syntax. Each
3
+ // subcommand gets a runner that runs only the commands on its own allowlist:
4
+ // `init`, `upgrade` and `doctor` reach only `git` and `gh`, and `deep-scan`
5
+ // alone adds the accepted sandbox runtimes' CLIs and the 1Password CLI, which
6
+ // reads its model credential (ADR 0019). There is no
7
+ // second runner that bypasses this. Every module takes a runner as a
8
+ // parameter; tests inject a fake one, or a fake spawn behind the real
9
+ // allowlist. A runner also has `start`, the same command run without
10
+ // blocking (`deep-scan`'s long sandbox steps), so an interrupt can stop the
11
+ // step and the sandbox still be torn down; it checks the same allowlist.
4
12
 
5
- import { spawnSync } from "node:child_process";
13
+ import { spawn as spawnChild, spawnSync } from "node:child_process";
6
14
 
7
- const ALLOWED = new Set(["git", "gh"]);
15
+ /** The sandbox runtimes' command-line tools, which only `deep-scan` may run. */
16
+ export const RUNTIME_CLIS = Object.freeze([
17
+ "sbx",
18
+ "docker",
19
+ "runsc",
20
+ "kata-runtime",
21
+ "firecracker",
22
+ ]);
23
+
24
+ /** The secret managers' command-line tools, which only `deep-scan` may run. */
25
+ export const SECRET_MANAGER_CLIS = Object.freeze(["op"]);
26
+
27
+ const ALLOWLISTS = Object.freeze({
28
+ init: Object.freeze(["git", "gh"]),
29
+ upgrade: Object.freeze(["git", "gh"]),
30
+ doctor: Object.freeze(["git", "gh"]),
31
+ "deep-scan": Object.freeze(["git", ...RUNTIME_CLIS, ...SECRET_MANAGER_CLIS]),
32
+ });
8
33
 
9
34
  /**
10
- * @typedef {{ status: number | null, stdout: string, stderr: string }} RunResult
11
- * @typedef {{ status: number | null, stdout: Buffer, stderr: string }} BufferResult
12
- * @typedef {(cmd: string, args: string[], opts?: { cwd?: string, env?: NodeJS.ProcessEnv, encoding?: "utf8" | "buffer" }) => RunResult} Runner
35
+ * @typedef {{ status: number | null, stdout: string, stderr: string, code?: string }} RunResult
36
+ * @typedef {{ status: number | null, stdout: Buffer, stderr: string, code?: string }} BufferResult
37
+ * @typedef {{ status: number | null, signal: string | null, aborted: boolean, truncated?: boolean, stdout: Buffer, stderr: string }} StartResult
38
+ * `aborted` is true when `opts.signal` stopped the command; `truncated`
39
+ * when its output passed `opts.maxOutput`, and it was killed for it.
40
+ * @typedef {(cmd: string, args: string[], opts?: { cwd?: string, env?: NodeJS.ProcessEnv, stdin?: Buffer | string, signal?: AbortSignal, maxOutput?: number }) => Promise<StartResult>} Start
41
+ * @typedef {((cmd: string, args: string[], opts?: { cwd?: string, env?: NodeJS.ProcessEnv, encoding?: "utf8" | "buffer", maxBuffer?: number }) => RunResult) & { start: Start }} Runner
13
42
  * With `encoding: "buffer"`, stdout is the raw bytes (a Buffer): use it for
14
- * file contents, which need not be UTF-8. stderr is always text.
43
+ * file contents, which need not be UTF-8. stderr is always text. `start`
44
+ * runs a command without blocking, feeds it `stdin`, and kills it when
45
+ * `signal` aborts.
15
46
  */
16
47
 
17
- /** @type {Runner} */
18
- export function systemRunner(cmd, args, opts = {}) {
19
- if (!ALLOWED.has(cmd)) throw new Error(`refusing to run ${cmd}: only git and gh are allowed`);
20
- if (!Array.isArray(args) || args.some((a) => typeof a !== "string")) {
21
- throw new TypeError("runner arguments must be an array of strings");
22
- }
23
- const result = spawnSync(cmd, args, {
24
- cwd: opts.cwd,
25
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1", ...opts.env },
26
- encoding: "buffer",
27
- shell: false,
28
- windowsHide: true,
29
- maxBuffer: 64 * 1024 * 1024,
48
+ /** The commands a subcommand's runner may run. */
49
+ export function allowedCommands(subcommand) {
50
+ const list = Object.hasOwn(ALLOWLISTS, subcommand) ? ALLOWLISTS[subcommand] : null;
51
+ if (!list) throw new Error(`no process allowlist for ${JSON.stringify(subcommand)}`);
52
+ return list;
53
+ }
54
+
55
+ const MAX_OUTPUT = 64 * 1024 * 1024;
56
+
57
+ /**
58
+ * How much of a child's error output is kept: its start and its end. Only
59
+ * the first line or the last lines are ever shown, and the output can come
60
+ * from untrusted code (a setup step), so it must not fill the heap.
61
+ */
62
+ const MAX_ERR_HEAD = 64 * 1024;
63
+ const MAX_ERR_TAIL = 1024 * 1024;
64
+ const ERR_CUT = "\n[... error output cut ...]\n";
65
+
66
+ /** A collector for a child's error output that keeps its head and a tail ring. */
67
+ function errorCollector() {
68
+ const head = [];
69
+ let headSize = 0;
70
+ let tail = [];
71
+ let tailSize = 0;
72
+ let cut = false;
73
+ return {
74
+ push(b) {
75
+ if (headSize < MAX_ERR_HEAD) {
76
+ const take = b.subarray(0, MAX_ERR_HEAD - headSize);
77
+ head.push(take);
78
+ headSize += take.length;
79
+ b = b.subarray(take.length);
80
+ }
81
+ if (!b.length) return;
82
+ tail.push(b);
83
+ tailSize += b.length;
84
+ while (tail.length > 1 && tailSize - tail[0].length >= MAX_ERR_TAIL) {
85
+ tailSize -= tail.shift().length;
86
+ cut = true;
87
+ }
88
+ },
89
+ text() {
90
+ let rest = Buffer.concat(tail);
91
+ if (rest.length > MAX_ERR_TAIL) {
92
+ rest = rest.subarray(rest.length - MAX_ERR_TAIL);
93
+ cut = true;
94
+ }
95
+ return `${Buffer.concat(head).toString("utf8")}${cut ? ERR_CUT : ""}${rest.toString("utf8")}`;
96
+ },
97
+ };
98
+ }
99
+
100
+ /**
101
+ * The runner for one subcommand. `spawn` and `spawnAsync` are the process
102
+ * boundary (blocking and not), replaceable only by tests; the allowlist check
103
+ * always runs first.
104
+ * @param {string} subcommand
105
+ * @param {{ spawn?: typeof spawnSync, spawnAsync?: typeof spawnChild }} [opts]
106
+ * @returns {Runner}
107
+ */
108
+ export function runnerFor(subcommand, { spawn = spawnSync, spawnAsync = spawnChild } = {}) {
109
+ return makeRunner(allowedCommands(subcommand), subcommand, spawn, spawnAsync);
110
+ }
111
+
112
+ function makeRunner(list, who, spawn, spawnAsync = spawnChild) {
113
+ const allowed = new Set(list);
114
+ const names = `${list.slice(0, -1).join(", ")} and ${list.at(-1)}`;
115
+ const check = (cmd, args) => {
116
+ if (!allowed.has(cmd)) {
117
+ throw new Error(`refusing to run ${cmd}: ${who} may run only ${names}`);
118
+ }
119
+ if (!Array.isArray(args) || args.some((a) => typeof a !== "string")) {
120
+ throw new TypeError("runner arguments must be an array of strings");
121
+ }
122
+ };
123
+ const envFor = (opts) => ({
124
+ ...process.env,
125
+ GIT_TERMINAL_PROMPT: "0",
126
+ GH_PROMPT_DISABLED: "1",
127
+ ...opts.env,
30
128
  });
31
- const raw = opts.encoding === "buffer";
32
- if (result.error) {
129
+ /** @type {Start} */
130
+ const start = (cmd, args, opts = {}) => {
131
+ check(cmd, args);
132
+ return new Promise((resolve) => {
133
+ let done = false;
134
+ let aborted = false;
135
+ const out = [];
136
+ const err = errorCollector();
137
+ let size = 0;
138
+ let truncated = false;
139
+ const cap = opts.maxOutput ?? MAX_OUTPUT;
140
+ const finish = (result) => {
141
+ if (done) return;
142
+ done = true;
143
+ opts.signal?.removeEventListener("abort", onAbort);
144
+ resolve({ aborted, ...(truncated ? { truncated } : {}), ...result });
145
+ };
146
+ let child;
147
+ const onAbort = () => {
148
+ aborted = true;
149
+ child?.kill("SIGTERM");
150
+ };
151
+ try {
152
+ child = spawnAsync(cmd, args, {
153
+ cwd: opts.cwd,
154
+ env: envFor(opts),
155
+ shell: false,
156
+ windowsHide: true,
157
+ stdio: ["pipe", "pipe", "pipe"],
158
+ });
159
+ } catch (e) {
160
+ finish({
161
+ status: null,
162
+ signal: null,
163
+ stdout: Buffer.alloc(0),
164
+ stderr: `${cmd}: ${e.message}`,
165
+ });
166
+ return;
167
+ }
168
+ child.stdout.on("data", (b) => {
169
+ size += b.length;
170
+ if (size <= cap) out.push(b);
171
+ else if (opts.maxOutput !== undefined && !truncated) {
172
+ // Past the caller's cap: read no more of it.
173
+ truncated = true;
174
+ child.kill("SIGKILL");
175
+ }
176
+ });
177
+ child.stderr.on("data", (b) => err.push(b));
178
+ child.on("error", (e) =>
179
+ finish({
180
+ status: null,
181
+ signal: null,
182
+ stdout: Buffer.alloc(0),
183
+ stderr: `${cmd}: ${e.message}`,
184
+ }),
185
+ );
186
+ child.on("close", (status, signal) =>
187
+ finish({
188
+ status,
189
+ signal,
190
+ stdout: Buffer.concat(out),
191
+ stderr: err.text(),
192
+ }),
193
+ );
194
+ if (opts.signal?.aborted) onAbort();
195
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
196
+ child.stdin.on("error", () => {});
197
+ child.stdin.end(opts.stdin ?? undefined);
198
+ });
199
+ };
200
+ function run(cmd, args, opts = {}) {
201
+ check(cmd, args);
202
+ const result = spawn(cmd, args, {
203
+ cwd: opts.cwd,
204
+ env: envFor(opts),
205
+ encoding: "buffer",
206
+ shell: false,
207
+ windowsHide: true,
208
+ maxBuffer: opts.maxBuffer ?? MAX_OUTPUT,
209
+ });
210
+ const raw = opts.encoding === "buffer";
211
+ if (result.error) {
212
+ return {
213
+ status: null,
214
+ stdout: raw ? Buffer.alloc(0) : "",
215
+ stderr: `${cmd}: ${result.error.message}`,
216
+ ...(result.error.code ? { code: result.error.code } : {}),
217
+ };
218
+ }
219
+ const stdout = result.stdout ?? Buffer.alloc(0);
33
220
  return {
34
- status: null,
35
- stdout: raw ? Buffer.alloc(0) : "",
36
- stderr: `${cmd}: ${result.error.message}`,
221
+ status: result.status,
222
+ stdout: raw ? stdout : stdout.toString("utf8"),
223
+ stderr: (result.stderr ?? Buffer.alloc(0)).toString("utf8"),
37
224
  };
38
225
  }
39
- const stdout = result.stdout ?? Buffer.alloc(0);
40
- return {
41
- status: result.status,
42
- stdout: raw ? stdout : stdout.toString("utf8"),
43
- stderr: (result.stderr ?? Buffer.alloc(0)).toString("utf8"),
44
- };
226
+ run.start = start;
227
+ return run;
45
228
  }
46
229
 
230
+ /**
231
+ * A `git` and `gh` runner, the allowlist `init`, `upgrade` and `doctor` share.
232
+ * @type {Runner}
233
+ */
234
+ export const systemRunner = makeRunner(["git", "gh"], "agent-kit", spawnSync);
235
+
47
236
  /**
48
237
  * The line of a command's stderr that says what went wrong, for short
49
238
  * messages: the first `fatal:` or `error:` line, else the first line that is
package/src/init.mjs CHANGED
@@ -63,11 +63,20 @@ const LABELS = [
63
63
  ["agent:implement", "0E8A16", "Agent-kit: implement the Verified plan"],
64
64
  ["agent:review", "5319E7", "Agent-kit: review this PR"],
65
65
  ];
66
+ const RESPONSE_LABEL = [
67
+ "agent:address-review",
68
+ "FBCA04",
69
+ "Agent-kit: answer the review on this PR",
70
+ ];
66
71
 
67
72
  /** The `init` answers, as flags name them, with what each one asks. */
68
73
  export const QUESTIONS = [
69
74
  { key: "tag", flag: "--tag <vX>", ask: "Agent-kit tag to adopt (for example v1.0.0)" },
70
- { key: "flows", flag: "--flows pipeline,audit", ask: "Flows to set up (pipeline, audit)" },
75
+ {
76
+ key: "flows",
77
+ flag: "--flows pipeline,audit,review-response",
78
+ ask: "Flows to set up (pipeline, audit, review-response)",
79
+ },
71
80
  {
72
81
  key: "actors",
73
82
  flag: "--actors <login,...>",
@@ -78,19 +87,19 @@ export const QUESTIONS = [
78
87
  key: "verify",
79
88
  flag: "--verify <commands>",
80
89
  ask: "verify_commands (lint/tests/typecheck; use \\n between commands)",
81
- only: "pipeline",
90
+ only: ["pipeline", "review-response"],
82
91
  },
83
92
  {
84
93
  key: "preset",
85
94
  flag: "--preset <name|none>",
86
95
  ask: "setup_commands preset (python, node, mixed, redis-service, or none)",
87
- only: "pipeline",
96
+ only: ["pipeline", "review-response"],
88
97
  },
89
98
  {
90
99
  key: "threatPackDir",
91
100
  flag: "--threat-pack-dir <dir>",
92
101
  ask: "Folder for the Threat pack",
93
- only: "audit",
102
+ only: ["audit"],
94
103
  },
95
104
  ];
96
105
 
@@ -118,7 +127,9 @@ export function parseAnswer(key, raw, { prompted = false } = {}) {
118
127
  const flows = [...new Set(split(s))];
119
128
  const bad = flows.filter((f) => !(f in FLOWS));
120
129
  if (flows.length === 0 || bad.length) {
121
- return { error: `--flows takes pipeline and/or audit, got ${JSON.stringify(s)}` };
130
+ return {
131
+ error: `--flows takes pipeline, audit and/or review-response, got ${JSON.stringify(s)}`,
132
+ };
122
133
  }
123
134
  return { value: Object.keys(FLOWS).filter((f) => flows.includes(f)) };
124
135
  }
@@ -184,7 +195,7 @@ export async function collectAnswers({ flags, prompt, yes, defaultBranch }) {
184
195
  const answers = {};
185
196
  const missing = [];
186
197
  for (const q of QUESTIONS) {
187
- if (q.only && answers.flows && !answers.flows.includes(q.only)) continue;
198
+ if (q.only && answers.flows && !q.only.some((f) => answers.flows.includes(f))) continue;
188
199
  let raw = flags[q.key];
189
200
  let prompted = false;
190
201
  const fallback = q.key === "defaultBranch" ? defaultBranch : DEFAULTS[q.key];
@@ -414,6 +425,7 @@ export function planInit({ runner, root, snap, answers, force }) {
414
425
  export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
415
426
  const pipeline = flows.includes("pipeline");
416
427
  const audit = flows.includes("audit");
428
+ const response = flows.includes("review-response");
417
429
  const lines = [];
418
430
  let n = 0;
419
431
  const step = (title, ...cmds) => {
@@ -425,13 +437,16 @@ export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
425
437
  command("gh", "secret", "set", "CLAUDE_CODE_OAUTH_TOKEN"),
426
438
  ...(audit ? [command("gh", "secret", "set", "AGENT_KIT_ADVISORIES_TOKEN")] : []),
427
439
  );
428
- if (pipeline) {
440
+ const labels = [...(pipeline ? LABELS : []), ...(response ? [RESPONSE_LABEL] : [])];
441
+ if (labels.length) {
429
442
  step(
430
443
  "Trigger labels:",
431
- ...LABELS.map(([name, color, description]) =>
444
+ ...labels.map(([name, color, description]) =>
432
445
  command("gh", "label", "create", name, "--color", color, "--description", description),
433
446
  ),
434
447
  );
448
+ }
449
+ if (pipeline) {
435
450
  step("Install the Claude GitHub App on this repository: https://github.com/apps/claude");
436
451
  }
437
452
  step(
@@ -442,12 +457,23 @@ export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
442
457
  step(
443
458
  "Last, after you have reviewed and pushed the Callers, turn the flows on (Kill switch variables):",
444
459
  ...(pipeline
445
- ? [command("gh", "variable", "set", "CLAUDE_PIPELINE_ENABLED", "--body", "true")]
460
+ ? [command("gh", "variable", "set", "CLAUDE_AGENT_FLOW_ENABLED", "--body", "true")]
446
461
  : []),
447
462
  ...(audit
448
463
  ? [command("gh", "variable", "set", "CLAUDE_SECURITY_AUDIT_ENABLED", "--body", "true")]
449
464
  : []),
465
+ ...(response
466
+ ? [command("gh", "variable", "set", "CLAUDE_REVIEW_RESPONSE_ENABLED", "--body", "true")]
467
+ : []),
450
468
  );
469
+ if (response) {
470
+ step(
471
+ "Optional, Review response auto mode (a finished review starts a round): first give your " +
472
+ "review Caller response_mode and response_workflow, as " +
473
+ `${serverUrl}/${kitRepo}/blob/${tag}/docs/review-response.md#auto-mode says, then:`,
474
+ command("gh", "variable", "set", "CLAUDE_REVIEW_RESPONSE_MODE", "--body", "auto"),
475
+ );
476
+ }
451
477
  return lines;
452
478
  }
453
479
 
@@ -4,13 +4,15 @@
4
4
  // - forDeletion (the default): `upgrade` deletes every entry before copying
5
5
  // it fresh, so only the permitted shapes pass, the same rule
6
6
  // scripts/kit-owned-paths-contract.test.py enforces on the kit side. A tag
7
- // that broke that rule must not delete Consumer files.
7
+ // that broke that rule must not delete Consumer files. Tests in
8
+ // scripts/cli-upgrade-contract.test.mjs hold ALLOWED_SHAPE equal to the
9
+ // Python pattern and parse this repository's own kit-owned-paths.txt with it.
8
10
  // - read-only (`forDeletion: false`, used by doctor): any plain relative
9
11
  // folder path is accepted, so an older CLI can still check a newer tag that
10
12
  // adds a new kind of Kit-owned path. Nothing is deleted on this path.
11
13
 
12
- const ALLOWED_SHAPE =
13
- /^(?:\.claude\/skills\/[A-Za-z0-9._-]+\/|\.github\/(?:agent-runtime|agent-pipeline|security-audit)\/)$/;
14
+ export const ALLOWED_SHAPE =
15
+ /^(?:\.claude\/skills\/[A-Za-z0-9._-]+\/|\.github\/(?:agent-runtime|agent-pipeline|security-audit|agent-review-response)\/)$/;
14
16
  const SAFE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\/$/;
15
17
 
16
18
  export class ManifestError extends Error {}
package/src/kit-tag.mjs CHANGED
@@ -82,13 +82,22 @@ export function openKitRepo({ runner, repo, serverUrl = DEFAULT_SERVER, remoteUr
82
82
  const dir = join(tmp, "repo.git");
83
83
  const noHooks = join(tmp, "no-hooks");
84
84
  mkdirSync(noHooks);
85
- const cleanup = () => rmSync(tmp, { recursive: true, force: true });
85
+ // The retries are a fallback only: with background maintenance off (below)
86
+ // no git process is left writing in `tmp` once its command has returned.
87
+ const cleanup = () =>
88
+ rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
89
+ // No background maintenance: `git fetch` ends with `git maintenance run
90
+ // --auto`, which newer git detaches (maintenance.autoDetach, gc.autoDetach).
91
+ // The detached process outlives the fetch and can still be writing in the
92
+ // repository (objects/maintenance.lock, gc.pid) when cleanup() removes it,
93
+ // which failed cleanup with ENOTEMPTY.
94
+ const noBackground = ["-c", "maintenance.auto=false", "-c", "gc.auto=0"];
86
95
  // No hooks run, whatever the adopter's global git config says.
87
- const base = ["-C", dir, "-c", `core.hooksPath=${noHooks}`];
96
+ const base = ["-C", dir, "-c", `core.hooksPath=${noHooks}`, ...noBackground];
88
97
  const git = (...args) => runner("git", [...base, ...args]);
89
98
  const gitBytes = (...args) => runner("git", [...base, ...args], { encoding: "buffer" });
90
99
  try {
91
- const r = runner("git", ["init", "--bare", "--quiet", "--template=", dir]);
100
+ const r = runner("git", [...noBackground, "init", "--bare", "--quiet", "--template=", dir]);
92
101
  if (r.status !== 0) throw new KitTagError(`git init failed: ${firstLine(r.stderr)}`);
93
102
  } catch (err) {
94
103
  cleanup();
@@ -13,7 +13,15 @@
13
13
  // configured clean/process filter drivers, so hashing a checkout runs no
14
14
  // command that the checkout's or the adopter's git config names.
15
15
 
16
- import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
16
+ import {
17
+ existsSync,
18
+ lstatSync,
19
+ mkdirSync,
20
+ mkdtempSync,
21
+ readdirSync,
22
+ rmSync,
23
+ writeFileSync,
24
+ } from "node:fs";
17
25
  import { tmpdir } from "node:os";
18
26
  import { isAbsolute, join, resolve } from "node:path";
19
27
  import { firstLine } from "./exec.mjs";
@@ -76,11 +84,62 @@ export function gitSafetyArgs({ runner, root, noHooks }) {
76
84
  return safety;
77
85
  }
78
86
 
87
+ /** `lstat`, or null when nothing is there. */
88
+ export function lstatOrNull(path) {
89
+ try {
90
+ return lstatSync(path);
91
+ } catch (err) {
92
+ if (err.code === "ENOENT" || err.code === "ENOTDIR") return null;
93
+ throw err;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * The first symbolic link or junction at, above or inside the folder `path`
99
+ * (relative to `root`, ending in /), as a path without a trailing slash, or
100
+ * null. git looks straight through a Windows junction, stops at a symlink
101
+ * with "beyond a symbolic link", and stores a symlink inside a folder as a
102
+ * link entry, so this is checked before git ever sees the path.
103
+ */
104
+ export function linkAt(root, path) {
105
+ const folder = path.replace(/\/$/, "");
106
+ const parts = folder.split("/");
107
+ for (let i = 1; i <= parts.length; i++) {
108
+ const sub = parts.slice(0, i).join("/");
109
+ const st = lstatOrNull(join(root, sub));
110
+ if (!st) return null;
111
+ if (st.isSymbolicLink()) return sub;
112
+ }
113
+ return linksUnder(root, folder)[0] ?? null;
114
+ }
115
+
116
+ /**
117
+ * Every symbolic link or junction at or inside `rel` (relative to `root`, no
118
+ * trailing slash), in sorted walk order: never followed or guessed at. doctor
119
+ * reports what it finds and upgrade refuses to delete through it, so both
120
+ * agree on what is linked.
121
+ */
122
+ export function linksUnder(root, rel) {
123
+ const found = [];
124
+ const walk = (sub) => {
125
+ const st = lstatOrNull(join(root, sub));
126
+ if (!st) return;
127
+ if (st.isSymbolicLink()) found.push(sub);
128
+ else if (st.isDirectory()) {
129
+ for (const name of readdirSync(join(root, sub)).sort()) walk(`${sub}/${name}`);
130
+ }
131
+ };
132
+ walk(rel);
133
+ return found;
134
+ }
135
+
79
136
  /**
80
137
  * @param {{ runner: import("./exec.mjs").Runner, cwd: string, paths: string[] }} opts
81
- * @returns {{ root: string, hashes: Map<string, string | null>, skipped: Map<string, string>, notes: Map<string, string> }}
138
+ * @returns {{ root: string, hashes: Map<string, string | null>, skipped: Map<string, string>, notes: Map<string, string>, links: Map<string, string> }}
82
139
  * A null hash means the path is missing locally; `skipped` holds paths that
83
- * could not be compared, with the reason; `notes` explains how a path was compared.
140
+ * could not be compared, with the reason; `notes` explains how a path was compared;
141
+ * `links` maps a path that is, sits under, or holds a symbolic link or junction to
142
+ * that link. A linked path is never hashed.
84
143
  */
85
144
  export function localTreeHashes({ runner, cwd, paths }) {
86
145
  for (const p of paths) {
@@ -137,7 +196,13 @@ export function localTreeHashes({ runner, cwd, paths }) {
137
196
  const hashes = new Map();
138
197
  const skipped = new Map();
139
198
  const notes = new Map();
199
+ const links = new Map();
140
200
  for (const path of paths) {
201
+ const link = linkAt(root, path);
202
+ if (link !== null) {
203
+ links.set(path, link);
204
+ continue;
205
+ }
141
206
  // The real index (read only) knows skip-worktree entries (`S`), which
142
207
  // have no files on disk. Everything else comes from the working copy
143
208
  // (`git add`); only the S files are then reset to HEAD's copy, so local
@@ -233,7 +298,7 @@ export function localTreeHashes({ runner, cwd, paths }) {
233
298
  }
234
299
  hashes.set(path, tree.stdout.trim());
235
300
  }
236
- return { root, hashes, skipped, notes };
301
+ return { root, hashes, skipped, notes, links };
237
302
  } finally {
238
303
  rmSync(tmp, { recursive: true, force: true });
239
304
  }
@@ -3,20 +3,12 @@
3
3
  // and carrying out a plan. Both commands plan first and write second: every
4
4
  // refusal (a Refusal) is raised while planning, before anything is written.
5
5
 
6
- import {
7
- chmodSync,
8
- lstatSync,
9
- mkdirSync,
10
- mkdtempSync,
11
- readdirSync,
12
- rmSync,
13
- writeFileSync,
14
- } from "node:fs";
6
+ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
15
7
  import { tmpdir } from "node:os";
16
8
  import { dirname, join } from "node:path";
17
9
  import { firstLine } from "./exec.mjs";
18
10
  import { EXECUTABLE_MODE } from "./kit-tag.mjs";
19
- import { fileModeIsOff, gitSafetyArgs } from "./local-tree.mjs";
11
+ import { fileModeIsOff, gitSafetyArgs, linksUnder, lstatOrNull } from "./local-tree.mjs";
20
12
  import { checkSafePath } from "./safe-paths.mjs";
21
13
 
22
14
  /** A reason not to start. Nothing has been written when this is thrown. */
@@ -43,14 +35,8 @@ export function reportRefusal(out, err) {
43
35
  return 1;
44
36
  }
45
37
 
46
- export function lstatOrNull(path) {
47
- try {
48
- return lstatSync(path);
49
- } catch (err) {
50
- if (err.code === "ENOENT" || err.code === "ENOTDIR") return null;
51
- throw err;
52
- }
53
- }
38
+ // Defined beside the link walk doctor uses (local-tree.mjs imports nothing from here).
39
+ export { lstatOrNull };
54
40
 
55
41
  /**
56
42
  * Refuse unless `rel` (a repository-relative path, no trailing slash) can be
@@ -95,21 +81,6 @@ export function checkNoLinks(root, rel, { deleted = [] } = {}) {
95
81
  }
96
82
  }
97
83
 
98
- /** Links inside `rel`: never followed or guessed at. */
99
- function linksUnder(root, rel) {
100
- const found = [];
101
- const walk = (sub) => {
102
- const st = lstatOrNull(join(root, sub));
103
- if (!st) return;
104
- if (st.isSymbolicLink()) found.push(sub);
105
- else if (st.isDirectory()) {
106
- for (const name of readdirSync(join(root, sub)).sort()) walk(`${sub}/${name}`);
107
- }
108
- };
109
- walk(rel);
110
- return found;
111
- }
112
-
113
84
  /** Refuse unless folder `rel` can be deleted whole: checkLocalPath, and no link inside it. */
114
85
  export function checkDeletable(root, rel) {
115
86
  checkLocalPath(root, rel);
package/src/templates.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  export class TemplateError extends Error {}
9
9
 
10
- /** The two flows init sets up, keyed by the name `--flows` takes. */
10
+ /** The flows init sets up, keyed by the name `--flows` takes, in the order it writes them. */
11
11
  export const FLOWS = {
12
12
  pipeline: {
13
13
  example: "examples/plan-implement-review-caller.yml",
@@ -17,6 +17,10 @@ export const FLOWS = {
17
17
  example: "examples/security-audit-caller.yml",
18
18
  caller: ".github/workflows/security-audit.yml",
19
19
  },
20
+ "review-response": {
21
+ example: "examples/review-response-caller.yml",
22
+ caller: ".github/workflows/agent-review-response.yml",
23
+ },
20
24
  };
21
25
 
22
26
  export const DEFAULT_THREAT_PACK_DIR = ".security";
@@ -44,31 +48,31 @@ export const PLACEHOLDERS = [
44
48
  {
45
49
  name: "your-github-login",
46
50
  pattern: /your-github-login/g,
47
- counts: { pipeline: 4, audit: 1 },
51
+ counts: { pipeline: 5, audit: 1, "review-response": 1 },
48
52
  replace: (v) => () => v.actors.join('","'),
49
53
  },
50
54
  {
51
55
  name: "the @vX.Y.Z pin of each Agent-kit uses:",
52
56
  pattern: KIT_PIN,
53
- counts: { pipeline: 3, audit: 1 },
57
+ counts: { pipeline: 3, audit: 1, "review-response": 1 },
54
58
  replace: (v) => (_, path) => `${path}@${v.tag}`,
55
59
  },
56
60
  {
57
61
  name: '"main" (the default branch)',
58
62
  pattern: /"main"/g,
59
- counts: { pipeline: 2, audit: 0 },
63
+ counts: { pipeline: 2, audit: 0, "review-response": 0 },
60
64
  replace: (v) => () => `"${v.defaultBranch}"`,
61
65
  },
62
66
  {
63
67
  name: "the placeholder verify_commands echo line",
64
68
  pattern: VERIFY_LINE,
65
- counts: { pipeline: 1, audit: 0 },
69
+ counts: { pipeline: 1, audit: 0, "review-response": 1 },
66
70
  replace: (v) => (_, indent) => indentLines(v.verify, indent),
67
71
  },
68
72
  {
69
73
  name: "the commented `# setup_commands: |` block",
70
74
  pattern: SETUP_BLOCK,
71
- counts: { pipeline: 1, audit: 0 },
75
+ counts: { pipeline: 1, audit: 0, "review-response": 1 },
72
76
  replace: (v) => (match, indent) =>
73
77
  v.preset === null
74
78
  ? match
@@ -77,13 +81,13 @@ export const PLACEHOLDERS = [
77
81
  {
78
82
  name: '".security/threat-model.md"',
79
83
  pattern: /"\.security\/threat-model\.md"/g,
80
- counts: { pipeline: 0, audit: 1 },
84
+ counts: { pipeline: 0, audit: 1, "review-response": 0 },
81
85
  replace: (v) => () => `"${v.threatPackDir}/threat-model.md"`,
82
86
  },
83
87
  {
84
88
  name: '".security/findings-ledger.md"',
85
89
  pattern: /"\.security\/findings-ledger\.md"/g,
86
- counts: { pipeline: 0, audit: 1 },
90
+ counts: { pipeline: 0, audit: 1, "review-response": 0 },
87
91
  replace: (v) => () => `"${v.threatPackDir}/findings-ledger.md"`,
88
92
  },
89
93
  ];