@a2f0/agent-tool 0.1.66 → 0.1.68
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 +2 -1
- package/package.json +1 -1
- package/src/cli.ts +21 -1
- package/src/config.ts +8 -1
- package/src/git/currentBranchPr.ts +14 -10
- package/src/git/prContext.ts +13 -4
- package/src/permissions/catalog.ts +4 -2
- package/src/pr/baseFreshness.ts +2 -2
- package/src/pr/mergeChecks.ts +2 -2
- package/src/pr/squashMerge.ts +30 -2
- package/src/skills/link.ts +320 -0
- package/src/system/boundedCalls.ts +5 -0
- package/src/system/githubRetry.ts +116 -0
- package/src/workflows/baseHealth.ts +4 -3
- package/src/workflows/core.ts +18 -5
- package/src/workflows/pr.ts +6 -4
- package/src/workflows/repository.ts +15 -6
package/README.md
CHANGED
|
@@ -82,7 +82,8 @@ validation suite, and release procedures.
|
|
|
82
82
|
aggregate gates, release verification, durable validation receipts, and
|
|
83
83
|
toolchain/protection diagnostics.
|
|
84
84
|
- [CLI reference](docs/reference.md): existing review, version, skill installation,
|
|
85
|
-
command capture, import-graph checks, configuration, and
|
|
85
|
+
user-wide skill links, command capture, import-graph checks, configuration, and
|
|
86
|
+
distribution contracts.
|
|
86
87
|
- [Development](docs/development.md): setup, source layout, validation, and release
|
|
87
88
|
procedures for this package.
|
|
88
89
|
- [Images](docs/images.md): declarative brand sources and generated outputs.
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { carryReviewCommand } from "./review/carry";
|
|
|
12
12
|
import { runAgentToolAction } from "./runAgentToolAction";
|
|
13
13
|
import { BUNDLED_SKILLS } from "./skills/bundled";
|
|
14
14
|
import { checkSkills, installSkills } from "./skills/install";
|
|
15
|
+
import { checkSkillLinks, linkSkills } from "./skills/link";
|
|
15
16
|
import { bunCommand } from "./bun/dependencies";
|
|
16
17
|
import { checkPermissions, installPermissions, showPermissions } from "./permissions/install";
|
|
17
18
|
import { bumpVersions, checkVersions, planVersions } from "./version/bumpVersions";
|
|
@@ -74,6 +75,8 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
|
|
|
74
75
|
skills list
|
|
75
76
|
skills install [--harness <all|claude|codex|opencode|hermes>] [--apply]
|
|
76
77
|
skills check [--harness <all|claude|codex|opencode|hermes>]
|
|
78
|
+
skills link [--apply] Link agent-tool.json skills.user into each user skill directory
|
|
79
|
+
skills check-links Read-only: exit 1 while a declared user skill link is missing, broken, or conflicts
|
|
77
80
|
bun install [--cwd <dir>] Frozen-lockfile install with the pinned Bun
|
|
78
81
|
bun add <name@version>... [--dev|--optional|--peer] [--exact] [--cwd <dir>]
|
|
79
82
|
bun update <name[@version]>... [--cwd <dir>] Change versions of declared dependencies only
|
|
@@ -191,7 +194,24 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
|
|
|
191
194
|
if (command === "skills") {
|
|
192
195
|
const action = args.shift();
|
|
193
196
|
if (action === "list") { usage(args.length === 0, "Usage: agent-tool skills list"); output(Object.keys(BUNDLED_SKILLS)); return 0; }
|
|
194
|
-
|
|
197
|
+
if (action === "link" || action === "check-links") {
|
|
198
|
+
let apply = false;
|
|
199
|
+
while (args.length) {
|
|
200
|
+
const flag = args.shift();
|
|
201
|
+
if (flag === "--apply") { usage(action === "link", "skills check-links is read-only; --apply is not allowed."); usage(!apply, "Duplicate --apply."); apply = true; }
|
|
202
|
+
else throw new Error(`Unknown skills ${action} argument '${flag}'.`);
|
|
203
|
+
}
|
|
204
|
+
// The checkout's top level, so a subdirectory cannot read as a repository that declares nothing.
|
|
205
|
+
const root = gitRoot();
|
|
206
|
+
const names = loadConfig(root).skills.user;
|
|
207
|
+
if (action === "check-links") {
|
|
208
|
+
const result = checkSkillLinks(root, names);
|
|
209
|
+
output(result); return result.ok ? 0 : 1;
|
|
210
|
+
}
|
|
211
|
+
const result = linkSkills(root, names, apply);
|
|
212
|
+
output(result); return result.changes.some(change => change.status === "conflict" || change.result === "failed") ? 1 : 0;
|
|
213
|
+
}
|
|
214
|
+
usage(action === "install" || action === "check", "Usage: agent-tool skills <list|install|check|link|check-links>");
|
|
195
215
|
let target = "all", apply = false;
|
|
196
216
|
while (args.length) {
|
|
197
217
|
const flag = args.shift();
|
package/src/config.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface AgentToolConfig extends WorkflowConfig {
|
|
|
26
26
|
screenshots: ScreenshotsConfig;
|
|
27
27
|
graph: GraphConfig;
|
|
28
28
|
permissions: { executables: Record<string, PermissionClass> };
|
|
29
|
+
/** `user`: skills `skills link` links into each user skill directory, by skill directory name. */
|
|
30
|
+
skills: { user: string[] };
|
|
29
31
|
/** Null when the repository declares no push gate. */
|
|
30
32
|
pushGate: PushGateConfig | null;
|
|
31
33
|
}
|
|
@@ -49,6 +51,7 @@ export const DEFAULT_CONFIG: AgentToolConfig = {
|
|
|
49
51
|
screenshots: structuredClone(SCREENSHOTS_DEFAULTS),
|
|
50
52
|
graph: structuredClone(GRAPH_DEFAULTS),
|
|
51
53
|
permissions: { executables: {} },
|
|
54
|
+
skills: { user: [] },
|
|
52
55
|
pushGate: null,
|
|
53
56
|
};
|
|
54
57
|
|
|
@@ -101,7 +104,7 @@ export function parseConfig(source: string): AgentToolConfig {
|
|
|
101
104
|
keys(input, Object.keys(DEFAULT_CONFIG), "config");
|
|
102
105
|
if (input.schemaVersion !== 1) throw new Error("Unsupported config schemaVersion; expected 1.");
|
|
103
106
|
const result = structuredClone(DEFAULT_CONFIG);
|
|
104
|
-
for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions"] as const) {
|
|
107
|
+
for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions", "skills"] as const) {
|
|
105
108
|
if (input[section] === undefined) continue;
|
|
106
109
|
const settings = object(input[section], section);
|
|
107
110
|
keys(settings, Object.keys(result[section]), section);
|
|
@@ -146,6 +149,10 @@ export function parseConfig(source: string): AgentToolConfig {
|
|
|
146
149
|
// Names become literal tokens in harness rules, so keep them free of rule syntax.
|
|
147
150
|
const executables = object(result.permissions.executables, "permissions.executables");
|
|
148
151
|
for (const [name, value] of Object.entries(executables)) if (!/^[\w.+-]+$/.test(name) || !(typeof value === "string" && Object.hasOwn(CLASSES, value))) invalid(`permissions.executables.${name}`);
|
|
152
|
+
// Names become entries in user skill directories, so each is a plain skill directory name, once.
|
|
153
|
+
// `synced` is Claude Code's own account-synced skill store.
|
|
154
|
+
const user = result.skills.user;
|
|
155
|
+
if (!Array.isArray(user) || user.some(name => typeof name !== "string" || name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name === "synced") || new Set(user).size !== user.length) invalid("skills.user");
|
|
149
156
|
validateWorkflowConfig(result);
|
|
150
157
|
return result;
|
|
151
158
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { retryGitHubResult } from "../system/githubRetry";
|
|
2
3
|
|
|
3
4
|
interface CurrentBranchPr {
|
|
4
5
|
readonly baseRefName: string;
|
|
@@ -18,18 +19,21 @@ interface CommandResult {
|
|
|
18
19
|
|
|
19
20
|
type CommandRunner = (command: string, args: string[]) => CommandResult;
|
|
20
21
|
|
|
22
|
+
/** A read-only `gh` call, repeated after a transient network or server failure. */
|
|
21
23
|
function runWithResult(command: string, args: string[]): CommandResult {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
24
|
+
return retryGitHubResult(() => {
|
|
25
|
+
const result = spawnSync(command, args, {
|
|
26
|
+
encoding: "utf8",
|
|
27
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
28
|
+
});
|
|
29
|
+
const output = {
|
|
30
|
+
status: result.status,
|
|
31
|
+
signal: result.signal,
|
|
32
|
+
stderr: result.stderr,
|
|
33
|
+
stdout: result.stdout,
|
|
34
|
+
};
|
|
35
|
+
return result.error ? { ...output, error: result.error } : output;
|
|
25
36
|
});
|
|
26
|
-
const output = {
|
|
27
|
-
status: result.status,
|
|
28
|
-
signal: result.signal,
|
|
29
|
-
stderr: result.stderr,
|
|
30
|
-
stdout: result.stdout,
|
|
31
|
-
};
|
|
32
|
-
return result.error ? { ...output, error: result.error } : output;
|
|
33
37
|
}
|
|
34
38
|
|
|
35
39
|
function field(source: string, key: string): unknown {
|
package/src/git/prContext.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { gitEnvironment } from "./environment";
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { boundedExecFileSync } from "../system/boundedCalls";
|
|
4
|
+
import { retryGitHubRead } from "../system/githubRetry";
|
|
4
5
|
import { randomUUID } from "node:crypto";
|
|
5
6
|
|
|
6
7
|
import { viewCurrentBranchPr } from "./currentBranchPr";
|
|
@@ -39,9 +40,17 @@ export function run(command: string, args: string[]): string {
|
|
|
39
40
|
}).trim();
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
/**
|
|
44
|
+
* `run` for a read-only GitHub call: a transient network or server failure is
|
|
45
|
+
* repeated within `retryGitHubRead`'s budget. Never use it for a mutation.
|
|
46
|
+
*/
|
|
47
|
+
export function runRead(command: string, args: string[]): string {
|
|
48
|
+
return retryGitHubRead(() => run(command, args));
|
|
49
|
+
}
|
|
50
|
+
|
|
42
51
|
function tryRun(command: string, args: string[]): string | null {
|
|
43
52
|
try {
|
|
44
|
-
return
|
|
53
|
+
return runRead(command, args);
|
|
45
54
|
} catch {
|
|
46
55
|
return null;
|
|
47
56
|
}
|
|
@@ -134,7 +143,7 @@ export function selectRepositoryGitUrl(
|
|
|
134
143
|
}
|
|
135
144
|
|
|
136
145
|
export function resolveRepositoryGitUrl(repo: string): string {
|
|
137
|
-
const repoRaw =
|
|
146
|
+
const repoRaw = runRead("gh", ["repo", "view", repo, "--json", "url,sshUrl"]);
|
|
138
147
|
const httpsUrl = stringField(repoRaw, "url");
|
|
139
148
|
const sshUrl = stringField(repoRaw, "sshUrl");
|
|
140
149
|
let host = "";
|
|
@@ -334,7 +343,7 @@ export function findOpenPrNumber(branch: string, repo: string): string {
|
|
|
334
343
|
|
|
335
344
|
/** Read a known-open PR's title and base identity from GitHub. */
|
|
336
345
|
function viewPr(branch: string, repo: string, prNumber: string): PrView {
|
|
337
|
-
const viewRaw =
|
|
346
|
+
const viewRaw = runRead("gh", [
|
|
338
347
|
"pr",
|
|
339
348
|
"view",
|
|
340
349
|
prNumber,
|
|
@@ -406,7 +415,7 @@ function fetchPrView(): PrView {
|
|
|
406
415
|
/** Current GitHub state of a PR (e.g. "OPEN", "MERGED", "CLOSED"). */
|
|
407
416
|
export function prState(prNumber: string, repo: string): string {
|
|
408
417
|
return stringField(
|
|
409
|
-
|
|
418
|
+
runRead("gh", ["pr", "view", prNumber, "--json", "state", "-R", repo]),
|
|
410
419
|
"state",
|
|
411
420
|
);
|
|
412
421
|
}
|
|
@@ -9,7 +9,7 @@ export const CLASSES = {
|
|
|
9
9
|
share: { decision: "allow", description: "Publishes work for review without changing a shared branch: pushes a feature branch, opens a PR, answers review threads, or prunes a merged PR's feature branch." },
|
|
10
10
|
release: { decision: "ask", description: "Merges into a shared branch, publishes a package, or deletes remote state." },
|
|
11
11
|
intake: { decision: "ask", description: "Brings new third-party code into the repository." },
|
|
12
|
-
policy: { decision: "ask", description: "Changes the permissions agents run with." },
|
|
12
|
+
policy: { decision: "ask", description: "Changes the permissions agents run with, or links user-wide skills every session loads." },
|
|
13
13
|
exec: { decision: "ask", description: "Runs whatever command or file its arguments name." },
|
|
14
14
|
} as const;
|
|
15
15
|
export type PermissionClass = keyof typeof CLASSES;
|
|
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
|
|
|
19
19
|
export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
|
|
20
20
|
|
|
21
21
|
export const CATALOG: CatalogEntry[] = [
|
|
22
|
-
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
|
|
22
|
+
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "skills check-links", "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"]
|
|
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 })),
|
|
@@ -27,6 +27,8 @@ export const CATALOG: CatalogEntry[] = [
|
|
|
27
27
|
{ command: "hooks install", class: "read", applyClass: "local" },
|
|
28
28
|
{ command: "teardown", class: "read", applyClass: "local" },
|
|
29
29
|
{ command: "permissions install", class: "read", applyClass: "policy" },
|
|
30
|
+
// Linking writes outside the checkout, into the user skill directories every session loads.
|
|
31
|
+
{ command: "skills link", class: "read", applyClass: "policy" },
|
|
30
32
|
...["branch push", "pr open", "pr cancel-runs", "pr threads reply", "pr threads resolve"].map(command => ({ command, class: "share" as const })),
|
|
31
33
|
{ command: "pr merge", class: "release" },
|
|
32
34
|
// Cleanup acts only after GitHub confirms the PR MERGED and the local and remote
|
package/src/pr/baseFreshness.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { run } from "../git/prContext";
|
|
1
|
+
import { run, runRead } from "../git/prContext";
|
|
2
2
|
|
|
3
3
|
function field(value: unknown, key: string): unknown {
|
|
4
4
|
return typeof value === "object" && value !== null
|
|
@@ -26,7 +26,7 @@ function strictStatusRule(rule: unknown): boolean {
|
|
|
26
26
|
export function assertStrictBaseFreshness(
|
|
27
27
|
repo: string,
|
|
28
28
|
baseRef: string,
|
|
29
|
-
read: typeof run =
|
|
29
|
+
read: typeof run = runRead,
|
|
30
30
|
): void {
|
|
31
31
|
const where = `${repo}:${baseRef}`;
|
|
32
32
|
let rulesetIds: unknown[];
|
package/src/pr/mergeChecks.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { run } from "../git/prContext";
|
|
1
|
+
import { run, runRead } from "../git/prContext";
|
|
2
2
|
import { loadConfig, type AgentToolConfig } from "../config";
|
|
3
3
|
|
|
4
4
|
type CheckPolicy = Pick<AgentToolConfig["merge"], "requireChecks" | "requiredChecks">;
|
|
@@ -43,7 +43,7 @@ export function assertMergeChecks(source: string, expectedHead: string, policy:
|
|
|
43
43
|
export function requirePassingMergeChecks(
|
|
44
44
|
pr: { readonly prNumber: string; readonly repo: string },
|
|
45
45
|
expectedHead: string,
|
|
46
|
-
read: typeof run =
|
|
46
|
+
read: typeof run = runRead,
|
|
47
47
|
policy: CheckPolicy = loadConfig().merge,
|
|
48
48
|
): void {
|
|
49
49
|
// gh pr checks paginates and selects the latest run per workflow/job/event.
|
package/src/pr/squashMerge.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
|
|
3
3
|
import { loadConfig } from "../config";
|
|
4
|
-
import { prState, resolvePr,
|
|
4
|
+
import { prState, resolvePr, runRead, spawnExitCode } from "../git/prContext";
|
|
5
5
|
import { assertStrictBaseFreshness } from "./baseFreshness";
|
|
6
6
|
import { requirePassingMergeChecks } from "./mergeChecks";
|
|
7
7
|
import {
|
|
@@ -120,7 +120,7 @@ export function resolvePullRequestMergeTarget(
|
|
|
120
120
|
throw new Error(`Invalid repository slug '${pr.repo}'.`);
|
|
121
121
|
}
|
|
122
122
|
const [owner, name] = repoParts;
|
|
123
|
-
const source =
|
|
123
|
+
const source = runRead("gh", [
|
|
124
124
|
"api",
|
|
125
125
|
"graphql",
|
|
126
126
|
"-f",
|
|
@@ -167,6 +167,32 @@ export function buildSquashMergeArgs(
|
|
|
167
167
|
];
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
+
/**
|
|
171
|
+
* After a failed merge mutation, read the PR's state once more and say whether
|
|
172
|
+
* the merge landed anyway, so nobody sends it again blindly. The mutation was
|
|
173
|
+
* bound to the reviewed head through `expectedHeadOid`; repeating `pr merge`
|
|
174
|
+
* reruns every gate first.
|
|
175
|
+
*/
|
|
176
|
+
function reportFailedMerge(prNumber: string, repo: string): void {
|
|
177
|
+
let state: string;
|
|
178
|
+
try {
|
|
179
|
+
state = prState(prNumber, repo);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
process.stderr.write(
|
|
182
|
+
`The merge mutation for PR #${prNumber} failed, and its state could not be read again: ${(error as Error).message}\n` +
|
|
183
|
+
"Check whether it merged before running pr merge again.\n",
|
|
184
|
+
);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
process.stderr.write(
|
|
188
|
+
state === "MERGED"
|
|
189
|
+
? `The merge mutation for PR #${prNumber} reported a failure, but GitHub now reports the PR MERGED. ` +
|
|
190
|
+
"Do not merge again; confirm its merge commit and head before cleanup.\n"
|
|
191
|
+
: `The merge mutation for PR #${prNumber} failed and GitHub reports the PR ${state || "in an unknown state"}, so it did not merge. ` +
|
|
192
|
+
"Read the error above; running pr merge again repeats every gate first.\n",
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
170
196
|
/**
|
|
171
197
|
* Squash-merge the open PR for the current branch with a subject-only commit
|
|
172
198
|
* message — no auto-generated body or extended message. The subject defaults to
|
|
@@ -212,6 +238,8 @@ export function squashMerge(
|
|
|
212
238
|
);
|
|
213
239
|
const exitCode = spawnExitCode("GitHub mergePullRequest mutation", result);
|
|
214
240
|
if (exitCode !== 0) {
|
|
241
|
+
// Never sent twice: a mutation that failed in transit may still have merged.
|
|
242
|
+
reportFailedMerge(pr.prNumber, pr.repo);
|
|
215
243
|
return exitCode;
|
|
216
244
|
}
|
|
217
245
|
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, realpathSync, renameSync, statSync, symlinkSync, unlinkSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { readRegularFile } from "../system/files";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* User-wide skills: a repository declares them by name in `skills.user`, and `skills link`
|
|
9
|
+
* links each into every user skill directory, so every harness session sees them whatever
|
|
10
|
+
* repository it starts in. Claude Code reads `<config dir>/skills` for each config directory;
|
|
11
|
+
* `~/.agents/skills` is the user-level counterpart of a project's `.agents/skills`.
|
|
12
|
+
*/
|
|
13
|
+
export type UserSkillHarness = "claude" | "agents";
|
|
14
|
+
export interface UserSkillDirectory { harness: UserSkillHarness; directory: string }
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What a link path holds: nothing (`create`); a symbolic link that does not resolve to a skill
|
|
18
|
+
* directory, or that resolves to another copy of the skill in this repository (`repair`); a link
|
|
19
|
+
* to this repository's source (`unchanged`); a link to the same skill elsewhere, such as another
|
|
20
|
+
* clone (`kept`); or anything else (`conflict`): a file or directory, or a link to a different
|
|
21
|
+
* skill. Only `create` and `repair` are ever written.
|
|
22
|
+
*/
|
|
23
|
+
export type SkillLinkStatus = "create" | "repair" | "unchanged" | "kept" | "conflict";
|
|
24
|
+
/** One declared skill in one user skill directory: `status` is the plan's classification and `current` an existing link's own text. */
|
|
25
|
+
export interface SkillLinkPlan { skill: string; directory: string; path: string; target: string; status: SkillLinkStatus; current?: string }
|
|
26
|
+
/**
|
|
27
|
+
* A planned entry and, only when an applied write was attempted, its `result`: `written`, or
|
|
28
|
+
* `failed` with `error` saying why. An entry without one was not written.
|
|
29
|
+
*/
|
|
30
|
+
export type SkillLink = SkillLinkPlan & ({ result?: never; error?: never } | { result: "written"; error?: never } | { result: "failed"; error: string });
|
|
31
|
+
|
|
32
|
+
type Environment = Record<string, string | undefined>;
|
|
33
|
+
const errorCode = (error: unknown) => (error as NodeJS.ErrnoException).code ?? "";
|
|
34
|
+
/** Errors that mean a path, or what a link names, does not exist as asked. */
|
|
35
|
+
const ABSENT = ["ENOENT", "ENOTDIR", "ELOOP"];
|
|
36
|
+
|
|
37
|
+
function statOrNull(file: string) {
|
|
38
|
+
try { return statSync(file); } catch (error) { if (ABSENT.includes(errorCode(error))) return null; throw error; }
|
|
39
|
+
}
|
|
40
|
+
function isLink(file: string): boolean {
|
|
41
|
+
try { return lstatSync(file).isSymbolicLink(); } catch (error) { if (ABSENT.includes(errorCode(error))) return false; throw error; }
|
|
42
|
+
}
|
|
43
|
+
const isDirectory = (file: string) => statOrNull(file)?.isDirectory() ?? false;
|
|
44
|
+
/** A directory holding a regular `SKILL.md`, following links as the harnesses do. */
|
|
45
|
+
const holdsSkill = (directory: string) => isDirectory(directory) && (statOrNull(path.join(directory, "SKILL.md"))?.isFile() ?? false);
|
|
46
|
+
function within(parent: string, child: string): boolean {
|
|
47
|
+
const relative = path.relative(parent, child);
|
|
48
|
+
return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The home directory, from `HOME` first so tests and callers can isolate it. */
|
|
52
|
+
export function userHome(env: Environment = process.env): string {
|
|
53
|
+
return path.resolve(env.HOME || homedir());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Keeps the first of each real path, so links and aliases name one directory once. */
|
|
57
|
+
function unique<T>(items: T[], key: (item: T) => string): T[] {
|
|
58
|
+
const seen = new Set<string>();
|
|
59
|
+
return items.filter(item => { const value = key(item); if (seen.has(value)) return false; seen.add(value); return true; });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The real path of a directory that may not exist yet: its nearest existing ancestor's, then the
|
|
64
|
+
* rest, following a dangling link to where it points, so a link to a directory not created yet
|
|
65
|
+
* names that directory. A link loop stops after 40 links, at whichever name it reached, which
|
|
66
|
+
* planning then refuses as a link that does not resolve to a directory.
|
|
67
|
+
*/
|
|
68
|
+
function realDirectory(directory: string, hops = 0): string {
|
|
69
|
+
try { return realpathSync(directory); }
|
|
70
|
+
catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
|
|
71
|
+
const parent = path.dirname(directory);
|
|
72
|
+
if (parent === directory) return directory;
|
|
73
|
+
const resolved = path.join(realDirectory(parent, hops), path.basename(directory));
|
|
74
|
+
if (hops >= 40 || !isLink(resolved)) return resolved;
|
|
75
|
+
return realDirectory(path.resolve(path.dirname(resolved), readlinkSync(resolved)), hops + 1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Claude Code config directories, in this order: the one `CLAUDE_CONFIG_DIR` names when it is set
|
|
80
|
+
* to an absolute path; `~/.claude`; then every other directory directly in home whose name starts with
|
|
81
|
+
* `.claude` and that holds `settings.json` or `.claude.json`, such as `~/.claude2`. Claude Code
|
|
82
|
+
* writes `.claude.json` into a directory it runs with, and provisioning links `settings.json` into
|
|
83
|
+
* one. Only existing directories count, so files such as `~/.claude.json` never do, and a
|
|
84
|
+
* directory reached twice, by a link or by `CLAUDE_CONFIG_DIR`, counts once, by real path.
|
|
85
|
+
*/
|
|
86
|
+
export function claudeConfigDirectories(env: Environment = process.env): string[] {
|
|
87
|
+
const home = userHome(env);
|
|
88
|
+
const candidates: string[] = [];
|
|
89
|
+
// Only an absolute path: a relative one depends on where Claude Code started, which is unknown here.
|
|
90
|
+
if (env.CLAUDE_CONFIG_DIR && path.isAbsolute(env.CLAUDE_CONFIG_DIR)) candidates.push(path.normalize(env.CLAUDE_CONFIG_DIR));
|
|
91
|
+
candidates.push(path.join(home, ".claude"));
|
|
92
|
+
let names: string[] = [];
|
|
93
|
+
try { names = readdirSync(home).sort(); } catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
|
|
94
|
+
for (const name of names) {
|
|
95
|
+
if (!name.startsWith(".claude") || name === ".claude") continue;
|
|
96
|
+
const directory = path.join(home, name);
|
|
97
|
+
if (["settings.json", ".claude.json"].some(marker => existsSync(path.join(directory, marker)))) candidates.push(directory);
|
|
98
|
+
}
|
|
99
|
+
return unique(candidates.filter(isDirectory), directory => realpathSync(directory));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `~/.agents/skills`, then `<dir>/skills` for each Claude Code config directory. A skills
|
|
104
|
+
* directory reached twice, such as `~/.claude2/skills` linked to `~/.claude/skills`, counts once,
|
|
105
|
+
* under the name that is not itself a link, so a link to a directory not created yet resolves
|
|
106
|
+
* once that directory is created.
|
|
107
|
+
*/
|
|
108
|
+
export function userSkillDirectories(env: Environment = process.env): UserSkillDirectory[] {
|
|
109
|
+
const directories = [
|
|
110
|
+
{ harness: "agents" as const, directory: path.join(userHome(env), ".agents", "skills") },
|
|
111
|
+
...claudeConfigDirectories(env).map(directory => ({ harness: "claude" as const, directory: path.join(directory, "skills") })),
|
|
112
|
+
].map(item => ({ ...item, key: realDirectory(item.directory), link: isLink(item.directory) }));
|
|
113
|
+
const chosen = new Map<string, typeof directories[number]>();
|
|
114
|
+
for (const item of directories) {
|
|
115
|
+
const first = chosen.get(item.key);
|
|
116
|
+
if (!first || (first.link && !item.link)) chosen.set(item.key, item);
|
|
117
|
+
}
|
|
118
|
+
return directories.filter(item => chosen.get(item.key) === item).map(({ harness, directory }) => ({ harness, directory }));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The repository directory a harness links to for one skill: its installed copy for that harness
|
|
123
|
+
* when it holds `SKILL.md` (`.claude/skills/<name>` or `.agents/skills/<name>`), otherwise the
|
|
124
|
+
* repository-owned `skills/<name>`, as an absolute real path inside the repository.
|
|
125
|
+
*/
|
|
126
|
+
export function skillSource(root: string, harness: UserSkillHarness, name: string): string {
|
|
127
|
+
const installed = harness === "claude" ? ".claude/skills" : ".agents/skills";
|
|
128
|
+
const found = [`${installed}/${name}`, `skills/${name}`].find(relative => holdsSkill(path.join(root, relative)));
|
|
129
|
+
if (!found) throw new Error(`Declared user skill '${name}' has no SKILL.md in ${installed}/${name} or skills/${name}.`);
|
|
130
|
+
const source = realpathSync(path.join(root, found));
|
|
131
|
+
if (!within(root, source)) throw new Error(`Declared user skill '${name}' resolves outside the repository: ${found}.`);
|
|
132
|
+
// Links are matched to skills by name, so a source must be the skill it is declared as.
|
|
133
|
+
const named = skillName(source);
|
|
134
|
+
if (named !== name) throw new Error(`Declared user skill '${name}' is named '${named}' in ${found}/SKILL.md.`);
|
|
135
|
+
return source;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The skill a directory holds: its `SKILL.md` front matter `name`, else the directory's name; none without `SKILL.md`. */
|
|
139
|
+
function skillName(directory: string): string | undefined {
|
|
140
|
+
if (!holdsSkill(directory)) return undefined;
|
|
141
|
+
// One non-blocking, link-refusing read of the resolved file, so a FIFO cannot stall the check.
|
|
142
|
+
let file: string;
|
|
143
|
+
try { file = realpathSync(path.join(directory, "SKILL.md")); }
|
|
144
|
+
catch (error) { if (ABSENT.includes(errorCode(error))) return undefined; throw error; }
|
|
145
|
+
const read = readRegularFile(file);
|
|
146
|
+
if (read.status !== "file") return undefined;
|
|
147
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(read.contents)?.[1];
|
|
148
|
+
const raw = front === undefined ? undefined : /^name:[ \t]*(.*?)[ \t]*$/m.exec(front)?.[1];
|
|
149
|
+
// A quoted value keeps everything inside its quotes; a YAML comment may follow either form.
|
|
150
|
+
const name = raw === undefined ? undefined : /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(raw)?.[2] ?? raw.replace(/(?:^|\s+)#.*$/, "");
|
|
151
|
+
return name || path.basename(directory);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Whether anything, even a dangling link, exists at `file`; an entry that cannot be inspected counts. */
|
|
155
|
+
function hasEntry(file: string): boolean {
|
|
156
|
+
try { lstatSync(file); return true; } catch (error) { return errorCode(error) !== "ENOENT"; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Inside the repository and not inside a repository nested in it, such as a workspace's checkouts. */
|
|
160
|
+
function inRepository(root: string, file: string): boolean {
|
|
161
|
+
if (!within(root, file)) return false;
|
|
162
|
+
for (let directory = file; directory !== root && within(root, directory); directory = path.dirname(directory)) {
|
|
163
|
+
if (hasEntry(path.join(directory, ".git"))) return false;
|
|
164
|
+
}
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Classify one link path against its intended target without changing anything. */
|
|
169
|
+
function classify(root: string, file: string, target: string, skill: string): Pick<SkillLinkPlan, "status" | "current"> {
|
|
170
|
+
let link: boolean;
|
|
171
|
+
try { link = lstatSync(file).isSymbolicLink(); }
|
|
172
|
+
catch (error) { if (errorCode(error) === "ENOENT") return { status: "create" }; throw error; }
|
|
173
|
+
if (!link) return { status: "conflict" };
|
|
174
|
+
const current = readlinkSync(file);
|
|
175
|
+
let resolved: string;
|
|
176
|
+
try { resolved = realpathSync(file); }
|
|
177
|
+
catch (error) { if (ABSENT.includes(errorCode(error))) return { status: "repair", current }; throw error; }
|
|
178
|
+
if (resolved === target) return { status: "unchanged", current };
|
|
179
|
+
const name = skillName(resolved);
|
|
180
|
+
if (name === undefined) return { status: "repair", current };
|
|
181
|
+
if (name !== skill) return { status: "conflict", current };
|
|
182
|
+
// This repository owns both copies, so the link moves to the one this harness should load.
|
|
183
|
+
return { status: inRepository(root, resolved) ? "repair" : "kept", current };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Whether a user skill directory exists; one that names anything but a directory is refused. */
|
|
187
|
+
function directoryExists(directory: string): boolean {
|
|
188
|
+
try { lstatSync(directory); }
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (errorCode(error) === "ENOENT") return false;
|
|
191
|
+
// A parent that is a file or a link loop: refused below as not a directory.
|
|
192
|
+
if (errorCode(error) !== "ENOTDIR" && errorCode(error) !== "ELOOP") throw error;
|
|
193
|
+
}
|
|
194
|
+
if (isDirectory(directory)) return true;
|
|
195
|
+
if (isLink(directory)) throw new Error(`User skill directory is a link that does not resolve to a directory: ${directory} -> ${readlinkSync(directory)}`);
|
|
196
|
+
throw new Error(`User skill directory is not a directory: ${directory}`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* One entry per declared skill and user skill directory. Every source resolves first, for both
|
|
201
|
+
* harnesses, so a declaration without one fails on every machine and before anything is read
|
|
202
|
+
* from home. Only the declared names are ever examined.
|
|
203
|
+
*/
|
|
204
|
+
export function planSkillLinks(rootDir: string, names: string[], env: Environment = process.env): SkillLinkPlan[] {
|
|
205
|
+
if (!names.length) return [];
|
|
206
|
+
const root = realpathSync(rootDir);
|
|
207
|
+
const sources = {
|
|
208
|
+
agents: names.map(name => skillSource(root, "agents", name)),
|
|
209
|
+
claude: names.map(name => skillSource(root, "claude", name)),
|
|
210
|
+
};
|
|
211
|
+
const links: SkillLinkPlan[] = [];
|
|
212
|
+
for (const { harness, directory } of userSkillDirectories(env)) {
|
|
213
|
+
const exists = directoryExists(directory);
|
|
214
|
+
names.forEach((skill, index) => {
|
|
215
|
+
const target = sources[harness][index]!, file = path.join(directory, skill);
|
|
216
|
+
links.push({ skill, directory, path: file, target, ...(exists ? classify(root, file, target, skill) : { status: "create" as const }) });
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return links;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Replace a link through a fresh temporary link and a rename, so the name is never missing. Only
|
|
224
|
+
* the link the plan classified is replaced: the path must still hold a link with the same text
|
|
225
|
+
* just before the rename. Node has no exchanging rename, so a writer racing that instant is
|
|
226
|
+
* outside this guard; only another process writing the user's skill directories could do it.
|
|
227
|
+
*/
|
|
228
|
+
function replaceLink(link: SkillLinkPlan): void {
|
|
229
|
+
const temporary = path.join(link.directory, `.${link.skill}.agent-tool-${randomUUID()}.tmp`);
|
|
230
|
+
symlinkSync(link.target, temporary, "dir");
|
|
231
|
+
let renamed = false;
|
|
232
|
+
try {
|
|
233
|
+
let current: string | undefined;
|
|
234
|
+
// EINVAL: not a link.
|
|
235
|
+
try { current = readlinkSync(link.path); } catch (error) { if (!["ENOENT", "ENOTDIR", "EINVAL"].includes(errorCode(error))) throw error; }
|
|
236
|
+
if (current === undefined || current !== link.current) throw new Error(`Refusing to replace ${link.path}, which changed since the plan.`);
|
|
237
|
+
renameSync(temporary, link.path);
|
|
238
|
+
renamed = true;
|
|
239
|
+
} finally {
|
|
240
|
+
// Best effort: the original error matters more than a temporary link left behind.
|
|
241
|
+
if (!renamed) try { unlinkSync(temporary); } catch {}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Writes a plan's `create` and `repair` entries. Each write stands alone: one that fails, such as
|
|
247
|
+
* a create whose path was taken since the plan, records its `error` and the rest still run, so
|
|
248
|
+
* the result says exactly what was written. Nothing that is not a link is replaced or removed,
|
|
249
|
+
* and a plan with a conflict writes nothing. `linkSkills` also refuses linked worktrees first;
|
|
250
|
+
* this is exported so tests can change the filesystem between the plan and the writes.
|
|
251
|
+
*/
|
|
252
|
+
export function applySkillLinks(changes: SkillLinkPlan[]): SkillLink[] {
|
|
253
|
+
if (changes.some(change => change.status === "conflict")) return changes;
|
|
254
|
+
return changes.map((change): SkillLink => {
|
|
255
|
+
if (change.status !== "create" && change.status !== "repair") return change;
|
|
256
|
+
try {
|
|
257
|
+
if (change.status === "create") {
|
|
258
|
+
mkdirSync(change.directory, { recursive: true, mode: 0o700 });
|
|
259
|
+
// Fails rather than overwrites if anything appeared since the plan.
|
|
260
|
+
symlinkSync(change.target, change.path, "dir");
|
|
261
|
+
} else replaceLink(change);
|
|
262
|
+
return { ...change, result: "written" };
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return { ...change, result: "failed", error: error instanceof Error ? error.message : String(error) };
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Whether a directory is, or is inside, a `modules` directory of a Git directory. */
|
|
270
|
+
function insideModules(directory: string): boolean {
|
|
271
|
+
for (let current = directory; path.dirname(current) !== current; current = path.dirname(current)) {
|
|
272
|
+
if (path.basename(current) === "modules" && existsSync(path.join(path.dirname(current), "HEAD"))) return true;
|
|
273
|
+
}
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Whether the checkout lives in a linked worktree. `git rev-parse --git-common-dir` would miss a
|
|
279
|
+
* submodule inside a linked worktree, so this reads the layout: the checkout's `.git` is a file
|
|
280
|
+
* naming a Git directory that, or one of whose ancestors up to the enclosing `.git` directory,
|
|
281
|
+
* holds `commondir`, which Git writes only into a linked worktree's Git directory. The ancestors
|
|
282
|
+
* cover a submodule checked out inside a linked worktree, whose Git directory sits under that
|
|
283
|
+
* worktree's `modules/`. The walk stops at the outermost Git directory, so a stray `commondir`
|
|
284
|
+
* above the repository never counts.
|
|
285
|
+
*/
|
|
286
|
+
function linkedWorktree(root: string): boolean {
|
|
287
|
+
const read = readRegularFile(path.join(root, ".git"));
|
|
288
|
+
const gitdir = read.status === "file" ? /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(read.contents)?.[1] : undefined;
|
|
289
|
+
if (gitdir === undefined) return false;
|
|
290
|
+
for (let directory = path.resolve(root, gitdir); ; directory = path.dirname(directory)) {
|
|
291
|
+
if (existsSync(path.join(directory, "commondir"))) return true;
|
|
292
|
+
const parent = path.dirname(directory);
|
|
293
|
+
if (parent === directory || path.basename(directory) === ".git") return false;
|
|
294
|
+
// A Git directory that is not a submodule's, under another Git directory's `modules/`, is the
|
|
295
|
+
// outermost, as with `--separate-git-dir`.
|
|
296
|
+
if (existsSync(path.join(directory, "HEAD")) && !insideModules(parent)) return false;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Previews by default. With `apply`, creates missing links, creating a missing skills directory
|
|
302
|
+
* (mode 0700), and repairs broken ones. A conflict anywhere blocks every write. Links follow the
|
|
303
|
+
* checked-out working tree, so a linked worktree, which is removed when its work is done, is refused.
|
|
304
|
+
* `applied` is true only when every write succeeded; a failed one carries `error`.
|
|
305
|
+
*/
|
|
306
|
+
export function linkSkills(rootDir: string, names: string[], apply = false, env: Environment = process.env): { applied: boolean; changes: SkillLink[] } {
|
|
307
|
+
const changes = planSkillLinks(rootDir, names, env);
|
|
308
|
+
if (!apply || changes.some(change => change.status === "conflict")) return { applied: false, changes };
|
|
309
|
+
if (changes.some(change => change.status === "create" || change.status === "repair") && linkedWorktree(realpathSync(rootDir))) {
|
|
310
|
+
throw new Error("Refusing to link user-wide skills from a linked worktree, whose removal would break them; run skills link from the main checkout.");
|
|
311
|
+
}
|
|
312
|
+
const applied = applySkillLinks(changes);
|
|
313
|
+
return { applied: applied.every(change => change.result !== "failed"), changes: applied };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Read-only: ok while every declared link is unchanged or kept, so health reports can gate on it. */
|
|
317
|
+
export function checkSkillLinks(rootDir: string, names: string[], env: Environment = process.env): { ok: boolean; changes: SkillLink[] } {
|
|
318
|
+
const changes = planSkillLinks(rootDir, names, env);
|
|
319
|
+
return { ok: changes.every(change => change.status === "unchanged" || change.status === "kept"), changes };
|
|
320
|
+
}
|
|
@@ -18,6 +18,11 @@ export async function withCallDeadline<T>(until: number, inspect: () => T | Prom
|
|
|
18
18
|
return await deadlines.run(until, inspect);
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/** The deadline of the wait running the current call, or undefined outside every wait. */
|
|
22
|
+
export function callDeadline(): number | undefined {
|
|
23
|
+
return deadlines.getStore();
|
|
24
|
+
}
|
|
25
|
+
|
|
21
26
|
function currentLimit(): number | undefined {
|
|
22
27
|
const deadline = deadlines.getStore();
|
|
23
28
|
if (deadline === undefined) return undefined;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { callDeadline } from "./boundedCalls";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The retry budget for a GitHub call that failed transiently: `attempts` calls
|
|
5
|
+
* in all, sleeping `initialDelayMs` before the first retry and doubling up to
|
|
6
|
+
* `maxDelayMs`, so 1, 2, then 4 seconds by default. Mutable for tests.
|
|
7
|
+
*/
|
|
8
|
+
export const GITHUB_RETRY = { attempts: 4, initialDelayMs: 1_000, maxDelayMs: 8_000 };
|
|
9
|
+
|
|
10
|
+
// The same request would fail the same way: authentication, permissions,
|
|
11
|
+
// validation, absent objects, and rate limits. These win over any transient match.
|
|
12
|
+
const PERMANENT = /\bHTTP 4\d\d\b|gh auth login|authentication|bad credentials|not found|could not resolve to|rate limit/i;
|
|
13
|
+
// Network failures and server errors that a later call commonly survives, as
|
|
14
|
+
// Go's HTTP client and GitHub report them through `gh`.
|
|
15
|
+
const TRANSIENT = [
|
|
16
|
+
/i\/o timeout/i,
|
|
17
|
+
/connection reset/i,
|
|
18
|
+
/broken pipe/i,
|
|
19
|
+
/\bEOF\b/,
|
|
20
|
+
/TLS handshake timeout/i,
|
|
21
|
+
/context deadline exceeded|Client\.Timeout exceeded/i,
|
|
22
|
+
/\bHTTP 50[234]\b/,
|
|
23
|
+
// GraphQL's own server-side timeout, reported with HTTP 200.
|
|
24
|
+
/Something went wrong while executing your query/i,
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
/** The failure output to classify: a command's stderr when it has any, else the error's message. */
|
|
28
|
+
function failureText(failure: unknown): string {
|
|
29
|
+
if (typeof failure === "string") return failure;
|
|
30
|
+
const stderr: unknown = typeof failure === "object" && failure !== null ? Reflect.get(failure, "stderr") : undefined;
|
|
31
|
+
const text = typeof stderr === "string" ? stderr : Buffer.isBuffer(stderr) ? stderr.toString("utf8") : "";
|
|
32
|
+
if (text.trim()) return text;
|
|
33
|
+
return failure instanceof Error ? failure.message : String(failure);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Whether a failed GitHub call is worth repeating: a network or server error, never a client error. */
|
|
37
|
+
export function transientGitHubFailure(failure: unknown): boolean {
|
|
38
|
+
const text = failureText(failure);
|
|
39
|
+
return !PERMANENT.test(text) && TRANSIENT.some(pattern => pattern.test(text));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A GitHub call that still failed transiently once its retry budget, or its wait's deadline, ran out. */
|
|
43
|
+
export class TransientGitHubError extends Error {
|
|
44
|
+
constructor(readonly attempts: number, cause: unknown) {
|
|
45
|
+
const message = cause instanceof Error ? cause.message : failureText(cause);
|
|
46
|
+
super(`${message.trimEnd()}\nGitHub failed transiently on all ${attempts} attempt(s); try again once it is reachable.`, { cause });
|
|
47
|
+
this.name = "TransientGitHubError";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The pause before retry number `retry` (1-based), or null when the budget is
|
|
53
|
+
* spent or the pause would end past the deadline of the wait making the call,
|
|
54
|
+
* so retries never stretch a wait beyond its timeout.
|
|
55
|
+
*/
|
|
56
|
+
function retryDelay(retry: number): number | null {
|
|
57
|
+
if (retry >= GITHUB_RETRY.attempts) return null;
|
|
58
|
+
const delay = Math.min(GITHUB_RETRY.maxDelayMs, GITHUB_RETRY.initialDelayMs * 2 ** (retry - 1));
|
|
59
|
+
const deadline = callDeadline();
|
|
60
|
+
return deadline !== undefined && Date.now() + delay >= deadline ? null : delay;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type Outcome<T> = { ok: true; value: T } | { ok: false; error: unknown };
|
|
64
|
+
|
|
65
|
+
function repeat<T>(call: () => T, transient: (outcome: Outcome<T>) => boolean): { outcome: Outcome<T>; attempts: number } {
|
|
66
|
+
for (let attempts = 1; ; attempts++) {
|
|
67
|
+
let outcome: Outcome<T>;
|
|
68
|
+
try { outcome = { ok: true, value: call() }; } catch (error) { outcome = { ok: false, error }; }
|
|
69
|
+
const delay = transient(outcome) ? retryDelay(attempts) : null;
|
|
70
|
+
if (delay === null) return { outcome, attempts };
|
|
71
|
+
Bun.sleepSync(delay);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Run a read-only GitHub call, repeating it after a transient failure within
|
|
77
|
+
* the budget. A client error is thrown at once; a transient failure that
|
|
78
|
+
* outlasts the budget is thrown as `TransientGitHubError`. Never pass a
|
|
79
|
+
* mutation: a request that failed in transit may still have taken effect.
|
|
80
|
+
*/
|
|
81
|
+
export function retryGitHubRead<T>(read: () => T): T {
|
|
82
|
+
const { outcome, attempts } = repeat(read, result => !result.ok && transientGitHubFailure(result.error));
|
|
83
|
+
if (outcome.ok) return outcome.value;
|
|
84
|
+
throw transientGitHubFailure(outcome.error) ? new TransientGitHubError(attempts, outcome.error) : outcome.error;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* `retryGitHubRead` for a runner that reports failure in its result, as
|
|
89
|
+
* `spawnSync` does, rather than by throwing. Once the budget runs out the last
|
|
90
|
+
* result is returned for the caller to report as before.
|
|
91
|
+
*/
|
|
92
|
+
export function retryGitHubResult<T extends { status: number | null; stderr?: string | null }>(read: () => T): T {
|
|
93
|
+
const { outcome } = repeat(read, result => result.ok && result.value.status !== 0 && transientGitHubFailure(result.value.stderr ?? ""));
|
|
94
|
+
if (outcome.ok) return outcome.value;
|
|
95
|
+
throw outcome.error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Send a mutation that is safe to repeat only once its preconditions are read
|
|
100
|
+
* again. After a transient failure and the backoff pause, `recheck` rereads
|
|
101
|
+
* them: it throws when they no longer hold, returns true when the failed
|
|
102
|
+
* attempt already took effect, and false to send the mutation again. Any other
|
|
103
|
+
* failure propagates at once, and the last transient one as
|
|
104
|
+
* `TransientGitHubError`.
|
|
105
|
+
*/
|
|
106
|
+
export function retryCheckedGitHubMutation(mutate: () => void, recheck: () => boolean): void {
|
|
107
|
+
for (let attempts = 1; ; attempts++) {
|
|
108
|
+
try { mutate(); return; } catch (error) {
|
|
109
|
+
if (!transientGitHubFailure(error)) throw error;
|
|
110
|
+
const delay = retryDelay(attempts);
|
|
111
|
+
if (delay === null) throw new TransientGitHubError(attempts, error);
|
|
112
|
+
Bun.sleepSync(delay);
|
|
113
|
+
if (recheck()) return;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { loadConfig, type RequiredCheck } from "../config";
|
|
2
|
-
import {
|
|
2
|
+
import { runRead } from "../git/prContext";
|
|
3
|
+
import { assert, json, nativeBranch, option, output, repository } from "./core";
|
|
3
4
|
|
|
4
5
|
/** The health of a branch's tip: one of four closed states. */
|
|
5
6
|
export type BaseHealthStatus = "green" | "red" | "pending" | "no-ci";
|
|
@@ -113,7 +114,7 @@ export function baseHealthCommand(args: string[]): number {
|
|
|
113
114
|
const required = loadConfig().merge.requiredChecks;
|
|
114
115
|
// Every page, one entry per line, so a failing required check is never past the first page. Required
|
|
115
116
|
// checks are check runs or, for external CI, commit status contexts; the combined status keeps each context's latest.
|
|
116
|
-
const lines = (args: string[]) =>
|
|
117
|
+
const lines = (args: string[]) => runRead("gh", args).split("\n").filter(Boolean).map(line => JSON.parse(line) as CheckRun);
|
|
117
118
|
const checkRuns: CheckRun[] = required.length ? [
|
|
118
119
|
...lines(["api", "--paginate", `repos/${name}/commits/${tip}/check-runs?per_page=100`, "--jq", ".check_runs[] | {name, status, conclusion, url: .html_url}"]),
|
|
119
120
|
...lines(["api", "--paginate", `repos/${name}/commits/${tip}/status?per_page=100`, "--jq", '.statuses[] | {name: .context, status: (if .state == "pending" then "in_progress" else "completed" end), conclusion: (if .state == "success" then "success" elif .state == "pending" then null else .state end), url: .target_url}']),
|
|
@@ -127,7 +128,7 @@ export function baseHealthCommand(args: string[]): number {
|
|
|
127
128
|
if (status === "no-ci") notes.push(`No push-triggered workflow ran on ${branch} within the last ${limit} runs; this repository lacks CI on pushes to it.`);
|
|
128
129
|
else if (!tipHasRuns) notes.push(`No push run has started on the tip yet, or path filters skipped it; workflows show their latest run on ${branch}.`);
|
|
129
130
|
const failingRuns = latest.filter(run => outcome(run.status, run.conclusion) === "failing");
|
|
130
|
-
const failingJobs: FailingJob[] = failingRuns.flatMap(run =>
|
|
131
|
+
const failingJobs: FailingJob[] = failingRuns.flatMap(run => runRead("gh", ["api", "--paginate", `repos/${name}/actions/runs/${run.id}/jobs?per_page=100`, "--jq", ".jobs[] | {id, name, status, conclusion, url: .html_url}"]).split("\n").filter(Boolean).map(line => JSON.parse(line) as Job)
|
|
131
132
|
.filter(job => outcome(job.status, job.conclusion) === "failing")
|
|
132
133
|
.map(job => ({ workflow: run.name, runId: run.id, runUrl: run.url, headOid: run.headSha, job: job.name, jobId: job.id, url: job.url, conclusion: job.conclusion })));
|
|
133
134
|
// A failing required check outside those runs (another app, or a run beyond the window) is listed by its own link.
|
package/src/workflows/core.ts
CHANGED
|
@@ -2,7 +2,9 @@ import { spawnSync } from "node:child_process";
|
|
|
2
2
|
import { lstatSync, realpathSync, writeSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { gitEnvironment } from "../git/environment";
|
|
5
|
+
import { runRead } from "../git/prContext";
|
|
5
6
|
import { boundedExecFileSync, withCallDeadline } from "../system/boundedCalls";
|
|
7
|
+
import { TransientGitHubError } from "../system/githubRetry";
|
|
6
8
|
|
|
7
9
|
export function output(value: unknown): void { writeSync(1, `${JSON.stringify(value, null, 2)}\n`); }
|
|
8
10
|
export function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); }
|
|
@@ -11,7 +13,8 @@ export function read(command: string, args: string[], cwd = process.cwd()): stri
|
|
|
11
13
|
return boundedExecFileSync(command, args, { cwd, env: gitEnvironment(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trimEnd();
|
|
12
14
|
}
|
|
13
15
|
export function git(args: string[], cwd = process.cwd()): string { return read("git", args, cwd); }
|
|
14
|
-
|
|
16
|
+
/** A read-only `gh` call's JSON output; transient failures are retried (`runRead`), so never pass a mutation. */
|
|
17
|
+
export function json<T>(args: string[]): T { return JSON.parse(runRead("gh", args)) as T; }
|
|
15
18
|
/**
|
|
16
19
|
* Mutating Git commands deliberately retain normal hooks and their environment.
|
|
17
20
|
* This one streams Git's and its hooks' output to stderr for commands people
|
|
@@ -110,13 +113,23 @@ export function timeoutOptions(args: string[], defaultSeconds = 900): { timeoutM
|
|
|
110
113
|
assert(Number.isFinite(seconds) && seconds >= 0 && seconds <= 86400 && Number.isFinite(interval) && interval >= 1 && interval <= 60, "Timeout must be 0–86400 seconds and interval 1–60 seconds.");
|
|
111
114
|
return { timeoutMs: seconds * 1000, intervalMs: interval * 1000 };
|
|
112
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Inspect until done or the deadline passes. An inspection whose GitHub read
|
|
118
|
+
* still failed transiently after its retries is a missed observation rather
|
|
119
|
+
* than a failed wait while time remains; at the deadline its error is thrown.
|
|
120
|
+
*/
|
|
113
121
|
export async function poll<T>(inspect: () => { done: boolean; value: T } | Promise<{ done: boolean; value: T }>, options: { timeoutMs: number; intervalMs: number }): Promise<T> {
|
|
114
122
|
const deadline = Date.now() + options.timeoutMs;
|
|
115
123
|
while (true) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
124
|
+
let result: { done: boolean; value: T } | undefined;
|
|
125
|
+
try {
|
|
126
|
+
// Each external call inside an inspection is bounded too, so a hung one cannot outlast the wait.
|
|
127
|
+
result = await withCallDeadline(deadline, inspect);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (!(error instanceof TransientGitHubError) || Date.now() >= deadline) throw error;
|
|
130
|
+
}
|
|
131
|
+
if (result?.done) return result.value;
|
|
132
|
+
if (result) assert(Date.now() < deadline, `Timed out waiting: ${JSON.stringify(result.value)} Pass --timeout <seconds> to wait longer.`);
|
|
120
133
|
await new Promise(resolve => setTimeout(resolve, Math.min(options.intervalMs, deadline - Date.now())));
|
|
121
134
|
}
|
|
122
135
|
}
|
package/src/workflows/pr.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { assertStrictBaseFreshness } from "../pr/baseFreshness";
|
|
|
10
10
|
import { baseFreshness, behindReason, cancelRuns } from "./prFreshness";
|
|
11
11
|
import { resolvePullRequestMergeTarget, squashMerge } from "../pr/squashMerge";
|
|
12
12
|
import { planVersions } from "../version/bumpVersions";
|
|
13
|
-
import { assert, clean, currentBranch, git, head, json, oid, option, flag, output, poll, timeoutOptions } from "./core";
|
|
13
|
+
import { assert, clean, currentBranch, git, head, json, oid, option, flag, output, poll, read, timeoutOptions } from "./core";
|
|
14
14
|
|
|
15
15
|
export interface PullRequest {
|
|
16
16
|
number: number; url: string; state: string; title: string; headRefName: string; headRefOid: string;
|
|
@@ -157,8 +157,10 @@ export function mergeReviewedHead(rootDir: string, subject: string | undefined,
|
|
|
157
157
|
interface Comment { id: string; databaseId: number; body: string; url: string; author: { login: string } | null }
|
|
158
158
|
interface Page<T> { nodes: T[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
|
|
159
159
|
interface Thread { id: string; isResolved: boolean; isOutdated: boolean; path: string; line: number | null; comments: Page<Comment> }
|
|
160
|
-
|
|
161
|
-
|
|
160
|
+
/** A GraphQL query, retried after a transient failure, or a mutation, which is sent once. */
|
|
161
|
+
function graphql<T>(query: string, variables: Record<string, string | number>, mutation = false): T {
|
|
162
|
+
const args = ["api", "graphql", "-f", `query=${query}`, ...Object.entries(variables).flatMap(([key, value]) => [typeof value === "number" ? "-F" : "-f", `${key}=${value}`])];
|
|
163
|
+
const response = (mutation ? JSON.parse(read("gh", args)) : json(args)) as { data?: T; errors?: unknown[] };
|
|
162
164
|
assert(response.data && !response.errors?.length, "GitHub GraphQL response was incomplete.");
|
|
163
165
|
return response.data;
|
|
164
166
|
}
|
|
@@ -207,7 +209,7 @@ function threadsCommand(args: string[]): number {
|
|
|
207
209
|
const thread = reviewThreads(identity).find(thread => thread.id === args[0]);
|
|
208
210
|
assert(thread, "Thread does not belong to this PR.");
|
|
209
211
|
if (thread.isResolved) { output({ id: thread.id, isResolved: true, changed: false }); return 0; }
|
|
210
|
-
output(graphql("mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id isResolved}}}", { id: thread.id })); return 0;
|
|
212
|
+
output(graphql("mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id isResolved}}}", { id: thread.id }, true)); return 0;
|
|
211
213
|
}
|
|
212
214
|
|
|
213
215
|
export async function prWorkflowCommand(args: string[]): Promise<number> {
|
|
@@ -2,7 +2,8 @@ import { spawnSync } from "node:child_process";
|
|
|
2
2
|
import { existsSync, readFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { loadConfig } from "../config";
|
|
5
|
-
import { remoteBranchHead, resolveFreshBaseRef, resolveRepositoryGitUrl } from "../git/prContext";
|
|
5
|
+
import { remoteBranchHead, resolveFreshBaseRef, resolveRepositoryGitUrl, runRead } from "../git/prContext";
|
|
6
|
+
import { retryCheckedGitHubMutation, retryGitHubResult } from "../system/githubRetry";
|
|
6
7
|
import { viewCurrentBranchPr } from "../git/currentBranchPr";
|
|
7
8
|
import { assert, clean, currentBranch, flag, git, head, mutateGitCaptured, oid, output, read, repository } from "./core";
|
|
8
9
|
import { pullRequest } from "./pr";
|
|
@@ -46,12 +47,13 @@ export function repoCommand(args: string[]): number {
|
|
|
46
47
|
const url = resolveRepositoryGitUrl(repo.nameWithOwner);
|
|
47
48
|
const remoteFeature = remoteBranchHead(url, pr.headRefName);
|
|
48
49
|
assert(!remoteFeature || remoteFeature === shipped, "Remote feature branch moved beyond the shipped HEAD.");
|
|
49
|
-
const
|
|
50
|
+
const mergeOid = pr.mergeCommit.oid;
|
|
51
|
+
const plan = { repo: repo.nameWithOwner, pr: pr.number, mergeOid, shippedHead: shipped, defaultBranch, featureBranch: pr.headRefName, keepBranch: keep };
|
|
50
52
|
if (!apply) { output({ ...plan, applied: false }); return 0; }
|
|
51
53
|
const completed: string[] = [];
|
|
52
54
|
try {
|
|
53
55
|
const defaultOid = resolveFreshBaseRef(repo.nameWithOwner, defaultBranch);
|
|
54
|
-
assert(git(["merge-base", defaultOid,
|
|
56
|
+
assert(git(["merge-base", defaultOid, mergeOid]) === mergeOid, "Default branch does not contain the confirmed merge commit.");
|
|
55
57
|
const localDefault = spawnSync("git", ["rev-parse", "--verify", `refs/heads/${defaultBranch}`], { encoding: "utf8" });
|
|
56
58
|
if (localDefault.status === 0) {
|
|
57
59
|
assert(git(["merge-base", localDefault.stdout.trim(), defaultOid]) === localDefault.stdout.trim(), "Local default branch diverged; preserve it for inspection.");
|
|
@@ -69,7 +71,14 @@ export function repoCommand(args: string[]): number {
|
|
|
69
71
|
assert(!live || live === shipped, "Remote feature branch changed before deletion.");
|
|
70
72
|
if (live) {
|
|
71
73
|
// REST avoids pre-push hooks. GitHub has no expected-OID delete guard.
|
|
72
|
-
read("gh", ["api", "--method", "DELETE", `repos/${repo.nameWithOwner}/git/refs/heads/${encodeURIComponent(pr.headRefName)}`]);
|
|
74
|
+
retryCheckedGitHubMutation(() => { read("gh", ["api", "--method", "DELETE", `repos/${repo.nameWithOwner}/git/refs/heads/${encodeURIComponent(pr.headRefName)}`]); }, () => {
|
|
75
|
+
// A delete that failed in transit may have landed: confirm the merge and the ref again before resending it.
|
|
76
|
+
const current = pullRequest(args[0], repo.nameWithOwner);
|
|
77
|
+
assert(current.state === "MERGED" && current.headRefOid === shipped && current.mergeCommit?.oid === mergeOid, "PR is no longer confirmed MERGED at the shipped HEAD; not retrying the remote branch deletion.");
|
|
78
|
+
const remote = remoteBranchHead(url, pr.headRefName);
|
|
79
|
+
assert(!remote || remote === shipped, "Remote feature branch changed before deletion.");
|
|
80
|
+
return !remote;
|
|
81
|
+
});
|
|
73
82
|
completed.push("deleted-remote-branch");
|
|
74
83
|
}
|
|
75
84
|
}
|
|
@@ -81,8 +90,8 @@ export function policyCommand(args: string[]): number {
|
|
|
81
90
|
assert(args.length === 1 && args[0] === "check", "Usage: policy check");
|
|
82
91
|
const repo = repository();
|
|
83
92
|
const branch = repo.defaultBranchRef.name;
|
|
84
|
-
const rules =
|
|
85
|
-
const protection = spawnSync("gh", ["api", `repos/${repo.nameWithOwner}/branches/${encodeURIComponent(branch)}/protection`], { encoding: "utf8" });
|
|
93
|
+
const rules = runRead("gh", ["api", "--paginate", `repos/${repo.nameWithOwner}/rules/branches/${encodeURIComponent(branch)}`, "--jq", ".[]"]).split("\n").filter(Boolean).map((line): unknown => JSON.parse(line));
|
|
94
|
+
const protection = retryGitHubResult(() => spawnSync("gh", ["api", `repos/${repo.nameWithOwner}/branches/${encodeURIComponent(branch)}/protection`], { encoding: "utf8" }));
|
|
86
95
|
assert(protection.status === 0 || /HTTP 404/.test(protection.stderr), "Could not read classic branch protection.");
|
|
87
96
|
const classic = protection.status === 0 ? JSON.parse(protection.stdout) as { required_status_checks?: { contexts?: string[]; checks?: { context: string }[]; strict?: boolean } } : null;
|
|
88
97
|
const required = new Set<string>(classic?.required_status_checks?.contexts ?? []);
|