@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.
Files changed (120) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +332 -5
  4. package/src/deep-scan/docker-driver.mjs +70 -3
  5. package/src/deep-scan/lifecycle.mjs +2 -2
  6. package/src/deep-scan/sbx-driver.mjs +34 -47
  7. package/src/doctor.mjs +53 -1
  8. package/src/exec.mjs +18 -5
  9. package/src/factory/budget/budget.mjs +260 -0
  10. package/src/factory/build/command.mjs +321 -0
  11. package/src/factory/build/factory.mjs +473 -0
  12. package/src/factory/build/findings.mjs +55 -0
  13. package/src/factory/build/host.mjs +230 -0
  14. package/src/factory/build/notes.mjs +191 -0
  15. package/src/factory/build/pull-request.mjs +74 -0
  16. package/src/factory/bundle.mjs +146 -0
  17. package/src/factory/checks/allowed-paths.mjs +50 -0
  18. package/src/factory/checks/plan-header.mjs +296 -0
  19. package/src/factory/checks/qa.mjs +85 -0
  20. package/src/factory/checks/review.mjs +73 -0
  21. package/src/factory/checks/security.mjs +50 -0
  22. package/src/factory/checks/stage-check.mjs +89 -0
  23. package/src/factory/claims/command.mjs +187 -0
  24. package/src/factory/claims/release.mjs +111 -0
  25. package/src/factory/decision/answers.mjs +103 -0
  26. package/src/factory/decision/command.mjs +64 -0
  27. package/src/factory/decision/plan.mjs +99 -0
  28. package/src/factory/decision/request.mjs +116 -0
  29. package/src/factory/doctor/files.mjs +349 -0
  30. package/src/factory/doctor/index.mjs +56 -0
  31. package/src/factory/doctor/local.mjs +513 -0
  32. package/src/factory/doctor/orchestrate.mjs +146 -0
  33. package/src/factory/engine/lease.mjs +146 -0
  34. package/src/factory/engine/local-engine.mjs +177 -0
  35. package/src/factory/engine/lockfile.mjs +64 -0
  36. package/src/factory/engine/workflow-engine.mjs +124 -0
  37. package/src/factory/gate/comment.mjs +88 -0
  38. package/src/factory/gate/config.mjs +57 -0
  39. package/src/factory/gate/gate-core.mjs +250 -0
  40. package/src/factory/gate/guarded.mjs +17 -0
  41. package/src/factory/gate/reads.mjs +105 -0
  42. package/src/factory/gate/task.mjs +193 -0
  43. package/src/factory/gate/trip-reads.mjs +82 -0
  44. package/src/factory/gate/trip.mjs +87 -0
  45. package/src/factory/init/blueprint.mjs +181 -0
  46. package/src/factory/init/index.mjs +338 -0
  47. package/src/factory/labels/evidence.mjs +162 -0
  48. package/src/factory/labels/moves.mjs +32 -0
  49. package/src/factory/labels/reconcile.mjs +267 -0
  50. package/src/factory/labels/revert.mjs +87 -0
  51. package/src/factory/labels/timeline.mjs +72 -0
  52. package/src/factory/labels/voided.mjs +59 -0
  53. package/src/factory/limits/harness.mjs +39 -0
  54. package/src/factory/limits/limits.mjs +131 -0
  55. package/src/factory/merge/command.mjs +172 -0
  56. package/src/factory/outbox/check.mjs +240 -0
  57. package/src/factory/outbox/rulings.mjs +195 -0
  58. package/src/factory/plan/command.mjs +66 -0
  59. package/src/factory/plan/comment.mjs +156 -0
  60. package/src/factory/plan/publish.mjs +149 -0
  61. package/src/factory/plan/risk.mjs +153 -0
  62. package/src/factory/qa/command.mjs +301 -0
  63. package/src/factory/qa/decide.mjs +86 -0
  64. package/src/factory/qa/report.mjs +50 -0
  65. package/src/factory/records/engine-record.mjs +133 -0
  66. package/src/factory/records/main.mjs +96 -0
  67. package/src/factory/records/record.mjs +226 -0
  68. package/src/factory/records/sink.mjs +57 -0
  69. package/src/factory/report/build.mjs +92 -0
  70. package/src/factory/report/command.mjs +80 -0
  71. package/src/factory/report/facts.mjs +226 -0
  72. package/src/factory/report/gate-section.mjs +122 -0
  73. package/src/factory/report/metrics.mjs +111 -0
  74. package/src/factory/report/reads.mjs +246 -0
  75. package/src/factory/report/render.mjs +121 -0
  76. package/src/factory/report/rollout.mjs +154 -0
  77. package/src/factory/review/brief.mjs +195 -0
  78. package/src/factory/review/command.mjs +182 -0
  79. package/src/factory/run/awake.mjs +70 -0
  80. package/src/factory/run/collect.mjs +77 -0
  81. package/src/factory/run/command.mjs +556 -0
  82. package/src/factory/run/gh.mjs +46 -0
  83. package/src/factory/run/launch.mjs +66 -0
  84. package/src/factory/run/pipelines.mjs +694 -0
  85. package/src/factory/run/raw.mjs +96 -0
  86. package/src/factory/run/restart.mjs +83 -0
  87. package/src/factory/run/s3.mjs +193 -0
  88. package/src/factory/run/secrets.mjs +142 -0
  89. package/src/factory/run/teardown.mjs +242 -0
  90. package/src/factory/run/token.mjs +70 -0
  91. package/src/factory/run/worktree.mjs +160 -0
  92. package/src/factory/security/audit.mjs +353 -0
  93. package/src/factory/security/command.mjs +157 -0
  94. package/src/factory/setup/app.mjs +122 -0
  95. package/src/factory/setup/command.mjs +472 -0
  96. package/src/factory/setup/labels.mjs +25 -0
  97. package/src/factory/setup/reads.mjs +159 -0
  98. package/src/factory/setup/writes.mjs +138 -0
  99. package/src/factory/snapshot/write.mjs +176 -0
  100. package/src/factory/stop/command.mjs +136 -0
  101. package/src/factory/sweep/actions-main.mjs +119 -0
  102. package/src/factory/sweep/command.mjs +65 -0
  103. package/src/factory/sweep/knobs.mjs +78 -0
  104. package/src/factory/sweep/marker-version.mjs +15 -0
  105. package/src/factory/sweep/markers.mjs +112 -0
  106. package/src/factory/sweep/overlap.mjs +24 -0
  107. package/src/factory/sweep/run.mjs +198 -0
  108. package/src/factory/sweep/shell.mjs +398 -0
  109. package/src/factory/sweep/split.mjs +104 -0
  110. package/src/factory/sweep/states.mjs +87 -0
  111. package/src/factory/sweep/sweep-core.mjs +2009 -0
  112. package/src/factory/tracker/github.mjs +713 -0
  113. package/src/factory/tracker/operations.mjs +153 -0
  114. package/src/factory/upgrade/index.mjs +83 -0
  115. package/src/init.mjs +62 -24
  116. package/src/kit-owned-paths.mjs +1 -1
  117. package/src/stage/build.mjs +100 -0
  118. package/src/stage/factory-live.mjs +288 -0
  119. package/src/stage.mjs +100 -4
  120. package/src/upgrade.mjs +39 -7
package/README.md CHANGED
@@ -36,11 +36,12 @@ npx @mnaimfaizy/agent-kit harness test custom:<name>
36
36
  - `stage audit` is the Launcher's path for the static security audit, which the [security audit workflow](../docs/security-audit.md#the-audit-through-the-launcher) calls for `codex`. It takes the brief and writes the report to `--result`, the raw transcript to `--transcript` and the error output to `--error-log`, each a new file. The harness is `--harness`'s, else `AGENT_KIT_SECURITY_AUDIT_HARNESS`, else `AGENT_KIT_HARNESS`, else `claude-code`, and it takes `deep-scan`'s `--credential`, `--credential-from`, `--model`, `--effort`, limit flags and `--proving-run`; a pair below `tried` is refused without that flag. It copies the checked-out commit into the same sandbox on an accepted runtime, without the harness's own config, with its instruction files from `--trusted-ref` (default the checked-out commit), and with untracked files only under `--untracked`. It exits 0 only when the harness exited cleanly and left an audit report, 3 when a limit stopped it. It refuses a GitHub token in its environment and writes nothing to GitHub.
37
37
  - `stage plan` is the Launcher's path for the plan, which the [plan workflow](../docs/plan-implement-review.md#the-plan-through-the-launcher) calls for [every harness but `claude-code`](../docs/harnesses.md#which-harness-runs-each-stage) (on `cursor` the key sits in the sandbox, in the weaker form: [Cursor CLI](../docs/harnesses.md#cursor-cli)). It takes `stage audit`'s flags except `--untracked`, which it refuses, with the harness else from `AGENT_KIT_PLAN_HARNESS`, and runs a pair at `documented` with a warning. It exits 0 only when the harness exited cleanly and left a plan, a Markdown file that opens with `## Agent plan`, at most 256 KiB; 3 when a limit stopped it. It writes nothing to GitHub: the workflow's trusted step posts the plan.
38
38
  - `stage review` is the Launcher's path for the review, which the [review workflow](../docs/plan-implement-review.md#the-review-through-the-launcher) calls for [every harness but `claude-code`](../docs/harnesses.md#which-harness-runs-each-stage) (on `cursor` the key sits in the sandbox, in the weaker form: [Cursor CLI](../docs/harnesses.md#cursor-cli)). It takes `stage audit`'s flags except `--untracked`, which it refuses, with the harness else from `AGENT_KIT_REVIEW_HARNESS`, runs a pair at `documented` with a warning, and takes `--input <file>`, repeatable, to copy a prepared file such as the diff in beside the brief. It exits 0 only when the harness exited cleanly and left a JSON result of the review's shape, at most 256 KiB; 3 when a limit stopped it. It writes nothing to GitHub: the workflow's trusted step posts the result.
39
+ - `stage build` is not a shell command: the Orchestrate engine runs it in process (the Chief of Staff in factory mode, with its Snapshot and Outbox folders), and it has no flags for them ([the build Stage](../docs/factory/orchestrate.md)).
39
40
  - `stage implement` is the Launcher's path for the implementer, which the [implement workflow](../docs/plan-implement-review.md#the-implementer-through-the-launcher) calls for [every harness but `claude-code`](../docs/harnesses.md#which-harness-runs-each-stage) (on `cursor` the key sits in the sandbox, in the weaker form: [Cursor CLI](../docs/harnesses.md#cursor-cli)). It takes `stage review`'s flags, with the harness else from `AGENT_KIT_IMPLEMENT_HARNESS`, and `--bundle <file>`. `--sandbox-image <ref>` names the image the harness is layered on, glibc Linux with git and bash (default: the kit's Harness image; a tag is accepted and its digest printed); `--setup-commands <file>` runs in a setup container of its own, reaching the `--setup-registries <hosts>` alone (none: no network); the agent then runs, with the network cut, in a fresh container from the same image that takes only the workspace, `.git/` and the checkout from the trusted commit, and the absolute paths `--setup-paths <paths>` names, one per line (default: none; the harness's files, shell and git config, `/etc`, `/tmp` and the image's program and library folders are refused; ADR 0047). With `--verify-commands <file>` it is the verify run instead: no agent, brief or credential; it runs the setup the same way, and those commands with no network in the fresh container, on the checked-out commit, exiting 0 when they pass ([the sandbox image and setup](../docs/plan-implement-review.md#the-sandbox-image-and-setup)). The sandbox's copy is a git repository holding the checked-out commit alone, and the agent commits there. It exits 0 only when the harness exited cleanly and left both a JSON `title` and `body`, at most 64 KiB, and a git bundle of at least one commit; a run a limit stopped (exit 3) writes neither. It pushes nothing and writes nothing to GitHub: the workflow's trusted jobs validate the bundle, push it and open the draft pull request.
40
41
  - `stage review-response` is the Launcher's path for the Review responder, which the [Review response workflow](../docs/review-response.md#the-responder-through-the-launcher) calls for [every harness but `claude-code`](../docs/harnesses.md#which-harness-runs-each-stage). It takes `stage implement`'s flags (the sandbox, setup and `--bundle`, not `--input` or `--verify-commands`), with the harness else from `AGENT_KIT_REVIEW_RESPONSE_HARNESS`. The agent commits in the same one-commit repository, and the result is a JSON object whose one key, `findings`, holds a reply and Verdict for each thread: at most 150 KB and 20 entries, each with a `thread_id`, a `verdict` (`fixed`, `addressed` or `declined`), a `reply`, and a full `commit` sha for `fixed` alone. A round with no commit is a whole round: it writes the result and no bundle. The workflow's trusted jobs check every thread against a Work list publish rebuilds from GitHub (a reviewer thread resolved since is dropped with a note; any other unknown thread fails the run), validate the bundle, push it and post the replies; nothing here does.
41
42
  - `harness test custom:<name>` runs the live probe suite on a [Custom harness](../docs/harnesses.md#custom-harness) file, `.agent-kit/harnesses/<name>.json`, as the default branch (or `--trusted-ref`) holds it, against a stub model under gVisor, with no model credential. It is the first half of a Proving run. `deep-scan` and `stage` take the same `custom:<name>`, reading the file from the same trusted commit, and `doctor` checks it.
42
43
  - `deep-scan --verify <file> --ref <ref>` is a [Verification run](../docs/security-audit.md#verification-run): it re-attempts the Reproduction of the findings in `<file>` (each a `###` section with `- **Concept id:**`, `- **Location:**` and `- **Observation:**`, as a deep report gives them) on `<ref>`, a local branch, tag or commit such as your fix branch, exported as committed, never the working tree. The recipe, the skill and the Threat pack still come from the default branch. It is confirm-only (no `full` walk, no exploration, no new findings): the agent gets the Verification-run procedure, not the full deep procedure, and the finding file goes in with its brief after the network cut. Its defaults are scan 15 min, 50 turns and the same token cap. Each flag needs the other, and `--report` is not taken with them (usage errors, exit 2). A finding file that is missing, unreadable or out of shape, or a ref that is not a local commit, is refused, exit 1, before any runtime starts. The report goes only to a new private folder; `deep-scan` prints each finding's `Reproduced: yes` (the fix does not hold) or `no` (it holds), exits 1 if the report misses one, and files or posts nothing. It is local only: refused, exit 1, in GitHub Actions (`GITHUB_ACTIONS=true`).
43
44
 
44
- The package version matches the Agent-kit Release line: `@mnaimfaizy/agent-kit@1.0.0-beta.15` is published from tag `v1.0.0-beta.15`, with npm provenance.
45
+ The package version matches the Agent-kit Release line: `@mnaimfaizy/agent-kit@1.0.0-beta.17` is published from tag `v1.0.0-beta.17`, with npm provenance.
45
46
 
46
47
  Full documentation: [Getting started](https://github.com/mnaimfaizy/agent-kit/blob/main/docs/getting-started.md) and [Adopt](https://github.com/mnaimfaizy/agent-kit/blob/main/docs/adopt.md#check-an-adoption-with-doctor).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnaimfaizy/agent-kit",
3
- "version": "1.0.0-beta.15",
3
+ "version": "1.0.0-beta.17",
4
4
  "description": "Adopt, upgrade and check Agent-kit in a Consumer repository. Reads kit files from the pinned git tag.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -6,8 +6,16 @@
6
6
  // tearing the sandbox down), 130 or 143 one was interrupted by SIGINT or
7
7
  // SIGTERM (likewise).
8
8
 
9
+ import { readFileSync } from "node:fs";
10
+ import { homedir, hostname } from "node:os";
9
11
  import { parseArgs } from "node:util";
10
12
  import { runDeepScan } from "./deep-scan.mjs";
13
+ import { runFactoryReport } from "./factory/report/command.mjs";
14
+ import { parseDuration, runFactoryRun } from "./factory/run/command.mjs";
15
+ import { patPermissionsSummary, runFactorySetup } from "./factory/setup/command.mjs";
16
+ import { readLock, stateDirOf } from "./factory/engine/lockfile.mjs";
17
+ import { runFactoryStop } from "./factory/stop/command.mjs";
18
+ import { runFactorySweep } from "./factory/sweep/command.mjs";
11
19
  import { formatReport, runDoctor } from "./doctor.mjs";
12
20
  import { runHarnessTest } from "./harness-test.mjs";
13
21
  import { REPO_PATTERN, sanitizeLine } from "./checks/result.mjs";
@@ -20,6 +28,20 @@ import { runUpgrade } from "./upgrade.mjs";
20
28
 
21
29
  export const VERSION = CLI_VERSION;
22
30
 
31
+ /** Wrap `text` to `width` columns; lines after the first start with `indent` spaces. */
32
+ function wrapHelp(text, indent, width) {
33
+ const lines = [];
34
+ let line = "";
35
+ for (const word of text.split(" ")) {
36
+ if (line && line.length + 1 + word.length > width - 0) {
37
+ lines.push(line);
38
+ line = word;
39
+ } else line = line ? `${line} ${word}` : word;
40
+ }
41
+ lines.push(line);
42
+ return lines.join(`\n${" ".repeat(indent)}`);
43
+ }
44
+
23
45
  const USAGE = `Usage: agent-kit <command> [options]
24
46
 
25
47
  Commands:
@@ -54,6 +76,30 @@ Commands:
54
76
  checked-out commit in, hands the harness the brief it is
55
77
  given, and writes the Stage result and the raw transcript to
56
78
  private files. Writes nothing to GitHub.
79
+ factory factory setup: the GitHub side of adopting the Factory (after
80
+ init --factory): labels, the pinned and locked control issue, the App and
81
+ its key, the ruleset. Asks before each write.
82
+ factory sweep: one sweep of this repository's factory issues,
83
+ the same sweep the factory-dispatcher workflow runs. With the
84
+ Kill switch AGENT_KIT_FACTORY_ENABLED exactly true, it claims each
85
+ queued, ready-for-agent issue (a Claim comment, read back), sets
86
+ factory:planning and starts that Stage's Caller; a queued issue
87
+ without ready-for-agent goes to factory:needs-decision. Otherwise
88
+ it changes nothing. The Kill switch is read from the environment,
89
+ else from the repository's variables.
90
+ factory report: how the Factory is doing, from the tracker alone
91
+ and your own gh login: merge rate, first-pass success, lead time,
92
+ escalation and revert rates and tokens per merged pull request,
93
+ by Risk tier; the Rollout phase your config matches and whether
94
+ the next bar is met. Reads only; posts nothing.
95
+ factory stop: stops the Factory at once, as gh run cancel would:
96
+ cancels every queued or running run of the Dispatcher and the
97
+ Stage Callers. Releases no Claim; never sets the Kill switch.
98
+ On a machine running factory run it also asks that engine to drain.
99
+ factory run: the Orchestrate engine (preview): the same sweep, run
100
+ from this machine in a loop, with Stages in Launcher sandboxes.
101
+ Needs AGENT_KIT_GITHUB_TOKEN (a fine-grained token for this one
102
+ repository, or an op:// reference) and a model key.
57
103
  harness harness test custom:<name>: run the live probe suite on your
58
104
  own Custom harness file, against a stub model, in the real
59
105
  sandbox under gVisor. The first half of a Proving run. It needs
@@ -65,6 +111,21 @@ Options for doctor:
65
111
  --strict Treat warnings as failures.
66
112
  --repo <o/r> The GitHub repository to check (default: gh's choice for
67
113
  the current directory).
114
+ On the Orchestrate engine doctor also checks the PAT's reach and reads, through
115
+ AGENT_KIT_GITHUB_TOKEN where it holds a literal (not an op:// reference).
116
+
117
+ Options for init --factory (adopt the Factory blueprint; local files only; each answer is asked
118
+ for when missing, on a terminal; --tag and --yes and --force work as below):
119
+ --factory Write the Factory blueprint instead of the flows: the
120
+ Callers, the factory config, the risk rules, CODEOWNERS
121
+ lines, a ruleset JSON and the Kit-owned bundle.
122
+ --engine <e> workflow (default) or orchestrate (no Callers, no bundle,
123
+ nothing for the App; the steps printed name the PAT and
124
+ the host recipe, docs/factory/host.md).
125
+ --codeowners <owners> Who approves changes to the Guarded paths (@login or
126
+ @org/team, comma-separated).
127
+ --ci-checks <names> Your CI's check names, which the ruleset requires
128
+ (comma-separated; never a factory/* context).
68
129
 
69
130
  Options for init (each one is asked for when missing, on a terminal):
70
131
  --tag <vX> The Agent-kit tag to adopt.
@@ -189,6 +250,11 @@ min, scan 30 min, 100 turns, 5000000 tokens):
189
250
  --transcript <file> Write the harness's raw event stream here
190
251
  (default: a new private folder). Never read.
191
252
  --error-log <file> Write the harness's error output here.
253
+ --usage <file> Write the run's usage here, as JSON with two keys:
254
+ tokens (the model proxy's count) and stopped
255
+ (turns, tokens, minutes or null). Nothing the
256
+ agent wrote. Absent on a harness the proxy cannot
257
+ front.
192
258
  --trusted-ref <ref> The commit the harness's instruction files come
193
259
  from (default: the checked-out one). A Custom
194
260
  harness's file is read from it too (without it,
@@ -254,6 +320,49 @@ Options for harness test:
254
320
  Exit codes: 0 every Guard held in every scenario, 1 refused or failed, 2
255
321
  usage error.
256
322
 
323
+ Options for factory setup (needs a terminal and an admin gh login; refuses in CI;
324
+ asks before each write; safe to run again; never sets the Kill switch):
325
+ --repo <o/r> The repository to set up (default: gh's choice for the
326
+ current directory).
327
+ --engine <e> workflow (default: labels, the pinned and locked control issue, the
328
+ GitHub App and its key, the ruleset) or orchestrate (labels,
329
+ control issue and ruleset; no App; prints the PAT's steps:
330
+ one repository, ${wrapHelp(patPermissionsSummary(), 18, 62)}).
331
+
332
+ Options for factory sweep:
333
+ --repo <o/r> The repository to sweep (default: GITHUB_REPOSITORY, else
334
+ gh's choice for the current directory).
335
+ --dry-run Read the tracker and print the actions, write nothing.
336
+ Exit codes: 0 swept or drained, 1 an action failed, 2 usage error.
337
+
338
+ Options for factory run (the Orchestrate engine, preview; one engine per repository):
339
+ --repo <o/r> The repository to run (default: GITHUB_REPOSITORY, else gh's
340
+ choice for the current directory).
341
+ --once Run one sweep, wait for the Stages it started, and exit.
342
+ --drain <dur> How long a first Ctrl-C lets running Stages finish before it
343
+ cancels them (default 10m; 90s, 10m, 2h). A second Ctrl-C
344
+ stops at once.
345
+ --poll <dur> The time between sweeps (default 60s, at least 30s).
346
+ --upload-raw Also upload each run folder to the S3 raw-folder Sink, once its
347
+ bucket's lifecycle expires raw/ (never the security Stage).
348
+ Without it nothing raw leaves the machine.
349
+ Exit codes: 0 drained or swept, 1 refused (token, lease, lock) or the lease lost
350
+ during the run, 2 usage error or a missing secret, 130 stopped at once.
351
+
352
+ Options for factory stop (cancels workflow runs only; needs a gh login with
353
+ actions write):
354
+ --repo <o/r> The repository to stop (default: GITHUB_REPOSITORY, else
355
+ gh's choice for the current directory).
356
+ Exit codes: 0 stopped (or nothing running), 1 a cancel failed, 2 usage error.
357
+
358
+ Options for factory report (reads only; never posts):
359
+ --repo <o/r> The repository to report on (default: GITHUB_REPOSITORY, else
360
+ gh's choice for the current directory).
361
+ --since <Nd> The window of tasks that reached a terminal state (default 30d).
362
+ --json Print the stable factory-report/1 JSON instead of text.
363
+ --gate Add the shadow-to-on bar per tier, from the merge gate's comments.
364
+ Exit codes: 0 reported, 1 a read failed, 2 usage error.
365
+
257
366
  Options for upgrade:
258
367
  --tag <vY> The Agent-kit tag to move to (asked for when missing).
259
368
  --from <vX> The tag you are leaving, when the pins already name <vY>
@@ -268,6 +377,18 @@ Options for upgrade:
268
377
 
269
378
  const COMMAND_OPTIONS = {
270
379
  doctor: ["ci", "strict", "repo"],
380
+ factory: [
381
+ "repo",
382
+ "dry-run",
383
+ "engine",
384
+ "since",
385
+ "json",
386
+ "gate",
387
+ "once",
388
+ "drain",
389
+ "poll",
390
+ "upload-raw",
391
+ ],
271
392
  harness: ["trusted-ref", "default-branch"],
272
393
  init: [
273
394
  "tag",
@@ -280,6 +401,10 @@ const COMMAND_OPTIONS = {
280
401
  "threat-pack-dir",
281
402
  "yes",
282
403
  "force",
404
+ "factory",
405
+ "engine",
406
+ "codeowners",
407
+ "ci-checks",
283
408
  ],
284
409
  upgrade: ["tag", "from", "yes", "force"],
285
410
  "deep-scan": [
@@ -315,6 +440,7 @@ const COMMAND_OPTIONS = {
315
440
  "bundle",
316
441
  "transcript",
317
442
  "error-log",
443
+ "usage",
318
444
  "trusted-ref",
319
445
  "untracked",
320
446
  "input",
@@ -369,6 +495,18 @@ export async function main(argv, io) {
369
495
  ci: { type: "boolean" },
370
496
  strict: { type: "boolean" },
371
497
  repo: { type: "string" },
498
+ "dry-run": { type: "boolean" },
499
+ since: { type: "string" },
500
+ json: { type: "boolean" },
501
+ gate: { type: "boolean" },
502
+ once: { type: "boolean" },
503
+ drain: { type: "string" },
504
+ poll: { type: "string" },
505
+ "upload-raw": { type: "boolean" },
506
+ factory: { type: "boolean" },
507
+ engine: { type: "string" },
508
+ codeowners: { type: "string" },
509
+ "ci-checks": { type: "string" },
372
510
  tag: { type: "string" },
373
511
  from: { type: "string" },
374
512
  flows: { type: "string" },
@@ -395,6 +533,7 @@ export async function main(argv, io) {
395
533
  bundle: { type: "string" },
396
534
  transcript: { type: "string" },
397
535
  "error-log": { type: "string" },
536
+ usage: { type: "string" },
398
537
  "trusted-ref": { type: "string" },
399
538
  untracked: { type: "boolean" },
400
539
  input: { type: "string", multiple: true },
@@ -429,7 +568,11 @@ export async function main(argv, io) {
429
568
  }
430
569
  // `stage` takes its Stage's name; no other command takes an argument.
431
570
  if (command === "stage") {
432
- const names = Object.keys(STAGE_COMMANDS).join(", ");
571
+ // `build` runs in process, from the engine (it has no flags for its folders): not a shell Stage.
572
+ const names = Object.entries(STAGE_COMMANDS)
573
+ .filter(([, definition]) => !definition.FACTORY)
574
+ .map(([name]) => name)
575
+ .join(", ");
433
576
  if (!rest.length) {
434
577
  stderr(`stage needs a Stage name: ${names}`);
435
578
  return 2;
@@ -438,6 +581,27 @@ export async function main(argv, io) {
438
581
  stderr(`stage takes one Stage, got: ${rest.join(" ")}`);
439
582
  return 2;
440
583
  }
584
+ } else if (command === "factory") {
585
+ if (rest.length !== 1 || !["sweep", "setup", "report", "stop", "run"].includes(rest[0])) {
586
+ stderr(
587
+ "factory takes `sweep`, `setup`, `report`, `stop` or `run`, as in: agent-kit factory setup",
588
+ );
589
+ return 2;
590
+ }
591
+ const runOnly =
592
+ rest[0] === "run"
593
+ ? []
594
+ : ["once", "drain", "poll", "upload-raw"].filter((k) => values[k] !== undefined);
595
+ if (runOnly.length) {
596
+ stderr(`factory ${rest[0]} does not take ${runOnly.map((k) => `--${k}`).join(", ")}`);
597
+ return 2;
598
+ }
599
+ const own =
600
+ rest[0] === "report" ? [] : ["since", "json", "gate"].filter((k) => values[k] !== undefined);
601
+ if (own.length) {
602
+ stderr(`factory ${rest[0]} does not take ${own.map((k) => `--${k}`).join(", ")}`);
603
+ return 2;
604
+ }
441
605
  } else if (command === "harness") {
442
606
  if (rest.length !== 2 || rest[0] !== "test") {
443
607
  stderr("harness takes `test custom:<name>`, as in: agent-kit harness test custom:mine");
@@ -458,14 +622,46 @@ export async function main(argv, io) {
458
622
  io.runner ??
459
623
  // `stage` and `harness test` run in the Deep scan's sandbox, on the same
460
624
  // commands.
461
- runnerFor(command === "stage" || command === "harness" ? "deep-scan" : command, {
462
- ...(io.spawn ? { spawn: io.spawn } : {}),
463
- ...(io.spawnAsync ? { spawnAsync: io.spawnAsync } : {}),
464
- });
625
+ // `factory sweep` reaches only `git` and `gh`, on `doctor`'s allowlist.
626
+ runnerFor(
627
+ command === "stage" || command === "harness"
628
+ ? "deep-scan"
629
+ : command === "factory"
630
+ ? rest[0] === "run"
631
+ ? "factory-run"
632
+ : "doctor"
633
+ : command,
634
+ {
635
+ ...(io.spawn ? { spawn: io.spawn } : {}),
636
+ ...(io.spawnAsync ? { spawnAsync: io.spawnAsync } : {}),
637
+ },
638
+ );
465
639
 
466
640
  if (command === "init") {
467
641
  stdout(`agent-kit init ${VERSION}`);
642
+ const factoryOnly = ["engine", "codeowners", "ci-checks"].filter(
643
+ (k) => values[k] !== undefined,
644
+ );
645
+ if (!values.factory && factoryOnly.length) {
646
+ stderr(`${factoryOnly.map((k) => `--${k}`).join(", ")} only go with init --factory`);
647
+ return 2;
648
+ }
649
+ const flowFlags = ["flows", "actors", "verify", "preset", "harness", "threat-pack-dir"].filter(
650
+ (k) => values[k] !== undefined,
651
+ );
652
+ if (values.factory && flowFlags.length) {
653
+ stderr(`init --factory does not take ${flowFlags.map((k) => `--${k}`).join(", ")}`);
654
+ return 2;
655
+ }
468
656
  return runInit({
657
+ ...(values.factory
658
+ ? {
659
+ factory: {
660
+ engine: values.engine ?? "workflow",
661
+ flags: { codeowners: values.codeowners, ciChecks: values["ci-checks"] },
662
+ },
663
+ }
664
+ : {}),
469
665
  cwd,
470
666
  runner,
471
667
  flags: {
@@ -527,6 +723,7 @@ export async function main(argv, io) {
527
723
  bundlePath: values.bundle,
528
724
  transcriptPath: values.transcript,
529
725
  errorLogPath: values["error-log"],
726
+ usagePath: values.usage,
530
727
  trustedRef: values["trusted-ref"],
531
728
  untracked: Boolean(values.untracked),
532
729
  inputPaths: values.input,
@@ -556,6 +753,136 @@ export async function main(argv, io) {
556
753
  err: stderr,
557
754
  });
558
755
  }
756
+ if (command === "factory" && rest[0] === "run") {
757
+ const unfit = ["dry-run", "engine", "since", "json", "gate"].filter(
758
+ (k) => values[k] !== undefined,
759
+ );
760
+ if (unfit.length) {
761
+ stderr(`factory run does not take ${unfit.map((k) => `--${k}`).join(", ")}`);
762
+ return 2;
763
+ }
764
+ if (values.repo !== undefined && !REPO_PATTERN.test(values.repo)) {
765
+ stderr(`--repo must be owner/name, got: ${JSON.stringify(values.repo)}`);
766
+ return 2;
767
+ }
768
+ const drainMs = values.drain === undefined ? undefined : parseDuration(values.drain);
769
+ const pollMs = values.poll === undefined ? undefined : parseDuration(values.poll);
770
+ if (drainMs === null || pollMs === null) {
771
+ stderr(`${drainMs === null ? "--drain" : "--poll"} is a duration such as 90s, 10m or 2h`);
772
+ return 2;
773
+ }
774
+ stdout(`agent-kit factory run ${VERSION}`);
775
+ return runFactoryRun({
776
+ runner,
777
+ env: io.env ?? process.env,
778
+ repo: values.repo,
779
+ once: Boolean(values.once),
780
+ uploadRaw: Boolean(values["upload-raw"]),
781
+ cwd,
782
+ ...(drainMs === undefined ? {} : { drainMs }),
783
+ ...(pollMs === undefined ? {} : { pollMs }),
784
+ ...(io.clock ? { clock: io.clock } : {}),
785
+ ...(io.nonce ? { nonce: io.nonce } : {}),
786
+ ...(io.signals ? { signals: io.signals } : {}),
787
+ ...(io.platform ? { platform: io.platform } : {}),
788
+ ...(io.engineHost ?? {}),
789
+ out: stdout,
790
+ err: stderr,
791
+ });
792
+ }
793
+ if (command === "factory" && rest[0] === "report") {
794
+ const unfit = ["dry-run", "engine"].filter((k) => values[k] !== undefined);
795
+ if (unfit.length) {
796
+ stderr(`factory report does not take ${unfit.map((k) => `--${k}`).join(", ")}`);
797
+ return 2;
798
+ }
799
+ if (values.repo !== undefined && !REPO_PATTERN.test(values.repo)) {
800
+ stderr(`--repo must be owner/name, got: ${JSON.stringify(values.repo)}`);
801
+ return 2;
802
+ }
803
+ return runFactoryReport({
804
+ runner,
805
+ env: io.env ?? process.env,
806
+ repo: values.repo,
807
+ since: values.since,
808
+ json: Boolean(values.json),
809
+ gate: Boolean(values.gate),
810
+ ...(io.clock ? { clock: io.clock } : {}),
811
+ out: stdout,
812
+ err: stderr,
813
+ });
814
+ }
815
+ if (command === "factory" && rest[0] === "stop") {
816
+ const unfit = ["dry-run", "engine"].filter((k) => values[k] !== undefined);
817
+ if (unfit.length) {
818
+ stderr(`factory stop does not take ${unfit.map((k) => `--${k}`).join(", ")}`);
819
+ return 2;
820
+ }
821
+ if (values.repo !== undefined && !REPO_PATTERN.test(values.repo)) {
822
+ stderr(`--repo must be owner/name, got: ${JSON.stringify(values.repo)}`);
823
+ return 2;
824
+ }
825
+ stdout(`agent-kit factory stop ${VERSION}`);
826
+ return runFactoryStop({
827
+ gh: (args) => runner("gh", args),
828
+ env: io.env ?? process.env,
829
+ repo: values.repo,
830
+ local: io.localEngine ?? {
831
+ holder: (slug) =>
832
+ readLock({
833
+ dir: stateDirOf(homedir(), slug),
834
+ fs: { readFileSync },
835
+ }),
836
+ host: hostname(),
837
+ kill: (pid) => process.kill(pid, "SIGTERM"),
838
+ },
839
+ out: stdout,
840
+ err: stderr,
841
+ });
842
+ }
843
+ if (command === "factory" && rest[0] === "setup") {
844
+ stdout(`agent-kit factory setup ${VERSION}`);
845
+ if (values["dry-run"]) {
846
+ stderr("factory setup does not take --dry-run");
847
+ return 2;
848
+ }
849
+ if (values.repo !== undefined && !REPO_PATTERN.test(values.repo)) {
850
+ stderr(`--repo must be owner/name, got: ${JSON.stringify(values.repo)}`);
851
+ return 2;
852
+ }
853
+ return runFactorySetup({
854
+ runner,
855
+ env: io.env ?? process.env,
856
+ repo: values.repo,
857
+ engine: values.engine ?? "workflow",
858
+ cwd,
859
+ prompt,
860
+ ...(io.appFlow ? { appFlow: io.appFlow } : {}),
861
+ out: stdout,
862
+ err: stderr,
863
+ });
864
+ }
865
+ if (command === "factory") {
866
+ if (values.engine !== undefined) {
867
+ stderr("factory sweep does not take --engine");
868
+ return 2;
869
+ }
870
+ stdout(`agent-kit factory sweep ${VERSION}`);
871
+ if (values.repo !== undefined && !REPO_PATTERN.test(values.repo)) {
872
+ stderr(`--repo must be owner/name, got: ${JSON.stringify(values.repo)}`);
873
+ return 2;
874
+ }
875
+ return runFactorySweep({
876
+ runner,
877
+ env: io.env ?? process.env,
878
+ repo: values.repo,
879
+ dryRun: Boolean(values["dry-run"]),
880
+ ...(io.clock ? { clock: io.clock } : {}),
881
+ ...(io.nonce ? { nonce: io.nonce } : {}),
882
+ out: stdout,
883
+ err: stderr,
884
+ });
885
+ }
559
886
  if (command === "upgrade") {
560
887
  return upgrade(values, { cwd, runner, openRepo, prompt, stdout, stderr });
561
888
  }
@@ -47,6 +47,40 @@ import {
47
47
  import { failed, must, StepFailed, ENDS_HERE } from "./steps.mjs";
48
48
  import { singleFileOf } from "./tar.mjs";
49
49
 
50
+ /**
51
+ * The user every step runs as in a sandbox that asks for it (`runtime.agentUser`, set for the
52
+ * factory-mode build Stage alone): uid 1000, gid 1000, home /home/agent, as in a Docker Sandboxes
53
+ * template (sbx-driver.mjs). A user that is not root is what lets that Stage's Snapshot stay
54
+ * read-only to the agent (ADR 0039). Every other Stage runs as the image's user, root.
55
+ */
56
+ const AGENT_USER = "1000:1000";
57
+ const AGENT_HOME = "/home/agent";
58
+
59
+ /**
60
+ * Run as root once the sandbox is up: give uid 1000 a passwd entry (a harness may ask the
61
+ * system for its own user) and its home, whatever image the sandbox runs. An image that has
62
+ * a uid 1000 account (`node`) keeps it and its home; the others get /home/agent. `docker exec
63
+ * --user` takes HOME from the passwd entry, so no step sets it.
64
+ */
65
+ const MAKE_AGENT_HOME = [
66
+ "getent passwd 1000 >/dev/null 2>&1 || {",
67
+ " getent group 1000 >/dev/null 2>&1 || groupadd -g 1000 agent >/dev/null 2>&1 || echo 'agent:x:1000:' >> /etc/group;",
68
+ ` useradd -u 1000 -g 1000 -M -d ${AGENT_HOME} -s /bin/bash agent >/dev/null 2>&1 || echo 'agent:x:1000:1000::${AGENT_HOME}:/bin/sh' >> /etc/passwd;`,
69
+ "};",
70
+ 'home="$(getent passwd 1000 | cut -d: -f6)"; [ -n "$home" ] || home=' +
71
+ AGENT_HOME +
72
+ '; mkdir -p "$home" && chown 1000:1000 "$home"',
73
+ ].join(" ");
74
+
75
+ /**
76
+ * What `copyIn` runs, as root, after it unpacks: the sandbox's own user may write in /workspace
77
+ * and /agent-kit, except the factory-mode Stage's Snapshot (read-only to it) and Outbox (its own
78
+ * mode). /agent-kit itself is never loosened (-mindepth 1): 0777 without the sticky bit would
79
+ * let the agent swap the Snapshot link. As the Docker Sandboxes driver does.
80
+ */
81
+ const LOOSEN =
82
+ "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";
83
+
50
84
  /** The label every sandbox resource carries, so a stray one can be found. */
51
85
  export const LABEL = "agent-kit.deep-scan";
52
86
 
@@ -90,6 +124,8 @@ export function envArgs(env, secret, flag) {
90
124
  * @returns {import("./lifecycle.mjs").Driver}
91
125
  */
92
126
  export function dockerDriver({ runtime, id, call, plan }) {
127
+ /** True when every step runs as uid 1000 unless it names a user: the build Stage's sandbox. */
128
+ const asAgent = runtime.agentUser === true;
93
129
  const { displayName } = plan.identity;
94
130
  const name = `agent-kit-deep-${id}`;
95
131
  const label = `${LABEL}=${id}`;
@@ -211,13 +247,18 @@ export function dockerDriver({ runtime, id, call, plan }) {
211
247
  * writes into a running container is hidden from the sandbox once the
212
248
  * sandbox has looked up that path (#404).
213
249
  */
214
- async copyIn(tar, what) {
250
+ async copyIn(tar, what, { loosen = true } = {}) {
215
251
  must(
216
252
  await docker(["exec", "-i", "--user", "0:0", name, "tar", "-x", "-f", "-", "-C", "/"], {
217
253
  stdin: tar,
218
254
  }),
219
255
  what,
220
256
  );
257
+ // A copy made while the agent runs only unpacks: the loosening walks the tree as root, and
258
+ // a link the agent swaps in between `find` and `chmod` would make root chmod its target.
259
+ if (loosen && asAgent) {
260
+ await docker(["exec", "--user", "0:0", "--workdir", "/", name, "sh", "-c", LOOSEN]);
261
+ }
221
262
  },
222
263
 
223
264
  /** The harness is already in the image. */
@@ -265,10 +306,20 @@ export function dockerDriver({ runtime, id, call, plan }) {
265
306
 
266
307
  refused: () => proxy?.refused ?? [],
267
308
 
268
- exec: (script, { env = [], workdir = "/workspace" } = {}) => {
309
+ exec: (script, { env = [], workdir = "/workspace", user } = {}) => {
269
310
  const { args, childEnv } = envArgs(env, plan.launch?.secretEnv ?? [], "--env");
311
+ const runAs = user ?? (asAgent ? AGENT_USER : null);
270
312
  return docker(
271
- ["exec", ...args, ...(workdir ? ["--workdir", workdir] : []), name, "sh", "-c", script],
313
+ [
314
+ "exec",
315
+ ...(runAs ? ["--user", runAs] : []),
316
+ ...args,
317
+ ...(workdir ? ["--workdir", workdir] : []),
318
+ name,
319
+ "sh",
320
+ "-c",
321
+ script,
322
+ ],
272
323
  { env: childEnv },
273
324
  );
274
325
  },
@@ -426,6 +477,22 @@ export function dockerDriver({ runtime, id, call, plan }) {
426
477
  ]),
427
478
  what,
428
479
  );
480
+ if (asAgent) {
481
+ must(
482
+ await docker([
483
+ "exec",
484
+ "--user",
485
+ "0:0",
486
+ "--workdir",
487
+ "/",
488
+ name,
489
+ "sh",
490
+ "-c",
491
+ MAKE_AGENT_HOME,
492
+ ]),
493
+ "making the agent's home",
494
+ );
495
+ }
429
496
  }
430
497
 
431
498
  async function closeProxy() {
@@ -99,13 +99,13 @@ const SETUP_ORDER = ["setup", "start", "ready", "seed"];
99
99
  * container: string,
100
100
  * prepare: (steps: object, ctx: { archive: Function, out: Function, branch: string, short: string }) => Promise<void>,
101
101
  * start: (steps: object) => Promise<{ isolation?: string } | void>,
102
- * copyIn: (tar: Buffer, what: string) => Promise<void>,
102
+ * copyIn: (tar: Buffer, what: string, opts?: { loosen?: boolean }) => Promise<void>,
103
103
  * installAgent: (out: Function) => Promise<void>,
104
104
  * carryOut: (script: string, opts: { maxBytes: number }) => Promise<{ data: Buffer } | { error: string }>,
105
105
  * renew: () => Promise<void>,
106
106
  * openSetupEgress: (registries: string[]) => Promise<{ env: string[], note: string }>,
107
107
  * refused: () => string[],
108
- * exec: (script: string, opts?: { env?: string[], workdir?: string | null }) => Promise<import("../exec.mjs").StartResult>,
108
+ * exec: (script: string, opts?: { env?: string[], workdir?: string | null, user?: string }) => Promise<import("../exec.mjs").StartResult>,
109
109
  * cutEgress: () => Promise<void>,
110
110
  * egressLeft: () => Promise<string | null>,
111
111
  * openModelRoute: (startProxy: (bind: string) => Promise<{ port: number, close: () => Promise<void> }>) => Promise<{ url: string, note: string, isolation?: string }>,