@a2f0/agent-tool 0.1.72 → 0.1.74

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 (36) hide show
  1. package/README.md +10 -8
  2. package/package.json +2 -1
  3. package/skills/performance-pass/SKILL.md +107 -0
  4. package/skills/performance-pass/agents/openai.yaml +4 -0
  5. package/skills/performance-pass/references/lessons.md +30 -0
  6. package/skills/space-cleanup/SKILL.md +96 -0
  7. package/skills/space-cleanup/agents/openai.yaml +4 -0
  8. package/skills/take-screenshots/SKILL.md +103 -0
  9. package/skills/take-screenshots/agents/openai.yaml +4 -0
  10. package/skills/take-screenshots/references/adding-capture.md +121 -0
  11. package/src/cli.ts +14 -1
  12. package/src/perf/browser.ts +269 -0
  13. package/src/perf/command.ts +82 -0
  14. package/src/perf/diff.ts +115 -0
  15. package/src/perf/graph.ts +110 -0
  16. package/src/perf/options.ts +107 -0
  17. package/src/perf/serve.ts +163 -0
  18. package/src/permissions/catalog.ts +6 -1
  19. package/src/screenshots/build.ts +4 -3
  20. package/src/screenshots/store/capture.ts +317 -0
  21. package/src/screenshots/store/clones.ts +145 -0
  22. package/src/screenshots/store/command.ts +317 -0
  23. package/src/screenshots/store/git.ts +14 -0
  24. package/src/screenshots/store/link.ts +201 -0
  25. package/src/screenshots/store/lock.ts +94 -0
  26. package/src/screenshots/store/namespace.ts +311 -0
  27. package/src/screenshots/store/record.ts +157 -0
  28. package/src/screenshots/store/store.ts +47 -0
  29. package/src/screenshots/store/targets.ts +68 -0
  30. package/src/skills/bundled.ts +14 -0
  31. package/src/space/candidates.ts +228 -0
  32. package/src/space/command.ts +325 -0
  33. package/src/space/machine.ts +303 -0
  34. package/src/space/processes.ts +186 -0
  35. package/src/space/targets.ts +24 -0
  36. package/src/system/checkouts.ts +135 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * `perf serve`: a production build served the way a CDN with revalidation serves
3
+ * it, so local measurements stand in for the deployment.
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import { mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, type Stats, statSync } from "node:fs";
7
+ import { createServer, type IncomingMessage, ServerResponse } from "node:http";
8
+ import { createSecureServer, type Http2ServerRequest, type Http2ServerResponse } from "node:http2";
9
+ import type { AddressInfo } from "node:net";
10
+ import { tmpdir } from "node:os";
11
+ import path from "node:path";
12
+ import { gzipSync } from "node:zlib";
13
+
14
+ const TYPES: Record<string, string> = {
15
+ ".html": "text/html",
16
+ ".js": "text/javascript",
17
+ ".mjs": "text/javascript",
18
+ ".css": "text/css",
19
+ ".json": "application/json",
20
+ ".svg": "image/svg+xml",
21
+ ".png": "image/png",
22
+ ".jpg": "image/jpeg",
23
+ ".ico": "image/x-icon",
24
+ ".wasm": "application/wasm",
25
+ ".txt": "text/plain",
26
+ };
27
+ const COMPRESSED = new Set([".html", ".js", ".mjs", ".css", ".json", ".svg", ".txt"]);
28
+
29
+ /** A file version's validator: its size and modification time. */
30
+ const etagOf = (stats: Stats) => `"${stats.size}-${stats.mtimeMs}"`;
31
+
32
+ /** A throwaway self-signed certificate for localhost, so the server can speak HTTP/2 as CDNs do. */
33
+ function certificate(): { key: Buffer; cert: Buffer } {
34
+ const directory = mkdtempSync(path.join(tmpdir(), "perf-cert-"));
35
+ try {
36
+ const result = spawnSync(
37
+ "openssl",
38
+ [
39
+ "req",
40
+ "-x509",
41
+ "-newkey",
42
+ "rsa:2048",
43
+ "-nodes",
44
+ "-days",
45
+ "2",
46
+ "-subj",
47
+ "/CN=localhost",
48
+ "-keyout",
49
+ path.join(directory, "key.pem"),
50
+ "-out",
51
+ path.join(directory, "cert.pem"),
52
+ ],
53
+ { stdio: "ignore" },
54
+ );
55
+ if (result.status !== 0) throw new Error("openssl could not make a localhost certificate; pass --http1 to serve without TLS.");
56
+ return { key: readFileSync(path.join(directory, "key.pem")), cert: readFileSync(path.join(directory, "cert.pem")) };
57
+ } finally {
58
+ rmSync(directory, { recursive: true, force: true });
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Serves a build the way a CDN with revalidation does: over HTTP/2 (browsers allow six
64
+ * HTTP/1.1 connections per host, which queues module graphs that a CDN serves in parallel),
65
+ * text compressed once per file version so compression never costs request time, and
66
+ * `no-cache` with an ETag. Paths outside `root` 404.
67
+ */
68
+ export function serve(root: string, port: number, http1 = false) {
69
+ const base = realpathSync(path.resolve(root));
70
+ const cache = new Map<string, { key: string; body: Buffer }>();
71
+ // The file a path names, resolved through symlinks, or undefined when that leaves the root.
72
+ const inside = (pathname: string) => {
73
+ try {
74
+ const file = realpathSync(path.resolve(base, `.${pathname}`));
75
+ return file.startsWith(base + path.sep) && statSync(file).isFile() ? file : undefined;
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ };
80
+ const compressed = (file: string, etag: string, body: Buffer) => {
81
+ if (cache.get(file)?.key !== etag) cache.set(file, { key: etag, body: gzipSync(body, { level: 9 }) });
82
+ return cache.get(file)!.body;
83
+ };
84
+ // Compress every text file before serving, so the first measured load pays no compression.
85
+ // Symlinked directories are left to be compressed on request.
86
+ const warm = (directory: string) => {
87
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
88
+ const full = path.join(directory, entry.name);
89
+ if (entry.isDirectory()) {
90
+ warm(full);
91
+ continue;
92
+ }
93
+ const file = inside(`/${path.relative(base, full).split(path.sep).join("/")}`);
94
+ if (!file || !COMPRESSED.has(path.extname(file).toLowerCase())) continue;
95
+ compressed(file, etagOf(statSync(file)), readFileSync(file));
96
+ }
97
+ };
98
+ warm(base);
99
+ const handler = (request: IncomingMessage | Http2ServerRequest, response: ServerResponse | Http2ServerResponse) => {
100
+ // Another site's page reaching this port through a name it rebound to 127.0.0.1 names that host.
101
+ if (!loopbackHost(request)) return respond(response, { status: 421 });
102
+ try {
103
+ const pathname = requestPath(request.url);
104
+ const file = pathname ? inside(pathname) : undefined;
105
+ respond(response, file ? reply(request, file, compressed) : { status: 404 });
106
+ } catch {
107
+ // A file removed or replaced mid-request, as a rebuild does, fails that request, not the server.
108
+ if (!response.headersSent) respond(response, { status: 404 });
109
+ }
110
+ };
111
+ const server = http1 ? createServer(handler) : createSecureServer({ ...certificate(), allowHTTP1: true }, handler);
112
+ server.once("error", error => {
113
+ process.stderr.write(`perf serve: ${error.message}\n`);
114
+ process.exitCode = 1;
115
+ });
116
+ // Loopback only: the build is for this machine's browser, not the network.
117
+ return server.listen(port, "127.0.0.1", () =>
118
+ console.log(`Serving ${base} at ${http1 ? "http" : "https"}://127.0.0.1:${(server.address() as AddressInfo).port}/`),
119
+ );
120
+ }
121
+
122
+ interface Reply {
123
+ status: number;
124
+ headers?: Record<string, string>;
125
+ body?: Buffer;
126
+ }
127
+
128
+ /** What a request for a served file gets: 304 when its ETag matches, else the file, gzipped when its type and the client allow. */
129
+ function reply(request: IncomingMessage | Http2ServerRequest, file: string, compressed: (file: string, etag: string, body: Buffer) => Buffer): Reply {
130
+ const extension = path.extname(file).toLowerCase();
131
+ const etag = etagOf(statSync(file));
132
+ const headers: Record<string, string> = { "content-type": TYPES[extension] ?? "application/octet-stream", "cache-control": "no-cache", etag };
133
+ if (request.headers["if-none-match"] === etag) return { status: 304, headers };
134
+ let body: Buffer = readFileSync(file);
135
+ if (COMPRESSED.has(extension) && /\bgzip\b/.test(String(request.headers["accept-encoding"] ?? ""))) {
136
+ body = compressed(file, etag, body);
137
+ headers["content-encoding"] = "gzip";
138
+ }
139
+ return { status: 200, headers, body };
140
+ }
141
+
142
+ function respond(response: ServerResponse | Http2ServerResponse, { status, headers, body }: Reply): void {
143
+ if (response instanceof ServerResponse) response.writeHead(status, headers).end(body);
144
+ else if (body) response.writeHead(status, headers).end(body);
145
+ else response.writeHead(status, headers).end();
146
+ }
147
+
148
+ /** Whether a request names this machine (`127.0.0.1` or `localhost`, any port) as its host. */
149
+ function loopbackHost(request: IncomingMessage | Http2ServerRequest): boolean {
150
+ const host = String(request.headers[":authority"] ?? request.headers.host ?? "").toLowerCase();
151
+ return /^(?:127\.0\.0\.1|localhost)(?::\d+)?$/.test(host);
152
+ }
153
+
154
+ /** The decoded path a request names, a directory's naming its index.html; empty when it does not decode. */
155
+ function requestPath(url: string | undefined): string {
156
+ let pathname: string;
157
+ try {
158
+ pathname = decodeURIComponent(new URL(url ?? "/", "http://localhost").pathname);
159
+ } catch {
160
+ pathname = "";
161
+ }
162
+ return pathname.endsWith("/") ? `${pathname}index.html` : pathname;
163
+ }
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list", "perf diff", "screenshots status"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -40,6 +40,11 @@ export const CATALOG: CatalogEntry[] = [
40
40
  ];
41
41
  // `run`, `run-group`, `push-gate run` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
42
42
  // `seo probe` requests whatever host its arguments name, and public hosts its fetched pages name, like curl, so it keeps the harness default too.
43
+ // So do `perf measure` and `perf shot`, which open any URL in Chrome and evaluate the JavaScript their arguments give,
44
+ // `perf serve`, which serves a directory to every local user, `perf graph`, whose --out overwrites any file, and `space`, whose --apply removes output in other
45
+ // checkouts and developer caches across the machine, with --include-busy even where other sessions work.
46
+ // `screenshots link` and `screenshots capture` keep it as well: --apply links every clone on the machine with
47
+ // --all and writes the shared store outside the checkout, and capture runs the repository's `screenshots` script.
43
48
  // `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
44
49
  // Package scripts are not classified, so `bun run` keeps the harness default.
45
50
 
@@ -5,9 +5,10 @@ import { pngSize } from "../images/png";
5
5
  import { assertNoLinks, replaceFile } from "../system/files";
6
6
  import type { ScreenshotsConfig, ScreenshotTarget } from "./config";
7
7
  import type { ScreenshotCapture, ScreenshotEntry, ScreenshotManifest } from "./manifest";
8
+ import { RECORD } from "./store/record";
8
9
 
9
- /** The record the take-screenshots skill keeps beside a shared capture. */
10
- export const CAPTURE_RECORD = "capture.json";
10
+ /** The record `screenshots capture` keeps beside a shared capture. */
11
+ export const CAPTURE_RECORD = RECORD;
11
12
  const MANIFEST = "manifest.json";
12
13
  const IMAGES = "img";
13
14
 
@@ -41,7 +42,7 @@ export function checkCapture(root: string, source: string, raw: string | undefin
41
42
  try { record = JSON.parse(raw) as CaptureRecord; } catch { throw new Error(`The shared screenshot capture record ${CAPTURE_RECORD} is not JSON; recapture.`); }
42
43
  if (!record || typeof record !== "object") throw new Error(`The shared screenshot capture record ${CAPTURE_RECORD} is not an object; recapture.`);
43
44
  if (record.status !== "complete") throw new Error(`The shared screenshot capture is ${String(record.status)}; wait for it or recapture.`);
44
- if (typeof record.commit !== "string" || !/^[0-9a-f]{40}$/.test(record.commit)) throw new Error("The shared screenshot capture record names no commit; recapture.");
45
+ if (typeof record.commit !== "string" || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(record.commit)) throw new Error("The shared screenshot capture record names no commit; recapture.");
45
46
  if (record.dirty !== false) throw new Error("The shared screenshots were captured from uncommitted changes; recapture from a commit.");
46
47
  const partial = Array.isArray(record.args) ? record.args.map(String) : [];
47
48
  return { commit: record.commit, finishedAt: typeof record.finishedAt === "string" ? record.finishedAt : null, partial };
@@ -0,0 +1,317 @@
1
+ /** Running a repository's capture under the lock and recording it. */
2
+ import { spawn } from "node:child_process";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { git, gitValue } from "./git";
6
+ import { linkState } from "./link";
7
+ import { acquireLock, alive, type LockInfo, replaceLock } from "./lock";
8
+ import { claimNamespace } from "./namespace";
9
+ import {
10
+ type CaptureRecord,
11
+ type FinishedStatus,
12
+ type RecordFields,
13
+ type RunningRecord,
14
+ readRecord,
15
+ type StoredRecord,
16
+ transition,
17
+ writeRecord,
18
+ } from "./record";
19
+ import { LINK, LOCK, storeDir, type Target } from "./store";
20
+ import { packageScripts } from "./targets";
21
+
22
+ export interface Runner {
23
+ /**
24
+ * Starts the repository's capture with inherited output and the given
25
+ * environment, in a process group of its own when it can. Resolves with its
26
+ * exit code and that group, which must be empty before the lock is released.
27
+ */
28
+ capture(root: string, args: string[], env: NodeJS.ProcessEnv, started: (pgid: number) => void): Promise<{ code: number | null; pgid?: number }>;
29
+ }
30
+
31
+ export const RUNNER: Runner = {
32
+ capture(root, args, env, started) {
33
+ return new Promise((resolve, reject) => {
34
+ // detached gives the capture its own process group, so its descendants can be found, signalled, and waited for.
35
+ // The script's output goes to stderr, so a --json report on stdout stays parseable.
36
+ const child = spawn("bun", ["run", "screenshots", ...args], { cwd: root, env, stdio: ["inherit", 2, "inherit"], detached: true });
37
+ child.once("error", error => reject(new Error(`Could not run bun: ${error.message}`)));
38
+ child.once("spawn", () => {
39
+ if (child.pid) started(child.pid);
40
+ });
41
+ child.once("exit", code => resolve({ code, ...(child.pid ? { pgid: child.pid } : {}) }));
42
+ });
43
+ },
44
+ };
45
+
46
+ /**
47
+ * Waits for every process in a group to exit, stopping them after `graceMs`.
48
+ * `exited` means they finished on their own; `stopped` that they had to be
49
+ * killed, so their output is incomplete; `stuck` that some still run.
50
+ */
51
+ export async function drainGroup(pgid: number, graceMs = 30_000, killMs = 10_000): Promise<"exited" | "stopped" | "stuck"> {
52
+ const empty = () => !alive(-pgid);
53
+ const wait = async (ms: number) => {
54
+ for (const deadline = Date.now() + ms; Date.now() < deadline; await new Promise(done => setTimeout(done, 100))) if (empty()) return true;
55
+ return empty();
56
+ };
57
+ if (await wait(graceMs)) return "exited";
58
+ process.stderr.write(`Capture processes in group ${pgid} outlived the capture; stopping them, so this capture fails.\n`);
59
+ try {
60
+ process.kill(-pgid, "SIGTERM");
61
+ } catch {
62
+ /* exited meanwhile */
63
+ }
64
+ if (await wait(killMs)) return "stopped";
65
+ try {
66
+ process.kill(-pgid, "SIGKILL");
67
+ } catch {
68
+ /* exited meanwhile */
69
+ }
70
+ return (await wait(killMs)) ? "stopped" : "stuck";
71
+ }
72
+
73
+ /** A capture as planned: what it would run and record. */
74
+ interface PlannedCapture {
75
+ readonly name: string;
76
+ readonly project: string;
77
+ readonly store: string;
78
+ readonly command: string;
79
+ readonly commit: string;
80
+ readonly branch: string | null;
81
+ readonly dirty: boolean;
82
+ readonly merged: boolean | null;
83
+ readonly previous?: StoredRecord;
84
+ readonly applied?: never;
85
+ readonly record?: never;
86
+ }
87
+
88
+ /** A planned capture that ran, with the record it left; `--json` prints `applied` before `record`. */
89
+ interface AppliedCapture extends Omit<PlannedCapture, "applied" | "record"> {
90
+ readonly applied: true;
91
+ readonly record: CaptureRecord;
92
+ }
93
+
94
+ export type CapturePlan = PlannedCapture | AppliedCapture;
95
+
96
+ /** Local changes, including edits behind assume-unchanged or skip-worktree flags that git status cannot see. */
97
+ function isDirty(root: string): boolean {
98
+ const checked = (...args: string[]) => {
99
+ const result = git(root, ...args);
100
+ // A check that fails proves nothing about the tree, so it never passes for clean.
101
+ if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed in ${root}; cannot tell whether it has local changes`);
102
+ return result.stdout;
103
+ };
104
+ // `ls-files -v` tags assume-unchanged entries in lowercase and skip-worktree entries with S.
105
+ if (
106
+ checked("ls-files", "-v")
107
+ .split("\n")
108
+ .some(line => /^[a-zS] /.test(line))
109
+ )
110
+ return true;
111
+ // Configured submodule ignore settings could hide a submodule's changes; count them all.
112
+ return checked("status", "--porcelain=v1", "--untracked-files=normal", "--ignore-submodules=none") !== "";
113
+ }
114
+
115
+ /** How long leftover capture processes get before they are stopped; tests shorten it. */
116
+ export interface Timing {
117
+ readonly graceMs?: number;
118
+ readonly killMs?: number;
119
+ /** Waits for the capture's group; tests substitute one that reports a group that would not stop. */
120
+ readonly drain?: (pgid: number, graceMs?: number, killMs?: number) => Promise<Awaited<ReturnType<typeof drainGroup>>>;
121
+ }
122
+
123
+ export interface CaptureOptions {
124
+ readonly apply: boolean;
125
+ readonly allowDirty: boolean;
126
+ readonly args: string[];
127
+ }
128
+
129
+ export async function capture(target: Target, artifacts: string, options: CaptureOptions, runner: Runner = RUNNER, timing: Timing = {}): Promise<CapturePlan> {
130
+ const plan = planCapture(target, artifacts, options);
131
+ if (!options.apply) return plan;
132
+ return runCapture(target, artifacts, plan, options.args, runner, timing);
133
+ }
134
+
135
+ /**
136
+ * Checks the repository can be captured and describes the capture, changing
137
+ * nothing. `willLink` plans a clone that is not linked yet as linked, for a
138
+ * caller that links it before capturing; capture() itself never passes it.
139
+ */
140
+ export function planCapture(target: Target, artifacts: string, options: Omit<CaptureOptions, "apply">, willLink = false): PlannedCapture {
141
+ if (typeof packageScripts(target.root).screenshots !== "string") {
142
+ throw new Error(`${target.name} has no \`screenshots\` package script; see the take-screenshots skill's repository contract`);
143
+ }
144
+ const state = linkState(target, artifacts);
145
+ if (state.state !== "linked" && !willLink) throw new Error(`${target.name}/${LINK} is ${state.state}, not linked to the store; run \`link --apply\` first`);
146
+ // Refused here too, not only under the lock, so a capture into another repository's namespace links no clone.
147
+ const foreign = claimNamespace(target, artifacts, false);
148
+ if (foreign) throw new Error(foreign);
149
+ const commit = gitValue(target.root, "rev-parse", "HEAD");
150
+ if (!commit) throw new Error(`${target.name} has no commit to capture`);
151
+ const dirty = isDirty(target.root);
152
+ if (dirty && !options.allowDirty) {
153
+ throw new Error(`${target.name} has local changes; a shared capture would publish them. Commit first, or pass --allow-dirty for a local-only look`);
154
+ }
155
+ const branch = gitValue(target.root, "symbolic-ref", "--quiet", "--short", "HEAD") ?? null;
156
+ const upstream = gitValue(target.root, "rev-parse", "--verify", "--quiet", "refs/remotes/origin/HEAD");
157
+ const merged = upstream ? git(target.root, "merge-base", "--is-ancestor", commit, upstream).status === 0 : null;
158
+ const store = storeDir(target, artifacts);
159
+ const planned = readRecord(store);
160
+ return {
161
+ name: target.name,
162
+ project: target.project,
163
+ store,
164
+ command: ["bun", "run", "screenshots", ...options.args].join(" "),
165
+ commit,
166
+ branch,
167
+ dirty,
168
+ merged,
169
+ ...(planned ? { previous: planned } : {}),
170
+ };
171
+ }
172
+
173
+ /** Signals that would end this process while its capture keeps writing: a closed terminal sends SIGHUP. */
174
+ const FORWARDED: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"];
175
+
176
+ /** Runs a planned capture under the project's lock and records how it finished. */
177
+ async function runCapture(target: Target, artifacts: string, plan: PlannedCapture, args: string[], runner: Runner, timing: Timing): Promise<AppliedCapture> {
178
+ const { store } = plan;
179
+ const startedAt = new Date().toISOString();
180
+ const lockFile = path.join(artifacts, target.project, LOCK);
181
+ const holder: LockInfo = { pid: process.pid, host: os.hostname(), checkout: target.root, startedAt };
182
+ const release = acquireLock(lockFile, holder);
183
+ // Forward SIGINT, SIGTERM, and SIGHUP to the capture's group and finish here, so the record and lock are settled.
184
+ let signal: NodeJS.Signals | undefined;
185
+ let group: number | undefined;
186
+ const hold = (received: NodeJS.Signals) => {
187
+ signal = received;
188
+ if (group !== undefined)
189
+ try {
190
+ process.kill(-group, received);
191
+ } catch {
192
+ /* already gone */
193
+ }
194
+ };
195
+ for (const name of FORWARDED) process.on(name, hold);
196
+ try {
197
+ // Re-read under the lock: the previous capture is now settled.
198
+ const previous = readRecord(store);
199
+ const foreign = claimNamespace(target, artifacts, true);
200
+ if (foreign) throw new Error(foreign);
201
+ const { base, inheritsIncomplete } = runningRecord(target, plan, args, previous, startedAt);
202
+ const running = transition(previous, { type: "start", fields: base });
203
+ writeRecord(store, running);
204
+ let exitCode: number | null = null;
205
+ // Runners that honor SCREENSHOT_OUTPUT_DIR must write through the link, whatever the caller's shell exports.
206
+ const env = { ...process.env, SCREENSHOT_OUTPUT_DIR: path.join(target.root, LINK) };
207
+ let drained: Awaited<ReturnType<typeof drainGroup>> = "exited";
208
+ let finished: CaptureRecord;
209
+ try {
210
+ const result = await runner.capture(target.root, args, env, pgid => {
211
+ group = pgid;
212
+ // Record the capture's own group in the lock, so a person can find leftovers if this process is killed.
213
+ // This runs in the spawn listener, where a throw would end agent-tool with the capture unsupervised.
214
+ try {
215
+ replaceLock(lockFile, { ...holder, pgid });
216
+ } catch (error) {
217
+ process.stderr.write(`Could not record the capture's process group ${pgid} in ${lockFile}: ${(error as Error).message}\n`);
218
+ }
219
+ });
220
+ exitCode = result.code;
221
+ if (result.pgid !== undefined) drained = await (timing.drain ?? drainGroup)(result.pgid, timing.graceMs, timing.killMs);
222
+ } finally {
223
+ finished = finishedRecord(target, artifacts, plan, running, { exitCode, signal, drained, inheritsIncomplete });
224
+ // The capture may have replaced the shared directory's contents; the record goes back in either way.
225
+ writeRecord(store, finished);
226
+ }
227
+ if (drained === "stuck") throw new Error(`capture processes in group ${group} would not stop; the lock ${lockFile} stays until they are gone`);
228
+ release();
229
+ return { ...plan, applied: true, record: finished };
230
+ } catch (error) {
231
+ // Release only when no capture process can still be writing.
232
+ if (group === undefined || !alive(-group)) release();
233
+ throw error;
234
+ } finally {
235
+ for (const name of FORWARDED) process.off(name, hold);
236
+ }
237
+ }
238
+
239
+ /** The record's fields while the capture runs, and whether a complete one still counts as incomplete. */
240
+ function runningRecord(
241
+ target: Target,
242
+ plan: PlannedCapture,
243
+ args: string[],
244
+ previous: StoredRecord | undefined,
245
+ startedAt: string,
246
+ ): { base: RecordFields; inheritsIncomplete: boolean } {
247
+ const { commit, branch, dirty, merged } = plan;
248
+ // A partial capture keeps whatever else the store holds; with no record, that is of unknown provenance.
249
+ const partial = args.length > 0;
250
+ const inheritsDirty = partial && previous?.dirty === true;
251
+ const inheritsIncomplete = partial && (previous === undefined || previous.status !== "complete");
252
+ const base = {
253
+ schemaVersion: 1 as const,
254
+ project: target.project,
255
+ ...(target.repo ? { repo: target.repo } : {}),
256
+ commit,
257
+ branch,
258
+ dirty: dirty || inheritsDirty,
259
+ args,
260
+ // Kept images are only as merged as the capture that made them.
261
+ merged: partial && previous && previous.merged !== true && merged !== false ? previous.merged : merged,
262
+ ...(partial && previous ? { over: { commit: previous.commit, status: previous.status, dirty: previous.dirty } } : {}),
263
+ checkout: target.root,
264
+ host: os.hostname(),
265
+ startedAt,
266
+ };
267
+ return { base, inheritsIncomplete };
268
+ }
269
+
270
+ /** How a capture's run ended, as the finished record judges it. */
271
+ interface RunOutcome {
272
+ readonly exitCode: number | null;
273
+ readonly signal: NodeJS.Signals | undefined;
274
+ readonly drained: Awaited<ReturnType<typeof drainGroup>>;
275
+ readonly inheritsIncomplete: boolean;
276
+ }
277
+
278
+ /** The record of a finished capture, after checking that the clone still shows the planned commit through the link. */
279
+ function finishedRecord(target: Target, artifacts: string, plan: PlannedCapture, running: RunningRecord, outcome: RunOutcome): CaptureRecord {
280
+ const { exitCode, signal, drained, inheritsIncomplete } = outcome;
281
+ const shows = showsPlannedCommit(target, artifacts, plan);
282
+ const finalStatus = (): FinishedStatus => {
283
+ if (exitCode !== 0 || signal || !shows || drained !== "exited") return "failed";
284
+ return inheritsIncomplete ? "incomplete" : "complete";
285
+ };
286
+ return transition(running, { type: "finish", status: finalStatus(), finishedAt: new Date().toISOString(), exitCode });
287
+ }
288
+
289
+ /**
290
+ * Whether the clone still shows the planned commit through the link, saying why when it does not.
291
+ * A check that fails proves nothing, so it counts as not showing it: the record must still be written.
292
+ */
293
+ function showsPlannedCommit(target: Target, artifacts: string, plan: PlannedCapture): boolean {
294
+ const { commit, dirty } = plan;
295
+ let kept: boolean;
296
+ let moved: boolean;
297
+ try {
298
+ // A capture that deleted and recreated .screenshots wrote into the clone, not the store.
299
+ kept = linkState(target, artifacts).state === "linked";
300
+ // The record names one commit: a branch switch or new edit mid-capture makes that untrue.
301
+ moved = gitValue(target.root, "rev-parse", "HEAD") !== commit || (!dirty && isDirty(target.root));
302
+ } catch (error) {
303
+ process.stderr.write(
304
+ `Could not check ${target.name} after the capture (${error instanceof Error ? error.message : String(error)}), so it fails; capture again.\n`,
305
+ );
306
+ return false;
307
+ }
308
+ if (moved)
309
+ process.stderr.write(
310
+ `${target.name} changed commit or gained local changes during the capture, so it does not show ${commit.slice(0, 10)}; capture again.\n`,
311
+ );
312
+ if (!kept)
313
+ process.stderr.write(
314
+ `${target.name}/${LINK} is no longer linked: the capture replaced it, so the store did not receive it. Never remove ${LINK} itself; clear its contents.\n`,
315
+ );
316
+ return kept && !moved;
317
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Every clone on this machine that shares a store, and linking the ones that
3
+ * need no decision.
4
+ */
5
+ import { type Dirent, readdirSync, realpathSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { isMatrixWorkspace, toplevel } from "../../system/checkouts";
8
+ import { type LinkResult, link, linkState } from "./link";
9
+ import { claimNamespace, existingCase, knownNamespace, linkedNamespace, OWNER, targetFor } from "./namespace";
10
+ import { LINK, lexists, storeDir, type Target } from "./store";
11
+ import { artifactsRoot, captures } from "./targets";
12
+
13
+ /** The store --all works on: the one the repository holding cwd resolves, else MATRIX_ARTIFACTS_DIR. */
14
+ export function sharedStore(cwd: string, env: NodeJS.ProcessEnv = process.env): string {
15
+ const here = toplevel(cwd);
16
+ if (here) return artifactsRoot(realpathSync(here), env);
17
+ if (env.MATRIX_ARTIFACTS_DIR) return path.resolve(env.MATRIX_ARTIFACTS_DIR);
18
+ throw new Error(`${cwd} is not inside a git repository; run --all from a clone or set MATRIX_ARTIFACTS_DIR`);
19
+ }
20
+
21
+ /**
22
+ * The store with its directory resolved through symlinks (such as macOS's /tmp),
23
+ * so the clones beside it compare and name by real paths. The store itself may
24
+ * be a link elsewhere; its clones still sit beside the link.
25
+ */
26
+ function realStore(artifacts: string): string {
27
+ const parent = path.dirname(artifacts);
28
+ return path.join(realPath(parent)[0] ?? parent, path.basename(artifacts));
29
+ }
30
+
31
+ /**
32
+ * Where a clone that resolves this store lives: directly beside it (a clone
33
+ * outside a workspace keeps matrix-artifacts beside itself), or in the
34
+ * checkouts of a matrix workspace beside it. Linked worktrees count as clones.
35
+ */
36
+ function candidateRoots(store: string): string[] {
37
+ const parent = path.dirname(store);
38
+ const roots = directories(parent).flatMap(name => {
39
+ const directory = path.join(parent, name);
40
+ if (directory === store) return [];
41
+ if (isMatrixWorkspace(directory)) return [directory, ...checkoutsOf(directory)];
42
+ return lexists(path.join(directory, ".git")) ? [directory] : [];
43
+ });
44
+ return [...new Set(roots.flatMap(realPath))].sort();
45
+ }
46
+
47
+ /** A directory's real path, or nothing when it vanished meanwhile. */
48
+ function realPath(directory: string): string[] {
49
+ try {
50
+ return [realpathSync(directory)];
51
+ } catch {
52
+ return [];
53
+ }
54
+ }
55
+
56
+ /** Real directories only: a symlinked folder is another name for a clone found directly. */
57
+ function directories(parent: string): string[] {
58
+ let entries: Dirent[];
59
+ try {
60
+ entries = readdirSync(parent, { withFileTypes: true });
61
+ } catch {
62
+ return [];
63
+ }
64
+ return entries.filter(entry => entry.isDirectory()).map(entry => entry.name);
65
+ }
66
+
67
+ function checkoutsOf(workspace: string): string[] {
68
+ const checkouts = path.join(workspace, "checkouts");
69
+ return directories(checkouts)
70
+ .map(name => path.join(checkouts, name))
71
+ .filter(root => lexists(path.join(root, ".git")));
72
+ }
73
+
74
+ /** Identity from origin's URL alone, so a sweep of every clone makes no network calls. */
75
+ const OFFLINE = () => undefined;
76
+
77
+ /**
78
+ * Every clone beside the store that captures screenshots into a namespace the
79
+ * store already holds, named by its path from the store's parent directory. A
80
+ * repository joins the store when one of its clones runs `link` or `capture`;
81
+ * after that, --all finds the rest. Identities come from origin's URL, so a
82
+ * renamed repository's clones are found once one clone has recorded the rename
83
+ * online. A clone of another repository is left out unless it is linked into
84
+ * the store, where status reports it as foreign.
85
+ */
86
+ export function clonesSharing(artifacts: string): Target[] {
87
+ const store = realStore(artifacts);
88
+ return candidateRoots(store).flatMap(root => {
89
+ try {
90
+ return sharingClone(root, artifacts, path.dirname(store));
91
+ } catch {
92
+ // A clone that cannot be read, such as one without a GitHub origin, which names its namespace with
93
+ // --project one clone at a time, is left out rather than stopping the others or a capture.
94
+ return [];
95
+ }
96
+ });
97
+ }
98
+
99
+ function sharingClone(root: string, artifacts: string, parent: string): Target[] {
100
+ if (!captures(root)) return [];
101
+ const target = existingCase(knownNamespace(targetFor(root, undefined, OFFLINE), artifacts), artifacts);
102
+ if (!lexists(path.join(artifacts, target.project, OWNER))) return [];
103
+ if (claimNamespace(target, artifacts, false) && linkedNamespace(target, artifacts) === undefined) return [];
104
+ return [{ ...target, name: path.relative(parent, root) }];
105
+ }
106
+
107
+ /** Link actions that need no one's decision: creating a missing link, or replacing an empty directory with one. */
108
+ const AUTOMATIC = new Set<LinkResult["action"]>(["link", "replace-empty-directory"]);
109
+
110
+ /**
111
+ * Plans, and with apply makes, the links that need no decision. Returns a
112
+ * result for each target that is not linked: applied (or planned) for the
113
+ * automatic actions, and `blocked` with the reason for the rest, such as a
114
+ * clone that holds its own capture, which `link` in that clone decides.
115
+ */
116
+ export function linkAutomatically(targets: Target[], artifacts: string, apply: boolean): LinkResult[] {
117
+ return targets.flatMap(target => {
118
+ let before: LinkResult["before"] = "other";
119
+ try {
120
+ before = linkState(target, artifacts).state;
121
+ return linkOne(target, artifacts, apply);
122
+ } catch (error) {
123
+ // One clone that cannot be linked never stops the others, or the capture that asked.
124
+ return [
125
+ {
126
+ name: target.name,
127
+ project: target.project,
128
+ store: storeDir(target, artifacts),
129
+ before,
130
+ blocked: error instanceof Error ? error.message : String(error),
131
+ },
132
+ ];
133
+ }
134
+ });
135
+ }
136
+
137
+ /** One target's result: none once linked, the link when it needs no decision, else why it waits. */
138
+ function linkOne(target: Target, artifacts: string, apply: boolean): LinkResult[] {
139
+ const plan = link(target, artifacts, false);
140
+ if (plan.blocked) return [plan];
141
+ if (plan.before === "linked") return [];
142
+ if (AUTOMATIC.has(plan.action)) return [apply ? link(target, artifacts, true) : plan];
143
+ const { name, project, store, before } = plan;
144
+ return [{ name, project, store, before, blocked: `${LINK} holds this clone's own capture; run \`link\` there to decide` }];
145
+ }