@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
|
@@ -31,9 +31,9 @@
|
|
|
31
31
|
// (986-987), removed with `sbx policy rm network --sandbox --resource` for
|
|
32
32
|
// the cut (1148, 1179-1180); `sbx policy ls <sandbox> --json` (812, 822)
|
|
33
33
|
// then shows, from the host, that no network allow is left.
|
|
34
|
-
// - Files move
|
|
35
|
-
//
|
|
36
|
-
// report is copied into a private host folder and checked there.
|
|
34
|
+
// - Files move in over `sbx exec -i` (a tar streamed to `tar -x` as root, no
|
|
35
|
+
// file the sandbox's user can reach), and out with `sbx cp`, whose host side
|
|
36
|
+
// is a path: the report is copied into a private host folder and checked there.
|
|
37
37
|
// - The model route (#370): the key-injecting model proxy listens on the
|
|
38
38
|
// host's 127.0.0.1, which the sandbox calls as host.docker.internal:<its
|
|
39
39
|
// port>, and one per-sandbox rule allows only that, which sbx's policy
|
|
@@ -239,7 +239,6 @@ export function sbxDriver({ id, call, plan }) {
|
|
|
239
239
|
/** The per-sandbox allow rules in place, as their resource lists. */
|
|
240
240
|
const allowed = [];
|
|
241
241
|
let host = null; // a private host folder for the files sbx cp moves
|
|
242
|
-
let copies = 0;
|
|
243
242
|
let modelRoute = null; // the one allow rule the scan may have
|
|
244
243
|
let modelProxy = null;
|
|
245
244
|
|
|
@@ -257,11 +256,12 @@ export function sbxDriver({ id, call, plan }) {
|
|
|
257
256
|
);
|
|
258
257
|
allowed.splice(allowed.indexOf(list), 1);
|
|
259
258
|
};
|
|
260
|
-
const exec = (script, { env = [], workdir = "/workspace", user } = {}) => {
|
|
259
|
+
const exec = (script, { env = [], workdir = "/workspace", user, stdin, maxOutput } = {}) => {
|
|
261
260
|
const { args, childEnv } = envArgs(env, plan.launch?.secretEnv ?? [], "-e");
|
|
262
261
|
return sbx(
|
|
263
262
|
[
|
|
264
263
|
"exec",
|
|
264
|
+
...(stdin === undefined ? [] : ["-i"]),
|
|
265
265
|
...(user ? ["-u", user] : []),
|
|
266
266
|
...args,
|
|
267
267
|
...(workdir ? ["-w", workdir] : []),
|
|
@@ -270,7 +270,11 @@ export function sbxDriver({ id, call, plan }) {
|
|
|
270
270
|
"-c",
|
|
271
271
|
script,
|
|
272
272
|
],
|
|
273
|
-
{
|
|
273
|
+
{
|
|
274
|
+
env: childEnv,
|
|
275
|
+
...(stdin === undefined ? {} : { stdin }),
|
|
276
|
+
...(maxOutput === undefined ? {} : { maxOutput }),
|
|
277
|
+
},
|
|
274
278
|
);
|
|
275
279
|
};
|
|
276
280
|
|
|
@@ -373,24 +377,24 @@ export function sbxDriver({ id, call, plan }) {
|
|
|
373
377
|
await create("creating the sandbox");
|
|
374
378
|
},
|
|
375
379
|
|
|
376
|
-
async copyIn(tar, what) {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
must(await sbx(["cp", file, `${name}:${inside}`], { cwd: hostDir() }), what);
|
|
384
|
-
} finally {
|
|
385
|
-
rmSync(join(hostDir(), file), { force: true });
|
|
386
|
-
}
|
|
380
|
+
async copyIn(tar, what, { loosen = true } = {}) {
|
|
381
|
+
// `loosen: false` (a copy made while the agent runs) only unpacks: the loosening below
|
|
382
|
+
// walks the tree as root, and a link the agent swaps in between `find` and `chmod` would
|
|
383
|
+
// make root chmod its target.
|
|
384
|
+
// Streamed to `tar -x` as root over `sbx exec -i`, as the docker driver does: no file the
|
|
385
|
+
// sandbox's own user can reach (a predictable /tmp name it could pre-create or link) is
|
|
386
|
+
// ever involved, so a copy made while the agent runs cannot be swapped under root.
|
|
387
387
|
must(
|
|
388
388
|
await exec(
|
|
389
|
-
//
|
|
390
|
-
|
|
391
|
-
|
|
389
|
+
// Then the sandbox's own user may write there, except the factory-mode Stage's Snapshot
|
|
390
|
+
// (read-only to it) and Outbox (its own mode). /agent-kit itself is never loosened
|
|
391
|
+
// (-mindepth 1): 0777 without the sticky bit would let the agent swap the Snapshot link.
|
|
392
|
+
loosen
|
|
393
|
+
? `tar -x -f - -C / && { chmod -R a+rwX /workspace 2>/dev/null; find /agent-kit -mindepth 1 \( -path /agent-kit/snapshots -o -path /agent-kit/snapshot -o -path /agent-kit/outbox \) -prune -o ! -type l -exec chmod a+rwX {} + 2>/dev/null; true; }`
|
|
394
|
+
: "tar -x -f - -C /",
|
|
395
|
+
{ user: "root", workdir: null, stdin: tar },
|
|
392
396
|
),
|
|
393
|
-
|
|
397
|
+
what,
|
|
394
398
|
{ showOutput: true },
|
|
395
399
|
);
|
|
396
400
|
},
|
|
@@ -399,37 +403,20 @@ export function sbxDriver({ id, call, plan }) {
|
|
|
399
403
|
async installAgent() {},
|
|
400
404
|
|
|
401
405
|
/**
|
|
402
|
-
* The archive `script` writes, run as root in the sandbox
|
|
403
|
-
*
|
|
404
|
-
*
|
|
406
|
+
* The archive `script` writes, run as root in the sandbox and streamed out on `sbx exec`'s
|
|
407
|
+
* stdout, as the docker driver does (ADR 0047): no file in the sandbox is involved, so
|
|
408
|
+
* nothing the sandbox's own user can reach (a link, a file it owns, a folder, a FIFO at a
|
|
409
|
+
* fixed /tmp path) is ever written or read by root.
|
|
405
410
|
*/
|
|
406
411
|
async carryOut(script, { maxBytes }) {
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
{ user: "root", workdir: null },
|
|
411
|
-
);
|
|
412
|
-
if (made.status === 5) return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
|
|
413
|
-
if (made.status !== 0) {
|
|
412
|
+
const r = await exec(script, { user: "root", workdir: null, maxOutput: maxBytes });
|
|
413
|
+
if (r.truncated) return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
|
|
414
|
+
if (r.status !== 0) {
|
|
414
415
|
return {
|
|
415
|
-
error: `tar exited ${
|
|
416
|
+
error: `tar exited ${r.status ?? "abnormally"}: ${firstLine(r.stderr) || "no output"}`,
|
|
416
417
|
};
|
|
417
418
|
}
|
|
418
|
-
|
|
419
|
-
try {
|
|
420
|
-
const r = await sbx(["cp", `${name}:${inside}`, "."], { cwd: into });
|
|
421
|
-
if (r.status !== 0)
|
|
422
|
-
return { error: `sbx cp failed: ${firstLine(r.stderr) || `exit ${r.status}`}` };
|
|
423
|
-
const entries = readdirSync(into);
|
|
424
|
-
const file = entries.length === 1 ? join(into, entries[0]) : null;
|
|
425
|
-
if (file === null || !lstatSync(file).isFile()) return { error: "sbx cp gave no one file" };
|
|
426
|
-
if (lstatSync(file).size > maxBytes) {
|
|
427
|
-
return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
|
|
428
|
-
}
|
|
429
|
-
return { data: readFileSync(file) };
|
|
430
|
-
} finally {
|
|
431
|
-
rmSync(into, { recursive: true, force: true });
|
|
432
|
-
}
|
|
419
|
+
return { data: r.stdout };
|
|
433
420
|
},
|
|
434
421
|
|
|
435
422
|
/**
|
package/src/doctor.mjs
CHANGED
|
@@ -41,6 +41,15 @@ import {
|
|
|
41
41
|
STAGE_CHECKS,
|
|
42
42
|
} from "./checks/stages.mjs";
|
|
43
43
|
import { firstLine } from "./exec.mjs";
|
|
44
|
+
import {
|
|
45
|
+
engineOf,
|
|
46
|
+
FACTORY_FILE_CHECKS,
|
|
47
|
+
FACTORY_LOCAL_CHECKS,
|
|
48
|
+
factoryFileResults,
|
|
49
|
+
factoryLocalChecks,
|
|
50
|
+
diskReads,
|
|
51
|
+
hasFactory,
|
|
52
|
+
} from "./factory/doctor/index.mjs";
|
|
44
53
|
import { createGitHub } from "./github.mjs";
|
|
45
54
|
import { openKitTag, PreManifestTagError, serverFromEnv } from "./kit-tag.mjs";
|
|
46
55
|
|
|
@@ -81,6 +90,7 @@ const skipAll = (ids, reason) => ids.map(([id, title]) => result(id, title, "ski
|
|
|
81
90
|
* repo?: string,
|
|
82
91
|
* openTag?: typeof openKitTag,
|
|
83
92
|
* env?: NodeJS.ProcessEnv,
|
|
93
|
+
* now?: () => number,
|
|
84
94
|
* }} opts
|
|
85
95
|
* @returns {{ mode: "local" | "ci", modeReason: string | null, repo: string | null, tag: string | null, results: object[], refusal: string | null, exitCode: number }}
|
|
86
96
|
*/
|
|
@@ -92,6 +102,7 @@ export function runDoctor({
|
|
|
92
102
|
repo: repoArg,
|
|
93
103
|
openTag = openKitTag,
|
|
94
104
|
env = process.env,
|
|
105
|
+
now = Date.now,
|
|
95
106
|
}) {
|
|
96
107
|
const results = [];
|
|
97
108
|
let mode = ci ? "ci" : "local";
|
|
@@ -204,6 +215,10 @@ export function runDoctor({
|
|
|
204
215
|
|
|
205
216
|
results.push(guarded("scan-recipe", () => checkScanRecipe({ root }), "Scan recipe"));
|
|
206
217
|
|
|
218
|
+
// A checkout with no Factory is checked exactly as before.
|
|
219
|
+
const factory = hasFactory(root);
|
|
220
|
+
if (factory) results.push(...guardedFactoryFiles({ root, tag: pins.tag }));
|
|
221
|
+
|
|
207
222
|
if (mode === "ci") {
|
|
208
223
|
results.push(
|
|
209
224
|
...skipAll(
|
|
@@ -211,9 +226,31 @@ export function runDoctor({
|
|
|
211
226
|
`CI mode (${modeReason}): needs a local run with an admin gh login.`,
|
|
212
227
|
),
|
|
213
228
|
);
|
|
229
|
+
if (factory) {
|
|
230
|
+
results.push(
|
|
231
|
+
...skipAll(
|
|
232
|
+
FACTORY_LOCAL_CHECKS,
|
|
233
|
+
`CI mode (${modeReason}): needs a local run with an admin gh login.`,
|
|
234
|
+
),
|
|
235
|
+
);
|
|
236
|
+
}
|
|
214
237
|
} else {
|
|
215
238
|
results.push(...localChecks({ runner, cwd, root, info, files, callers, snapshot }));
|
|
216
239
|
results.push(...harnessChecks({ runner, cwd, root, info, callers, snapshot }));
|
|
240
|
+
if (factory) {
|
|
241
|
+
const github = createGitHub(runner, { cwd, hostname: info.host ?? null });
|
|
242
|
+
results.push(
|
|
243
|
+
...factoryLocalChecks({
|
|
244
|
+
github,
|
|
245
|
+
runner,
|
|
246
|
+
cwd,
|
|
247
|
+
info,
|
|
248
|
+
engine: engineOf(diskReads(root)),
|
|
249
|
+
guard: guarded,
|
|
250
|
+
now,
|
|
251
|
+
}),
|
|
252
|
+
);
|
|
253
|
+
}
|
|
217
254
|
}
|
|
218
255
|
} finally {
|
|
219
256
|
snapshot?.cleanup();
|
|
@@ -229,6 +266,19 @@ export function runDoctor({
|
|
|
229
266
|
});
|
|
230
267
|
}
|
|
231
268
|
|
|
269
|
+
/** The Factory's file checks; a crash becomes one failed check, never a silent pass. */
|
|
270
|
+
function guardedFactoryFiles({ root, tag }) {
|
|
271
|
+
try {
|
|
272
|
+
return factoryFileResults({ root, tag });
|
|
273
|
+
} catch (err) {
|
|
274
|
+
return FACTORY_FILE_CHECKS.map(([id, title]) =>
|
|
275
|
+
result(id, title, "fail", `Check crashed: ${firstLine(err?.message ?? err)}`, {
|
|
276
|
+
details: ["This is a bug in doctor; the other checks still ran."],
|
|
277
|
+
}),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
232
282
|
function repoInfo(github, repoArg) {
|
|
233
283
|
return github.repoInfo(repoArg);
|
|
234
284
|
}
|
|
@@ -478,7 +528,7 @@ export function formatResult(r) {
|
|
|
478
528
|
}
|
|
479
529
|
|
|
480
530
|
/** doctor --ci's pin and Kit-owned path checks, against an already-fetched tag. */
|
|
481
|
-
export function fileAndPinChecks({ runner, root, snap }) {
|
|
531
|
+
export function fileAndPinChecks({ runner, root, snap, factory = false }) {
|
|
482
532
|
let pins;
|
|
483
533
|
try {
|
|
484
534
|
pins = checkPins(readWorkflows(root).files);
|
|
@@ -504,6 +554,8 @@ export function fileAndPinChecks({ runner, root, snap }) {
|
|
|
504
554
|
result("kit-owned-trees", "Kit-owned paths match the pinned tag", "fail", err.message),
|
|
505
555
|
);
|
|
506
556
|
}
|
|
557
|
+
// `upgrade` asks for the Factory's file checks too, when the checkout has a Factory.
|
|
558
|
+
if (factory) results.push(...guardedFactoryFiles({ root, tag: snap.tag }));
|
|
507
559
|
return results;
|
|
508
560
|
}
|
|
509
561
|
|
package/src/exec.mjs
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// Runs commands as argument arrays, never through a shell, so no string from a
|
|
2
2
|
// Consumer file or a GitHub response is ever parsed as shell syntax. Each
|
|
3
3
|
// subcommand gets a runner that runs only the commands on its own allowlist:
|
|
4
|
-
// `init`, `upgrade` and `doctor` reach only `git` and `gh
|
|
5
|
-
//
|
|
6
|
-
// reads
|
|
4
|
+
// `init`, `upgrade` and `doctor` reach only `git` and `gh`; `deep-scan` and
|
|
5
|
+
// `factory-run` add the accepted sandbox runtimes' CLIs and the 1Password CLI, which
|
|
6
|
+
// reads the model credential (ADR 0019), and `factory-run` adds `gh` beside them and the
|
|
7
|
+
// host's keep-awake tools (`caffeinate`, `systemd-inhibit`) and the running Node
|
|
8
|
+
// binary (`process.execPath`, for its trusted child scripts). There is no
|
|
7
9
|
// second runner that bypasses this. Every module takes a runner as a
|
|
8
10
|
// parameter; tests inject a fake one, or a fake spawn behind the real
|
|
9
11
|
// allowlist. A runner also has `start`, the same command run without
|
|
@@ -12,7 +14,7 @@
|
|
|
12
14
|
|
|
13
15
|
import { spawn as spawnChild, spawnSync } from "node:child_process";
|
|
14
16
|
|
|
15
|
-
/** The sandbox runtimes' command-line tools, which only `deep-scan` may run. */
|
|
17
|
+
/** The sandbox runtimes' command-line tools, which only `deep-scan` and `factory-run` may run. */
|
|
16
18
|
export const RUNTIME_CLIS = Object.freeze([
|
|
17
19
|
"sbx",
|
|
18
20
|
"docker",
|
|
@@ -21,7 +23,7 @@ export const RUNTIME_CLIS = Object.freeze([
|
|
|
21
23
|
"firecracker",
|
|
22
24
|
]);
|
|
23
25
|
|
|
24
|
-
/** The secret managers' command-line tools, which only `deep-scan` may run. */
|
|
26
|
+
/** The secret managers' command-line tools, which only `deep-scan` and `factory-run` may run. */
|
|
25
27
|
export const SECRET_MANAGER_CLIS = Object.freeze(["op"]);
|
|
26
28
|
|
|
27
29
|
const ALLOWLISTS = Object.freeze({
|
|
@@ -29,6 +31,17 @@ const ALLOWLISTS = Object.freeze({
|
|
|
29
31
|
upgrade: Object.freeze(["git", "gh"]),
|
|
30
32
|
doctor: Object.freeze(["git", "gh"]),
|
|
31
33
|
"deep-scan": Object.freeze(["git", ...RUNTIME_CLIS, ...SECRET_MANAGER_CLIS]),
|
|
34
|
+
"factory-run": Object.freeze([
|
|
35
|
+
"git",
|
|
36
|
+
"gh",
|
|
37
|
+
...SECRET_MANAGER_CLIS,
|
|
38
|
+
...RUNTIME_CLIS,
|
|
39
|
+
"caffeinate",
|
|
40
|
+
"systemd-inhibit",
|
|
41
|
+
// The running Node binary, for the engine's trusted child scripts (the review
|
|
42
|
+
// publish). Exactly this path: not `node` from PATH.
|
|
43
|
+
process.execPath,
|
|
44
|
+
]),
|
|
32
45
|
});
|
|
33
46
|
|
|
34
47
|
/**
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// The Daily cap's arithmetic (#516, ADR 0042): pure functions, no IO, no clock.
|
|
2
|
+
// The sweep core (sweep/sweep-core.mjs) calls them; docs/factory/budget.md says
|
|
3
|
+
// the rules in prose. Tokens only, never money.
|
|
4
|
+
//
|
|
5
|
+
// effective cap = AGENT_KIT_FACTORY_DAILY_TOKENS (owner-only variable), else
|
|
6
|
+
// budget.daily_tokens of the factory config, else no cap
|
|
7
|
+
// spent today = tokens in the engine's release comments posted since 00:00
|
|
8
|
+
// UTC; a total that is missing, unknown or edited counts at
|
|
9
|
+
// the Stage's full cap, and so does a Claim written today that
|
|
10
|
+
// left no release comment
|
|
11
|
+
// reserved = the full cap of every Stage still running, once per Stage; QA counts 0,
|
|
12
|
+
// and so does a Stage the engine does not run
|
|
13
|
+
// a Stage starts only if spent + reserved + its own cap <= the cap
|
|
14
|
+
//
|
|
15
|
+
// A value that cannot be read never loosens the cap: an invalid override, an
|
|
16
|
+
// invalid `budget` or `limits` value and an unreadable spend all stop new Claims.
|
|
17
|
+
|
|
18
|
+
import { DEFAULT_STAGE_LIMITS, TASK_SIZES } from "../limits/limits.mjs";
|
|
19
|
+
import { parseReleaseComment } from "../claims/release.mjs";
|
|
20
|
+
|
|
21
|
+
/** The two thresholds that post a notice on the Factory control issue, in percent. */
|
|
22
|
+
export const BUDGET_THRESHOLDS = Object.freeze([80, 100]);
|
|
23
|
+
|
|
24
|
+
/** The names a notice gives for where the effective cap came from. */
|
|
25
|
+
export const BUDGET_SOURCE_CONFIG = "budget.daily_tokens";
|
|
26
|
+
export const BUDGET_SOURCE_OVERRIDE = "AGENT_KIT_FACTORY_DAILY_TOKENS";
|
|
27
|
+
|
|
28
|
+
const BUDGET_DAY_MS = 86_400_000;
|
|
29
|
+
const BUDGET_WHOLE = /^[1-9][0-9]{0,14}$/;
|
|
30
|
+
const BUDGET_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
31
|
+
|
|
32
|
+
const budgetIsObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
33
|
+
|
|
34
|
+
/** Midnight UTC that starts the day `ms` falls in. */
|
|
35
|
+
export const budgetDayStart = (ms) => Math.floor(ms / BUDGET_DAY_MS) * BUDGET_DAY_MS;
|
|
36
|
+
|
|
37
|
+
/** `YYYY-MM-DD`, the UTC day `ms` falls in. */
|
|
38
|
+
export const budgetDayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `budget` and `limits` of the factory config's text, for the cap. `text` is
|
|
42
|
+
* null when the file is absent (no cap) and anything else that is not a string
|
|
43
|
+
* when the read failed (a `problem`, which stops new Claims).
|
|
44
|
+
* @returns {{ value: { daily_tokens?: number, notify: string[], limits?: object }, problem?: string }}
|
|
45
|
+
*/
|
|
46
|
+
export function budgetFromConfig(text) {
|
|
47
|
+
const none = { value: { notify: [] } };
|
|
48
|
+
if (text === null || text === undefined) return none;
|
|
49
|
+
const stop = (problem) => ({ value: { notify: [], problem }, problem });
|
|
50
|
+
if (typeof text !== "string") return stop("the factory config could not be read");
|
|
51
|
+
// A file that is not a JSON object names no cap, and no Stage runs on it either:
|
|
52
|
+
// `stage-limits` refuses it (docs/factory/limits.md). Only a read that failed, and a
|
|
53
|
+
// `budget` or `limits` value that is wrong, stop new Claims.
|
|
54
|
+
let data;
|
|
55
|
+
try {
|
|
56
|
+
data = JSON.parse(text);
|
|
57
|
+
} catch {
|
|
58
|
+
return none;
|
|
59
|
+
}
|
|
60
|
+
if (!budgetIsObject(data)) return none;
|
|
61
|
+
const value = { notify: [] };
|
|
62
|
+
if ("limits" in data) {
|
|
63
|
+
if (!budgetIsObject(data.limits)) return stop("limits is not an object");
|
|
64
|
+
value.limits = data.limits;
|
|
65
|
+
}
|
|
66
|
+
if (!("budget" in data)) return { value };
|
|
67
|
+
const budget = data.budget;
|
|
68
|
+
if (!budgetIsObject(budget)) return stop("budget is not an object");
|
|
69
|
+
if ("daily_tokens" in budget) {
|
|
70
|
+
const n = budget.daily_tokens;
|
|
71
|
+
if (!Number.isSafeInteger(n) || n < 1) {
|
|
72
|
+
return stop("budget.daily_tokens must be a whole number of 1 or more");
|
|
73
|
+
}
|
|
74
|
+
value.daily_tokens = n;
|
|
75
|
+
}
|
|
76
|
+
if ("notify" in budget) {
|
|
77
|
+
const list = budget.notify;
|
|
78
|
+
const logins = Array.isArray(list) ? list.map((l) => String(l).replace(/^@/, "")) : [];
|
|
79
|
+
if (!Array.isArray(list) || !logins.every((l) => BUDGET_LOGIN.test(l))) {
|
|
80
|
+
return stop("budget.notify must be a list of GitHub logins");
|
|
81
|
+
}
|
|
82
|
+
value.notify = [...new Set(logins)];
|
|
83
|
+
}
|
|
84
|
+
return { value };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The effective Daily cap and where it came from. The override (the repository
|
|
89
|
+
* variable, set only by an owner or admin) wins over the config; an override
|
|
90
|
+
* that is not a whole number stops new Claims rather than fall back.
|
|
91
|
+
* @param {{ budget?: { daily_tokens?: number, notify?: string[], problem?: string }, override?: string }} input
|
|
92
|
+
* @returns {{ cap: number, source: string, notify: string[] } | { none: true } | { error: string }}
|
|
93
|
+
*/
|
|
94
|
+
export function effectiveCap({ budget, override } = {}) {
|
|
95
|
+
const notify = budget?.notify ?? [];
|
|
96
|
+
// A config that cannot be read stops new Claims even under an override: its limits are
|
|
97
|
+
// what the reservation is made of.
|
|
98
|
+
if (budget?.problem) return { error: budget.problem };
|
|
99
|
+
if (override !== undefined && String(override).trim() !== "") {
|
|
100
|
+
const raw = String(override).trim();
|
|
101
|
+
if (!BUDGET_WHOLE.test(raw)) {
|
|
102
|
+
return {
|
|
103
|
+
error: `${BUDGET_SOURCE_OVERRIDE} is ${JSON.stringify(raw.slice(0, 40))}, not a whole number of tokens`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return { cap: Number(raw), source: BUDGET_SOURCE_OVERRIDE, notify };
|
|
107
|
+
}
|
|
108
|
+
if (budget?.daily_tokens !== undefined) {
|
|
109
|
+
return { cap: budget.daily_tokens, source: BUDGET_SOURCE_CONFIG, notify };
|
|
110
|
+
}
|
|
111
|
+
return { none: true };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const wholeTokens = (v) => (Number.isSafeInteger(v) && v > 0 ? v : null);
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A Stage's per-run token cap (`limits.<stage>.tokens`, the starting values
|
|
118
|
+
* where the config names none). For a build without a Task size, the largest
|
|
119
|
+
* size's cap. Null when the value cannot be read as a whole number.
|
|
120
|
+
*/
|
|
121
|
+
export function budgetStageCap({ limits, stage, size }) {
|
|
122
|
+
const merged = { ...DEFAULT_STAGE_LIMITS, ...(budgetIsObject(limits) ? limits : {}) };
|
|
123
|
+
const row = merged[stage];
|
|
124
|
+
if (stage !== "build") return budgetIsObject(row) ? wholeTokens(row.tokens) : null;
|
|
125
|
+
if (!budgetIsObject(row)) return null;
|
|
126
|
+
if (TASK_SIZES.includes(size)) {
|
|
127
|
+
return budgetIsObject(row[size]) ? wholeTokens(row[size].tokens) : null;
|
|
128
|
+
}
|
|
129
|
+
const all = TASK_SIZES.map((s) => (budgetIsObject(row[s]) ? wholeTokens(row[s].tokens) : null));
|
|
130
|
+
return all.some((n) => n === null) ? null : Math.max(...all);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The release comments posted today by the engine, one per Stage run (its
|
|
135
|
+
* Claim nonce): `Map<"stage:claim", { stage, claim, issue, tokens, counted }>`.
|
|
136
|
+
* `tokens` is a whole number, or `"unknown"` when the total is missing, malformed
|
|
137
|
+
* or edited after it was written (an edit is anything that moved the comment's
|
|
138
|
+
* `updatedAt` past its `createdAt`, or names an `editor`). A second comment for
|
|
139
|
+
* the same run keeps the worse total.
|
|
140
|
+
* @param {{ comments: Array<{ issue?: number, author: string, body: string, createdAt: string, updatedAt?: string, editor?: string | null }>, isEngine: (login: string) => boolean, nowMs: number }} input
|
|
141
|
+
*/
|
|
142
|
+
export function todaysReleases({ comments, isEngine, nowMs }) {
|
|
143
|
+
const start = budgetDayStart(nowMs);
|
|
144
|
+
const out = new Map();
|
|
145
|
+
for (const comment of comments ?? []) {
|
|
146
|
+
if (!isEngine(comment.author)) continue;
|
|
147
|
+
const release = parseReleaseComment(comment.body);
|
|
148
|
+
if (!release) continue;
|
|
149
|
+
const at = Date.parse(comment.createdAt);
|
|
150
|
+
if (!Number.isFinite(at) || at < start || at >= start + BUDGET_DAY_MS) continue;
|
|
151
|
+
const edited =
|
|
152
|
+
Boolean(comment.editor) ||
|
|
153
|
+
(comment.updatedAt !== undefined && Date.parse(comment.updatedAt) !== at);
|
|
154
|
+
const tokens = edited ? "unknown" : release.tokens;
|
|
155
|
+
const key = `${release.stage}:${release.claim}`;
|
|
156
|
+
const before = out.get(key);
|
|
157
|
+
const worse =
|
|
158
|
+
before === undefined
|
|
159
|
+
? tokens
|
|
160
|
+
: before.tokens === "unknown" || tokens === "unknown"
|
|
161
|
+
? "unknown"
|
|
162
|
+
: Math.max(before.tokens, tokens);
|
|
163
|
+
out.set(key, {
|
|
164
|
+
stage: release.stage,
|
|
165
|
+
claim: release.claim,
|
|
166
|
+
issue: comment.issue ?? before?.issue,
|
|
167
|
+
tokens: worse,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Tokens spent today: each release's total, or the Stage's full cap where the
|
|
175
|
+
* total is unknown, plus the full cap of each Stage run that left no release.
|
|
176
|
+
* @param {{ releases: Map<string, { stage: string, issue?: number, tokens: number | "unknown" }>, missing: Array<{ stage: string, issue?: number }>, capFor: (stage: string, issue?: number) => number | null }} input
|
|
177
|
+
* @returns {{ spent: number } | { error: string }}
|
|
178
|
+
*/
|
|
179
|
+
export function tokensSpent({ releases, missing, capFor }) {
|
|
180
|
+
let spent = 0;
|
|
181
|
+
const full = capFor;
|
|
182
|
+
for (const release of releases.values()) {
|
|
183
|
+
if (release.tokens === "unknown") {
|
|
184
|
+
const cap = full(release.stage, release.issue);
|
|
185
|
+
if (cap === null) return { error: `the ${release.stage} Stage's token cap is not readable` };
|
|
186
|
+
spent += cap;
|
|
187
|
+
} else {
|
|
188
|
+
spent += release.tokens;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
for (const run of missing) {
|
|
192
|
+
const cap = full(run.stage, run.issue);
|
|
193
|
+
if (cap === null) return { error: `the ${run.stage} Stage's token cap is not readable` };
|
|
194
|
+
spent += cap;
|
|
195
|
+
}
|
|
196
|
+
return { spent };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A Stage may start only if what is spent, what is reserved and its own cap fit the cap. */
|
|
200
|
+
export const budgetFits = ({ cap, spent, reserved, own }) => spent + reserved + own <= cap;
|
|
201
|
+
|
|
202
|
+
/** The whole percent of the cap that is spent (rounded down; the cap is never zero). */
|
|
203
|
+
export const budgetPercent = ({ cap, spent }) => Math.floor((spent * 100) / cap);
|
|
204
|
+
|
|
205
|
+
/** The notice marker, and its reader. One comment per threshold per UTC day. */
|
|
206
|
+
export const budgetNoticeMarker = ({ day, threshold }) =>
|
|
207
|
+
`<!-- factory:budget-notice v=1 day=${day} threshold=${threshold} -->`;
|
|
208
|
+
|
|
209
|
+
const NOTICE_MARKER =
|
|
210
|
+
/^<!-- factory:budget-notice v=1 day=(\d{4}-\d{2}-\d{2}) threshold=(80|100) -->/;
|
|
211
|
+
|
|
212
|
+
export function parseBudgetNotice(body) {
|
|
213
|
+
const match = NOTICE_MARKER.exec(String(body ?? ""));
|
|
214
|
+
return match ? { day: match[1], threshold: Number(match[2]) } : null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The threshold to post a notice for now, or null. The highest one crossed that
|
|
219
|
+
* the control issue's engine comments do not already show for today; once the
|
|
220
|
+
* 100% notice stands, the 80% one is never posted late. A notice someone else
|
|
221
|
+
* edited does not count (it is evidence the engine did not write last).
|
|
222
|
+
* @param {{ cap: number, spent: number, nowMs: number, comments: Array<{ author: string, body: string, editor?: string | null }>, isEngine: (login: string) => boolean }} input
|
|
223
|
+
*/
|
|
224
|
+
export function noticeDue({ cap, spent, nowMs, comments, isEngine }) {
|
|
225
|
+
const day = budgetDayOf(nowMs);
|
|
226
|
+
const percent = budgetPercent({ cap, spent });
|
|
227
|
+
const posted = new Set(
|
|
228
|
+
(comments ?? [])
|
|
229
|
+
.filter((c) => isEngine(c.author) && (!c.editor || isEngine(c.editor)))
|
|
230
|
+
.map((c) => parseBudgetNotice(c.body))
|
|
231
|
+
.filter((n) => n?.day === day)
|
|
232
|
+
.map((n) => n.threshold),
|
|
233
|
+
);
|
|
234
|
+
const crossed = BUDGET_THRESHOLDS.filter((t) => percent >= t);
|
|
235
|
+
const top = crossed.at(-1);
|
|
236
|
+
if (top === undefined) return null;
|
|
237
|
+
return BUDGET_THRESHOLDS.some((t) => t >= top && posted.has(t)) ? null : top;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The comment for one threshold: names the cap and its source, mentions `budget.notify`. */
|
|
241
|
+
export function renderBudgetNotice({ nowMs, threshold, cap, spent, source, notify }) {
|
|
242
|
+
const day = budgetDayOf(nowMs);
|
|
243
|
+
const who = notify.length
|
|
244
|
+
? notify.map((l) => `@${l}`).join(" ")
|
|
245
|
+
: "(nobody is listed in `budget.notify`)";
|
|
246
|
+
const where =
|
|
247
|
+
source === BUDGET_SOURCE_OVERRIDE
|
|
248
|
+
? "the repository variable `AGENT_KIT_FACTORY_DAILY_TOKENS`"
|
|
249
|
+
: "`budget.daily_tokens` in the factory config";
|
|
250
|
+
const what =
|
|
251
|
+
threshold >= 100
|
|
252
|
+
? "The Daily cap is reached: the Factory takes no new Claims until 00:00 UTC. Running Stages finish and merges go on."
|
|
253
|
+
: "The Factory takes no new Claim once the cap is reached, and starts again at 00:00 UTC.";
|
|
254
|
+
return [
|
|
255
|
+
budgetNoticeMarker({ day, threshold }),
|
|
256
|
+
`Factory Daily cap: ${threshold}% reached on ${day} (UTC). ${spent} of ${cap} tokens are spent today. The cap is ${cap} tokens, set by ${where}.`,
|
|
257
|
+
what,
|
|
258
|
+
who,
|
|
259
|
+
].join("\n");
|
|
260
|
+
}
|