@a2f0/agent-tool 0.1.73 → 0.1.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/package.json +1 -1
- package/skills/optimize-ci/SKILL.md +98 -0
- package/skills/optimize-ci/agents/openai.yaml +4 -0
- package/skills/optimize-ci/references/lessons.md +30 -0
- package/skills/performance-pass/SKILL.md +1 -1
- package/skills/take-screenshots/SKILL.md +103 -0
- package/skills/take-screenshots/agents/openai.yaml +4 -0
- package/skills/take-screenshots/references/adding-capture.md +121 -0
- package/src/ci/command.ts +96 -0
- package/src/ci/timings.ts +174 -0
- package/src/cli.ts +15 -2
- package/src/perf/graph.ts +13 -3
- package/src/permissions/catalog.ts +3 -1
- package/src/screenshots/build.ts +4 -3
- package/src/screenshots/store/capture.ts +317 -0
- package/src/screenshots/store/clones.ts +145 -0
- package/src/screenshots/store/command.ts +317 -0
- package/src/screenshots/store/git.ts +14 -0
- package/src/screenshots/store/link.ts +201 -0
- package/src/screenshots/store/lock.ts +94 -0
- package/src/screenshots/store/namespace.ts +311 -0
- package/src/screenshots/store/record.ts +157 -0
- package/src/screenshots/store/store.ts +47 -0
- package/src/screenshots/store/targets.ts +68 -0
- package/src/skills/bundled.ts +11 -1
- package/src/system/checkouts.ts +29 -7
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure analysis behind `agent-tool ci timings`: which jobs hold a workflow's
|
|
3
|
+
* wall clock across recent runs, where one run's jobs spend their steps, and
|
|
4
|
+
* which tasks and test files a job log executed.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface TimedStep { name: string; conclusion: string | null; startedAt: string | null; completedAt: string | null }
|
|
8
|
+
export interface TimedJob { id: number; name: string; conclusion: string | null; startedAt: string | null; completedAt: string | null; steps?: TimedStep[] }
|
|
9
|
+
export interface TimedRun { id: number; event: string; attempt: number; createdAt: string; jobs: TimedJob[] }
|
|
10
|
+
|
|
11
|
+
const minutesBetween = (from: string, to: string) => (Date.parse(to) - Date.parse(from)) / 60_000;
|
|
12
|
+
const round = (value: number, places = 1) => Number(value.toFixed(places));
|
|
13
|
+
|
|
14
|
+
/** The nearest-rank value at fraction `q` of `values`; 0 when there are none. */
|
|
15
|
+
export function quantile(values: number[], q: number): number {
|
|
16
|
+
if (!values.length) return 0;
|
|
17
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
18
|
+
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]!;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A job's lane: its name without shard counters such as `2/3`, so a split suite's shards count as one. */
|
|
22
|
+
export function lane(name: string): string {
|
|
23
|
+
return name.replace(/\s*\b\d+\/\d+\b\s*/g, " ").replace(/\(\s*\)/g, "").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").replace(/\s{2,}/g, " ").trim();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Jobs that ran in this attempt: skipped jobs and jobs without both timestamps are left out. */
|
|
27
|
+
export function executedJobs(jobs: TimedJob[]): (TimedJob & { startedAt: string; completedAt: string })[] {
|
|
28
|
+
return jobs.filter((job): job is TimedJob & { startedAt: string; completedAt: string } =>
|
|
29
|
+
job.conclusion !== "skipped" && !!job.startedAt && !!job.completedAt && Date.parse(job.completedAt) >= Date.parse(job.startedAt));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Spread { median: number; p90: number; min: number; max: number }
|
|
33
|
+
const spread = (values: number[], places = 1): Spread =>
|
|
34
|
+
({ median: round(quantile(values, 0.5), places), p90: round(quantile(values, 0.9), places), min: round(values.length ? Math.min(...values) : 0, places), max: round(values.length ? Math.max(...values) : 0, places) });
|
|
35
|
+
|
|
36
|
+
export interface JobStats {
|
|
37
|
+
name: string;
|
|
38
|
+
lane: string;
|
|
39
|
+
runs: number;
|
|
40
|
+
minutes: Spread;
|
|
41
|
+
/** Share of runs in which the job took at least the threshold: how often it did real work rather than replay a cache. */
|
|
42
|
+
overThresholdShare: number;
|
|
43
|
+
/** Seconds from the run's creation to the job's start; a steady lag is a `needs` chain, a spiky p90 is queueing. */
|
|
44
|
+
startLagSeconds: Spread;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface TimingSummary {
|
|
48
|
+
runs: number;
|
|
49
|
+
/** Runs left out: re-run attempts mix timestamps of several attempts, and runs without the named gate job. */
|
|
50
|
+
excluded: { reruns: number; missingGate: number };
|
|
51
|
+
thresholdMinutes: number;
|
|
52
|
+
/** Run creation to the gate job's end, or to the last job's end without a gate. */
|
|
53
|
+
wallMinutes: Spread;
|
|
54
|
+
/** Run creation to its first job's start: time spent waiting for any runner. */
|
|
55
|
+
firstStartLagSeconds: Spread;
|
|
56
|
+
/** How often each lane finished last among the jobs the gate waits for, which is what holds the wall clock. */
|
|
57
|
+
lastToFinish: { lane: string; runs: number }[];
|
|
58
|
+
jobs: JobStats[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Summarize successful runs of one workflow. A gate job, when named, ends the wall clock and is left out of `lastToFinish`. */
|
|
62
|
+
export function summarizeRuns(runs: TimedRun[], options: { gate?: string; thresholdMinutes: number }): TimingSummary {
|
|
63
|
+
const excluded = { reruns: 0, missingGate: 0 };
|
|
64
|
+
const walls: number[] = [], firstLags: number[] = [];
|
|
65
|
+
const last = new Map<string, number>();
|
|
66
|
+
const perJob = new Map<string, { durations: number[]; lags: number[] }>();
|
|
67
|
+
for (const run of runs) {
|
|
68
|
+
if (run.attempt > 1) { excluded.reruns++; continue; }
|
|
69
|
+
const jobs = executedJobs(run.jobs);
|
|
70
|
+
if (!jobs.length) continue;
|
|
71
|
+
const gate = options.gate === undefined ? undefined : jobs.find(job => job.name === options.gate);
|
|
72
|
+
if (options.gate !== undefined && !gate) { excluded.missingGate++; continue; }
|
|
73
|
+
const work = jobs.filter(job => job !== gate);
|
|
74
|
+
const end = gate?.completedAt ?? work.reduce((latest, job) => job.completedAt > latest ? job.completedAt : latest, work[0]!.completedAt);
|
|
75
|
+
walls.push(minutesBetween(run.createdAt, end));
|
|
76
|
+
firstLags.push(Math.max(0, minutesBetween(run.createdAt, jobs.reduce((first, job) => job.startedAt < first ? job.startedAt : first, jobs[0]!.startedAt)) * 60));
|
|
77
|
+
const finisher = work.reduce<(typeof work)[number] | undefined>((latest, job) => !latest || job.completedAt > latest.completedAt ? job : latest, undefined);
|
|
78
|
+
if (finisher) last.set(lane(finisher.name), (last.get(lane(finisher.name)) ?? 0) + 1);
|
|
79
|
+
for (const job of work) {
|
|
80
|
+
const entry = perJob.get(job.name) ?? { durations: [], lags: [] };
|
|
81
|
+
entry.durations.push(minutesBetween(job.startedAt, job.completedAt));
|
|
82
|
+
entry.lags.push(Math.max(0, minutesBetween(run.createdAt, job.startedAt) * 60));
|
|
83
|
+
perJob.set(job.name, entry);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const jobs = [...perJob].map(([name, { durations, lags }]): JobStats => ({
|
|
87
|
+
name,
|
|
88
|
+
lane: lane(name),
|
|
89
|
+
runs: durations.length,
|
|
90
|
+
minutes: spread(durations),
|
|
91
|
+
overThresholdShare: round(durations.filter(value => value >= options.thresholdMinutes).length / durations.length, 2),
|
|
92
|
+
startLagSeconds: spread(lags, 0),
|
|
93
|
+
})).sort((a, b) => b.minutes.median - a.minutes.median || a.name.localeCompare(b.name));
|
|
94
|
+
return {
|
|
95
|
+
runs: walls.length,
|
|
96
|
+
excluded,
|
|
97
|
+
thresholdMinutes: options.thresholdMinutes,
|
|
98
|
+
wallMinutes: spread(walls),
|
|
99
|
+
firstStartLagSeconds: spread(firstLags, 0),
|
|
100
|
+
lastToFinish: [...last].map(([name, count]) => ({ lane: name, runs: count })).sort((a, b) => b.runs - a.runs || a.lane.localeCompare(b.lane)),
|
|
101
|
+
jobs,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface JobSteps { id: number; name: string; minutes: number; startOffsetMinutes: number; steps: { name: string; seconds: number }[] }
|
|
106
|
+
|
|
107
|
+
/** One run's executed jobs, longest first, each with the steps that took at least `minSeconds`. */
|
|
108
|
+
export function runSteps(createdAt: string, jobs: TimedJob[], minSeconds: number): JobSteps[] {
|
|
109
|
+
return executedJobs(jobs).map(job => ({
|
|
110
|
+
id: job.id,
|
|
111
|
+
name: job.name,
|
|
112
|
+
minutes: round(minutesBetween(job.startedAt, job.completedAt)),
|
|
113
|
+
startOffsetMinutes: round(Math.max(0, minutesBetween(createdAt, job.startedAt))),
|
|
114
|
+
steps: (job.steps ?? []).filter(step => step.startedAt && step.completedAt)
|
|
115
|
+
.map(step => ({ name: step.name, seconds: round(minutesBetween(step.startedAt!, step.completedAt!) * 60, 0) }))
|
|
116
|
+
.filter(step => step.seconds >= minSeconds),
|
|
117
|
+
})).sort((a, b) => b.minutes - a.minutes || a.name.localeCompare(b.name));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface LogTask { task: string; cache: "hit" | "miss" | "bypass" }
|
|
121
|
+
export interface LogFile { task: string | null; file: string; seconds: number; cases: number; cached: boolean }
|
|
122
|
+
export interface LogTimings { tasks: LogTask[]; files: LogFile[]; casesWithoutDuration: number }
|
|
123
|
+
|
|
124
|
+
// GitHub prefixes every log line with an ISO timestamp; Turbo and Bun color their output.
|
|
125
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z ?/;
|
|
126
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
127
|
+
const CASE = /^\((pass|fail|skip|todo)\)\s/;
|
|
128
|
+
const DURATION = /\[(\d+(?:\.\d+)?)(ms|s)\]\s*$/;
|
|
129
|
+
const CACHE = /^cache (hit|miss|bypass)\b/;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Read a GitHub Actions job log: each Turbo task's cache result (`##[group]<task>` followed by
|
|
133
|
+
* `cache hit`, `cache miss`, or `cache bypass`), and each Bun test file's summed case durations
|
|
134
|
+
* (`##[group]<file>:` followed by `(pass) name [12.34ms]` lines). Files a replayed (cached)
|
|
135
|
+
* task printed are marked `cached`: their durations come from the run that filled the cache.
|
|
136
|
+
*/
|
|
137
|
+
export function parseJobLog(text: string): LogTimings {
|
|
138
|
+
const lines = text.split(/\r?\n/).map(line => line.replace(TIMESTAMP, "").replace(ANSI, ""));
|
|
139
|
+
const tasks: LogTask[] = [];
|
|
140
|
+
const files = new Map<string, LogFile>();
|
|
141
|
+
const stack: { kind: "task" | "file" | "other"; name: string; cached: boolean }[] = [];
|
|
142
|
+
let casesWithoutDuration = 0;
|
|
143
|
+
for (let index = 0; index < lines.length; index++) {
|
|
144
|
+
const line = lines[index]!;
|
|
145
|
+
if (line.startsWith("##[group]")) {
|
|
146
|
+
const name = line.slice("##[group]".length).trim();
|
|
147
|
+
const next = lines.slice(index + 1).find(candidate => candidate.trim() !== "")?.trim() ?? "";
|
|
148
|
+
const cache = next.match(CACHE)?.[1] as LogTask["cache"] | undefined;
|
|
149
|
+
const parent = [...stack].reverse().find(entry => entry.kind === "task");
|
|
150
|
+
if (cache) { tasks.push({ task: name, cache }); stack.push({ kind: "task", name, cached: cache === "hit" }); }
|
|
151
|
+
else if (name.endsWith(":")) stack.push({ kind: "file", name: name.slice(0, -1), cached: parent?.cached ?? false });
|
|
152
|
+
else stack.push({ kind: "other", name, cached: parent?.cached ?? false });
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (line.startsWith("##[endgroup]")) { stack.pop(); continue; }
|
|
156
|
+
const trimmed = line.trim();
|
|
157
|
+
if (!CASE.test(trimmed)) continue;
|
|
158
|
+
const top = stack.at(-1);
|
|
159
|
+
if (top?.kind !== "file") continue;
|
|
160
|
+
const duration = trimmed.match(DURATION);
|
|
161
|
+
const task = [...stack].reverse().find(entry => entry.kind === "task")?.name ?? null;
|
|
162
|
+
const key = `${task ?? ""}\u0000${top.name}`;
|
|
163
|
+
const entry = files.get(key) ?? { task, file: top.name, seconds: 0, cases: 0, cached: top.cached };
|
|
164
|
+
entry.cases++;
|
|
165
|
+
if (duration) entry.seconds += Number(duration[1]) / (duration[2] === "ms" ? 1000 : 1);
|
|
166
|
+
else if (!trimmed.startsWith("(skip)") && !trimmed.startsWith("(todo)")) casesWithoutDuration++;
|
|
167
|
+
files.set(key, entry);
|
|
168
|
+
}
|
|
169
|
+
return {
|
|
170
|
+
tasks,
|
|
171
|
+
files: [...files.values()].map(file => ({ ...file, seconds: round(file.seconds) })).sort((a, b) => b.seconds - a.seconds || a.file.localeCompare(b.file)),
|
|
172
|
+
casesWithoutDuration,
|
|
173
|
+
};
|
|
174
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -8,8 +8,10 @@ import { checkGraph } from "./graph/check";
|
|
|
8
8
|
import { stateMachinesCommand } from "./stateMachines/command";
|
|
9
9
|
import { seoCommand } from "./seo/probe";
|
|
10
10
|
import { buildScreenshots, describeScreenshots } from "./screenshots/build";
|
|
11
|
+
import { screenshotsStoreCommand } from "./screenshots/store/command";
|
|
11
12
|
import { spaceCommand } from "./space/command";
|
|
12
13
|
import { perfCommand } from "./perf/command";
|
|
14
|
+
import { ciTimingsCommand } from "./ci/command";
|
|
13
15
|
import { review } from "./harnesses";
|
|
14
16
|
import { carryReviewCommand } from "./review/carry";
|
|
15
17
|
import { runAgentToolAction } from "./runAgentToolAction";
|
|
@@ -58,6 +60,8 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
|
|
|
58
60
|
repo base-health [--branch name] [--limit N] CI health of the default branch's tip (GitHub only)
|
|
59
61
|
policy check | toolchain check
|
|
60
62
|
ci gate <needs.json|-> [--policy policy.json]
|
|
63
|
+
ci timings [--workflow file] [--limit N] [--gate job] | --run <id> | --job <id>
|
|
64
|
+
Which jobs hold a workflow's wall clock; ci timings --help lists options
|
|
61
65
|
release plan <package.json> [--github-output] [--allow-private-source]
|
|
62
66
|
release verify <package> <version> <merge-oid> --workflow name [--timeout seconds]
|
|
63
67
|
logs <file> [--max-bytes N] [--tail-lines N] Bounded local log tail
|
|
@@ -91,6 +95,9 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
|
|
|
91
95
|
images list [target...] JSON files each image target writes
|
|
92
96
|
images build [target...] [--out <dir>] Render assets/brand/*.svg per agent-tool.json
|
|
93
97
|
screenshots build [target...] [--out <dir>] [--json] Stage guarded captures and a gallery manifest
|
|
98
|
+
screenshots status [repo...] [--all] [--json] Each clone's link to the shared store and its newest capture
|
|
99
|
+
screenshots link [repo...] [--all] [--apply] [--supersede] [--json] Point .screenshots at the shared store
|
|
100
|
+
screenshots capture [repo] [--apply] [--allow-dirty] [--json] [-- args...] Run the screenshots script under the store lock and record it
|
|
94
101
|
graph check Import cycles and layer violations per agent-tool.json
|
|
95
102
|
state-machines [path...] [--limit N] [--min-score N] [--json] Rank files that look like implicit state machines
|
|
96
103
|
seo probe [--page|--headers|--links|--sitemap] <host> [path...] Live search and preview metadata of a site
|
|
@@ -131,7 +138,12 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
|
|
|
131
138
|
}
|
|
132
139
|
if (command === "--version") { usage(args.length === 0, "Unexpected version arguments."); writeSync(1, `${metadata.version}\n`); return 0; }
|
|
133
140
|
if (command === "run") return runCommand(args);
|
|
134
|
-
if (command === "ci") {
|
|
141
|
+
if (command === "ci") {
|
|
142
|
+
const action = args.shift();
|
|
143
|
+
if (action === "timings") return ciTimingsCommand(args);
|
|
144
|
+
usage(action === "gate", "Usage: ci gate <needs.json|-> [--policy policy.json] | ci timings [options]");
|
|
145
|
+
return gateCommand(args);
|
|
146
|
+
}
|
|
135
147
|
if (command === "release") return releaseCommand(args);
|
|
136
148
|
if (command === "proc") return procCommand(args);
|
|
137
149
|
if (command === "teardown") return teardownCommand(args);
|
|
@@ -176,8 +188,9 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
|
|
|
176
188
|
});
|
|
177
189
|
}
|
|
178
190
|
if (command === "screenshots") {
|
|
191
|
+
if (args[0] === "status" || args[0] === "link" || args[0] === "capture") return screenshotsStoreCommand(args);
|
|
179
192
|
const action = args.shift();
|
|
180
|
-
usage(action === "build", "Usage: agent-tool screenshots build [target...] [--out <dir>] [--json]");
|
|
193
|
+
usage(action === "build", "Usage: agent-tool screenshots build [target...] [--out <dir>] [--json] | status|link|capture [repo...] [options]");
|
|
181
194
|
const names: string[] = [];
|
|
182
195
|
let out: string | undefined, json = false;
|
|
183
196
|
while (args.length) {
|
package/src/perf/graph.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** `perf graph`: the relative import closure of ES modules, for preload lists generated from built files. */
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
2
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -82,6 +82,12 @@ export function importsOf(source: string): string[] {
|
|
|
82
82
|
/** Every module reachable from the entries through relative imports, as paths within `root`, entries first. */
|
|
83
83
|
export function moduleGraph(root: string, entries: string[]): string[] {
|
|
84
84
|
const seen = new Set<string>();
|
|
85
|
+
let base: string;
|
|
86
|
+
try {
|
|
87
|
+
base = realpathSync(root);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
throw new Error(`Cannot read ${root}: ${(error as NodeJS.ErrnoException).code ?? (error as Error).message}.`);
|
|
90
|
+
}
|
|
85
91
|
const walk = (rel: string, from: string | undefined) => {
|
|
86
92
|
const where = from === undefined ? `entry ${rel}` : `${rel}, imported by ${from}`;
|
|
87
93
|
if (rel === ".." || rel.startsWith("../") || path.posix.isAbsolute(rel)) throw new Error(`The graph leaves ${root} at ${where}.`);
|
|
@@ -89,9 +95,13 @@ export function moduleGraph(root: string, entries: string[]): string[] {
|
|
|
89
95
|
seen.add(rel);
|
|
90
96
|
let source: string;
|
|
91
97
|
try {
|
|
92
|
-
|
|
98
|
+
// A symbolic link inside the directory can lead out of it, as `..` can.
|
|
99
|
+
const real = realpathSync(path.join(root, rel));
|
|
100
|
+
if (!real.startsWith(`${base}${path.sep}`)) throw new Error(`The graph leaves ${root} at ${where}, through a symbolic link.`);
|
|
101
|
+
source = readFileSync(real, "utf8");
|
|
93
102
|
} catch (error) {
|
|
94
|
-
|
|
103
|
+
if (!(error as NodeJS.ErrnoException).code) throw error;
|
|
104
|
+
throw new Error(`Cannot read ${where}: ${(error as NodeJS.ErrnoException).code}.`);
|
|
95
105
|
}
|
|
96
106
|
for (const spec of importsOf(source)) walk(path.posix.normalize(path.posix.join(path.posix.dirname(rel), spec)), rel);
|
|
97
107
|
};
|
|
@@ -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", "perf diff"]
|
|
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", "ci timings", "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 })),
|
|
@@ -43,6 +43,8 @@ export const CATALOG: CatalogEntry[] = [
|
|
|
43
43
|
// So do `perf measure` and `perf shot`, which open any URL in Chrome and evaluate the JavaScript their arguments give,
|
|
44
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
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.
|
|
46
48
|
// `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
|
|
47
49
|
// Package scripts are not classified, so `bun run` keeps the harness default.
|
|
48
50
|
|
package/src/screenshots/build.ts
CHANGED
|
@@ -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
|
|
10
|
-
export const CAPTURE_RECORD =
|
|
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}
|
|
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
|
+
}
|