@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.17
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.mjs +332 -5
- package/src/deep-scan/docker-driver.mjs +70 -3
- package/src/deep-scan/lifecycle.mjs +2 -2
- package/src/deep-scan/sbx-driver.mjs +34 -47
- package/src/doctor.mjs +53 -1
- package/src/exec.mjs +18 -5
- package/src/factory/budget/budget.mjs +260 -0
- package/src/factory/build/command.mjs +321 -0
- package/src/factory/build/factory.mjs +473 -0
- package/src/factory/build/findings.mjs +55 -0
- package/src/factory/build/host.mjs +230 -0
- package/src/factory/build/notes.mjs +191 -0
- package/src/factory/build/pull-request.mjs +74 -0
- package/src/factory/bundle.mjs +146 -0
- package/src/factory/checks/allowed-paths.mjs +50 -0
- package/src/factory/checks/plan-header.mjs +296 -0
- package/src/factory/checks/qa.mjs +85 -0
- package/src/factory/checks/review.mjs +73 -0
- package/src/factory/checks/security.mjs +50 -0
- package/src/factory/checks/stage-check.mjs +89 -0
- package/src/factory/claims/command.mjs +187 -0
- package/src/factory/claims/release.mjs +111 -0
- package/src/factory/decision/answers.mjs +103 -0
- package/src/factory/decision/command.mjs +64 -0
- package/src/factory/decision/plan.mjs +99 -0
- package/src/factory/decision/request.mjs +116 -0
- package/src/factory/doctor/files.mjs +349 -0
- package/src/factory/doctor/index.mjs +56 -0
- package/src/factory/doctor/local.mjs +513 -0
- package/src/factory/doctor/orchestrate.mjs +146 -0
- package/src/factory/engine/lease.mjs +146 -0
- package/src/factory/engine/local-engine.mjs +177 -0
- package/src/factory/engine/lockfile.mjs +64 -0
- package/src/factory/engine/workflow-engine.mjs +124 -0
- package/src/factory/gate/comment.mjs +88 -0
- package/src/factory/gate/config.mjs +57 -0
- package/src/factory/gate/gate-core.mjs +250 -0
- package/src/factory/gate/guarded.mjs +17 -0
- package/src/factory/gate/reads.mjs +105 -0
- package/src/factory/gate/task.mjs +193 -0
- package/src/factory/gate/trip-reads.mjs +82 -0
- package/src/factory/gate/trip.mjs +87 -0
- package/src/factory/init/blueprint.mjs +181 -0
- package/src/factory/init/index.mjs +338 -0
- package/src/factory/labels/evidence.mjs +162 -0
- package/src/factory/labels/moves.mjs +32 -0
- package/src/factory/labels/reconcile.mjs +267 -0
- package/src/factory/labels/revert.mjs +87 -0
- package/src/factory/labels/timeline.mjs +72 -0
- package/src/factory/labels/voided.mjs +59 -0
- package/src/factory/limits/harness.mjs +39 -0
- package/src/factory/limits/limits.mjs +131 -0
- package/src/factory/merge/command.mjs +172 -0
- package/src/factory/outbox/check.mjs +240 -0
- package/src/factory/outbox/rulings.mjs +195 -0
- package/src/factory/plan/command.mjs +66 -0
- package/src/factory/plan/comment.mjs +156 -0
- package/src/factory/plan/publish.mjs +149 -0
- package/src/factory/plan/risk.mjs +153 -0
- package/src/factory/qa/command.mjs +301 -0
- package/src/factory/qa/decide.mjs +86 -0
- package/src/factory/qa/report.mjs +50 -0
- package/src/factory/records/engine-record.mjs +133 -0
- package/src/factory/records/main.mjs +96 -0
- package/src/factory/records/record.mjs +226 -0
- package/src/factory/records/sink.mjs +57 -0
- package/src/factory/report/build.mjs +92 -0
- package/src/factory/report/command.mjs +80 -0
- package/src/factory/report/facts.mjs +226 -0
- package/src/factory/report/gate-section.mjs +122 -0
- package/src/factory/report/metrics.mjs +111 -0
- package/src/factory/report/reads.mjs +246 -0
- package/src/factory/report/render.mjs +121 -0
- package/src/factory/report/rollout.mjs +154 -0
- package/src/factory/review/brief.mjs +195 -0
- package/src/factory/review/command.mjs +182 -0
- package/src/factory/run/awake.mjs +70 -0
- package/src/factory/run/collect.mjs +77 -0
- package/src/factory/run/command.mjs +556 -0
- package/src/factory/run/gh.mjs +46 -0
- package/src/factory/run/launch.mjs +66 -0
- package/src/factory/run/pipelines.mjs +694 -0
- package/src/factory/run/raw.mjs +96 -0
- package/src/factory/run/restart.mjs +83 -0
- package/src/factory/run/s3.mjs +193 -0
- package/src/factory/run/secrets.mjs +142 -0
- package/src/factory/run/teardown.mjs +242 -0
- package/src/factory/run/token.mjs +70 -0
- package/src/factory/run/worktree.mjs +160 -0
- package/src/factory/security/audit.mjs +353 -0
- package/src/factory/security/command.mjs +157 -0
- package/src/factory/setup/app.mjs +122 -0
- package/src/factory/setup/command.mjs +472 -0
- package/src/factory/setup/labels.mjs +25 -0
- package/src/factory/setup/reads.mjs +159 -0
- package/src/factory/setup/writes.mjs +138 -0
- package/src/factory/snapshot/write.mjs +176 -0
- package/src/factory/stop/command.mjs +136 -0
- package/src/factory/sweep/actions-main.mjs +119 -0
- package/src/factory/sweep/command.mjs +65 -0
- package/src/factory/sweep/knobs.mjs +78 -0
- package/src/factory/sweep/marker-version.mjs +15 -0
- package/src/factory/sweep/markers.mjs +112 -0
- package/src/factory/sweep/overlap.mjs +24 -0
- package/src/factory/sweep/run.mjs +198 -0
- package/src/factory/sweep/shell.mjs +398 -0
- package/src/factory/sweep/split.mjs +104 -0
- package/src/factory/sweep/states.mjs +87 -0
- package/src/factory/sweep/sweep-core.mjs +2009 -0
- package/src/factory/tracker/github.mjs +713 -0
- package/src/factory/tracker/operations.mjs +153 -0
- package/src/factory/upgrade/index.mjs +83 -0
- package/src/init.mjs +62 -24
- package/src/kit-owned-paths.mjs +1 -1
- package/src/stage/build.mjs +100 -0
- package/src/stage/factory-live.mjs +288 -0
- package/src/stage.mjs +100 -4
- package/src/upgrade.mjs +39 -7
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// What the Orchestrate engine does when a Stage run ends, whatever ended it (#523):
|
|
2
|
+
//
|
|
3
|
+
// result the pipeline returned
|
|
4
|
+
// expiry the sweep cancelled it because its Claim expired
|
|
5
|
+
// cancel the sweep cancelled it for another reason (a pause, a withdrawal)
|
|
6
|
+
// drain the drain's time ran out, or the second Ctrl-C
|
|
7
|
+
// restart the next engine start found the run's folder and no process
|
|
8
|
+
//
|
|
9
|
+
// In that order of independence, each step catching its own failure so one cannot stop
|
|
10
|
+
// the next: (1) the run folder is collected under the home directory (collect.mjs),
|
|
11
|
+
// (2) it is uploaded raw, only with `--upload-raw` and never for the security Stage
|
|
12
|
+
// (raw.mjs), (3) the Stage's `run-record/2` is written to the Sink, and one
|
|
13
|
+
// per Delegation with the build run as their parent (records/engine-record.mjs).
|
|
14
|
+
// Every effect goes through injected `fs` and `fetch`. The Sink token lives in `sink`
|
|
15
|
+
// and the S3 keys in `s3`, closures this module never reads out.
|
|
16
|
+
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
delegationRunIdOf,
|
|
21
|
+
buildEngineRecord,
|
|
22
|
+
runIdOf,
|
|
23
|
+
writeEngineRecord,
|
|
24
|
+
} from "../records/engine-record.mjs";
|
|
25
|
+
import { uploadRawFolder } from "./raw.mjs";
|
|
26
|
+
import { collectRunFolder, leftoverFolders, pruneCollected } from "./collect.mjs";
|
|
27
|
+
|
|
28
|
+
export const TEARDOWN_KINDS = Object.freeze(["result", "expiry", "cancel", "drain", "restart"]);
|
|
29
|
+
const SHA = /^[0-9a-f]{40}$/;
|
|
30
|
+
const CHECK_STATES = ["pending", "success", "failure", "error"];
|
|
31
|
+
const CHECKED = ["review", "qa", "security"];
|
|
32
|
+
|
|
33
|
+
/** The working folder's name for a Claim nonce, as `runDir` makes it. */
|
|
34
|
+
const folderOf = (claim) => String(claim).replace(/[^A-Za-z0-9._-]/g, "_");
|
|
35
|
+
const message = (error) => (error instanceof Error ? error.message : "failed");
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {{
|
|
39
|
+
* fs: object, runsDir: string, slug: string, identity: string,
|
|
40
|
+
* sink: { repo: string, token: string } | null,
|
|
41
|
+
* s3: object | null, uploadRaw: boolean,
|
|
42
|
+
* fetch: Function, now: () => number, log: (line: string) => void,
|
|
43
|
+
* }} deps
|
|
44
|
+
*/
|
|
45
|
+
export function createTeardown({
|
|
46
|
+
fs,
|
|
47
|
+
runsDir,
|
|
48
|
+
slug,
|
|
49
|
+
identity,
|
|
50
|
+
sink,
|
|
51
|
+
s3,
|
|
52
|
+
uploadRaw,
|
|
53
|
+
fetch,
|
|
54
|
+
now,
|
|
55
|
+
log,
|
|
56
|
+
}) {
|
|
57
|
+
const repo = `github.com/${slug}`;
|
|
58
|
+
const read = (path) => {
|
|
59
|
+
try {
|
|
60
|
+
return fs.readFileSync(path, "utf8");
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
async function raw({ stage, folders, tag }) {
|
|
67
|
+
if (!uploadRaw) return "raw upload off";
|
|
68
|
+
if (stage === "security") return "raw upload skipped (security)";
|
|
69
|
+
if (!s3) return "raw upload not set up";
|
|
70
|
+
const notes = [];
|
|
71
|
+
for (const { runId, dir } of folders) {
|
|
72
|
+
const done = await uploadRawFolder({ s3, fs, dir, repo, login: identity, runId, stage, log });
|
|
73
|
+
notes.push(
|
|
74
|
+
done.status === "uploaded" ? `${done.files} files` : `${done.status}: ${done.detail}`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
log(`${tag} raw upload: ${notes.join("; ")}`);
|
|
78
|
+
return "raw upload on";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function keep(record, tag) {
|
|
82
|
+
if (!sink) return "no Run Record kept (no Sink)";
|
|
83
|
+
const done = await writeEngineRecord({ sink, record, login: identity, fetch });
|
|
84
|
+
log(
|
|
85
|
+
`${tag} Run Record ${record.run.id}: ${done.status}${done.detail ? ` (${done.detail})` : ""}`,
|
|
86
|
+
);
|
|
87
|
+
return done.status;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Ends one run. `end` is what the engine gives `onTeardown`; a restart gives one
|
|
92
|
+
* with the Claim's stage and no pipeline result.
|
|
93
|
+
*/
|
|
94
|
+
async function teardown(end) {
|
|
95
|
+
const { issue, stage, attempt, claim, kind, result, trace = {} } = end;
|
|
96
|
+
const tag = `#${issue} ${stage} (${kind})`;
|
|
97
|
+
let runId;
|
|
98
|
+
try {
|
|
99
|
+
runId = runIdOf(claim);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
log(`${tag}: no run id (${message(error)}): the folder stays where it is`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const working = join(runsDir, folderOf(claim));
|
|
105
|
+
const delegations = (trace.delegations ?? []).flatMap((d) => {
|
|
106
|
+
try {
|
|
107
|
+
return [
|
|
108
|
+
{ ...d, runId: delegationRunIdOf(claim, d.id), dir: join(working, "delegations", d.id) },
|
|
109
|
+
];
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
const usage = read(join(working, "usage.json"));
|
|
115
|
+
const delegationUsage = new Map(
|
|
116
|
+
delegations.map((d) => [d.id, read(join(d.dir, "usage.json"))]),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
let folders = [];
|
|
120
|
+
try {
|
|
121
|
+
const got = collectRunFolder({
|
|
122
|
+
fs,
|
|
123
|
+
root: runsDir,
|
|
124
|
+
source: working,
|
|
125
|
+
runId,
|
|
126
|
+
delegations: delegations.map((d) => ({ runId: d.runId, dir: d.dir })),
|
|
127
|
+
});
|
|
128
|
+
if (got.folder) {
|
|
129
|
+
folders = [
|
|
130
|
+
{ runId, dir: got.folder },
|
|
131
|
+
...delegations
|
|
132
|
+
.filter((d) => got.delegations.includes(join(runsDir, d.runId)))
|
|
133
|
+
.map((d) => ({ runId: d.runId, dir: join(runsDir, d.runId) })),
|
|
134
|
+
];
|
|
135
|
+
log(`${tag}: run folder kept at ${got.folder}`);
|
|
136
|
+
}
|
|
137
|
+
} catch (error) {
|
|
138
|
+
log(`${tag}: the run folder could not be collected (${message(error)})`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let rawState = uploadRaw ? "raw upload on" : "raw upload off";
|
|
142
|
+
try {
|
|
143
|
+
rawState = await raw({ stage, folders, tag });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
log(`${tag}: raw upload failed (${message(error)})`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
const head = trace.head ?? result?.head ?? null;
|
|
150
|
+
// A state the record does not know (a check can say anything) is no Stage check, not a lost record.
|
|
151
|
+
const stageCheck =
|
|
152
|
+
CHECKED.includes(stage) && CHECK_STATES.includes(result?.state) ? result.state : null;
|
|
153
|
+
const base = { repo, task: issue, attempt, rawUpload: uploadRaw, now: now() };
|
|
154
|
+
// Each record stands alone: one that cannot be built never costs the others.
|
|
155
|
+
const records = [
|
|
156
|
+
...delegations.map((d) => ({
|
|
157
|
+
...base,
|
|
158
|
+
runId: d.runId,
|
|
159
|
+
parentRunId: runId,
|
|
160
|
+
stage: "build",
|
|
161
|
+
code: d.code ?? null,
|
|
162
|
+
usageText: delegationUsage.get(d.id),
|
|
163
|
+
})),
|
|
164
|
+
{
|
|
165
|
+
...base,
|
|
166
|
+
runId,
|
|
167
|
+
stage,
|
|
168
|
+
headSha: typeof head === "string" && SHA.test(head) ? head : null,
|
|
169
|
+
stageCheck,
|
|
170
|
+
code: trace.launcherCode ?? null,
|
|
171
|
+
usageText: usage,
|
|
172
|
+
},
|
|
173
|
+
];
|
|
174
|
+
for (const input of records) {
|
|
175
|
+
try {
|
|
176
|
+
await keep(buildEngineRecord(input), tag);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
log(`${tag}: no Run Record was kept for ${input.runId} (${message(error)})`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
} catch (error) {
|
|
182
|
+
log(`${tag}: no Run Record was kept (${message(error)})`);
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
pruneCollected({ fs, root: runsDir, now: now() });
|
|
186
|
+
} catch {
|
|
187
|
+
// expiry is retried at the next teardown and the next start
|
|
188
|
+
}
|
|
189
|
+
log(`${tag}: ${rawState}`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Start-up: collects every working folder a dead run left (the Claims `left` it released
|
|
194
|
+
* tell which Stage and Attempt each was), writes its record as `no-result`, then prunes
|
|
195
|
+
* the collected folders past their expiry.
|
|
196
|
+
*/
|
|
197
|
+
async function restart({ left }) {
|
|
198
|
+
for (const name of leftoverFolders({ fs, root: runsDir })) {
|
|
199
|
+
const claim = left.find((c) => folderOf(c.claim) === name);
|
|
200
|
+
const delegations = [];
|
|
201
|
+
try {
|
|
202
|
+
const dir = join(runsDir, name, "delegations");
|
|
203
|
+
if (fs.existsSync(dir))
|
|
204
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true }))
|
|
205
|
+
if (e.isDirectory()) delegations.push({ id: e.name, code: null });
|
|
206
|
+
} catch {
|
|
207
|
+
// the folder is collected without its Delegations' records
|
|
208
|
+
}
|
|
209
|
+
if (claim) {
|
|
210
|
+
await teardown({
|
|
211
|
+
issue: claim.issue,
|
|
212
|
+
stage: claim.stage,
|
|
213
|
+
attempt: claim.attempt,
|
|
214
|
+
claim: name,
|
|
215
|
+
kind: "restart",
|
|
216
|
+
trace: { delegations },
|
|
217
|
+
});
|
|
218
|
+
} else {
|
|
219
|
+
// No open Claim names it: the folder is kept, with no record (its Stage is unknown).
|
|
220
|
+
try {
|
|
221
|
+
collectRunFolder({
|
|
222
|
+
fs,
|
|
223
|
+
root: runsDir,
|
|
224
|
+
source: join(runsDir, name),
|
|
225
|
+
runId: runIdOf(name),
|
|
226
|
+
});
|
|
227
|
+
log(`restart: run folder ${name} kept at ${join(runsDir, runIdOf(name))}`);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
log(`restart: run folder ${name} could not be collected (${message(error)})`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const removed = pruneCollected({ fs, root: runsDir, now: now() });
|
|
235
|
+
if (removed.length) log(`restart: removed ${removed.length} expired run folder(s)`);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
log(`restart: expired run folders could not be removed (${message(error)})`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return { teardown, restart };
|
|
242
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The token's reach (ADR 0039): the engine refuses a token it can tell reaches more than
|
|
2
|
+
// this one repository. A classic token (`ghp_...`, or any answer carrying an
|
|
3
|
+
// `X-OAuth-Scopes` header) reaches every repository its owner can. A fine-grained token
|
|
4
|
+
// is asked which repositories it lists (`GET /user/repos`): more than the one named, or
|
|
5
|
+
// a different one, is refused. A token whose reach cannot be read is let through with a
|
|
6
|
+
// notice; a fine-grained token's own settings still bound it.
|
|
7
|
+
|
|
8
|
+
import { PAT_PERMISSIONS, patPermissionsSummary } from "../setup/command.mjs";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string, token: string, permissions?: typeof PAT_PERMISSIONS }} deps
|
|
12
|
+
* @returns {{ login: string, notice?: string } | { refused: string }}
|
|
13
|
+
*/
|
|
14
|
+
export function checkToken({ gh, repo, token, permissions = PAT_PERMISSIONS }) {
|
|
15
|
+
if (token.startsWith("ghp_")) {
|
|
16
|
+
return {
|
|
17
|
+
refused: `the token is a classic token, which reaches every repository its owner can, not only ${repo}: make a fine-grained token for this one repository`,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const who = gh(["api", "-i", "user"]);
|
|
21
|
+
if (who.status !== 0) {
|
|
22
|
+
return {
|
|
23
|
+
refused: `GitHub did not accept the token (gh api user): ${String(who.stderr).trim().slice(0, 200)}`,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const split = String(who.stdout).split(/\r?\n\r?\n/);
|
|
27
|
+
const headers = split[0] ?? "";
|
|
28
|
+
let login;
|
|
29
|
+
try {
|
|
30
|
+
login = JSON.parse(split.slice(1).join("\n\n")).login;
|
|
31
|
+
} catch {
|
|
32
|
+
login = undefined;
|
|
33
|
+
}
|
|
34
|
+
if (!login) return { refused: "GitHub did not say whose token this is (gh api user)" };
|
|
35
|
+
if (/^x-oauth-scopes:/im.test(headers)) {
|
|
36
|
+
return {
|
|
37
|
+
refused: `the token is a classic token (it carries OAuth scopes), which reaches every repository ${login} can, not only ${repo}: make a fine-grained token for this one repository`,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const listed = gh(["api", "user/repos?per_page=100", "--paginate", "--slurp"]);
|
|
41
|
+
if (listed.status !== 0) {
|
|
42
|
+
return {
|
|
43
|
+
login,
|
|
44
|
+
notice: `the token's reach could not be read (${String(listed.stderr).trim().slice(0, 120)}): make sure it names ${repo} alone`,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
let names;
|
|
48
|
+
try {
|
|
49
|
+
names = JSON.parse(listed.stdout || "[]")
|
|
50
|
+
.flat()
|
|
51
|
+
.map((r) => String(r.full_name).toLowerCase());
|
|
52
|
+
} catch {
|
|
53
|
+
return {
|
|
54
|
+
login,
|
|
55
|
+
notice: "the token's reach could not be read: make sure it names this repository alone",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const here = names.includes(repo.toLowerCase());
|
|
59
|
+
const others = names.filter((n) => n !== repo.toLowerCase());
|
|
60
|
+
if (others.length > 0) {
|
|
61
|
+
return {
|
|
62
|
+
refused: `the token reaches ${names.length} repositories (also ${others.slice(0, 3).join(", ")}${others.length > 3 ? ", ..." : ""}), not only ${repo}: make a fine-grained token for this one repository`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (!here)
|
|
66
|
+
return {
|
|
67
|
+
refused: `the token does not reach ${repo}: it needs ${patPermissionsSummary(permissions)} there`,
|
|
68
|
+
};
|
|
69
|
+
return { login };
|
|
70
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// A checkout for one Stage call: a detached worktree of the host's repository at one commit
|
|
2
|
+
// (the pull request's head), made by the engine and removed by it when the Stage is done,
|
|
3
|
+
// whether it succeeded, failed or was cancelled. The host's own checkout, index and branch
|
|
4
|
+
// are never moved, so a Stage that judges a pull request's code runs on that code wherever
|
|
5
|
+
// the host's checkout sits.
|
|
6
|
+
|
|
7
|
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
9
|
+
|
|
10
|
+
import { gitSafetyArgs } from "../../local-tree.mjs";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Config for every git call here: no hook runs (a repository's `core.hooksPath` may be relative,
|
|
14
|
+
* so git would resolve it inside the pull request's own tree), no fsmonitor, no automatic gc or
|
|
15
|
+
* maintenance (which also prunes worktree entries), and every filter driver in the host's git
|
|
16
|
+
* config is blanked (git-lfs, git-crypt, nbstripout, any other): the head's own `.gitattributes`
|
|
17
|
+
* chooses the driver and the files it runs on, so an unblanked driver would run a program on the
|
|
18
|
+
* pull request's say. The Kit's own `gitSafetyArgs` builds the list; a checkout also needs
|
|
19
|
+
* `smudge` blanked, which that helper leaves alone, so the keys are added on top. A listing that
|
|
20
|
+
* fails (other than "no filter configured") or a driver name git cannot be told to turn off
|
|
21
|
+
* throws: the checkout is held, never made with a driver left on.
|
|
22
|
+
*/
|
|
23
|
+
function safeArgs(runner, cwd, noHooks) {
|
|
24
|
+
const listed = runner("git", ["config", "--name-only", "--get-regexp", "^filter\\."], { cwd });
|
|
25
|
+
if (listed.status !== 0 && listed.status !== 1) {
|
|
26
|
+
throw new Error("the git filter drivers could not be listed");
|
|
27
|
+
}
|
|
28
|
+
// Parsed here, not with the helper's `filterDrivers`, whose `.` skips a name holding a CR: that
|
|
29
|
+
// driver would stay on, unseen. A name git cannot be told to turn off is refused, never skipped.
|
|
30
|
+
const drivers = new Set(["lfs"]);
|
|
31
|
+
if (listed.status === 0) {
|
|
32
|
+
for (const key of String(listed.stdout ?? "").split("\n")) {
|
|
33
|
+
const m = /^filter\.([\s\S]+)\.[^.]+$/i.exec(key.trim());
|
|
34
|
+
if (!m) continue;
|
|
35
|
+
if (/[=\r\n]/.test(m[1])) {
|
|
36
|
+
throw new Error(`cannot turn off git filter driver ${JSON.stringify(m[1])}`);
|
|
37
|
+
}
|
|
38
|
+
drivers.add(m[1]);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const args = gitSafetyArgs({ runner, root: cwd, noHooks });
|
|
42
|
+
for (const d of drivers)
|
|
43
|
+
args.push(
|
|
44
|
+
"-c",
|
|
45
|
+
`filter.${d}.smudge=`,
|
|
46
|
+
"-c",
|
|
47
|
+
`filter.${d}.process=`,
|
|
48
|
+
"-c",
|
|
49
|
+
`filter.${d}.clean=`,
|
|
50
|
+
"-c",
|
|
51
|
+
`filter.${d}.required=false`,
|
|
52
|
+
);
|
|
53
|
+
return args;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A checkout older than this was left by a run that was killed: the sweep removes it. */
|
|
57
|
+
const STALE_MS = 24 * 60 * 60 * 1000;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {{ runner: Function, cwd: string, tmpDir: string, fetchUrl: string, fetchEnv?: Record<string,string>, fs?: object }} deps
|
|
61
|
+
* @returns {(sha: string) => { path: string, git: (args: string[]) => object, remove: () => void } | { error: string }}
|
|
62
|
+
*/
|
|
63
|
+
export function createCheckouts({ runner, cwd, tmpDir, fetchUrl, fetchEnv, fs = {} }) {
|
|
64
|
+
const mkdtemp = fs.mkdtempSync ?? mkdtempSync;
|
|
65
|
+
const rm = fs.rmSync ?? rmSync;
|
|
66
|
+
const mkdir = fs.mkdirSync ?? mkdirSync;
|
|
67
|
+
const stat = fs.statSync ?? statSync;
|
|
68
|
+
const readdir = fs.readdirSync ?? readdirSync;
|
|
69
|
+
|
|
70
|
+
return (sha) => {
|
|
71
|
+
if (!/^[0-9a-f]{40}$/i.test(String(sha)))
|
|
72
|
+
return { error: "the pull request's head is not a commit" };
|
|
73
|
+
let safe;
|
|
74
|
+
try {
|
|
75
|
+
const noHooks = resolve(tmpDir, "no-hooks");
|
|
76
|
+
mkdir(noHooks, { recursive: true, mode: 0o700 });
|
|
77
|
+
safe = safeArgs(runner, cwd, noHooks);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return { error: `no safe git for the checkout: ${error.message}` };
|
|
80
|
+
}
|
|
81
|
+
const git = (args, opts = {}) => runner("git", [...safe, ...args], { cwd, ...opts });
|
|
82
|
+
const root = resolve(tmpDir, "worktrees");
|
|
83
|
+
let path;
|
|
84
|
+
try {
|
|
85
|
+
mkdir(root, { recursive: true, mode: 0o700 });
|
|
86
|
+
path = mkdtemp(join(root, "stage-"));
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return { error: `no directory for the checkout: ${error.message}` };
|
|
89
|
+
}
|
|
90
|
+
// Only this engine's own `stage-*` worktrees are ever touched: git drops the entry, then the
|
|
91
|
+
// directory goes. No repository-wide `git worktree prune`, which would also drop the entries
|
|
92
|
+
// of the user's own worktrees whose folders are briefly unreachable.
|
|
93
|
+
const removeOwn = (dir) => {
|
|
94
|
+
git(["worktree", "remove", "--force", dir]);
|
|
95
|
+
rm(dir, { recursive: true, force: true });
|
|
96
|
+
};
|
|
97
|
+
const cleanup = () => {
|
|
98
|
+
// Removal never replaces the Stage's own result: a failure here leaves a directory the
|
|
99
|
+
// stale sweep takes later.
|
|
100
|
+
try {
|
|
101
|
+
removeOwn(path);
|
|
102
|
+
} catch {
|
|
103
|
+
/* swept when stale */
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
// A run that was killed leaves its worktree behind: remove the engine's own, a day old.
|
|
107
|
+
try {
|
|
108
|
+
for (const name of readdir(root)) {
|
|
109
|
+
const old = join(root, name);
|
|
110
|
+
if (/^stage-/.test(name) && old !== path && Date.now() - stat(old).mtimeMs > STALE_MS)
|
|
111
|
+
removeOwn(old);
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
/* nothing to sweep */
|
|
115
|
+
}
|
|
116
|
+
const hold = (why, result) => {
|
|
117
|
+
cleanup();
|
|
118
|
+
return {
|
|
119
|
+
error: `the pull request's head ${sha.slice(0, 7)} could not be checked out: ${String(result.stderr || why).trim()}`,
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
// No checkout inside `add`, so git runs no post-checkout hook; the files come from `reset`.
|
|
123
|
+
const add = () => git(["worktree", "add", "--no-checkout", "--detach", path, sha]);
|
|
124
|
+
let added = add();
|
|
125
|
+
if (added.status !== 0) {
|
|
126
|
+
// The head may not be in the host's repository yet: fetch that one commit by URL
|
|
127
|
+
// (never the checkout's `origin`), then try again. Only a failed `add` earns the fetch.
|
|
128
|
+
const fetched = git(["fetch", "--no-tags", "--quiet", "--refmap=", fetchUrl, sha], {
|
|
129
|
+
...(fetchEnv ? { env: fetchEnv } : {}),
|
|
130
|
+
});
|
|
131
|
+
if (fetched.status === 0) added = add();
|
|
132
|
+
else {
|
|
133
|
+
// The fetch's own reason (auth, network, a head that is gone), with no secret in it: the
|
|
134
|
+
// token rides in the child's environment, and any of those values is scrubbed from the text.
|
|
135
|
+
let why = String(fetched.stderr || "git fetch failed").trim();
|
|
136
|
+
for (const secret of Object.values(fetchEnv ?? {})) {
|
|
137
|
+
for (const part of String(secret).split(/\s+/)) {
|
|
138
|
+
if (part.length >= 8) why = why.split(part).join("***");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return hold(`could not fetch the head: ${why}`, {
|
|
142
|
+
stderr: `could not fetch the head: ${why}`,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (added.status !== 0) return hold("git worktree add failed", added);
|
|
147
|
+
const filled = runner("git", [...safe, "reset", "--hard", "--quiet"], { cwd: path });
|
|
148
|
+
if (filled.status !== 0) return hold("git reset failed", filled);
|
|
149
|
+
let removed = false;
|
|
150
|
+
return {
|
|
151
|
+
path,
|
|
152
|
+
git: (args) => runner("git", [...safe, ...args], { cwd: path }),
|
|
153
|
+
remove: () => {
|
|
154
|
+
if (removed) return;
|
|
155
|
+
removed = true;
|
|
156
|
+
cleanup();
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
}
|