@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.16

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 (110) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +314 -4
  4. package/src/doctor.mjs +53 -1
  5. package/src/exec.mjs +14 -5
  6. package/src/factory/budget/budget.mjs +259 -0
  7. package/src/factory/build/command.mjs +321 -0
  8. package/src/factory/build/factory.mjs +473 -0
  9. package/src/factory/build/findings.mjs +55 -0
  10. package/src/factory/build/host.mjs +230 -0
  11. package/src/factory/build/notes.mjs +191 -0
  12. package/src/factory/build/pull-request.mjs +74 -0
  13. package/src/factory/bundle.mjs +146 -0
  14. package/src/factory/checks/allowed-paths.mjs +50 -0
  15. package/src/factory/checks/plan-header.mjs +296 -0
  16. package/src/factory/checks/qa.mjs +85 -0
  17. package/src/factory/checks/review.mjs +73 -0
  18. package/src/factory/checks/security.mjs +50 -0
  19. package/src/factory/checks/stage-check.mjs +89 -0
  20. package/src/factory/claims/command.mjs +187 -0
  21. package/src/factory/claims/release.mjs +111 -0
  22. package/src/factory/decision/answers.mjs +103 -0
  23. package/src/factory/decision/command.mjs +64 -0
  24. package/src/factory/decision/plan.mjs +99 -0
  25. package/src/factory/decision/request.mjs +116 -0
  26. package/src/factory/doctor/files.mjs +329 -0
  27. package/src/factory/doctor/index.mjs +56 -0
  28. package/src/factory/doctor/local.mjs +497 -0
  29. package/src/factory/doctor/orchestrate.mjs +146 -0
  30. package/src/factory/engine/lease.mjs +146 -0
  31. package/src/factory/engine/local-engine.mjs +177 -0
  32. package/src/factory/engine/lockfile.mjs +64 -0
  33. package/src/factory/engine/workflow-engine.mjs +124 -0
  34. package/src/factory/gate/comment.mjs +88 -0
  35. package/src/factory/gate/config.mjs +57 -0
  36. package/src/factory/gate/gate-core.mjs +250 -0
  37. package/src/factory/gate/guarded.mjs +17 -0
  38. package/src/factory/gate/reads.mjs +105 -0
  39. package/src/factory/gate/task.mjs +193 -0
  40. package/src/factory/gate/trip-reads.mjs +82 -0
  41. package/src/factory/gate/trip.mjs +87 -0
  42. package/src/factory/init/blueprint.mjs +174 -0
  43. package/src/factory/init/index.mjs +337 -0
  44. package/src/factory/labels/evidence.mjs +162 -0
  45. package/src/factory/labels/moves.mjs +32 -0
  46. package/src/factory/labels/reconcile.mjs +267 -0
  47. package/src/factory/labels/revert.mjs +87 -0
  48. package/src/factory/labels/timeline.mjs +72 -0
  49. package/src/factory/labels/voided.mjs +59 -0
  50. package/src/factory/limits/harness.mjs +39 -0
  51. package/src/factory/limits/limits.mjs +123 -0
  52. package/src/factory/merge/command.mjs +172 -0
  53. package/src/factory/outbox/check.mjs +240 -0
  54. package/src/factory/outbox/rulings.mjs +195 -0
  55. package/src/factory/plan/command.mjs +66 -0
  56. package/src/factory/plan/comment.mjs +156 -0
  57. package/src/factory/plan/publish.mjs +149 -0
  58. package/src/factory/plan/risk.mjs +153 -0
  59. package/src/factory/qa/command.mjs +163 -0
  60. package/src/factory/records/engine-record.mjs +133 -0
  61. package/src/factory/records/main.mjs +96 -0
  62. package/src/factory/records/record.mjs +226 -0
  63. package/src/factory/records/sink.mjs +57 -0
  64. package/src/factory/report/build.mjs +92 -0
  65. package/src/factory/report/command.mjs +80 -0
  66. package/src/factory/report/facts.mjs +226 -0
  67. package/src/factory/report/gate-section.mjs +122 -0
  68. package/src/factory/report/metrics.mjs +111 -0
  69. package/src/factory/report/reads.mjs +246 -0
  70. package/src/factory/report/render.mjs +121 -0
  71. package/src/factory/report/rollout.mjs +154 -0
  72. package/src/factory/review/command.mjs +182 -0
  73. package/src/factory/run/awake.mjs +70 -0
  74. package/src/factory/run/collect.mjs +77 -0
  75. package/src/factory/run/command.mjs +490 -0
  76. package/src/factory/run/gh.mjs +46 -0
  77. package/src/factory/run/launch.mjs +47 -0
  78. package/src/factory/run/pipelines.mjs +261 -0
  79. package/src/factory/run/raw.mjs +96 -0
  80. package/src/factory/run/restart.mjs +83 -0
  81. package/src/factory/run/s3.mjs +193 -0
  82. package/src/factory/run/secrets.mjs +142 -0
  83. package/src/factory/run/teardown.mjs +242 -0
  84. package/src/factory/run/token.mjs +68 -0
  85. package/src/factory/security/command.mjs +157 -0
  86. package/src/factory/setup/app.mjs +122 -0
  87. package/src/factory/setup/command.mjs +409 -0
  88. package/src/factory/setup/labels.mjs +25 -0
  89. package/src/factory/setup/reads.mjs +129 -0
  90. package/src/factory/setup/writes.mjs +126 -0
  91. package/src/factory/snapshot/write.mjs +176 -0
  92. package/src/factory/stop/command.mjs +136 -0
  93. package/src/factory/sweep/actions-main.mjs +117 -0
  94. package/src/factory/sweep/command.mjs +65 -0
  95. package/src/factory/sweep/knobs.mjs +78 -0
  96. package/src/factory/sweep/marker-version.mjs +15 -0
  97. package/src/factory/sweep/markers.mjs +112 -0
  98. package/src/factory/sweep/overlap.mjs +24 -0
  99. package/src/factory/sweep/run.mjs +198 -0
  100. package/src/factory/sweep/shell.mjs +394 -0
  101. package/src/factory/sweep/split.mjs +104 -0
  102. package/src/factory/sweep/states.mjs +87 -0
  103. package/src/factory/sweep/sweep-core.mjs +1781 -0
  104. package/src/factory/tracker/github.mjs +674 -0
  105. package/src/factory/tracker/operations.mjs +153 -0
  106. package/src/factory/upgrade/index.mjs +83 -0
  107. package/src/init.mjs +62 -24
  108. package/src/kit-owned-paths.mjs +1 -1
  109. package/src/stage.mjs +19 -0
  110. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,153 @@
1
+ // The tracker adapter's named operations, as in TRACKERS.md, and how the
2
+ // `github` mapping realises each one. The sweep and its shell speak only these
3
+ // names; a second tracker would add a mapping beside `github`, not change them.
4
+ //
5
+ // `implemented` says whether the adapter realises the operation; every one does today. An
6
+ // operation marked `implemented: false` would throw when called, so a sweep that needs it
7
+ // fails loudly.
8
+
9
+ export const OPERATIONS = Object.freeze({
10
+ "read-state": {
11
+ implemented: true,
12
+ does: "Every open issue carrying a factory:* state label, with labels, the label timeline, comments (and who last edited each) and linked pull requests.",
13
+ github: "One GraphQL query, one aliased `issues(labels:)` field per state; then head statuses.",
14
+ },
15
+ "read-head-statuses": {
16
+ implemented: true,
17
+ does: "The commit statuses of each linked pull request's head commit.",
18
+ github:
19
+ "REST `GET repos/{r}/commits/{sha}/statuses?per_page=100` (newest first, every creator), one call per distinct head.",
20
+ },
21
+ "set-state": {
22
+ implemented: true,
23
+ does: "Move an issue's one Factory state label from one state to another.",
24
+ github: "REST: add the new label, then remove the old one (no compare-and-swap exists).",
25
+ },
26
+ claim: {
27
+ implemented: true,
28
+ does: "Write a Claim comment and return its id.",
29
+ github: "REST `POST repos/{r}/issues/{n}/comments`.",
30
+ },
31
+ "read-claim": {
32
+ implemented: true,
33
+ does: "Read an issue's comments again, fresh, to see which Claim won.",
34
+ github: "REST `GET repos/{r}/issues/{n}/comments`, paginated.",
35
+ },
36
+ release: {
37
+ implemented: true,
38
+ does: "Edit a Claim comment in place to add `released=<reason>`.",
39
+ github: "REST `GET` then `PATCH repos/{r}/issues/comments/{id}`.",
40
+ },
41
+ comment: {
42
+ implemented: true,
43
+ does: "Post a comment on an issue.",
44
+ github: "REST `POST repos/{r}/issues/{n}/comments`.",
45
+ },
46
+ "read-issue": {
47
+ implemented: true,
48
+ does: "An issue's body and labels, for the plan Stage's trusted step.",
49
+ github: "REST `GET repos/{r}/issues/{n}`.",
50
+ },
51
+ "read-comments": {
52
+ implemented: true,
53
+ does: "An issue's comments, fresh and complete, with their authors.",
54
+ github: "REST `GET repos/{r}/issues/{n}/comments`, paginated (the same read as `read-claim`).",
55
+ },
56
+ "post-comment": {
57
+ implemented: true,
58
+ does: "Post a comment from a body that may be large, and return its id and link.",
59
+ github: "REST `POST repos/{r}/issues/{n}/comments`, the body on stdin.",
60
+ },
61
+ "edit-comment": {
62
+ implemented: true,
63
+ does: "Replace a comment's body (a superseded plan's first line).",
64
+ github: "REST `PATCH repos/{r}/issues/comments/{id}`, the body on stdin.",
65
+ },
66
+ "read-file": {
67
+ implemented: true,
68
+ does: "A file's text on the base branch, or null when it is not there (the risk rules).",
69
+ github: "REST `GET repos/{r}/contents/{path}?ref={branch}`, raw media type.",
70
+ },
71
+ "read-writers": {
72
+ implemented: true,
73
+ does: "Which of some logins have write access, so only their replies to a Decision Request count.",
74
+ github:
75
+ "REST `GET repos/{r}/collaborators/{login}/permission`, one call per distinct login: `admin` and `write` count; a 404 is not a writer; any other failure throws.",
76
+ },
77
+ "read-pull": {
78
+ implemented: true,
79
+ does: "A pull request's state, head, base, changed paths and lines, and whether it merges cleanly (the merge gate).",
80
+ github: "REST `GET repos/{r}/pulls/{n}` and `.../files` (paginated); a diff cut short throws.",
81
+ },
82
+ "read-compare": {
83
+ implemented: true,
84
+ does: "How far one ref is ahead of and behind another, and the files that differ.",
85
+ github: "REST `GET repos/{r}/compare/{base}...{head}`; 300 files or more throws.",
86
+ },
87
+ "read-required-contexts": {
88
+ implemented: true,
89
+ does: "The status contexts the ruleset on a branch requires.",
90
+ github: "REST `GET repos/{r}/rules/branches/{branch}`: the `required_status_checks` rules.",
91
+ },
92
+ "read-checks": {
93
+ implemented: true,
94
+ does: "The checks and statuses on a commit or branch tip, by name, each success, failure or pending.",
95
+ github: "GraphQL `object(expression:) { ... on Commit { statusCheckRollup } }`.",
96
+ },
97
+ "update-branch": {
98
+ implemented: true,
99
+ does: "Merge the base into a pull request's branch, only if its head is the one the gate read.",
100
+ github: "REST `PUT repos/{r}/pulls/{n}/update-branch` with `expected_head_sha`.",
101
+ },
102
+ "write-stage-check": {
103
+ implemented: true,
104
+ does: "Write one Stage check on a commit (the gate's carry-over).",
105
+ github: "REST `POST repos/{r}/statuses/{sha}`, through the shared Stage check writer.",
106
+ },
107
+ "revert-label": {
108
+ implemented: true,
109
+ does: "Put an issue's labels back: add the state the evidence supports, then remove the wrong one.",
110
+ github: "REST `POST` then `DELETE repos/{r}/issues/{n}/labels`; a label already gone is done.",
111
+ },
112
+ "remove-label": {
113
+ implemented: true,
114
+ does: "Take one label off an issue (a Trigger label on a Factory issue).",
115
+ github: "REST `DELETE repos/{r}/issues/{n}/labels/{name}`; a label already gone is done.",
116
+ },
117
+ "read-control": {
118
+ implemented: true,
119
+ does: "The Factory control issue and its comments with who last edited each (the merge gate's trip marker).",
120
+ github:
121
+ "REST `GET repos/{r}/issues?state=open` to find the issue by its marker, then a GraphQL `issue.comments(first: 100, after: cursor)`, paged in full, for the editors.",
122
+ },
123
+ "add-assignee": {
124
+ implemented: true,
125
+ does: "Assign an issue to a login (the Orchestrate engine's Claims also assign the user).",
126
+ github: "REST `POST repos/{r}/issues/{n}/assignees`.",
127
+ },
128
+ "create-sub-issue": {
129
+ implemented: true,
130
+ does: "Create an issue under a parent, with its labels in the same request (a plan's split).",
131
+ github:
132
+ "REST `POST repos/{r}/issues` (title, body, labels), then `POST repos/{r}/issues/{parent}/sub_issues` with the new issue's id; an issue already attached is done.",
133
+ },
134
+ "add-blocked-by": {
135
+ implemented: true,
136
+ does: "Make one issue block another (a split child's `blocked_by`), unless it already does.",
137
+ github:
138
+ "REST `GET` then `POST repos/{r}/issues/{n}/dependencies/blocked_by` with the blocker's id.",
139
+ },
140
+ "read-split-parent": {
141
+ implemented: true,
142
+ does: "A split's parent: its state, comments with their last editor, and each sub-issue's state and whether it is merged.",
143
+ github:
144
+ "One GraphQL `issue(number:) { state comments subIssues }`; a sub-issue is merged when it is closed and carries `factory:merged`; more than 100 sub-issues throws.",
145
+ },
146
+ "close-issue": {
147
+ implemented: true,
148
+ does: "Close an issue as completed, after one comment (the parent of a split, once every child is merged).",
149
+ github: "REST `POST` a comment, then `PATCH repos/{r}/issues/{n}` with `state=closed`.",
150
+ },
151
+ });
152
+
153
+ export const OPERATION_NAMES = Object.freeze(Object.keys(OPERATIONS));
@@ -0,0 +1,83 @@
1
+ // The Factory's part of `agent-kit upgrade` (spec #500, #520), wired in by
2
+ // cli/src/upgrade.mjs. Upgrade replaces what the Kit owns: the bundle
3
+ // `.github/agent-factory/` is a Kit-owned path, so the Kit-owned step already
4
+ // replaces it whole, and every `uses:` pin of a Caller is moved to the new tag.
5
+ // What this adds is the second pin a Factory Caller holds: the version of the CLI
6
+ // it installs (`@mnaimfaizy/agent-kit@<version>`), which must be the tag's own.
7
+ //
8
+ // What upgrade never touches, and why that holds:
9
+ // - the factory config, the risk rules, the ruleset JSON and `CODEOWNERS` are the
10
+ // Consumer's after the first copy. They are no Kit-owned path: the parser of
11
+ // kit-owned-paths.txt takes only a short list of shapes for deletion (ALLOWED_SHAPE),
12
+ // so a tag that listed one is refused before anything is written. Only the two
13
+ // pins in a Caller are rewritten, and only in `.github/workflows/factory-*.yml`.
14
+ // - the control issue, the App and the secrets live on GitHub. Upgrade writes local
15
+ // files only: its runner is `git` and `gh` on doctor's allowlist, and it makes no `gh`
16
+ // call at all.
17
+ // Contract suite: scripts/factory-upgrade.test.mjs. Docs: docs/factory/upgrade.md.
18
+
19
+ import { versionForTag } from "../../tags.mjs";
20
+
21
+ /** The blueprint Callers, the only workflow files whose CLI pin upgrade moves. */
22
+ export const FACTORY_CALLER_PATH = /^\.github\/workflows\/factory-[a-z][a-z0-9-]*\.ya?ml$/;
23
+
24
+ const CLI_PIN = /(@mnaimfaizy\/agent-kit@)([0-9][0-9A-Za-z.+-]*)(?=$|[\s"'#\\])/gm;
25
+
26
+ /**
27
+ * `text` with every `@mnaimfaizy/agent-kit@<version>` moved to `version`. Only the
28
+ * version changes, so every other byte, the line endings included, stays.
29
+ * @returns {{ text: string, count: number }}
30
+ */
31
+ export function rewriteCliPins(text, version) {
32
+ let count = 0;
33
+ const next = String(text).replace(CLI_PIN, (all, prefix, found) => {
34
+ if (found === version) return all;
35
+ count++;
36
+ return `${prefix}${version}`;
37
+ });
38
+ return { text: next, count };
39
+ }
40
+
41
+ /**
42
+ * The edits of Factory Callers' CLI pins, laid over the edits upgrade already holds for their
43
+ * `uses:` pins (one write per file, holding both).
44
+ *
45
+ * @param {{
46
+ * files: { path: string, pins: object[] }[],
47
+ * edits: { path: string, count: number, bytes: Buffer, cliOnly?: boolean }[],
48
+ * readText: (path: string) => string,
49
+ * newTag: string,
50
+ * }} input
51
+ * @returns {{ edits: object[], cli: { path: string, count: number }[] }}
52
+ */
53
+ export function withCliPins({ files, edits, readText, newTag }) {
54
+ const version = versionForTag(newTag);
55
+ const byPath = new Map(edits.map((e) => [e.path, e]));
56
+ const cli = [];
57
+ for (const file of files) {
58
+ if (!FACTORY_CALLER_PATH.test(file.path)) continue;
59
+ const held = byPath.get(file.path);
60
+ const base = held ? held.bytes.toString("utf8") : readText(file.path);
61
+ const rewritten = rewriteCliPins(base, version);
62
+ if (rewritten.count === 0) continue;
63
+ cli.push({ path: file.path, count: rewritten.count });
64
+ byPath.set(file.path, {
65
+ path: file.path,
66
+ count: held?.count ?? 0,
67
+ cliOnly: held === undefined,
68
+ bytes: Buffer.from(rewritten.text, "utf8"),
69
+ });
70
+ }
71
+ // Keep the order upgrade already had, then the Callers only this step touched.
72
+ const order = [...edits.map((e) => e.path), ...cli.map((c) => c.path)];
73
+ return { edits: [...new Set(order)].map((p) => byPath.get(p)), cli };
74
+ }
75
+
76
+ /** The lines upgrade prints about the Factory when the checkout has one, after its examples/ diff. */
77
+ export function factoryNotes({ newTag }) {
78
+ return [
79
+ `The Factory blueprint (${"`.github/factory/`"} config, risk rules and ruleset, ${"`CODEOWNERS`"} lines) is yours:`,
80
+ `upgrade left it as it was and changed only the bundle and the Callers' pins. The examples/factory/ part of the diff above is for you to apply by hand where you want it.`,
81
+ `Nothing on GitHub was touched either: the control issue, the App and the secrets are as setup left them (${newTag}'s \`agent-kit factory setup\` is safe to run again).`,
82
+ ];
83
+ }
package/src/init.mjs CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  stageFileModes,
30
30
  uncommittedChanges,
31
31
  } from "./local-writes.mjs";
32
+ import { runFactoryInit } from "./factory/init/index.mjs";
32
33
  import { caseCollisions, checkSafePath, fileDirConflicts } from "./safe-paths.mjs";
33
34
  import { CLI_VERSION, isReleaseTag } from "./tags.mjs";
34
35
  import {
@@ -77,7 +78,7 @@ const HARNESS_NAME = /^[a-z][a-z0-9-]*$/;
77
78
  const SECRET_INPUT = /^[a-z][a-z0-9_]*$/;
78
79
  const HARNESS_FILE = "cli/harnesses.json";
79
80
  /** The first tag that ships `cli/harnesses.json`: older ones run claude-code alone. */
80
- const FIRST_HARNESS_TAG = "v1.0.0-beta.14";
81
+ const FIRST_HARNESS_TAG = "v1.0.0-beta.14"; // release:history
81
82
  /** The page that describes the Custom harness file. */
82
83
  const CUSTOM_DOCS_URL = `https://github.com/${DEFAULT_KIT_REPO}/blob/v${CLI_VERSION}/docs/adr/0027-a-harness-adapter-returns-a-launch-plan-as-data.md`;
83
84
 
@@ -525,6 +526,43 @@ function secretLines(harness, callers) {
525
526
  ];
526
527
  }
527
528
 
529
+ /**
530
+ * The Kit-owned paths `init` copies whole. One that already matches the tag
531
+ * (an earlier init, adding a flow now) is left as it is; any other existing
532
+ * one is an earlier adoption, replaced only with `force`. `skip` names
533
+ * Kit-owned paths to leave out (the Orchestrate engine carries no bundle).
534
+ * @returns {{ conflicts: string[], deletes: string[], writes: object[], unchanged: string[] }}
535
+ */
536
+ export function planKitOwned({ runner, root, snap, force, skip = [] }) {
537
+ const conflicts = [];
538
+ const deletes = [];
539
+ const owned = snap.kitOwnedPaths.filter((p) => !skip.includes(p));
540
+ const exists = (rel) => lstatOrNull(join(root, rel)) !== null;
541
+ const existing = owned.filter((p) => {
542
+ checkLocalPath(root, p.replace(/\/$/, ""));
543
+ return exists(p.replace(/\/$/, ""));
544
+ });
545
+ const local = existing.length
546
+ ? localTreeHashes({ runner, cwd: root, paths: existing }).hashes
547
+ : new Map();
548
+ const unchanged = existing.filter((p) => {
549
+ const hash = local.get(p);
550
+ return hash !== null && hash !== undefined && hash === snap.treeHash(p);
551
+ });
552
+ for (const p of existing.filter((x) => !unchanged.includes(x))) {
553
+ if (!force) conflicts.push(`${p} (Kit-owned path)`);
554
+ else {
555
+ const rel = p.replace(/\/$/, "");
556
+ checkDeletable(root, rel);
557
+ deletes.push(rel);
558
+ }
559
+ }
560
+ const writes = kitFileWrites({ ...snap, kitOwnedPaths: owned }).filter(
561
+ (w) => !unchanged.some((p) => w.path.startsWith(p)),
562
+ );
563
+ return { conflicts, deletes, writes, unchanged };
564
+ }
565
+
528
566
  /**
529
567
  * Work out everything init would write and throw Refusal for anything that
530
568
  * stops it. Touches nothing on disk.
@@ -550,29 +588,11 @@ export function planInit({ runner, root, snap, answers, force }) {
550
588
  return Boolean(st);
551
589
  };
552
590
 
553
- // Kit-owned paths: copied whole. One that already matches the tag (an
554
- // earlier init, adding a flow now) is left as it is; any other existing
555
- // one is an earlier adoption, replaced only with --force.
556
- const existing = snap.kitOwnedPaths.filter((p) => {
557
- checkLocalPath(root, p.replace(/\/$/, ""));
558
- return exists(p.replace(/\/$/, ""));
559
- });
560
- const local = existing.length
561
- ? localTreeHashes({ runner, cwd: root, paths: existing }).hashes
562
- : new Map();
563
- const unchanged = existing.filter((p) => {
564
- const hash = local.get(p);
565
- return hash !== null && hash !== undefined && hash === snap.treeHash(p);
566
- });
567
- for (const p of existing.filter((x) => !unchanged.includes(x))) {
568
- if (!force) conflicts.push(`${p} (Kit-owned path)`);
569
- else {
570
- const rel = p.replace(/\/$/, "");
571
- checkDeletable(root, rel);
572
- deletes.push(rel);
573
- }
574
- }
575
- writes.push(...kitFileWrites(snap).filter((w) => !unchanged.some((p) => w.path.startsWith(p))));
591
+ const kitPlan = planKitOwned({ runner, root, snap, force });
592
+ const { unchanged } = kitPlan;
593
+ conflicts.push(...kitPlan.conflicts);
594
+ deletes.push(...kitPlan.deletes);
595
+ writes.push(...kitPlan.writes);
576
596
 
577
597
  const dir = answers.threatPackDir ?? DEFAULT_THREAT_PACK_DIR;
578
598
  // Case-insensitive: on Windows and macOS `.Claude/skills/x` is `.claude/skills/x`.
@@ -816,7 +836,25 @@ export async function runInit({
816
836
  err,
817
837
  openTag = openKitTag,
818
838
  env = process.env,
839
+ factory = null,
819
840
  }) {
841
+ if (factory) {
842
+ return runFactoryInit({
843
+ cwd,
844
+ runner,
845
+ flags: { ...factory.flags, tag: flags.tag },
846
+ engine: factory.engine,
847
+ force,
848
+ yes,
849
+ prompt,
850
+ confirm,
851
+ out,
852
+ err,
853
+ openTag,
854
+ env,
855
+ planKitOwned,
856
+ });
857
+ }
820
858
  const refuse = (e) => reportRefusal(out, e);
821
859
 
822
860
  const collected = await collectAnswers({
@@ -12,7 +12,7 @@
12
12
  // adds a new kind of Kit-owned path. Nothing is deleted on this path.
13
13
 
14
14
  export const ALLOWED_SHAPE =
15
- /^(?:\.claude\/skills\/[A-Za-z0-9._-]+\/|\.github\/(?:agent-runtime|agent-pipeline|security-audit|agent-review-response)\/)$/;
15
+ /^(?:\.claude\/skills\/[A-Za-z0-9._-]+\/|\.github\/(?:agent-runtime|agent-pipeline|security-audit|agent-review-response|agent-factory)\/)$/;
16
16
  const SAFE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\/$/;
17
17
 
18
18
  export class ManifestError extends Error {}
package/src/stage.mjs CHANGED
@@ -50,7 +50,9 @@ import {
50
50
  parseLimits,
51
51
  STOPPED_EXIT,
52
52
  stoppedStatus,
53
+ TOKENS,
53
54
  TURNS,
55
+ WALL_CLOCK,
54
56
  LimitReached,
55
57
  } from "./deep-scan/limits.mjs";
56
58
  import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
@@ -134,6 +136,7 @@ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
134
136
  * bundlePath?: string,
135
137
  * transcriptPath?: string,
136
138
  * errorLogPath?: string,
139
+ * usagePath?: string,
137
140
  * trustedRef?: string,
138
141
  * untracked?: boolean,
139
142
  * inputPaths?: string[],
@@ -179,6 +182,7 @@ export async function runStage({
179
182
  bundlePath,
180
183
  transcriptPath,
181
184
  errorLogPath,
185
+ usagePath,
182
186
  trustedRef,
183
187
  untracked = false,
184
188
  inputPaths = [],
@@ -245,6 +249,8 @@ export async function runStage({
245
249
  ];
246
250
  const foreign = AGENT_FLAGS.find((_, i) => given[i] !== undefined);
247
251
  if (foreign) return usage(`The verify run starts no agent, so it takes no ${foreign}.`);
252
+ if (usagePath !== undefined)
253
+ return usage("The verify run starts no agent, so it takes no --usage.");
248
254
  } else if (briefPath === undefined || resultPath === undefined) {
249
255
  return usage(`stage ${stage} needs --brief <file> and --result <file>.`);
250
256
  }
@@ -341,6 +347,8 @@ export async function runStage({
341
347
  ...(definition.WRITES_BUNDLE ? [["--bundle", bundlePath, "branch.bundle"]] : []),
342
348
  ["--transcript", transcriptPath, "transcript.log"],
343
349
  ["--error-log", errorLogPath, "errors.log"],
350
+ // Only when asked for: the Factory's trusted step reads it (#515).
351
+ ...(usagePath === undefined ? [] : [["--usage", usagePath, "usage.json"]]),
344
352
  ]) {
345
353
  if (given === undefined) {
346
354
  privateDir ??= mkdtempSync(join(tmpdir(), "agent-kit-stage-"));
@@ -865,6 +873,17 @@ async function launch({
865
873
  });
866
874
 
867
875
  const stopped = clocks.stopped();
876
+ // The run's usage, for the Factory's trusted step: two numbers from the kit's
877
+ // own proxy and clocks, written before anything that can fail below. A
878
+ // harness the proxy cannot front has no count, so it writes none.
879
+ if (files["--usage"] !== undefined && hosts === null && proxy) {
880
+ const named = { [TURNS]: "turns", [TOKENS]: "tokens", [WALL_CLOCK]: "minutes" };
881
+ writeFileSync(
882
+ files["--usage"],
883
+ `${JSON.stringify({ tokens: proxy.tokens(), stopped: stopped ? (named[stopped.limit] ?? null) : null })}\n`,
884
+ { mode: 0o600, flag: "wx" },
885
+ );
886
+ }
868
887
  const failed = agent !== null && agent.status !== 0;
869
888
  if (stopped) {
870
889
  out(`${stoppedStatus(stopped)} Copying out what result the agent left.`);
package/src/upgrade.mjs CHANGED
@@ -14,6 +14,8 @@ import { PinRewriteError, readWorkflows, rewriteKitPins } from "./callers.mjs";
14
14
  import { checkPins } from "./checks/pins.mjs";
15
15
  import { fileAndPinChecks, printFileAndPinChecks } from "./doctor.mjs";
16
16
  import { firstLine } from "./exec.mjs";
17
+ import { hasFactory } from "./factory/doctor/index.mjs";
18
+ import { factoryNotes, withCliPins } from "./factory/upgrade/index.mjs";
17
19
  import { openKitRepo, PreManifestTagError, serverFromEnv } from "./kit-tag.mjs";
18
20
  import {
19
21
  applyPlan,
@@ -69,7 +71,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
69
71
  const writes = kitFileWrites(newSnap);
70
72
  for (const w of writes) checkLocalPath(root, w.path, { deleted: deletes });
71
73
 
72
- const pinEdits = [];
74
+ const pinEditsSoFar = [];
73
75
  if (pinnedTag !== newSnap.tag) {
74
76
  for (const file of files) {
75
77
  if (file.pins.length === 0) continue;
@@ -81,7 +83,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
81
83
  if (err instanceof PinRewriteError) throw new Refusal(`${file.path}: ${err.message}`);
82
84
  throw err;
83
85
  }
84
- pinEdits.push({
86
+ pinEditsSoFar.push({
85
87
  path: file.path,
86
88
  count: rewritten.count,
87
89
  bytes: Buffer.from(rewritten.text, "utf8"),
@@ -89,6 +91,19 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
89
91
  }
90
92
  }
91
93
 
94
+ // A Factory's Callers also pin the CLI they install: move that pin to the tag's version.
95
+ let cliPins = [];
96
+ let pinEdits = pinEditsSoFar;
97
+ const factory = hasFactory(root);
98
+ if (factory) {
99
+ ({ edits: pinEdits, cli: cliPins } = withCliPins({
100
+ files,
101
+ edits: pinEditsSoFar,
102
+ readText: (path) => readWorkflowText(root, path),
103
+ newTag: newSnap.tag,
104
+ }));
105
+ }
106
+
92
107
  const { changed: dirty, ignored } = uncommittedChanges({ runner, root, paths: deletes });
93
108
  if (dirty.length && !force) {
94
109
  throw new Refusal(
@@ -98,7 +113,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
98
113
  );
99
114
  }
100
115
 
101
- return { deletes, removed, writes, pinEdits, dirty, ignored };
116
+ return { deletes, removed, writes, pinEdits, cliPins, factory, dirty, ignored };
102
117
  }
103
118
 
104
119
  /**
@@ -199,12 +214,17 @@ export async function runUpgrade({
199
214
  out(`Delete (no longer in ${newTag}'s kit-owned-paths.txt):`);
200
215
  for (const p of plan.removed) out(` ${p}`);
201
216
  }
202
- if (plan.pinEdits.length) {
217
+ const usesEdits = plan.pinEdits.filter((e) => !e.cliOnly);
218
+ if (usesEdits.length) {
203
219
  out(`Rewrite uses: pins to @${newTag}:`);
204
- for (const e of plan.pinEdits) out(` ${e.path} (${e.count} pin${e.count === 1 ? "" : "s"})`);
220
+ for (const e of usesEdits) out(` ${e.path} (${e.count} pin${e.count === 1 ? "" : "s"})`);
205
221
  } else {
206
222
  out(`The uses: pins already name ${newTag}.`);
207
223
  }
224
+ if (plan.cliPins.length) {
225
+ out(`Rewrite the CLI pins of the Factory Callers to @${newTag.slice(1)}:`);
226
+ for (const e of plan.cliPins) out(` ${e.path} (${e.count} pin${e.count === 1 ? "" : "s"})`);
227
+ }
208
228
  if (plan.dirty.length) {
209
229
  out(`--force: discarding uncommitted changes in ${plan.dirty.length} file(s):`);
210
230
  for (const d of listed(plan.dirty)) out(` ${d}`);
@@ -272,9 +292,21 @@ export async function runUpgrade({
272
292
  }
273
293
  }
274
294
 
275
- // The same file and pin checks as `doctor --ci`, against the tag already fetched.
295
+ // The Factory is the Consumer's: say what upgrade left alone.
296
+ // Judged before the writes, from the Consumer's own Factory files, as the plan was.
297
+ const { factory } = plan;
298
+ if (factory) {
299
+ out("");
300
+ for (const line of factoryNotes({ newTag })) out(line);
301
+ }
302
+
303
+ // The same file and pin checks as `doctor --ci`, against the tag already fetched, and the
304
+ // Factory's file checks when the checkout has a Factory.
276
305
  out("");
277
- const failed = printFileAndPinChecks(out, fileAndPinChecks({ runner, root, snap: newSnap }));
306
+ const failed = printFileAndPinChecks(
307
+ out,
308
+ fileAndPinChecks({ runner, root, snap: newSnap, factory }),
309
+ );
278
310
  out("");
279
311
  out(
280
312
  failed