notusci 0.1.0 → 0.1.2
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/package.json +1 -1
- package/src/cli.mjs +83 -12
- package/src/core.mjs +112 -11
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -7,8 +7,8 @@ import { homedir, hostname } from "node:os";
|
|
|
7
7
|
import { delimiter, dirname, join } from "node:path";
|
|
8
8
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
9
9
|
import {
|
|
10
|
-
CliError, NPX, boundedWaitSeconds, buildSource, encodeSource, parseCommand, pickWorkflow, renderError,
|
|
11
|
-
repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain,
|
|
10
|
+
CliError, HELP, NPX, authFile, baseAttachment, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, parseCommand, pickWorkflow, renderError,
|
|
11
|
+
repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBaseSha, sourceIdentity,
|
|
12
12
|
} from "./core.mjs";
|
|
13
13
|
|
|
14
14
|
const DEFAULT_URL = "https://notusci-api.binh-08d.workers.dev";
|
|
@@ -17,7 +17,7 @@ const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
|
17
17
|
|
|
18
18
|
/** @param {unknown} value */
|
|
19
19
|
const print = value => process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
20
|
-
const authPath = () =>
|
|
20
|
+
const authPath = () => authFile(process.env.NOTUSCI_CONFIG_DIR, homedir());
|
|
21
21
|
|
|
22
22
|
/** @param {string} path @param {string} text */
|
|
23
23
|
function writePrivate(path, text) {
|
|
@@ -27,7 +27,7 @@ function writePrivate(path, text) {
|
|
|
27
27
|
renameSync(temp, path);
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
/** @typedef {{url: string, token?: string, state: {url?: string, token?: string, pending?: any}}} Session */
|
|
30
|
+
/** @typedef {{url: string, token?: string, state: {url?: string, token?: string, pending?: any, billing?: any}}} Session */
|
|
31
31
|
|
|
32
32
|
/** @returns {Session} */
|
|
33
33
|
function session() {
|
|
@@ -38,10 +38,12 @@ function session() {
|
|
|
38
38
|
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL_HOSTS.includes(url.hostname))) {
|
|
39
39
|
throw new CliError({ code: "usage", error: "NOTUSCI_URL must use https (http only for localhost)", next: "Fix NOTUSCI_URL and retry." });
|
|
40
40
|
}
|
|
41
|
-
|
|
41
|
+
const base = url.href.replace(/\/$/, "");
|
|
42
|
+
// A saved token goes only to the server that issued it.
|
|
43
|
+
return { url: base, token: process.env.NOTUSCI_TOKEN ?? ((state.url ?? DEFAULT_URL) === base ? state.token : undefined), state };
|
|
42
44
|
}
|
|
43
45
|
|
|
44
|
-
/** Save
|
|
46
|
+
/** Save private CLI state; a URL from NOTUSCI_URL is not persisted. @param {Session} s @param {{token?: string, pending?: any, billing?: any}} state */
|
|
45
47
|
function save(s, state) {
|
|
46
48
|
s.state = { url: process.env.NOTUSCI_URL ? s.state.url : s.url, ...state };
|
|
47
49
|
writePrivate(authPath(), `${JSON.stringify(s.state, null, 2)}\n`);
|
|
@@ -215,9 +217,35 @@ async function init(s, input) {
|
|
|
215
217
|
catch { mcp[name] = "failed"; }
|
|
216
218
|
}
|
|
217
219
|
}
|
|
220
|
+
if (input.billing) return billing(s, { repo, timeoutSeconds: 90 });
|
|
218
221
|
print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, next: `${NPX} verify` });
|
|
219
222
|
}
|
|
220
223
|
|
|
224
|
+
/** @param {Session} s @param {{repo?: string, timeoutSeconds: number}} input */
|
|
225
|
+
async function billing(s, input) {
|
|
226
|
+
const repo = repoOrOrigin(input.repo);
|
|
227
|
+
const deadline = Date.now() + input.timeoutSeconds * 1000;
|
|
228
|
+
let status = await api(s, "/api/billing", { query: { repo }, deadline });
|
|
229
|
+
if (status.status === "active") {
|
|
230
|
+
save(s, { token: s.state.token, pending: s.state.pending });
|
|
231
|
+
return print({ status: "ready", billing: status, next: `${NPX} verify` });
|
|
232
|
+
}
|
|
233
|
+
let action = s.state.billing;
|
|
234
|
+
if (!action || action.repo.toLowerCase() !== repo.toLowerCase() || new Date(action.expiresAt).getTime() <= Date.now()) {
|
|
235
|
+
action = { ...await api(s, "/api/billing/checkouts", { method: "POST", body: { repo }, deadline }), repo };
|
|
236
|
+
save(s, { token: s.state.token, pending: s.state.pending, billing: action });
|
|
237
|
+
}
|
|
238
|
+
while (Date.now() + 2_000 <= deadline) {
|
|
239
|
+
await sleep(2_000);
|
|
240
|
+
status = await api(s, "/api/billing", { query: { repo }, deadline });
|
|
241
|
+
if (status.status === "active") {
|
|
242
|
+
save(s, { token: s.state.token, pending: s.state.pending });
|
|
243
|
+
return print({ status: "ready", billing: status, next: `${NPX} verify` });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
print({ status: "action_required", action: action.action, expiresAt: action.expiresAt });
|
|
247
|
+
}
|
|
248
|
+
|
|
221
249
|
/** @param {Session} s */
|
|
222
250
|
async function doctor(s) {
|
|
223
251
|
/** @type {any[]} */
|
|
@@ -277,6 +305,38 @@ async function waitUntilReady(s, path, repo, deadline = Infinity) {
|
|
|
277
305
|
}
|
|
278
306
|
}
|
|
279
307
|
|
|
308
|
+
/** @param {Session} s @param {string} root @param {string} repo @param {string} workflow @param {number} timeoutSeconds */
|
|
309
|
+
async function verify(s, root, repo, workflow, timeoutSeconds) {
|
|
310
|
+
const baseSha = sourceBaseSha(root); const startedAt = performance.now(); const deadline = Date.now() + timeoutSeconds * 1000;
|
|
311
|
+
const base = await api(s, "/api/verify/base", { query: { repo, baseSha, workflow }, deadline });
|
|
312
|
+
if (base?.schemaVersion !== 2 || typeof base.present !== "boolean") throw new Error("invalid base probe response");
|
|
313
|
+
const source = buildSource(root, false);
|
|
314
|
+
if (source.baseSha !== baseSha) throw new Error("HEAD changed during verification upload");
|
|
315
|
+
const expectedIdentity = sourceIdentity(repo, source); const idempotencyKey = randomUUID();
|
|
316
|
+
const hint = dependencyHint(root, repo, workflow);
|
|
317
|
+
let body = { ...source, ...(hint ? { dependencyHint: hint } : {}) };
|
|
318
|
+
if (!base.present) {
|
|
319
|
+
const full = buildSource(root);
|
|
320
|
+
if (sourceIdentity(repo, full) !== expectedIdentity) throw new Error("working tree changed during verification upload");
|
|
321
|
+
body = { ...body, objects: full.objects };
|
|
322
|
+
}
|
|
323
|
+
let submitted = await api(s, "/api/verify/v2", { method: "POST", body: encodeSource(body), timeoutSeconds: 300,
|
|
324
|
+
deadline, query: { repo, workflow, idempotencyKey } });
|
|
325
|
+
if (submitted?.schemaVersion !== 2 || typeof submitted.verifyId !== "string" || submitted.sourceIdentity !== expectedIdentity
|
|
326
|
+
|| typeof submitted.baseRequired !== "boolean")
|
|
327
|
+
throw new Error("invalid Source v2 admission response");
|
|
328
|
+
if (submitted.baseRequired) {
|
|
329
|
+
const full = buildSource(root);
|
|
330
|
+
if (sourceIdentity(repo, full) !== expectedIdentity) throw new Error("working tree changed during base attachment");
|
|
331
|
+
submitted = await api(s, `/api/verifies/${submitted.verifyId}/base`, { method: "PUT", body: encodeSource(baseAttachment(full)), timeoutSeconds: 300,
|
|
332
|
+
deadline, query: { repo } });
|
|
333
|
+
if (submitted?.schemaVersion !== 2 || typeof submitted.verifyId !== "string" || submitted.sourceIdentity !== expectedIdentity || submitted.baseRequired !== false)
|
|
334
|
+
throw new Error("invalid Source v2 base attachment response");
|
|
335
|
+
}
|
|
336
|
+
const result = await waitUntilReady(s, `/api/verifies/${submitted.verifyId}/wait`, repo, deadline);
|
|
337
|
+
return { ...result, clientTiming: { probeToReadyMs: Math.round((performance.now() - startedAt) * 1000) / 1000 } };
|
|
338
|
+
}
|
|
339
|
+
|
|
280
340
|
/** Print a verify or ship result; one stopped by usage limits is also an error. @param {any} result */
|
|
281
341
|
function report(result) {
|
|
282
342
|
print(result);
|
|
@@ -289,6 +349,7 @@ async function main(s, input) {
|
|
|
289
349
|
case "init": return init(s, input);
|
|
290
350
|
case "doctor": return doctor(s);
|
|
291
351
|
case "login": return login(s, input);
|
|
352
|
+
case "billing": return billing(s, input);
|
|
292
353
|
case "logout": return logout(s);
|
|
293
354
|
case "token list": return print({ tokens: await api(s, "/api/tokens") });
|
|
294
355
|
case "token revoke":
|
|
@@ -299,16 +360,13 @@ async function main(s, input) {
|
|
|
299
360
|
let config;
|
|
300
361
|
try { config = JSON.parse(readFileSync(input.file, "utf8")); }
|
|
301
362
|
catch { throw new CliError({ code: "usage", error: `${input.file} must be a readable JSON file`, next: "Fix --file and retry." }); }
|
|
302
|
-
await api(s, `/api/repos/${repo}/target`, { method: "PUT", body: { config, digitaloceanToken: process.env.DIGITALOCEAN_TOKEN } });
|
|
363
|
+
await api(s, `/api/repos/${repo}/target`, { method: "PUT", body: { config, digitaloceanToken: process.env.DIGITALOCEAN_TOKEN, autoPromote: input.autoPromote } });
|
|
303
364
|
return print({ status: "saved", repo });
|
|
304
365
|
}
|
|
305
366
|
case "verify": {
|
|
306
367
|
const { root, repo } = gitRepo();
|
|
307
368
|
const workflow = input.workflow ?? workflowIn(root);
|
|
308
|
-
|
|
309
|
-
const { verifyId } = await api(s, "/api/verifies", { method: "POST", body: encodeSource(source), timeoutSeconds: 300,
|
|
310
|
-
query: { repo, workflow, idempotencyKey: randomUUID(), baseSha: source.baseSha } });
|
|
311
|
-
return report(await waitUntilReady(s, `/api/verifies/${verifyId}/wait`, repo, Date.now() + input.timeoutSeconds * 1000));
|
|
369
|
+
return report(await verify(s, root, repo, workflow, input.timeoutSeconds));
|
|
312
370
|
}
|
|
313
371
|
case "ship": {
|
|
314
372
|
const repo = repoOrOrigin(input.repo);
|
|
@@ -321,10 +379,23 @@ async function main(s, input) {
|
|
|
321
379
|
return print(await waitUntilReady(s, runPath(input.runId, "wait"), repo, Date.now() + input.timeoutSeconds * 1000));
|
|
322
380
|
}
|
|
323
381
|
case "failures": return print(await api(s, runPath(input.runId, "failures"), { query: { repo: repoOrOrigin(input.repo) } }));
|
|
382
|
+
case "search-logs": {
|
|
383
|
+
const kind = typeof input.runId === "string" ? "pushes" : "runs";
|
|
384
|
+
return print(await api(s, `/api/${kind}/${input.runId}/logs/search`, { query: { repo: repoOrOrigin(input.repo), query: input.query, limit: input.limit } }));
|
|
385
|
+
}
|
|
386
|
+
case "rerun-failed": {
|
|
387
|
+
const repo = repoOrOrigin(input.repo); let body;
|
|
388
|
+
try { body = JSON.parse(readFileSync(input.file, "utf8")); } catch { throw new CliError({ code: "usage", error: `${input.file} must be readable JSON`, next: "Fix --file and retry." }); }
|
|
389
|
+
return print(await api(s, `/api/agent/verifies/${input.failedVerifyId}/rerun`, { method: "POST", body: { ...body, repo } }));
|
|
390
|
+
}
|
|
324
391
|
}
|
|
325
392
|
}
|
|
326
393
|
|
|
327
|
-
try {
|
|
394
|
+
try {
|
|
395
|
+
const input = parseCommand(process.argv.slice(2));
|
|
396
|
+
if (input.command === "help") print(HELP);
|
|
397
|
+
else await main(session(), input);
|
|
398
|
+
}
|
|
328
399
|
catch (error) {
|
|
329
400
|
const body = error instanceof CliError ? error.body : { code: "error", error: error instanceof Error ? error.message : String(error) };
|
|
330
401
|
process.stderr.write(`${JSON.stringify(renderError(body))}\n`);
|
package/src/core.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { lstatSync, readFileSync, readlinkSync } from "node:fs";
|
|
3
4
|
import { Buffer } from "node:buffer";
|
|
5
|
+
import { join } from "node:path";
|
|
4
6
|
import { parseArgs } from "node:util";
|
|
5
7
|
|
|
6
8
|
const repositoryPattern = /^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/;
|
|
@@ -10,8 +12,10 @@ const MAX_TREE_BYTES = 256 * 1024 * 1024;
|
|
|
10
12
|
const MAX_PATHS = 20_000;
|
|
11
13
|
const MAX_PATH_BYTES = 1_024;
|
|
12
14
|
export const NPX = "npx -y notusci@latest";
|
|
15
|
+
/** @param {string | undefined} configDir @param {string} home */
|
|
16
|
+
export const authFile = (configDir, home) => configDir ? join(configDir, "auth.json") : join(home, ".config", "notusci", "auth.json");
|
|
13
17
|
const SCOPES = ["read", "verify", "ship:staging", "ship:prod"];
|
|
14
|
-
const DEFAULT_SCOPES = "
|
|
18
|
+
const DEFAULT_SCOPES = SCOPES.join(",");
|
|
15
19
|
|
|
16
20
|
/** An error printed as `{ error, code, next, ... }` on stderr. */
|
|
17
21
|
export class CliError extends Error {
|
|
@@ -26,18 +30,36 @@ function usage(error) {
|
|
|
26
30
|
|
|
27
31
|
/** @type {Record<string, Record<string, {type: "string" | "boolean"}>>} */
|
|
28
32
|
const OPTIONS = {
|
|
29
|
-
init: { scope: { type: "string" }, "no-mcp": { type: "boolean" } },
|
|
33
|
+
init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" } },
|
|
30
34
|
login: { scope: { type: "string" } },
|
|
31
35
|
doctor: {}, logout: {}, token: {},
|
|
32
|
-
target: { repo: { type: "string" }, file: { type: "string" } },
|
|
36
|
+
target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" } },
|
|
33
37
|
verify: { workflow: { type: "string" }, timeout: { type: "string" } },
|
|
34
38
|
wait: { repo: { type: "string" }, timeout: { type: "string" } },
|
|
35
39
|
failures: { repo: { type: "string" } },
|
|
40
|
+
"search-logs": { repo: { type: "string" }, query: { type: "string" }, limit: { type: "string" } },
|
|
41
|
+
"rerun-failed": { repo: { type: "string" }, file: { type: "string" } },
|
|
36
42
|
ship: { repo: { type: "string" } },
|
|
43
|
+
billing: { repo: { type: "string" }, timeout: { type: "string" } },
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const HELP = {
|
|
47
|
+
commands: [
|
|
48
|
+
"init [--scope SCOPES] [--no-mcp] [--billing]", "doctor", "login [--scope SCOPES]", "logout", "token list", "token revoke ID",
|
|
49
|
+
"target set --repo OWNER/REPO --file TARGET.json [--auto-promote on|off]", "verify [--workflow PATH] [--timeout SECONDS]",
|
|
50
|
+
"wait ID [--repo OWNER/REPO] [--timeout SECONDS]", "failures ID [--repo OWNER/REPO]", "ship ID [--repo OWNER/REPO]",
|
|
51
|
+
"billing [--repo OWNER/REPO] [--timeout SECONDS]",
|
|
52
|
+
"search-logs ID --query LITERAL [--repo OWNER/REPO] [--limit COUNT]",
|
|
53
|
+
"rerun-failed ID --file REQUEST.json [--repo OWNER/REPO]",
|
|
54
|
+
],
|
|
55
|
+
scopes: SCOPES,
|
|
56
|
+
docs: "https://ci.notusworks.com/docs/agents.md",
|
|
57
|
+
setup: "https://ci.notusworks.com/llms.txt",
|
|
37
58
|
};
|
|
38
59
|
|
|
39
60
|
/** @param {string[]} args @returns {any} */
|
|
40
61
|
export function parseCommand(args) {
|
|
62
|
+
if (!args.length || args[0] === "help" || args.includes("--help") || args.includes("-h")) return { command: "help" };
|
|
41
63
|
const [command = "", ...rest] = args;
|
|
42
64
|
if (!Object.hasOwn(OPTIONS, command)) throw usage(`unknown command: ${command || "(none)"}`);
|
|
43
65
|
/** @type {{values: Record<string, any>, positionals: string[]}} */
|
|
@@ -62,7 +84,7 @@ export function parseCommand(args) {
|
|
|
62
84
|
const scopes = [...new Set((values.scope ?? DEFAULT_SCOPES).split(","))];
|
|
63
85
|
const unknown = scopes.filter(scope => !SCOPES.includes(scope));
|
|
64
86
|
if (unknown.length) throw usage(`unknown scope ${unknown.join(",")}; scopes are ${SCOPES.join(",")}`);
|
|
65
|
-
return command === "init" ? { command, scopes, mcp: !values["no-mcp"] } : { command, scopes };
|
|
87
|
+
return command === "init" ? { command, scopes, mcp: !values["no-mcp"], billing: values.billing === true } : { command, scopes };
|
|
66
88
|
}
|
|
67
89
|
if (command === "doctor" || command === "logout") { expect(); return { command }; }
|
|
68
90
|
if (command === "token") {
|
|
@@ -73,13 +95,28 @@ export function parseCommand(args) {
|
|
|
73
95
|
if (command === "target") {
|
|
74
96
|
expect("set");
|
|
75
97
|
if (!values.file) throw usage("--file is required");
|
|
76
|
-
|
|
98
|
+
const auto = values["auto-promote"];
|
|
99
|
+
if (auto !== undefined && auto !== "on" && auto !== "off") throw usage("--auto-promote must be on or off");
|
|
100
|
+
return { command: "target set", repo: values.repo, file: values.file, autoPromote: auto === undefined ? undefined : auto === "on" };
|
|
77
101
|
}
|
|
78
102
|
if (command === "verify") {
|
|
79
103
|
expect();
|
|
80
104
|
if (values.workflow === "") throw usage("--workflow must not be empty");
|
|
81
105
|
return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
|
|
82
106
|
}
|
|
107
|
+
if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90 }; }
|
|
108
|
+
if (command === "search-logs") {
|
|
109
|
+
expect("*"); const runId = /^[1-9]\d*$/.test(positionals[0]) ? Number(positionals[0]) : positionals[0].toLowerCase();
|
|
110
|
+
if ((typeof runId === "number" ? !Number.isSafeInteger(runId) : !isPushRunId(runId)) || !values.query) throw usage("search-logs requires a valid ID and --query");
|
|
111
|
+
const limit = values.limit === undefined ? undefined : Number(values.limit);
|
|
112
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100)) throw usage("--limit must be 1 through 100");
|
|
113
|
+
return { command, runId, repo: values.repo, query: values.query, limit };
|
|
114
|
+
}
|
|
115
|
+
if (command === "rerun-failed") {
|
|
116
|
+
expect("*"); const id = positionals[0].toLowerCase();
|
|
117
|
+
if (!isPushRunId(id) || !values.file) throw usage("rerun-failed requires a verify UUID and --file");
|
|
118
|
+
return { command, failedVerifyId: id, repo: values.repo, file: values.file };
|
|
119
|
+
}
|
|
83
120
|
expect("*");
|
|
84
121
|
const raw = positionals[0];
|
|
85
122
|
const runId = /^[1-9]\d*$/.test(raw) ? Number(raw) : raw.toLowerCase();
|
|
@@ -121,8 +158,8 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
|
|
|
121
158
|
next: `Tell the human the monthly limit is reached and resets on ${resetsOn}. Do not retry.`, ...extra, resetsOn };
|
|
122
159
|
}
|
|
123
160
|
if (code === "payment_required") {
|
|
124
|
-
return { error: "The 300-minute NotusCI trial is used up.
|
|
125
|
-
next:
|
|
161
|
+
return { error: "The 300-minute NotusCI trial is used up. Set up billing to continue.", code,
|
|
162
|
+
next: `${NPX} billing`, ...extra };
|
|
126
163
|
}
|
|
127
164
|
if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
|
|
128
165
|
/** @type {Record<string, string>} */
|
|
@@ -212,6 +249,63 @@ function checkPath(path) {
|
|
|
212
249
|
if (!path || Buffer.byteLength(path) > MAX_PATH_BYTES) throw new Error(`path exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
|
|
213
250
|
}
|
|
214
251
|
|
|
252
|
+
/** @param {string} a @param {string} b */
|
|
253
|
+
const utf8Compare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
254
|
+
|
|
255
|
+
/** @param {Buffer|string} value */
|
|
256
|
+
const sha256 = value => createHash("sha256").update(value).digest("hex");
|
|
257
|
+
|
|
258
|
+
/** Compute the transport-neutral identity for a normalized Source v2 overlay.
|
|
259
|
+
* @param {string} repo @param {{baseSha:string,overlay:{path:string,mode:string,data:string}[],deletions:string[]}} source */
|
|
260
|
+
export function sourceIdentity(repo, source) {
|
|
261
|
+
const hash = createHash("sha256");
|
|
262
|
+
hash.update(`notusci-source-v2\0repo\0${repo.toLowerCase()}\0base\0${source.baseSha}\0`);
|
|
263
|
+
for (const file of [...source.overlay].sort((a, b) => utf8Compare(a.path, b.path))) {
|
|
264
|
+
const bytes = Buffer.from(file.data, "base64");
|
|
265
|
+
hash.update(`file\0${Buffer.byteLength(file.path)}\0${file.path}\0${file.mode}\0${sha256(bytes)}\0`);
|
|
266
|
+
}
|
|
267
|
+
for (const path of [...source.deletions].sort(utf8Compare)) hash.update(`delete\0${Buffer.byteLength(path)}\0${path}\0`);
|
|
268
|
+
return hash.digest("hex");
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Attach only the immutable Git base; the receipt already owns its overlay.
|
|
272
|
+
* @param {{baseSha:string,objects?:{oid:string,type:string,data:string}[],overlay?:unknown[],deletions?:string[]}} source */
|
|
273
|
+
export function baseAttachment(source) {
|
|
274
|
+
return { schemaVersion: 1, baseSha: source.baseSha, objects: source.objects ?? [], overlay: [], deletions: [] };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const dependencyNames = new Set(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc", "pnpmfile.cjs", ".pnpmfile.cjs"]);
|
|
278
|
+
|
|
279
|
+
/** @param {string} repo @param {string} workflow @param {{path:string,mode:string,bytes:Buffer}[]} files */
|
|
280
|
+
export function dependencyHintForFiles(repo, workflow, files) {
|
|
281
|
+
const entries = [];
|
|
282
|
+
for (const file of [...files].sort((a, b) => utf8Compare(a.path, b.path))) {
|
|
283
|
+
if (file.path.endsWith("pnpm-lock.yaml") && /^\s*patchedDependencies:\s*(?:#.*)?$/m.test(file.bytes.toString("utf8"))) return undefined;
|
|
284
|
+
entries.push(`file\0${Buffer.byteLength(file.path)}\0${file.path}\0${file.mode}\0${sha256(file.bytes)}\0`);
|
|
285
|
+
}
|
|
286
|
+
return sha256(`notusci-dependency-hint-v1\0repo\0${repo.toLowerCase()}\0workflow\0${Buffer.byteLength(workflow)}\0${workflow}\0${entries.join("")}`);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** A conservative, untrusted snapshot candidate hint. @param {string} cwd @param {string} repo @param {string} workflow */
|
|
290
|
+
export function dependencyHint(cwd, repo, workflow) {
|
|
291
|
+
const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
|
|
292
|
+
const candidates = new Set(paths(git(root, ["ls-files", "-co", "--exclude-standard", "-z"])));
|
|
293
|
+
candidates.add(workflow);
|
|
294
|
+
const selected = [...candidates].filter(path => path === workflow || dependencyNames.has(path.slice(path.lastIndexOf("/") + 1))).sort(utf8Compare);
|
|
295
|
+
const files = [];
|
|
296
|
+
for (const path of selected) {
|
|
297
|
+
checkPath(path);
|
|
298
|
+
let stat;
|
|
299
|
+
try { stat = lstatSync(`${root}/${path}`); } catch { return undefined; }
|
|
300
|
+
let mode, bytes;
|
|
301
|
+
if (stat.isSymbolicLink()) { mode = "120000"; bytes = Buffer.from(readlinkSync(`${root}/${path}`)); }
|
|
302
|
+
else if (stat.isFile()) { mode = stat.mode & 0o111 ? "100755" : "100644"; bytes = readFileSync(`${root}/${path}`); }
|
|
303
|
+
else return undefined;
|
|
304
|
+
files.push({ path, mode, bytes });
|
|
305
|
+
}
|
|
306
|
+
return dependencyHintForFiles(repo, workflow, files);
|
|
307
|
+
}
|
|
308
|
+
|
|
215
309
|
/** @param {string} entry */
|
|
216
310
|
export function parseTreeEntry(entry) {
|
|
217
311
|
const tab = entry.indexOf("\t");
|
|
@@ -220,11 +314,18 @@ export function parseTreeEntry(entry) {
|
|
|
220
314
|
return { mode: match[1], type: match[2], oid: match[3], size: Number(match[4]), path: entry.slice(tab + 1) };
|
|
221
315
|
}
|
|
222
316
|
|
|
223
|
-
/**
|
|
224
|
-
export function
|
|
317
|
+
/** @param {string} cwd */
|
|
318
|
+
export function sourceBaseSha(cwd) {
|
|
225
319
|
const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
|
|
226
320
|
const baseSha = git(root, ["rev-parse", "--verify", "HEAD"]).toString().trim();
|
|
227
321
|
if (!/^[0-9a-f]{40}$/.test(baseSha)) throw new Error("HEAD must resolve to a SHA-1 commit");
|
|
322
|
+
return baseSha;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Build the raw Git base and final local overlay. @param {string} cwd */
|
|
326
|
+
export function buildSource(cwd, includeObjects = true) {
|
|
327
|
+
const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
|
|
328
|
+
const baseSha = sourceBaseSha(root);
|
|
228
329
|
/** @type {Map<string,number>} */
|
|
229
330
|
const finalFiles = new Map();
|
|
230
331
|
for (const entry of paths(git(root, ["ls-tree", "-rlz", "--full-tree", baseSha]))) {
|
|
@@ -236,7 +337,7 @@ export function buildSource(cwd) {
|
|
|
236
337
|
if (!Number.isSafeInteger(size)) throw new Error(`invalid Git tree entry: ${path}`);
|
|
237
338
|
finalFiles.set(path, size);
|
|
238
339
|
}
|
|
239
|
-
const objectIds = [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)];
|
|
340
|
+
const objectIds = includeObjects ? [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)] : [];
|
|
240
341
|
let decodedBytes = 0;
|
|
241
342
|
const objects = objectIds.map(oid => {
|
|
242
343
|
const type = git(root, ["cat-file", "-t", oid]).toString().trim();
|
|
@@ -278,7 +379,7 @@ export function buildSource(cwd) {
|
|
|
278
379
|
let finalBytes = 0;
|
|
279
380
|
for (const size of finalFiles.values()) finalBytes += size;
|
|
280
381
|
if (finalBytes > MAX_TREE_BYTES) throw new Error("resolved source exceeds the 256 MiB decoded limit");
|
|
281
|
-
return { schemaVersion: 1, baseSha, objects, overlay, deletions };
|
|
382
|
+
return { schemaVersion: includeObjects ? 1 : 2, baseSha, ...(includeObjects ? { objects } : {}), overlay, deletions };
|
|
282
383
|
}
|
|
283
384
|
|
|
284
385
|
/** @param {ReturnType<typeof buildSource>} source */
|