@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,394 @@
1
+ // The sweep's IO shell: it reads the tracker, hands the read to the pure core,
2
+ // and applies the ordered actions through the tracker adapter and the engine.
3
+ // All the IO is in the two objects it is given, so the shell's own suite runs
4
+ // over fakes (scripts/factory-sweep-shell.test.mjs).
5
+ //
6
+ // Failure rule: when an action fails, the issue's later actions in this sweep
7
+ // are skipped, and the sweep goes on with the next issue. A Claim that is not
8
+ // read back as the winner fails the same way, so the issue is never moved.
9
+
10
+ import { budgetDayStart, effectiveCap } from "../budget/budget.mjs";
11
+ import { latestDecisionRequest } from "../decision/answers.mjs";
12
+ import { attachGateFacts } from "../gate/reads.mjs";
13
+ import { attachTrip } from "../gate/trip-reads.mjs";
14
+ import { moverLogins } from "../labels/timeline.mjs";
15
+ import { renderVoidedClaim } from "./markers.mjs";
16
+ import { parseChildMarker, renderCloseComment, renderSplitComment } from "./split.mjs";
17
+ import { claimsOf, sweep } from "./sweep-core.mjs";
18
+
19
+ class ClaimLost extends Error {}
20
+
21
+ /**
22
+ * An engine that runs only some Stages (`engine.stages`) never claims the others:
23
+ * a `claim` or `start-stage` of a Stage it lacks is dropped, with the `set-state` and
24
+ * `start-stage` that follow it for the same issue, and one notice says so. The task stays
25
+ * where it is, so no Attempt is spent on a Stage nothing can run.
26
+ */
27
+ export function withoutUnsupportedStages(actions, stages) {
28
+ if (!Array.isArray(stages)) return actions;
29
+ const dropped = new Set();
30
+ const kept = [];
31
+ for (const action of actions) {
32
+ const stage = action.type === "claim" ? action.claim.stage : action.stage;
33
+ const lacks =
34
+ (action.type === "claim" || action.type === "start-stage") && !stages.includes(stage);
35
+ if (lacks && !dropped.has(action.issue)) {
36
+ kept.push({
37
+ type: "notice",
38
+ issue: action.issue,
39
+ code: "stage-unsupported",
40
+ message: `this engine does not run the ${stage} Stage: the task waits`,
41
+ });
42
+ }
43
+ if (lacks) {
44
+ dropped.add(action.issue);
45
+ continue;
46
+ }
47
+ if (dropped.has(action.issue) && ["claim", "set-state", "start-stage"].includes(action.type)) {
48
+ continue;
49
+ }
50
+ kept.push(action);
51
+ }
52
+ return kept;
53
+ }
54
+
55
+ /** Which Claim stands for an issue: the oldest one that is live and unexpired. */
56
+ export function winningClaim(comments, engine, nowMs) {
57
+ const claims = claimsOf({ comments }, engine)
58
+ .filter((c) => c.released === undefined && Date.parse(c.expires) > nowMs)
59
+ .sort((a, b) => Number(a.commentId) - Number(b.commentId));
60
+ return claims[0] ?? null;
61
+ }
62
+
63
+ /**
64
+ * @param {{
65
+ * tracker: { readState: Function, readHeadStatuses?: Function, readWriters?: Function, setState: Function, claim: Function, readClaim: Function, release: Function, comment: Function },
66
+ * engine: { name: string, identity: string, startStage: Function, stages?: string[], assignee?: string },
67
+ * config?: object,
68
+ * killSwitch?: string | undefined,
69
+ * clock: () => number,
70
+ * run: string,
71
+ * nonce: (issue: number, attempt: number) => string,
72
+ * dryRun?: boolean,
73
+ * log?: (line: string) => void,
74
+ * readTripEvidence?: () => { issues: object[] },
75
+ * }} deps
76
+ * @returns {{ actions: object[], results: Array<{ action: object, status: "done" | "failed" | "skipped" | "planned", error?: string }> }}
77
+ */
78
+ export function runSweep({
79
+ tracker,
80
+ engine,
81
+ config,
82
+ killSwitch,
83
+ clock,
84
+ run,
85
+ nonce,
86
+ dryRun = false,
87
+ log = () => {},
88
+ readTripEvidence,
89
+ }) {
90
+ // The Kill switch drains before any read: a sweep that is off reads nothing.
91
+ const off = killSwitch !== "true";
92
+ const read = off ? { issues: [] } : tracker.readState();
93
+ if (!off && read.truncated?.length) {
94
+ log(
95
+ `notice: more than 100 open issues in ${read.truncated.join(", ")}; the rest wait for a later sweep`,
96
+ );
97
+ }
98
+ for (const issue of read.issues ?? []) {
99
+ if (issue.commentsTruncated) {
100
+ log(`notice #${issue.number}: more than 100 comments; only the newest 100 are read`);
101
+ }
102
+ }
103
+ if (!off && tracker.readHeadStatuses) {
104
+ const heads = read.issues
105
+ .flatMap((i) =>
106
+ (i.pulls ?? [])
107
+ .filter((p) => p.state !== "CLOSED" && p.state !== "MERGED")
108
+ .map((p) => p.head),
109
+ )
110
+ .filter(Boolean);
111
+ if (heads.length) read.statuses = tracker.readHeadStatuses(heads);
112
+ }
113
+ if (!off && tracker.readPull) attachGateFacts(read, tracker, engine, log);
114
+ // The gate's trip, only where the gate can merge (`on`); elsewhere nothing is read.
115
+ if (!off && config?.merge?.mode === "on") {
116
+ if (tracker.readControl && readTripEvidence) {
117
+ attachTrip(read, {
118
+ tracker,
119
+ engine,
120
+ readEvidence: readTripEvidence,
121
+ autoTiers: config.merge.auto_tiers ?? ["low"],
122
+ now: clock(),
123
+ log,
124
+ });
125
+ }
126
+ }
127
+ if (!off) attachSpend(read, { tracker, config, now: clock(), log });
128
+ if (!off) attachSplitParents(read, tracker, log);
129
+ if (!off && tracker.readWriters) attachWriters(read, tracker, engine, log);
130
+ if (!off && tracker.readWriters) attachMovers(read, tracker, log);
131
+ const planned = sweep({
132
+ read,
133
+ config,
134
+ killSwitch,
135
+ now: clock(),
136
+ ctx: { engine: { name: engine.name, identity: engine.identity }, run, nonce },
137
+ });
138
+ const actions = withoutUnsupportedStages(planned, engine.stages);
139
+
140
+ const results = [];
141
+ const failed = new Set();
142
+ for (const action of actions) {
143
+ if (action.type === "notice") {
144
+ log(`notice${action.issue ? ` #${action.issue}` : ""}: ${action.message}`);
145
+ results.push({ action, status: "done" });
146
+ continue;
147
+ }
148
+ if (failed.has(action.issue)) {
149
+ results.push({ action, status: "skipped" });
150
+ continue;
151
+ }
152
+ if (dryRun) {
153
+ results.push({ action, status: "planned" });
154
+ continue;
155
+ }
156
+ try {
157
+ apply(action, { tracker, engine, clock, log });
158
+ results.push({ action, status: "done" });
159
+ } catch (err) {
160
+ // A cancel that fails does not hold the Claim: the run may already be
161
+ // gone, and a result it still posts is ignored by its nonce.
162
+ if (action.type !== "cancel-stage") failed.add(action.issue);
163
+ const message = err instanceof Error ? err.message : String(err);
164
+ log(`#${action.issue} ${action.type} failed: ${message}`);
165
+ results.push({ action, status: "failed", error: message });
166
+ }
167
+ }
168
+ return { actions, results };
169
+ }
170
+
171
+ function apply(action, { tracker, engine, clock, log }) {
172
+ switch (action.type) {
173
+ case "claim": {
174
+ const id = tracker.claim(action.issue, action.body);
175
+ // Read it back, fresh: a Claim stands only if ours is the oldest live one.
176
+ const winner = winningClaim(tracker.readClaim(action.issue), engine, clock());
177
+ if (!winner || winner.claim !== action.claim.claim) {
178
+ tracker.release(id, "lost-race");
179
+ throw new ClaimLost(`Claim ${action.claim.claim} was not read back as the winner`);
180
+ }
181
+ // An engine that works as a person (the Orchestrate engine) also assigns the
182
+ // task to them. Best effort: a refused assignment does not undo the Claim.
183
+ if (engine.assignee && tracker.addAssignee) {
184
+ try {
185
+ tracker.addAssignee(action.issue, engine.assignee);
186
+ } catch (error) {
187
+ log(
188
+ `notice #${action.issue}: could not assign ${engine.assignee} (${error instanceof Error ? error.message : error})`,
189
+ );
190
+ }
191
+ }
192
+ return;
193
+ }
194
+ case "release":
195
+ // A voided Claim is rewritten whole, so the engine is its last editor again.
196
+ return action.voided
197
+ ? tracker.editComment(action.commentId, renderVoidedClaim(action.claimData, action.reason))
198
+ : tracker.release(action.commentId, action.reason);
199
+ case "edit-comment":
200
+ return tracker.editComment(action.commentId, action.body);
201
+ case "revert-label":
202
+ return tracker.revertLabels(action.issue, { add: action.add, remove: action.remove });
203
+ case "remove-label":
204
+ return tracker.removeLabel(action.issue, action.label);
205
+ case "set-state":
206
+ return tracker.setState(action.issue, action.from, action.to);
207
+ case "comment":
208
+ case "post-decision-request":
209
+ return tracker.comment(action.issue, action.body);
210
+ case "gate-comment":
211
+ return action.commentId
212
+ ? tracker.editComment(action.commentId, action.body)
213
+ : tracker.postComment(action.pull, action.body);
214
+ case "gate-update":
215
+ return tracker.updateBranch(action.pull, action.head);
216
+ case "copy-stage-checks":
217
+ for (const check of action.checks) tracker.writeStageCheck(action.head, check);
218
+ return;
219
+ case "split":
220
+ return applySplit(action, tracker);
221
+ case "close-parent":
222
+ return tracker.closeIssue(action.parent, renderCloseComment(action.children));
223
+ case "merge":
224
+ return engine.startMerge(action);
225
+ case "trip-marker":
226
+ case "budget-notice":
227
+ return tracker.postComment(action.issue, action.body);
228
+ case "start-stage":
229
+ return engine.startStage(action);
230
+ case "cancel-stage":
231
+ return engine.cancelStage(action);
232
+ default:
233
+ throw new Error(`unknown action type ${JSON.stringify(action.type)}`);
234
+ }
235
+ }
236
+
237
+ const lower = (login) => String(login ?? "").toLowerCase();
238
+
239
+ /**
240
+ * A plan's split (#508): each child not yet made is created as a queued sub-issue, every child is
241
+ * attached to the parent, `blocked_by` (sibling titles) becomes native blocking edges, and one
242
+ * comment lists the children. Each step is safe to run again, so a sweep that stopped half way
243
+ * finishes the rest the next time, and no child is made twice (the core hands over the children
244
+ * the read already holds as `existing`).
245
+ */
246
+ function applySplit(action, tracker) {
247
+ const numbers = new Map();
248
+ for (const entry of action.entries) {
249
+ numbers.set(
250
+ entry.index,
251
+ entry.existing ??
252
+ tracker.createSubIssue(action.issue, {
253
+ title: entry.title,
254
+ body: entry.body,
255
+ labels: entry.labels,
256
+ }).number,
257
+ );
258
+ }
259
+ for (const entry of action.entries) {
260
+ // A child made by an earlier sweep may not be attached yet.
261
+ if (entry.existing !== undefined) tracker.addSubIssue(action.issue, entry.existing);
262
+ }
263
+ // Siblings can share a title (the plan header does not forbid it), so a title names every
264
+ // sibling that carries it: an entry that is blocked by that title waits on all of them, and
265
+ // none is dropped. An entry never waits on itself.
266
+ const byTitle = new Map();
267
+ for (const entry of action.entries) {
268
+ byTitle.set(entry.title, [...(byTitle.get(entry.title) ?? []), numbers.get(entry.index)]);
269
+ }
270
+ for (const entry of action.entries) {
271
+ for (const title of entry.blocked_by) {
272
+ const blockers = byTitle.get(title);
273
+ if (blockers === undefined)
274
+ throw new Error(`blocked_by names no sibling titled ${JSON.stringify(title)}`);
275
+ for (const blocker of blockers) {
276
+ if (blocker !== numbers.get(entry.index))
277
+ tracker.addBlockedBy(numbers.get(entry.index), blocker);
278
+ }
279
+ }
280
+ }
281
+ tracker.postComment(
282
+ action.issue,
283
+ renderSplitComment({
284
+ plan: action.plan,
285
+ children: action.entries.map((e) => ({ number: numbers.get(e.index), title: e.title })),
286
+ }),
287
+ );
288
+ }
289
+
290
+ /**
291
+ * The parents of the children that may close them (#508): for each child in `ready-to-merge` or
292
+ * `merged`, its parent's state, comments and sub-issues (`read.splitParents`). A failed read is
293
+ * carried as `{ error }`: that parent is not closed this sweep.
294
+ */
295
+ function attachSplitParents(read, tracker, log) {
296
+ if (typeof tracker.readSplitParent !== "function") return;
297
+ const parents = new Set();
298
+ for (const issue of read.issues ?? []) {
299
+ const labels = issue.labels ?? [];
300
+ if (!labels.includes("factory:ready-to-merge") && !labels.includes("factory:merged")) continue;
301
+ const mark = typeof issue.body === "string" ? parseChildMarker(issue.body) : null;
302
+ if (mark) parents.add(mark.parent);
303
+ }
304
+ if (parents.size === 0) return;
305
+ read.splitParents = {};
306
+ for (const parent of [...parents].sort((a, b) => a - b)) {
307
+ try {
308
+ read.splitParents[parent] = tracker.readSplitParent(parent);
309
+ } catch (error) {
310
+ const message = error instanceof Error ? error.message : String(error);
311
+ read.splitParents[parent] = { error: message };
312
+ log(`notice #${parent}: the parent of a split could not be read (${message})`);
313
+ }
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Who has write access, for each queued issue that holds a Decision Request:
319
+ * the sweep counts a reply only from them. A queued issue is the one a person
320
+ * just re-queued, so it is the only one whose replies are judged. A failed
321
+ * read leaves `writers` unset, which the core reads as "cannot judge yet".
322
+ */
323
+ function attachWriters(read, tracker, engine, log) {
324
+ const isEngine = (login) =>
325
+ lower(login).replace(/\[bot\]$/, "") === lower(engine.identity).replace(/\[bot\]$/, "");
326
+ const cache = new Map();
327
+ for (const issue of read.issues ?? []) {
328
+ if (!(issue.labels ?? []).includes("factory:queued")) continue;
329
+ if (!latestDecisionRequest(issue.comments, isEngine)) continue;
330
+ const logins = [
331
+ ...new Set((issue.comments ?? []).map((c) => c.author).filter((a) => a && !isEngine(a))),
332
+ ];
333
+ try {
334
+ const unknown = logins.filter((l) => !cache.has(lower(l)));
335
+ const writers = new Set(tracker.readWriters(unknown).map(lower));
336
+ for (const login of unknown) cache.set(lower(login), writers.has(lower(login)));
337
+ issue.writers = logins.filter((l) => cache.get(lower(l)));
338
+ } catch (error) {
339
+ log(
340
+ `notice #${issue.number}: write access could not be read (${error instanceof Error ? error.message : error}); its Decision Request is not judged this sweep`,
341
+ );
342
+ }
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Who has write access, among the people who moved the labels now on each issue
348
+ * (read from its timeline): a label move is a Human move only by one of them
349
+ * (ADR 0038). A failed read leaves `writers` unset, which the core reads as
350
+ * "cannot judge yet".
351
+ */
352
+ function attachMovers(read, tracker, log) {
353
+ const timed = (read.issues ?? []).filter((i) => Array.isArray(i.timeline));
354
+ if (timed.length === 0) return;
355
+ const logins = [...new Set(timed.flatMap(moverLogins))];
356
+ try {
357
+ read.writers = logins.length ? tracker.readWriters(logins) : [];
358
+ } catch (error) {
359
+ log(
360
+ `notice: write access of the people who moved labels could not be read (${error instanceof Error ? error.message : error}); labels are not judged this sweep`,
361
+ );
362
+ }
363
+ }
364
+
365
+ /**
366
+ * The Daily cap's reads, only when a cap is named: the release comments posted since 00:00 UTC
367
+ * (`read.spend`) and the Factory control issue with its comments (`read.control`, where the
368
+ * notices go). A read that fails is carried as `{ error }`, which the core reads as "no new
369
+ * Claim this sweep".
370
+ */
371
+ function attachSpend(read, { tracker, config, now, log }) {
372
+ const cap = effectiveCap({ budget: config?.budget, override: config?.daily_override });
373
+ if (cap.none || cap.error) {
374
+ if (cap.error) log(`notice: the Daily cap is not readable (${cap.error}): no new Claim`);
375
+ return;
376
+ }
377
+ const since = new Date(budgetDayStart(now)).toISOString().replace(/\.\d+Z$/, "Z");
378
+ try {
379
+ if (typeof tracker.readReleases !== "function")
380
+ throw new Error("the tracker cannot read releases");
381
+ read.spend = { comments: tracker.readReleases(since) };
382
+ } catch (error) {
383
+ read.spend = { error: error instanceof Error ? error.message : String(error) };
384
+ log(`notice: tokens spent today could not be read (${read.spend.error}): no new Claim`);
385
+ }
386
+ try {
387
+ read.control = typeof tracker.readControl === "function" ? tracker.readControl() : null;
388
+ } catch (error) {
389
+ read.control = { error: error instanceof Error ? error.message : String(error) };
390
+ log(
391
+ `notice: the Factory control issue could not be read (${read.control.error}): no Daily cap notice`,
392
+ );
393
+ }
394
+ }
@@ -0,0 +1,104 @@
1
+ // A plan's split, as text (#508, docs/factory/split.md): the marker a child
2
+ // carries in its body, the comment the engine leaves on the parent, and the
3
+ // Decision Request a child gets when its own plan splits again. Pure: no IO.
4
+ //
5
+ // child body <summary>
6
+ // <hint: the split's allowed_paths, not a limit>
7
+ // <!-- factory:note v=1 reason=split-child parent=<n> plan=<k> index=<i> -->
8
+ //
9
+ // parent comment <!-- factory:note v=1 reason=split plan=<k> children=<a>,<b>,... -->
10
+ // a list of the children for a person
11
+ //
12
+ // Both are `factory:note` markers with their own `reason`, so the Kit writes no new marker name.
13
+ //
14
+ // The child marker tells the sweep which issue a child came from and which plan
15
+ // entry it is, so a repeated sweep creates no child twice, a child is not
16
+ // planned before its parent has finished splitting, and a child whose plan
17
+ // splits is stopped (one level only). The parent comment is the engine's list
18
+ // of the children: the parent closes when every one of them is merged.
19
+
20
+ import { untrustedText } from "../checks/plan-header.mjs";
21
+ import { VERSION_PATTERN, VERSION_TOKEN } from "./marker-version.mjs";
22
+
23
+ const SPLIT_CHILD_RE = new RegExp(
24
+ `<!-- factory:note${VERSION_PATTERN} reason=split-child parent=([1-9][0-9]*) plan=([1-9][0-9]*) index=([0-9]+) -->`,
25
+ );
26
+ const SPLIT_PARENT_RE = new RegExp(
27
+ `^<!-- factory:note${VERSION_PATTERN} reason=split plan=([1-9][0-9]*) children=([0-9]+(?:,[0-9]+)*) -->`,
28
+ );
29
+
30
+ /** The labels every child is created with. */
31
+ export const CHILD_LABELS = Object.freeze(["ready-for-agent", "factory:queued"]);
32
+
33
+ /** The start of the title of the Decision Request a child gets when its plan splits again. */
34
+ export const SPLIT_TOO_DEEP_TITLE = "splits again, and a split goes one level only";
35
+
36
+ /** The marker of one child. */
37
+ export const renderChildMarker = ({ parent, plan, index }) =>
38
+ `<!-- factory:note${VERSION_TOKEN} reason=split-child parent=${parent} plan=${plan} index=${index} -->`;
39
+
40
+ /** The child a body marks, or null: `{ parent, plan, index }`. Only a version this reader knows counts. */
41
+ export function parseChildMarker(body) {
42
+ const match = SPLIT_CHILD_RE.exec(String(body ?? ""));
43
+ if (!match) return null;
44
+ return { parent: Number(match[1]), plan: Number(match[2]), index: Number(match[3]) };
45
+ }
46
+
47
+ /**
48
+ * The body of a child: the split entry's summary, the entry's `allowed_paths` as a hint the
49
+ * child's own plan may ignore, and the marker. Each child is planned on its own.
50
+ */
51
+ export function renderChildBody({ summary, allowed_paths: paths = [], parent, plan, index }) {
52
+ const hint = paths.length
53
+ ? `\n\nHint from the plan of #${parent} (not a limit: this issue is planned on its own): ${paths
54
+ .map((p) => `\`${untrustedText(p, 200).replaceAll("`", "'")}\``)
55
+ .join(", ")}`
56
+ : "";
57
+ return `${untrustedText(summary, 1000)}${hint}\n\nSplit from #${parent}.\n${renderChildMarker({ parent, plan, index })}`;
58
+ }
59
+
60
+ /** The comment the engine leaves on the parent, listing its children. */
61
+ export function renderSplitComment({ plan, children }) {
62
+ return [
63
+ `<!-- factory:note${VERSION_TOKEN} reason=split plan=${plan} children=${children.map((c) => c.number).join(",")} -->`,
64
+ `Plan ${plan} splits this issue into ${children.length} queued sub-issues:`,
65
+ "",
66
+ ...children.map((c) => `- #${c.number} ${untrustedText(c.title, 200).replace(/\s+/g, " ")}`),
67
+ "",
68
+ "The Factory state of this issue is removed. The Factory closes it once every one of them is merged.",
69
+ ].join("\n");
70
+ }
71
+
72
+ /** What a split comment lists, or null when the body is none: `{ plan, children: number[] }`. */
73
+ export function parseSplitComment(body) {
74
+ const match = SPLIT_PARENT_RE.exec(String(body ?? ""));
75
+ if (!match) return null;
76
+ return { plan: Number(match[1]), children: match[2].split(",").map(Number) };
77
+ }
78
+
79
+ /** The comment the engine leaves when it closes a parent. */
80
+ export const renderCloseComment = (children) =>
81
+ `<!-- factory:note${VERSION_TOKEN} reason=split-done -->\nEvery sub-issue of this issue is merged (${children.map((n) => `#${n}`).join(", ")}), so the Factory closes it.`;
82
+
83
+ /** The Decision Request a child gets when its own plan splits (one level only). */
84
+ export function splitTooDeepRequest({ issue, plan, count, attempt, parent }) {
85
+ return {
86
+ attempt,
87
+ plan,
88
+ kinds: ["questions"],
89
+ title: `plan ${plan} ${SPLIT_TOO_DEEP_TITLE}`,
90
+ intro: `#${issue} is itself a sub-issue of #${parent}, and plan ${plan} splits it into ${count} more. The Factory splits one level deep only, so it is not split again and is held here. Plan it again as one task, or take it apart yourself.`,
91
+ questions: [
92
+ {
93
+ question: "How should this sub-issue go on?",
94
+ options: [
95
+ "Plan it again as one task: say what to keep out of scope, and it is planned with your answer as the feedback.",
96
+ "Split it yourself: create the pieces as issues, then withdraw this one.",
97
+ ],
98
+ recommendation:
99
+ "1, if one change can still be reviewed whole; otherwise 2, with the pieces as sub-issues.",
100
+ evidence: `Plan ${plan} lists ${count} split entries, and #${issue} came from the plan of #${parent}.`,
101
+ },
102
+ ],
103
+ };
104
+ }
@@ -0,0 +1,87 @@
1
+ // The Factory's vocabulary as constants: the nine Factory states and the
2
+ // modifier, the one label the sweep reads besides them, and the Stage names.
3
+ // Pure data. GLOSSARY.md (Factory section) names each term.
4
+
5
+ export const STATE_PREFIX = "factory:";
6
+
7
+ /** The nine Factory states, in lifecycle order (ADR 0034). */
8
+ export const STATES = Object.freeze([
9
+ "queued",
10
+ "planning",
11
+ "planned",
12
+ "building",
13
+ "reviewing",
14
+ "checking",
15
+ "ready-to-merge",
16
+ "merged",
17
+ "needs-decision",
18
+ ]);
19
+
20
+ /** The states in which a Stage runs under a Claim, so a slot is in use. */
21
+ export const RUNNING_STATES = Object.freeze(["planning", "building", "reviewing", "checking"]);
22
+
23
+ /**
24
+ * The states in which a task holds a build: its Allowed paths keep any planned task
25
+ * with an overlapping path from building (#507).
26
+ */
27
+ export const HELD_STATES = Object.freeze(["building", "reviewing", "checking", "ready-to-merge"]);
28
+
29
+ /** The modifier a person sets to freeze one task. */
30
+ export const PAUSED_LABEL = "factory:paused";
31
+ export const READY_LABEL = "ready-for-agent";
32
+
33
+ /** The state label of a state name. */
34
+ export const stateLabel = (state) => `${STATE_PREFIX}${state}`;
35
+
36
+ /** Every label the sweep reads an issue by. */
37
+ export const FACTORY_LABELS = Object.freeze([...STATES.map(stateLabel), PAUSED_LABEL]);
38
+
39
+ /** The state a label names, or null when it is not a Factory state label. */
40
+ export function stateOfLabel(label) {
41
+ if (typeof label !== "string" || !label.startsWith(STATE_PREFIX)) return null;
42
+ const name = label.slice(STATE_PREFIX.length);
43
+ return STATES.includes(name) ? name : null;
44
+ }
45
+
46
+ /** The Stage that works in each running state: planning, building, reviewing and checking (QA; security runs beside it). */
47
+ export const STAGE_OF_STATE = Object.freeze({
48
+ planning: "plan",
49
+ building: "build",
50
+ reviewing: "review",
51
+ checking: "qa",
52
+ });
53
+
54
+ export const DEFAULT_CONFIG = Object.freeze({
55
+ max_running: 3,
56
+ max_attempts: 3,
57
+ // The lowest Risk tier whose plans wait for a person (`none | low | medium | high`).
58
+ plan_approval: "high",
59
+ // The merge gate: `off` until a person changes the factory config.
60
+ merge: Object.freeze({ mode: "off", auto_tiers: Object.freeze(["low"]), method: "squash" }),
61
+ // Minutes a Stage's job may run, by Stage. The Claim expires this long after
62
+ // it is written, plus CLAIM_GRACE_MINUTES. The same as `limits.<stage>.minutes` of
63
+ // `examples/factory/factory-config.json`; the build row is keyed by Task size.
64
+ limits: Object.freeze({
65
+ plan: Object.freeze({ minutes: 30 }),
66
+ // The build Stage runs the implementer and then waits for the pull request's CI,
67
+ // which the Claim also covers (the grace).
68
+ build: Object.freeze({
69
+ s: Object.freeze({ minutes: 60 }),
70
+ m: Object.freeze({ minutes: 90 }),
71
+ l: Object.freeze({ minutes: 120 }),
72
+ }),
73
+ review: Object.freeze({ minutes: 45 }),
74
+ qa: Object.freeze({ minutes: 45 }),
75
+ security: Object.freeze({ minutes: 45 }),
76
+ }),
77
+ });
78
+
79
+ export const CLAIM_GRACE_MINUTES = 15;
80
+
81
+ /**
82
+ * The branch a build Stage's Attempt pushes to. The `factory-build` Caller names
83
+ * it by this rule (its `branch_name_template`), so the sweep can tell one
84
+ * Attempt's pull request from an earlier Attempt's: a contract test holds the
85
+ * two equal.
86
+ */
87
+ export const buildBranch = (issue, attempt) => `factory/${issue}/attempt-${attempt}`;