@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,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
|
+
}
|
|
@@ -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
|
+
}
|