@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.
- package/README.md +10 -8
- package/package.json +2 -1
- package/skills/performance-pass/SKILL.md +107 -0
- package/skills/performance-pass/agents/openai.yaml +4 -0
- package/skills/performance-pass/references/lessons.md +30 -0
- package/skills/space-cleanup/SKILL.md +96 -0
- package/skills/space-cleanup/agents/openai.yaml +4 -0
- 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/cli.ts +14 -1
- package/src/perf/browser.ts +269 -0
- package/src/perf/command.ts +82 -0
- package/src/perf/diff.ts +115 -0
- package/src/perf/graph.ts +110 -0
- package/src/perf/options.ts +107 -0
- package/src/perf/serve.ts +163 -0
- package/src/permissions/catalog.ts +6 -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 +14 -0
- package/src/space/candidates.ts +228 -0
- package/src/space/command.ts +325 -0
- package/src/space/machine.ts +303 -0
- package/src/space/processes.ts +186 -0
- package/src/space/targets.ts +24 -0
- package/src/system/checkouts.ts +135 -0
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-tool screenshots status|link|capture`: the shared screenshot store for
|
|
3
|
+
* every clone of a repository.
|
|
4
|
+
*
|
|
5
|
+
* Captured screenshots live outside the clones, in
|
|
6
|
+
* `<artifacts>/<project>/screenshots`, and each clone's gitignored
|
|
7
|
+
* `.screenshots` is a symlink to it. A capture in any clone therefore updates
|
|
8
|
+
* every clone, and a build or deploy in any clone publishes the newest capture
|
|
9
|
+
* instead of whatever that clone last took.
|
|
10
|
+
*
|
|
11
|
+
* `capture` runs the repository's own `bun run screenshots` under a per-project
|
|
12
|
+
* lock and records its provenance in `.screenshots/capture.json`, which
|
|
13
|
+
* `screenshots build` reads before it publishes. It first links every clone of
|
|
14
|
+
* the store's projects that has no `.screenshots`, itself included, so clones
|
|
15
|
+
* never drift apart. `link` and `capture` are dry runs until `--apply`.
|
|
16
|
+
*/
|
|
17
|
+
import { writeSync } from "node:fs";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { type CapturePlan, capture, planCapture, RUNNER, type Runner, type Timing } from "./capture";
|
|
21
|
+
import { clonesSharing, linkAutomatically, sharedStore } from "./clones";
|
|
22
|
+
import { type LinkResult, type LinkState, link, linkState } from "./link";
|
|
23
|
+
import { heldLockError, type LockInfo, readLock } from "./lock";
|
|
24
|
+
import { claimNamespace, existingCase, knownNamespace } from "./namespace";
|
|
25
|
+
import { RECORD, readRecord, relation, type StoredRecord } from "./record";
|
|
26
|
+
import { LOCK, lexists, storeDir, type Target } from "./store";
|
|
27
|
+
import { artifactsRoot, resolveTargets } from "./targets";
|
|
28
|
+
|
|
29
|
+
export const STORE_USAGE = `Usage: agent-tool screenshots <status|link|capture> [repo...] [options]
|
|
30
|
+
|
|
31
|
+
status [repo...] [--all] Link state and newest capture of each repository
|
|
32
|
+
link [repo...] [--all] [--apply] [--supersede]
|
|
33
|
+
Point each repository's .screenshots at the shared store,
|
|
34
|
+
moving an existing capture there when the store is empty;
|
|
35
|
+
--supersede moves it to <project>/superseded/ instead
|
|
36
|
+
capture [repo] [--apply] [--allow-dirty] [-- capture args...]
|
|
37
|
+
Run the repository's \`bun run screenshots\` under a lock
|
|
38
|
+
and record the capture's commit in .screenshots/capture.json,
|
|
39
|
+
first linking every clone of the store's projects that has
|
|
40
|
+
no .screenshots
|
|
41
|
+
|
|
42
|
+
Repos are checkout names or paths; none selects the current repository, or in a
|
|
43
|
+
matrix workspace every checkout that captures screenshots. --all selects every
|
|
44
|
+
clone on this machine that captures into a project the store holds: clones
|
|
45
|
+
beside the store and the checkouts of matrix workspaces beside it.
|
|
46
|
+
--project <name> names one repository's namespace in the store, which a
|
|
47
|
+
repository without a GitHub origin needs. MATRIX_ARTIFACTS_DIR overrides the
|
|
48
|
+
store, which defaults to matrix-artifacts beside the workspace (or beside the
|
|
49
|
+
repository outside one). --json prints the report as JSON.
|
|
50
|
+
`;
|
|
51
|
+
|
|
52
|
+
interface StatusEntry {
|
|
53
|
+
readonly name: string;
|
|
54
|
+
/** Set when the namespace belongs to another repository than this clone's origin. */
|
|
55
|
+
readonly foreign?: string;
|
|
56
|
+
readonly project: string;
|
|
57
|
+
readonly store: string;
|
|
58
|
+
readonly link: LinkState;
|
|
59
|
+
readonly capture?: StoredRecord;
|
|
60
|
+
readonly sinceCapture?: ReturnType<typeof relation>;
|
|
61
|
+
readonly lock?: LockInfo;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function status(target: Target, artifacts: string): StatusEntry {
|
|
65
|
+
const store = storeDir(target, artifacts);
|
|
66
|
+
const capture = readRecord(store);
|
|
67
|
+
const lock = readLock(path.join(artifacts, target.project, LOCK));
|
|
68
|
+
const foreign = claimNamespace(target, artifacts, false);
|
|
69
|
+
return {
|
|
70
|
+
name: target.name,
|
|
71
|
+
...(foreign ? { foreign } : {}),
|
|
72
|
+
project: target.project,
|
|
73
|
+
store,
|
|
74
|
+
link: linkState(target, artifacts),
|
|
75
|
+
...(capture ? { capture, sinceCapture: relation(target.root, capture.commit) } : {}),
|
|
76
|
+
...(lock ? { lock } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface Options {
|
|
81
|
+
readonly command: "status" | "link" | "capture";
|
|
82
|
+
readonly names: string[];
|
|
83
|
+
/** Every clone of the store's projects on this machine, instead of named or current repositories. */
|
|
84
|
+
readonly all: boolean;
|
|
85
|
+
readonly apply: boolean;
|
|
86
|
+
readonly json: boolean;
|
|
87
|
+
readonly allowDirty: boolean;
|
|
88
|
+
readonly supersede: boolean;
|
|
89
|
+
readonly project?: string;
|
|
90
|
+
readonly captureArgs: string[];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
type Switches = Record<"all" | "apply" | "json" | "allowDirty" | "supersede", boolean>;
|
|
94
|
+
|
|
95
|
+
/** The boolean options, by the field each sets. */
|
|
96
|
+
const SWITCHES = new Map<string, keyof Switches>([
|
|
97
|
+
["--all", "all"],
|
|
98
|
+
["--apply", "apply"],
|
|
99
|
+
["--json", "json"],
|
|
100
|
+
["--allow-dirty", "allowDirty"],
|
|
101
|
+
["--supersede", "supersede"],
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
export function parseOptions(argv: string[]): Options {
|
|
105
|
+
const [command, ...rest] = argv;
|
|
106
|
+
if (command !== "status" && command !== "link" && command !== "capture") throw new Error(`unknown command '${command ?? ""}'\n\n${STORE_USAGE}`);
|
|
107
|
+
const split = rest.indexOf("--");
|
|
108
|
+
const own = split === -1 ? rest : rest.slice(0, split);
|
|
109
|
+
const captureArgs = split === -1 ? [] : rest.slice(split + 1);
|
|
110
|
+
if (captureArgs.length > 0 && command !== "capture") throw new Error("only capture forwards arguments after --");
|
|
111
|
+
const { names, switches, project } = parseOwn(own);
|
|
112
|
+
checkApplies(command, switches);
|
|
113
|
+
checkSelection(switches, names, project);
|
|
114
|
+
const { all, apply, json, allowDirty, supersede } = switches;
|
|
115
|
+
return { command, names, all, apply, json, allowDirty, supersede, captureArgs, ...(project ? { project } : {}) };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** --all selects every clone, so it takes no repository names or namespace. */
|
|
119
|
+
function checkSelection({ all }: Switches, names: string[], project: string | undefined): void {
|
|
120
|
+
if (all && (names.length > 0 || project)) throw new Error("--all selects every clone; name no repository or --project with it");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The repositories, switches and project named before `--`. */
|
|
124
|
+
function parseOwn(own: string[]): { names: string[]; switches: Switches; project: string | undefined } {
|
|
125
|
+
const names: string[] = [];
|
|
126
|
+
const switches: Switches = { all: false, apply: false, json: false, allowDirty: false, supersede: false };
|
|
127
|
+
let project: string | undefined;
|
|
128
|
+
for (let index = 0; index < own.length; index++) {
|
|
129
|
+
const arg = own[index]!;
|
|
130
|
+
const field = SWITCHES.get(arg);
|
|
131
|
+
if (field) switches[field] = true;
|
|
132
|
+
else if (arg === "--project") {
|
|
133
|
+
project = own[++index];
|
|
134
|
+
// A flag in its place is a missing name, not a namespace called `--apply`.
|
|
135
|
+
if (project === undefined || project.startsWith("-")) throw new Error("--project needs a name");
|
|
136
|
+
}
|
|
137
|
+
else if (arg.startsWith("-")) throw new Error(`unknown option ${arg}\n\n${STORE_USAGE}`);
|
|
138
|
+
else names.push(arg);
|
|
139
|
+
}
|
|
140
|
+
return { names, switches, project };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Rejects options the command does not use. */
|
|
144
|
+
function checkApplies(command: Options["command"], { all, apply, allowDirty, supersede }: Switches): void {
|
|
145
|
+
if (apply && command === "status") throw new Error("status changes nothing; --apply does not apply");
|
|
146
|
+
if (allowDirty && command !== "capture") throw new Error("--allow-dirty applies only to capture");
|
|
147
|
+
if (supersede && command !== "link") throw new Error("--supersede applies only to link");
|
|
148
|
+
if (all && command === "capture") throw new Error("capture runs one repository; it links the other clones itself");
|
|
149
|
+
// Superseding moves a clone's own capture aside, which a person decides clone by clone.
|
|
150
|
+
if (all && supersede) throw new Error("--supersede needs the clone named; compare its capture first");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function describeCapture(entry: StatusEntry): string {
|
|
154
|
+
const record = entry.capture;
|
|
155
|
+
if (!record) return "no capture recorded";
|
|
156
|
+
const since = entry.sinceCapture!;
|
|
157
|
+
const where = {
|
|
158
|
+
current: "at HEAD",
|
|
159
|
+
behind: `${since.commits} commit(s) behind HEAD`,
|
|
160
|
+
ahead: `${since.commits} commit(s) ahead of HEAD`,
|
|
161
|
+
diverged: "on a branch HEAD does not contain",
|
|
162
|
+
unknown: "commit not in this clone; fetch",
|
|
163
|
+
}[since.relation];
|
|
164
|
+
const flags = [
|
|
165
|
+
record.dirty ? "dirty" : "",
|
|
166
|
+
record.merged === false ? "unmerged" : "",
|
|
167
|
+
record.args.length > 0 ? `partial: ${record.args.join(" ")}` : "",
|
|
168
|
+
].filter(Boolean);
|
|
169
|
+
return `${record.status} ${record.finishedAt ?? record.startedAt} at ${record.commit.slice(0, 10)}${record.branch ? ` (${record.branch})` : ""}, ${where}${flags.length ? `; ${flags.join(", ")}` : ""}`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const PRINT = (text: string) => {
|
|
173
|
+
writeSync(1, `${text}\n`);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* One store command. Returns its exit status: status 1 while a selected clone
|
|
178
|
+
* is not linked or not this repository's, link 1 when a clone is blocked, and
|
|
179
|
+
* capture 1 when an applied capture did not finish complete. Throws when the
|
|
180
|
+
* command cannot run.
|
|
181
|
+
*/
|
|
182
|
+
export async function screenshotsStore(
|
|
183
|
+
argv: string[],
|
|
184
|
+
cwd = process.cwd(),
|
|
185
|
+
runner: Runner = RUNNER,
|
|
186
|
+
print: (text: string) => void = PRINT,
|
|
187
|
+
timing: Timing = {},
|
|
188
|
+
): Promise<number> {
|
|
189
|
+
const own = argv.includes("--") ? argv.slice(0, argv.indexOf("--")) : argv;
|
|
190
|
+
if (own.includes("--help") || own.includes("-h") || argv.length === 0) {
|
|
191
|
+
print(STORE_USAGE);
|
|
192
|
+
return argv.length === 0 ? 2 : 0;
|
|
193
|
+
}
|
|
194
|
+
const options = parseOptions(argv);
|
|
195
|
+
return options.all ? allCommand(cwd, options, print) : selectedCommand(cwd, options, runner, print, timing);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A command over the named repositories, or the current one (every capturing checkout in a workspace). */
|
|
199
|
+
async function selectedCommand(cwd: string, options: Options, runner: Runner, print: (text: string) => void, timing: Timing): Promise<number> {
|
|
200
|
+
const { targets: found } = resolveTargets(cwd, options.names, options.project);
|
|
201
|
+
if (found.length === 0) {
|
|
202
|
+
print(options.json ? "[]" : "No repository here captures screenshots.");
|
|
203
|
+
return 0;
|
|
204
|
+
}
|
|
205
|
+
const { artifacts, targets } = inSharedStore(found);
|
|
206
|
+
if (options.command === "status") return statusCommand(targets, artifacts, options, print);
|
|
207
|
+
if (options.command === "link") return linkCommand(targets, artifacts, options, print);
|
|
208
|
+
if (targets.length !== 1) throw new Error("capture runs one repository at a time; name it");
|
|
209
|
+
return captureCommand(targets[0]!, artifacts, options, runner, print, timing);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** status or link over every clone that shares the store this repository resolves. */
|
|
213
|
+
function allCommand(cwd: string, options: Options, print: (text: string) => void): number {
|
|
214
|
+
const artifacts = sharedStore(cwd);
|
|
215
|
+
const targets = clonesSharing(artifacts);
|
|
216
|
+
if (targets.length === 0) {
|
|
217
|
+
print(options.json ? "[]" : `No clone on this machine captures into ${artifacts}.`);
|
|
218
|
+
return 0;
|
|
219
|
+
}
|
|
220
|
+
return options.command === "status" ? statusCommand(targets, artifacts, options, print) : linkCommand(targets, artifacts, options, print);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The store every selected repository resolves, and each one's namespace in it. */
|
|
224
|
+
function inSharedStore(found: Target[]): { artifacts: string; targets: Target[] } {
|
|
225
|
+
const artifacts = artifactsRoot(found[0]!.root);
|
|
226
|
+
if (found.some(target => artifactsRoot(target.root) !== artifacts))
|
|
227
|
+
throw new Error("the selected repositories resolve different stores; set MATRIX_ARTIFACTS_DIR");
|
|
228
|
+
return { artifacts, targets: found.map(target => existingCase(knownNamespace(target, artifacts), artifacts)) };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function statusCommand(targets: Target[], artifacts: string, options: Options, print: (text: string) => void): number {
|
|
232
|
+
const entries = targets.map(target => status(target, artifacts));
|
|
233
|
+
if (options.json) print(JSON.stringify({ artifacts, entries }, null, 2));
|
|
234
|
+
else for (const entry of entries) print(statusLine(entry));
|
|
235
|
+
return entries.every(entry => entry.link.state === "linked" && !entry.foreign) ? 0 : 1;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function statusLine(entry: StatusEntry): string {
|
|
239
|
+
const lock = entry.lock ? `; capture running in ${entry.lock.checkout} (pid ${entry.lock.pid})` : "";
|
|
240
|
+
return `${entry.name} [${entry.project}] ${entry.link.state}: ${entry.foreign ? `NOT THIS REPOSITORY'S: ${entry.foreign}` : describeCapture(entry)}${lock}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function linkCommand(targets: Target[], artifacts: string, options: Options, print: (text: string) => void): number {
|
|
244
|
+
// One clone that fails to link never stops the others, and is reported blocked with the reason.
|
|
245
|
+
const results = targets.map(target => {
|
|
246
|
+
try {
|
|
247
|
+
return link(target, artifacts, options.apply, options.supersede);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return { name: target.name, project: target.project, store: storeDir(target, artifacts), before: linkState(target, artifacts).state, blocked: (error as Error).message };
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
if (options.json) print(JSON.stringify({ artifacts, apply: options.apply, results }, null, 2));
|
|
253
|
+
else for (const result of results) print(`${result.name} [${result.project}] ${linkOutcome(result)}`);
|
|
254
|
+
if (!options.json && !options.apply && results.some(result => result.action && !result.blocked)) print("Dry run; rerun with --apply.");
|
|
255
|
+
return results.some(result => result.blocked) ? 1 : 0;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function linkOutcome(result: LinkResult): string {
|
|
259
|
+
if (result.blocked) return `blocked: ${result.blocked}`;
|
|
260
|
+
if (!result.action) return "already linked";
|
|
261
|
+
return `${result.applied ? "done" : "would"} ${result.action} -> ${result.store}${result.superseded ? `; its own capture to ${result.superseded}` : ""}`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Links the capturing clone first, so a clone with no .screenshots can capture,
|
|
266
|
+
* then every other clone of the store's projects, so all of them see it.
|
|
267
|
+
*/
|
|
268
|
+
function linkBeforeCapture(target: Target, artifacts: string, options: Options, print: (text: string) => void): LinkResult[] {
|
|
269
|
+
const others = clonesSharing(artifacts).filter(clone => clone.root !== target.root);
|
|
270
|
+
const links = linkAutomatically([target, ...others], artifacts, options.apply);
|
|
271
|
+
if (!options.json) for (const result of links) print(`${result.name} [${result.project}] ${linkOutcome(result)}`);
|
|
272
|
+
return links;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function captureCommand(
|
|
276
|
+
target: Target,
|
|
277
|
+
artifacts: string,
|
|
278
|
+
options: Options,
|
|
279
|
+
runner: Runner,
|
|
280
|
+
print: (text: string) => void,
|
|
281
|
+
timing: Timing,
|
|
282
|
+
): Promise<number> {
|
|
283
|
+
const captureOptions = { allowDirty: options.allowDirty, args: options.captureArgs };
|
|
284
|
+
// Every refusal comes before any link is made, so a capture that will not run changes nothing.
|
|
285
|
+
const willLink = linkAutomatically([target], artifacts, false).some(result => !result.blocked);
|
|
286
|
+
const planned = planCapture(target, artifacts, captureOptions, willLink);
|
|
287
|
+
// A held lock refuses the capture too; acquiring it again under the lock below still settles a race.
|
|
288
|
+
const lockFile = path.join(artifacts, target.project, LOCK);
|
|
289
|
+
if (options.apply && lexists(lockFile)) throw heldLockError(lockFile, { pid: process.pid, host: os.hostname(), checkout: target.root, startedAt: "" });
|
|
290
|
+
const links = linkBeforeCapture(target, artifacts, options, print);
|
|
291
|
+
const plan = options.apply ? await capture(target, artifacts, { ...captureOptions, apply: true }, runner, timing) : planned;
|
|
292
|
+
if (options.json) print(JSON.stringify(links.length > 0 ? { ...plan, links } : plan, null, 2));
|
|
293
|
+
else printCapture(target, plan, print);
|
|
294
|
+
return plan.applied && plan.record.status !== "complete" ? 1 : 0;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function printCapture(target: Target, plan: CapturePlan, print: (text: string) => void): void {
|
|
298
|
+
if (plan.applied) {
|
|
299
|
+
print(`Capture ${plan.record.status} (exit ${plan.record.exitCode}); recorded in ${path.join(plan.store, RECORD)}.`);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
print(
|
|
303
|
+
`Would run \`${plan.command}\` in ${target.root} at ${plan.commit.slice(0, 10)}${plan.merged === false ? " (not on origin's default branch)" : ""}, writing ${plan.store}.`,
|
|
304
|
+
);
|
|
305
|
+
if (plan.previous) print(`Replaces the ${plan.previous.status} capture of ${plan.previous.commit.slice(0, 10)} from ${plan.previous.checkout}.`);
|
|
306
|
+
print("Dry run; rerun with --apply.");
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The CLI entry: a command's exit status, or 2 with the message on stderr when it cannot run. */
|
|
310
|
+
export async function screenshotsStoreCommand(argv: string[]): Promise<number> {
|
|
311
|
+
try {
|
|
312
|
+
return await screenshotsStore(argv);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
writeSync(2, `${(error as Error).message}\n`);
|
|
315
|
+
return 2;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Git for the shared screenshot store, bound to the repository it is asked about. */
|
|
2
|
+
import { isolatedGit } from "../../system/checkouts";
|
|
3
|
+
|
|
4
|
+
/** Git without hooks, prompts, or variables that bind it to another repository; stdout is trimmed. */
|
|
5
|
+
export function git(cwd: string, ...args: string[]): { status: number | null; stdout: string } {
|
|
6
|
+
const result = isolatedGit(cwd, args);
|
|
7
|
+
if (result.error) throw new Error(`Could not run git: ${result.error.message}`);
|
|
8
|
+
return { status: result.status, stdout: result.stdout.trim() };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function gitValue(cwd: string, ...args: string[]): string | undefined {
|
|
12
|
+
const result = git(cwd, ...args);
|
|
13
|
+
return result.status === 0 && result.stdout ? result.stdout : undefined;
|
|
14
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Each clone's `.screenshots` link into the shared store. */
|
|
2
|
+
import { lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmdirSync, type Stats, symlinkSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { claimNamespace } from "./namespace";
|
|
5
|
+
import { LINK, lexists, storeDir, type Target } from "./store";
|
|
6
|
+
|
|
7
|
+
export type LinkState =
|
|
8
|
+
| { readonly state: "linked" }
|
|
9
|
+
| { readonly state: "missing" }
|
|
10
|
+
| { readonly state: "directory"; readonly entries: number }
|
|
11
|
+
| { readonly state: "elsewhere"; readonly target: string }
|
|
12
|
+
| { readonly state: "other" };
|
|
13
|
+
|
|
14
|
+
function sameFile(left: string, right: string): boolean {
|
|
15
|
+
try {
|
|
16
|
+
return realpathSync(left) === realpathSync(right);
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function linkState(target: Target, artifacts: string): LinkState {
|
|
23
|
+
const link = path.join(target.root, LINK);
|
|
24
|
+
let stats: Stats;
|
|
25
|
+
try {
|
|
26
|
+
stats = lstatSync(link);
|
|
27
|
+
} catch {
|
|
28
|
+
return { state: "missing" };
|
|
29
|
+
}
|
|
30
|
+
if (stats.isSymbolicLink()) {
|
|
31
|
+
const destination = path.resolve(target.root, readlinkSync(link));
|
|
32
|
+
// A link to the store's path counts even before the first capture creates the directory.
|
|
33
|
+
return destination === storeDir(target, artifacts) || sameFile(destination, storeDir(target, artifacts))
|
|
34
|
+
? { state: "linked" }
|
|
35
|
+
: { state: "elsewhere", target: destination };
|
|
36
|
+
}
|
|
37
|
+
if (stats.isDirectory()) return { state: "directory", entries: readdirSync(link).length };
|
|
38
|
+
return { state: "other" };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Whether the root .gitignore ignores `.screenshots` whatever its type. A
|
|
43
|
+
* trailing slash (`.screenshots/`) matches only a directory, so the link would
|
|
44
|
+
* show up as untracked and hold back `matrix sync`.
|
|
45
|
+
*/
|
|
46
|
+
function ignorePatternMatchesFile(root: string): boolean {
|
|
47
|
+
let text = "";
|
|
48
|
+
try {
|
|
49
|
+
text = readFileSync(path.join(root, ".gitignore"), "utf8");
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
return text
|
|
54
|
+
.split("\n")
|
|
55
|
+
.map(line => line.trim())
|
|
56
|
+
.some(line => [LINK, `/${LINK}`, `**/${LINK}`].includes(line));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function emptyOrMissing(directory: string): boolean {
|
|
60
|
+
try {
|
|
61
|
+
return readdirSync(directory).length === 0;
|
|
62
|
+
} catch {
|
|
63
|
+
return !lexists(directory);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface LinkResult {
|
|
68
|
+
readonly name: string;
|
|
69
|
+
readonly project: string;
|
|
70
|
+
readonly store: string;
|
|
71
|
+
readonly before: LinkState["state"];
|
|
72
|
+
/** What --apply does or did; absent when nothing needs doing. */
|
|
73
|
+
readonly action?: "link" | "move-and-link" | "replace-empty-directory" | "supersede-and-link";
|
|
74
|
+
/** With --supersede, where the clone's own capture was moved. */
|
|
75
|
+
readonly superseded?: string;
|
|
76
|
+
readonly applied?: boolean;
|
|
77
|
+
/** Why it cannot be linked automatically. */
|
|
78
|
+
readonly blocked?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type Action = NonNullable<LinkResult["action"]>;
|
|
82
|
+
|
|
83
|
+
/** Plan, and with apply perform, the link for one repository. */
|
|
84
|
+
export function link(target: Target, artifacts: string, apply: boolean, supersede = false, now = new Date()): LinkResult {
|
|
85
|
+
const store = storeDir(target, artifacts);
|
|
86
|
+
const base = { name: target.name, project: target.project, store };
|
|
87
|
+
const state = linkState(target, artifacts);
|
|
88
|
+
const blocked = (reason: string): LinkResult => ({ ...base, before: state.state, blocked: reason });
|
|
89
|
+
// A linked clone whose origin now names another repository must not keep reading this namespace.
|
|
90
|
+
if (state.state === "linked") {
|
|
91
|
+
// With --apply this also records a GitHub-confirmed rename in the owner file.
|
|
92
|
+
const foreign = claimNamespace(target, artifacts, apply);
|
|
93
|
+
return foreign ? blocked(`${foreign}; remove ${LINK} from this clone`) : { ...base, before: "linked" };
|
|
94
|
+
}
|
|
95
|
+
const refusal = linkRefusal(target, artifacts, state);
|
|
96
|
+
if (refusal) return blocked(refusal);
|
|
97
|
+
const action = linkAction(state, store, supersede);
|
|
98
|
+
if (!action)
|
|
99
|
+
return blocked(`${LINK} holds a capture and the store already holds another; compare them, then rerun with --supersede to move this clone's aside`);
|
|
100
|
+
const superseded = supersededPath(target, artifacts, action, now);
|
|
101
|
+
if (!apply) return { ...base, before: state.state, action, ...(superseded ? { superseded } : {}) };
|
|
102
|
+
const failure = applyLink(target, artifacts, store, state, action, superseded);
|
|
103
|
+
if (failure) return blocked(failure);
|
|
104
|
+
return { ...base, before: state.state, action, applied: true, ...(superseded ? { superseded } : {}) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Where supersede-and-link moves the clone's own capture; undefined for other
|
|
109
|
+
* actions. Kept, never deleted: a person removes superseded captures once
|
|
110
|
+
* nothing needs them.
|
|
111
|
+
*/
|
|
112
|
+
function supersededPath(target: Target, artifacts: string, action: Action, now: Date): string | undefined {
|
|
113
|
+
if (action !== "supersede-and-link") return undefined;
|
|
114
|
+
return path.join(artifacts, target.project, "superseded", `${target.name}-${now.toISOString().replace(/[:.]/g, "-")}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Why an unlinked clone cannot be linked automatically, checked in this order. */
|
|
118
|
+
function linkRefusal(target: Target, artifacts: string, state: LinkState): string | undefined {
|
|
119
|
+
if (isInside(artifacts, target.root)) return `the store ${artifacts} is inside the repository`;
|
|
120
|
+
if (!ignorePatternMatchesFile(target.root)) return `the root .gitignore must list ${LINK} without a trailing slash, so the link is ignored`;
|
|
121
|
+
const foreign = claimNamespace(target, artifacts, false);
|
|
122
|
+
if (foreign) return foreign;
|
|
123
|
+
if (state.state === "elsewhere") return `${LINK} already links to ${state.target}; remove it by hand if that is stale`;
|
|
124
|
+
if (state.state === "other") return `${LINK} is neither a directory nor a link`;
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** What linking does with the clone's current `.screenshots`; undefined when both it and the store hold captures. */
|
|
129
|
+
function linkAction(state: LinkState, store: string, supersede: boolean): Action | undefined {
|
|
130
|
+
if (state.state !== "directory") return "link";
|
|
131
|
+
if (state.entries === 0) return "replace-empty-directory";
|
|
132
|
+
if (emptyOrMissing(store)) return "move-and-link";
|
|
133
|
+
if (supersede) return "supersede-and-link";
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Performs a planned link; returns why it stopped, or undefined once linked.
|
|
139
|
+
* `makeLink` creates the symbolic link; tests substitute one that fails.
|
|
140
|
+
*/
|
|
141
|
+
export function applyLink(
|
|
142
|
+
target: Target,
|
|
143
|
+
artifacts: string,
|
|
144
|
+
store: string,
|
|
145
|
+
state: LinkState,
|
|
146
|
+
action: Action,
|
|
147
|
+
superseded: string | undefined,
|
|
148
|
+
makeLink: (target: string, file: string) => void = symlinkSync,
|
|
149
|
+
): string | undefined {
|
|
150
|
+
// Recheck at apply time: another process may have linked or written since the plan.
|
|
151
|
+
const current = linkState(target, artifacts);
|
|
152
|
+
if (current.state !== state.state || (current.state === "directory" && state.state === "directory" && current.entries !== state.entries)) {
|
|
153
|
+
return `${LINK} changed while planning; run link again`;
|
|
154
|
+
}
|
|
155
|
+
const claimed = claimNamespace(target, artifacts, true);
|
|
156
|
+
if (claimed) return claimed;
|
|
157
|
+
mkdirSync(path.dirname(store), { recursive: true });
|
|
158
|
+
const linkPath = path.join(target.root, LINK);
|
|
159
|
+
const relative = path.relative(realpathSync(target.root), path.join(realpathSync(path.dirname(store)), path.basename(store)));
|
|
160
|
+
const vacated = vacateLink(action, linkPath, store, superseded);
|
|
161
|
+
if (vacated) return vacated;
|
|
162
|
+
try {
|
|
163
|
+
makeLink(relative, linkPath);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (action === "move-and-link") renameSync(store, linkPath);
|
|
166
|
+
if (action === "supersede-and-link") renameSync(superseded!, linkPath);
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Moves the clone's `.screenshots` out of the way of the link, as the action says; returns why it could not. */
|
|
173
|
+
function vacateLink(action: Action, linkPath: string, store: string, superseded: string | undefined): string | undefined {
|
|
174
|
+
switch (action) {
|
|
175
|
+
case "move-and-link":
|
|
176
|
+
if (lexists(store)) rmdirSync(store); // empty, checked above; rename cannot replace it across all platforms
|
|
177
|
+
try {
|
|
178
|
+
renameSync(linkPath, store);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
return `could not move ${LINK} into the store (${(error as NodeJS.ErrnoException).code ?? String(error)}); move it by hand`;
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
case "supersede-and-link":
|
|
184
|
+
mkdirSync(path.dirname(superseded!), { recursive: true });
|
|
185
|
+
if (lexists(superseded!)) return `${superseded} already exists; run link again`;
|
|
186
|
+
renameSync(linkPath, superseded!);
|
|
187
|
+
break;
|
|
188
|
+
case "replace-empty-directory":
|
|
189
|
+
rmdirSync(linkPath); // fails, safely, if something was written meanwhile
|
|
190
|
+
mkdirSync(store, { recursive: true });
|
|
191
|
+
break;
|
|
192
|
+
default:
|
|
193
|
+
mkdirSync(store, { recursive: true });
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function isInside(child: string, parent: string): boolean {
|
|
199
|
+
const relative = path.relative(parent, child);
|
|
200
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
201
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** The per-project capture lock. */
|
|
2
|
+
import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { writeAtomic } from "./store";
|
|
5
|
+
|
|
6
|
+
export interface LockInfo {
|
|
7
|
+
readonly pid: number;
|
|
8
|
+
/** The holder's process group, which its capture's children share. */
|
|
9
|
+
readonly pgid?: number;
|
|
10
|
+
readonly host: string;
|
|
11
|
+
readonly checkout: string;
|
|
12
|
+
readonly startedAt: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The lock's holder, or undefined when the file is missing, unreadable, or lacks a field a decision reads. */
|
|
16
|
+
export function readLock(file: string): LockInfo | undefined {
|
|
17
|
+
let value: unknown;
|
|
18
|
+
try {
|
|
19
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
20
|
+
} catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
const lock = value as Record<string, unknown> | null;
|
|
24
|
+
const valid =
|
|
25
|
+
typeof lock === "object" &&
|
|
26
|
+
lock !== null &&
|
|
27
|
+
Number.isInteger(lock.pid) &&
|
|
28
|
+
(lock.pgid === undefined || Number.isInteger(lock.pgid)) &&
|
|
29
|
+
typeof lock.host === "string" &&
|
|
30
|
+
typeof lock.checkout === "string" &&
|
|
31
|
+
typeof lock.startedAt === "string";
|
|
32
|
+
return valid ? (lock as unknown as LockInfo) : undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether a process, or with a negative id every process of a group, still runs. */
|
|
36
|
+
export function alive(id: number): boolean {
|
|
37
|
+
try {
|
|
38
|
+
process.kill(id, 0);
|
|
39
|
+
return true;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Take the project's capture lock. The lock is written to a private file and
|
|
47
|
+
* then hard-linked into place, so it never exists without its holder. A lock
|
|
48
|
+
* whose holder died is never removed automatically: two recovering processes
|
|
49
|
+
* could each remove the other's fresh lock, so a person removes it.
|
|
50
|
+
*/
|
|
51
|
+
export function acquireLock(file: string, info: LockInfo): () => void {
|
|
52
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
53
|
+
const temporary = `${file}.${info.pid}.${process.hrtime.bigint()}.tmp`;
|
|
54
|
+
writeFileSync(temporary, `${JSON.stringify(info)}\n`, { flag: "wx", mode: 0o644 });
|
|
55
|
+
try {
|
|
56
|
+
linkSync(temporary, file);
|
|
57
|
+
return () => {
|
|
58
|
+
if (readLock(file)?.pid === info.pid) unlinkSync(file);
|
|
59
|
+
};
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
62
|
+
throw heldLockError(file, info);
|
|
63
|
+
} finally {
|
|
64
|
+
unlinkSync(temporary);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Why an existing lock refuses this capture. Only explains: every case leaves
|
|
70
|
+
* the lock in place for a person, whether its holder runs or died.
|
|
71
|
+
*/
|
|
72
|
+
export function heldLockError(file: string, info: LockInfo): Error {
|
|
73
|
+
const held = readLock(file);
|
|
74
|
+
if (!held) return new Error(`the capture lock ${file} is unreadable; remove it once no capture is running`);
|
|
75
|
+
if (held.host === info.host && !alive(held.pid)) {
|
|
76
|
+
// A killed holder's capture children keep its process group and may still be writing.
|
|
77
|
+
// The group can also hold the shell or agent that started it, so name it for a person to inspect; never suggest killing it.
|
|
78
|
+
if (held.pgid !== undefined && alive(-held.pgid)) {
|
|
79
|
+
return new Error(
|
|
80
|
+
`the capture lock ${file} belongs to pid ${held.pid}, which died, but its process group ${held.pgid} still has processes that may be writing screenshots; inspect them with \`ps -o pid,command -g ${held.pgid}\`, stop any leftover capture processes, then remove the lock`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return new Error(
|
|
84
|
+
`the capture lock ${file} belongs to pid ${held.pid}, which is no longer running (started ${held.startedAt} in ${held.checkout}); remove it, then capture again`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
return new Error(`another capture of this project is running: pid ${held.pid} on ${held.host} in ${held.checkout} since ${held.startedAt}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Rewrites a lock this process holds, atomically. */
|
|
91
|
+
export function replaceLock(file: string, info: LockInfo): void {
|
|
92
|
+
if (readLock(file)?.pid !== info.pid) throw new Error(`the capture lock ${file} is no longer this process's`);
|
|
93
|
+
writeAtomic(file, `${JSON.stringify(info)}\n`, 0o644);
|
|
94
|
+
}
|