@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,162 @@
1
+ // What the evidence on an issue supports (ADR 0038). Pure: the issue, its
2
+ // engine Claims (a voided Claim is left out), the head statuses and the clock
3
+ // in; the highest state the evidence reaches, and whether one label is
4
+ // supported, out.
5
+ //
6
+ // Evidence by state, each from its trusted writer only:
7
+ //
8
+ // planning an engine plan Claim
9
+ // planned a valid engine Plan header, or a plan Claim released `done`
10
+ // building an engine build Claim
11
+ // reviewing a build Claim released `done`, a review Claim, or the build
12
+ // Attempt's pull request with green CI
13
+ // checking a review Claim released `done`, or the engine's `factory/review`
14
+ // success on the pull request's head
15
+ // ready-to-merge as checking: the merge gate itself checks QA, security and the
16
+ // head, and sends the task back when they do not hold
17
+ // merged a merged pull request on one of the task's own branches
18
+ //
19
+ // Two states rest on more than rank:
20
+ //
21
+ // needs-decision the engine asked: a Decision Request, a not-ready or
22
+ // empty-answer note or a wider-paths request, newer than every Claim
23
+ // queued the engine's own return (the newest Claim is a plan Claim
24
+ // released failed, expired, error, lost-race or paused), or a live Claim
25
+ // written after the label (a sweep ended before the move)
26
+ //
27
+ // A label ranked above the evidence is a forward jump. A label below it is the
28
+ // sweep's own to move (a failed Attempt goes back), unless a Stage runs under a
29
+ // live Claim of a later state.
30
+
31
+ import { checkPlanHeader } from "../checks/plan-header.mjs";
32
+ import { REVIEW_CONTEXT } from "../checks/review.mjs";
33
+ import { engineStageCheck } from "../checks/stage-check.mjs";
34
+ import { parseDecisionRequest } from "../decision/request.mjs";
35
+ import { latestPlan } from "../plan/comment.mjs";
36
+ import { VERSION_PATTERN } from "../sweep/marker-version.mjs";
37
+ import { buildBranch } from "../sweep/states.mjs";
38
+
39
+ /** The evidence rank a label needs; `queued` and `needs-decision` rest on their own rules. */
40
+ export const NEEDS = Object.freeze({
41
+ planning: 2,
42
+ planned: 3,
43
+ building: 4,
44
+ reviewing: 5,
45
+ checking: 6,
46
+ "ready-to-merge": 6,
47
+ merged: 8,
48
+ });
49
+
50
+ const STATE_OF_RANK = Object.freeze({
51
+ 2: "planning",
52
+ 3: "planned",
53
+ 4: "building",
54
+ 5: "reviewing",
55
+ 6: "checking",
56
+ 8: "merged",
57
+ });
58
+
59
+ const STAGE_RANK = Object.freeze({ plan: 2, build: 4, review: 5, qa: 6, security: 6 });
60
+
61
+ const NOT_READY = new RegExp(
62
+ `<!-- factory:note${VERSION_PATTERN} reason=(?:not-ready|empty-answer) -->`,
63
+ );
64
+ const WIDER_PATHS_REQUEST = new RegExp(
65
+ `^<!-- factory:decision-request${VERSION_PATTERN} kind=wider-paths `,
66
+ );
67
+
68
+ /**
69
+ * @param {{
70
+ * issue: { number: number, comments?: object[], pulls?: object[] },
71
+ * rawComments?: object[], // the comments before voiding: that the engine asked is not undone by an edit
72
+ * claims: Array<{ stage: string, attempt: number, released?: string, expires: string, commentId: string|number, createdAt?: string, voided?: boolean }>,
73
+ * statuses?: Record<string, object[]>,
74
+ * isEngine: (login: string) => boolean,
75
+ * nowMs: number,
76
+ * }} input
77
+ */
78
+ export function evidenceOf({ issue, rawComments, claims, statuses, isEngine, nowMs }) {
79
+ const trusted = claims.filter((c) => !c.voided);
80
+ const of = (stage) => trusted.filter((c) => c.stage === stage);
81
+ const plan = latestPlan(issue.comments, isEngine);
82
+ const validPlan = plan !== null && checkPlanHeader(plan.data, { trusted: true }).ok;
83
+ const lastBuild = of("build").at(-1);
84
+ const pull = lastBuild
85
+ ? (issue.pulls ?? []).find(
86
+ (p) => p.state === "OPEN" && p.branch === buildBranch(issue.number, lastBuild.attempt),
87
+ )
88
+ : undefined;
89
+ const mergedPull = (issue.pulls ?? []).some(
90
+ (p) => p.state === "MERGED" && p.branch.startsWith(`factory/${issue.number}/attempt-`),
91
+ );
92
+
93
+ let rank = 0;
94
+ if (of("plan").length) rank = 2;
95
+ if (validPlan || of("plan").some((c) => c.released === "done")) rank = 3;
96
+ if (of("build").length) rank = 4;
97
+ if (
98
+ of("build").some((c) => c.released === "done") ||
99
+ of("review").length ||
100
+ pull?.ci === "SUCCESS"
101
+ )
102
+ rank = 5;
103
+ if (
104
+ of("review").some((c) => c.released === "done") ||
105
+ (pull?.head &&
106
+ engineStageCheck(statuses?.[pull.head], REVIEW_CONTEXT, isEngine)?.state === "success")
107
+ )
108
+ rank = 6;
109
+ if (mergedPull) rank = 8;
110
+
111
+ const newestClaim = Math.max(0, ...claims.map((c) => Number(c.commentId)));
112
+ const asked = (rawComments ?? issue.comments ?? []).some(
113
+ (c) =>
114
+ isEngine(c.author) &&
115
+ Number(c.id) > newestClaim &&
116
+ (parseDecisionRequest(c.body) !== null || NOT_READY.test(String(c.body))),
117
+ );
118
+ const live = trusted.filter((c) => c.released === undefined);
119
+ const running = live.filter((c) => Date.parse(c.expires) > nowMs);
120
+
121
+ return {
122
+ rank,
123
+ // The state to put a wrong label back to. Where the engine asked and nothing has
124
+ // run since, that is needs-decision: restoring it, not escalating.
125
+ target: asked ? "needs-decision" : (STATE_OF_RANK[rank] ?? null),
126
+ asked,
127
+ // A Claim of the engine's was edited by someone else: the sweep expires it, and
128
+ // the label is not judged until it has.
129
+ voided: claims.some((c) => c.voided),
130
+
131
+ /** Whether the evidence supports `state` as the issue's label, set at `at`. */
132
+ supports(state, at) {
133
+ if (state === "needs-decision") return asked || wider(issue, isEngine, newestClaim);
134
+ const written = (c) => (c.createdAt ? Date.parse(c.createdAt) : 0);
135
+ if (state === "queued") {
136
+ // A live Claim older than the label means a Stage is running: not the engine's move.
137
+ if (at !== undefined && running.some((c) => written(c) <= Date.parse(at))) return false;
138
+ if (running.length) return true;
139
+ const newest = claims.at(-1);
140
+ return (
141
+ newest !== undefined &&
142
+ newest.stage === "plan" &&
143
+ ["failed", "expired", "error", "lost-race", "paused"].includes(
144
+ newest.voided ? "expired" : (newest.released ?? ""),
145
+ )
146
+ );
147
+ }
148
+ const need = NEEDS[state];
149
+ if (need === undefined || rank < need) return false;
150
+ // A Stage running under a live Claim of a later state: the label is behind it.
151
+ return !running.some((c) => (STAGE_RANK[c.stage] ?? 0) > need);
152
+ },
153
+ };
154
+ }
155
+
156
+ /** A wider-paths request the engine wrote after the newest Claim. */
157
+ function wider(issue, isEngine, newestClaim) {
158
+ return (issue.comments ?? []).some(
159
+ (c) =>
160
+ isEngine(c.author) && Number(c.id) > newestClaim && WIDER_PATHS_REQUEST.test(String(c.body)),
161
+ );
162
+ }
@@ -0,0 +1,32 @@
1
+ // The six Human moves (ADR 0038). A person with write access may move a Factory
2
+ // label in exactly these ways; every other move is reverted. Pure.
3
+ //
4
+ // enter add `factory:queued` to an issue with no Factory state
5
+ // pause / unpause add or remove `factory:paused`
6
+ // needs-decision set `factory:needs-decision` from any state (Claim released)
7
+ // answer `factory:needs-decision` -> `factory:queued`
8
+ // restart `factory:queued` from any non-terminal state
9
+ // (Claim released, Attempts reset)
10
+ // withdraw remove every factory label. No label read finds the issue
11
+ // afterwards, so its Claim is released when the task is entered
12
+ // again (docs/factory/labels.md, Limits)
13
+ //
14
+ // No forward jump is a Human move: a person who wants to merge merges.
15
+
16
+ /** Moves a person may make to a state label, by the state they came from. */
17
+ export function humanMoveKind({ from, to, terminal = false }) {
18
+ if (to === "needs-decision")
19
+ return from === null || from === "merged" || terminal ? null : "needs-decision";
20
+ if (to !== "queued") return null;
21
+ if (terminal || from === "merged") return null;
22
+ if (from === null) return "enter";
23
+ if (from === "needs-decision") return "answer";
24
+ return "restart";
25
+ }
26
+
27
+ /** The words of the allowed moves, for the revert comment. */
28
+ export const ALLOWED_MOVES =
29
+ "A person with write access may: add `factory:queued` to an issue with no Factory state; " +
30
+ "add or remove `factory:paused`; set `factory:needs-decision`; swap `factory:needs-decision` " +
31
+ "for `factory:queued` once answered; set `factory:queued` to restart (Attempts start again); " +
32
+ "or remove every factory label to withdraw.";
@@ -0,0 +1,267 @@
1
+ // Label reconciliation for one issue (ADR 0038): the sweep's check that the
2
+ // label on an issue is one its evidence supports or a Human move of a person
3
+ // with write access. Pure: the issue (with its timeline), its Claims, the
4
+ // evidence and the write users in; actions out.
5
+ //
6
+ // an `agent:*` Trigger label -> remove-label, one comment (once)
7
+ // a label the evidence supports -> nothing
8
+ // an allowed Human move -> its effects: live Claims older than the
9
+ // move are cancelled and released `stopped`;
10
+ // enter and restart write the restart marker
11
+ // (the Attempts start again)
12
+ // any other move -> revert-label (back to the state the evidence
13
+ // supports, or off), one comment edited in
14
+ // place with a count and the latest actor
15
+ // two state labels -> an allowed Human move wins (set-state);
16
+ // otherwise the evidence-backed label stays
17
+ // `factory:paused` -> only a write user adds or removes it
18
+ //
19
+ // A revert is never an Attempt (it releases no Claim as failed) and never a
20
+ // Decision Request. Without a `timeline` (an older read) only the Trigger
21
+ // labels are checked; without `writers` (permission unread) nothing is judged.
22
+
23
+ import { PAUSED_LABEL, stateLabel, stateOfLabel } from "../sweep/states.mjs";
24
+ import { humanMoveKind } from "./moves.mjs";
25
+ import {
26
+ findRevert,
27
+ isTriggerRefused,
28
+ parseRevert,
29
+ plain,
30
+ renderRestart,
31
+ renderRevert,
32
+ renderTriggerRefused,
33
+ restartsOf,
34
+ } from "./revert.mjs";
35
+ import { pausedMove, stateMoves } from "./timeline.mjs";
36
+
37
+ const lowerCase = (s) => String(s ?? "").toLowerCase();
38
+
39
+ export const TRIGGER_PREFIX = "agent:";
40
+
41
+ /**
42
+ * @param {{
43
+ * issue: { number: number, labels?: string[], comments?: object[], timeline?: object[] },
44
+ * claims: Array<{ stage: string, claim: string, commentId: string|number, createdAt?: string, released?: string, voided?: boolean }>,
45
+ * evidence: ReturnType<typeof import("./evidence.mjs").evidenceOf>,
46
+ * isEngine: (login: string) => boolean,
47
+ * writers?: string[],
48
+ * }} input
49
+ * @returns {{ actions: object[], released: Array<string|number>, restartPending: boolean, stop: boolean }}
50
+ */
51
+ export function reconcileIssue({ issue, claims, evidence, isEngine, writers }) {
52
+ const n = issue.number;
53
+ const labels = issue.labels ?? [];
54
+ const actions = [];
55
+ const released = [];
56
+ const out = { actions, released, restartPending: false, stop: false };
57
+
58
+ // Trigger labels: consumed and refused, once.
59
+ const triggers = labels.filter((l) => l.startsWith(TRIGGER_PREFIX));
60
+ if (triggers.length) {
61
+ for (const label of triggers)
62
+ actions.push({ type: "remove-label", issue: n, label, reason: "trigger-label" });
63
+ const said = (issue.comments ?? []).some((c) => isEngine(c.author) && isTriggerRefused(c.body));
64
+ if (!said) actions.push({ type: "comment", issue: n, body: renderTriggerRefused(triggers) });
65
+ }
66
+
67
+ if (!Array.isArray(issue.timeline)) return out;
68
+ if (!Array.isArray(writers)) {
69
+ actions.push({
70
+ type: "notice",
71
+ issue: n,
72
+ code: "mover-unreadable",
73
+ message:
74
+ "Who moved this issue's labels, or their write access, could not be read: its labels are not judged this sweep.",
75
+ });
76
+ out.stop = true;
77
+ return out;
78
+ }
79
+ const isWriter = (login) => writers.map(lowerCase).includes(lowerCase(login));
80
+
81
+ const wrong = ({ label, actor, at, add, remove, target }) => {
82
+ const existing = findRevert(issue.comments, isEngine, label);
83
+ if (!(existing && existing.at === at)) {
84
+ const count = (existing?.count ?? 0) + 1;
85
+ const body = renderRevert({ label, count, actor, at, target });
86
+ actions.push(
87
+ existing
88
+ ? { type: "edit-comment", issue: n, commentId: existing.commentId, body }
89
+ : { type: "comment", issue: n, body },
90
+ );
91
+ }
92
+ actions.push({
93
+ type: "revert-label",
94
+ issue: n,
95
+ add,
96
+ remove,
97
+ label,
98
+ target: target ?? null,
99
+ actor: plain(actor),
100
+ reason: "wrong-move",
101
+ });
102
+ };
103
+
104
+ const effects = ({ kind, at, actor }) => {
105
+ for (const c of claims) {
106
+ if (c.released !== undefined || c.voided) continue;
107
+ if (c.createdAt && Date.parse(c.createdAt) > Date.parse(at)) continue;
108
+ actions.push(
109
+ { type: "cancel-stage", issue: n, stage: c.stage, claim: c.claim },
110
+ { type: "release", issue: n, commentId: c.commentId, reason: "stopped" },
111
+ );
112
+ released.push(c.commentId);
113
+ }
114
+ if (kind === "enter" || kind === "restart") {
115
+ out.restartPending = true;
116
+ if (!restartsOf(issue.comments, isEngine).some((r) => r.at === at)) {
117
+ actions.push({ type: "comment", issue: n, body: renderRestart({ at, kind, actor }) });
118
+ }
119
+ }
120
+ };
121
+
122
+ // `factory:paused`: only a write user adds or removes it. The sweep's own
123
+ // reversal of a pause move is the next paused event after a recorded revert.
124
+ const reverted = new Set(
125
+ (issue.comments ?? [])
126
+ .filter((c) => isEngine(c.author))
127
+ .map((c) => parseRevert(c.body))
128
+ .filter((r) => r?.label === PAUSED_LABEL)
129
+ .map((r) => Date.parse(r.at)),
130
+ );
131
+ const skip = new Set(
132
+ [...reverted].map(
133
+ (t) =>
134
+ (issue.timeline ?? [])
135
+ .filter((e) => e.label === PAUSED_LABEL && Date.parse(e.at) > t)
136
+ .sort((a, b) => Date.parse(a.at) - Date.parse(b.at))[0],
137
+ ),
138
+ );
139
+ const pm = pausedMove((issue.timeline ?? []).filter((e) => !skip.has(e)));
140
+ if (pm && !isWriter(pm.actor)) {
141
+ const present = labels.includes(PAUSED_LABEL);
142
+ if (present && pm.kind === "labeled") {
143
+ wrong({ label: PAUSED_LABEL, actor: pm.actor, at: pm.at, add: [], remove: [PAUSED_LABEL] });
144
+ out.stop = true;
145
+ } else if (!present && pm.kind === "unlabeled") {
146
+ wrong({
147
+ label: PAUSED_LABEL,
148
+ actor: pm.actor,
149
+ at: pm.at,
150
+ add: [PAUSED_LABEL],
151
+ remove: [],
152
+ target: PAUSED_LABEL,
153
+ });
154
+ out.stop = true;
155
+ }
156
+ }
157
+ if (out.stop || evidence.voided) return out;
158
+
159
+ // State labels.
160
+ const stateLabels = labels.filter((l) => stateOfLabel(l) !== null);
161
+ const moves = stateMoves(issue.timeline);
162
+ const state = (label) => stateOfLabel(label);
163
+ const supported = (label) => evidence.supports(state(label), moves.get(label)?.at);
164
+ const kindOf = (label) => {
165
+ const move = moves.get(label);
166
+ if (!move || !isWriter(move.actor)) return null;
167
+ return humanMoveKind({
168
+ from: move.from ? state(move.from) : null,
169
+ to: state(label),
170
+ terminal: evidence.rank === 8,
171
+ });
172
+ };
173
+ const targetLabel = evidence.target ? stateLabel(evidence.target) : null;
174
+
175
+ if (stateLabels.length === 1) {
176
+ const label = stateLabels[0];
177
+ const move = moves.get(label);
178
+ if (!move || supported(label)) return out;
179
+ const kind = kindOf(label);
180
+ if (kind) {
181
+ effects({ kind, at: move.at, actor: move.actor });
182
+ return out;
183
+ }
184
+ wrong({
185
+ label,
186
+ actor: move.actor,
187
+ at: move.at,
188
+ add: targetLabel ? [targetLabel] : [],
189
+ remove: [label],
190
+ target: targetLabel,
191
+ });
192
+ out.stop = true;
193
+ return out;
194
+ }
195
+
196
+ if (stateLabels.length > 1) {
197
+ out.stop = true;
198
+ const known = stateLabels.filter((l) => moves.has(l));
199
+ const newest = [...known]
200
+ .sort((a, b) => Date.parse(moves.get(a).at) - Date.parse(moves.get(b).at))
201
+ .at(-1);
202
+ if (!newest) {
203
+ actions.push({
204
+ type: "notice",
205
+ issue: n,
206
+ code: "two-states",
207
+ message: `Issue carries ${stateLabels.join(" and ")} and the timeline does not show who added them: left alone until a person keeps one.`,
208
+ });
209
+ return out;
210
+ }
211
+ const others = stateLabels.filter((l) => l !== newest);
212
+ const kind = !supported(newest) ? kindOf(newest) : null;
213
+ if (kind) {
214
+ const move = moves.get(newest);
215
+ actions.push({
216
+ type: "set-state",
217
+ issue: n,
218
+ from: state(others[0]),
219
+ to: state(newest),
220
+ reason: `human-move:${kind}`,
221
+ });
222
+ effects({ kind, at: move.at, actor: move.actor });
223
+ for (const label of others.slice(1)) {
224
+ actions.push({
225
+ type: "revert-label",
226
+ issue: n,
227
+ add: [],
228
+ remove: [label],
229
+ label,
230
+ target: newest,
231
+ actor: "unknown",
232
+ reason: "heal",
233
+ });
234
+ }
235
+ return out;
236
+ }
237
+ const keepers = stateLabels.filter(supported);
238
+ const at = (l) => (moves.has(l) ? Date.parse(moves.get(l).at) : 0);
239
+ const kept = keepers.length ? [...keepers].sort((a, b) => at(a) - at(b)).at(-1) : targetLabel;
240
+ const dropped = stateLabels.filter((l) => l !== kept);
241
+ for (const label of dropped) {
242
+ const move = moves.get(label);
243
+ if (keepers.length > 1 || !move) {
244
+ actions.push({
245
+ type: "revert-label",
246
+ issue: n,
247
+ add: [],
248
+ remove: [label],
249
+ label,
250
+ target: kept,
251
+ actor: "unknown",
252
+ reason: "heal",
253
+ });
254
+ } else {
255
+ wrong({
256
+ label,
257
+ actor: move.actor,
258
+ at: move.at,
259
+ add: kept && !labels.includes(kept) ? [kept] : [],
260
+ remove: [label],
261
+ target: kept,
262
+ });
263
+ }
264
+ }
265
+ }
266
+ return out;
267
+ }
@@ -0,0 +1,87 @@
1
+ // The comments the label reconciliation leaves, and the markers that find them
2
+ // again. Every one is the engine's own comment, found by marker, and a marker in
3
+ // anyone else's comment is nothing. Pure.
4
+ //
5
+ // <!-- factory:revert v=1 label=<label> count=<n> actor=<login> at=<ISO> -->
6
+ // one comment per issue per wrong label, edited in place: the count of
7
+ // reverts and the latest actor. `at` is the offending event's time, so a
8
+ // revert that is retried is not counted twice.
9
+ // <!-- factory:restart v=1 at=<ISO> kind=<move> actor=<login> -->
10
+ // a Human move that starts the Attempts again: only Claims written after
11
+ // this comment count.
12
+ // <!-- factory:trigger-refused v=1 -->
13
+ // an `agent:*` Trigger label taken off a Factory issue, said once.
14
+
15
+ import { VERSION_PATTERN, VERSION_TOKEN } from "../sweep/marker-version.mjs";
16
+ import { ALLOWED_MOVES } from "./moves.mjs";
17
+
18
+ const MARKER_VALUE = "[A-Za-z0-9._:+-]+";
19
+ const REVERT = new RegExp(
20
+ `^<!-- factory:revert${VERSION_PATTERN} label=(${MARKER_VALUE}) count=([1-9][0-9]*) actor=(${MARKER_VALUE}) at=(${MARKER_VALUE}) -->`,
21
+ );
22
+ const RESTART = new RegExp(
23
+ `^<!-- factory:restart${VERSION_PATTERN} at=(${MARKER_VALUE}) kind=(${MARKER_VALUE}) actor=(${MARKER_VALUE}) -->`,
24
+ );
25
+
26
+ /** What a Trigger-refused comment starts with: this version's marker. The previous one has no `v`. */
27
+ export const TRIGGER_REFUSED_MARKER = `<!-- factory:trigger-refused${VERSION_TOKEN} -->`;
28
+ const PREVIOUS_TRIGGER_REFUSED_MARKER = "<!-- factory:trigger-refused -->";
29
+
30
+ /** Whether a comment body is a Trigger-refused note, of this version or the previous one. */
31
+ export const isTriggerRefused = (body) =>
32
+ [TRIGGER_REFUSED_MARKER, PREVIOUS_TRIGGER_REFUSED_MARKER].some((m) =>
33
+ String(body ?? "").startsWith(m),
34
+ );
35
+
36
+ /** A login as one plain marker value: anything else becomes `_`. */
37
+ export function plain(login) {
38
+ return String(login ?? "unknown").replace(/[^A-Za-z0-9._:+-]/g, "_") || "unknown";
39
+ }
40
+
41
+ /** The revert comment, for `label` reverted `count` times, the latest by `actor` at `at`. */
42
+ export function renderRevert({ label, count, actor, at, target }) {
43
+ const back = target ? `back to \`${target}\`` : "off the issue: the evidence supports no state";
44
+ return [
45
+ `<!-- factory:revert${VERSION_TOKEN} label=${label} count=${count} actor=${plain(actor)} at=${at} -->`,
46
+ `The Factory reverted a label move: \`${label}\` was set by ${plain(actor)} and the evidence on this issue does not support it, so it was moved ${back}. ` +
47
+ `Reverted ${count} time${count === 1 ? "" : "s"}; this comment shows the latest actor.`,
48
+ "",
49
+ ALLOWED_MOVES,
50
+ ].join("\n");
51
+ }
52
+
53
+ /** `{ label, count, actor, at }` of a revert comment, or null. */
54
+ export function parseRevert(body) {
55
+ const m = REVERT.exec(String(body ?? ""));
56
+ return m ? { label: m[1], count: Number(m[2]), actor: m[3], at: m[4] } : null;
57
+ }
58
+
59
+ /** The revert comment the engine left for `label`, or null: `{ commentId, label, count, actor, at }`. */
60
+ export function findRevert(comments, isEngine, label) {
61
+ let best = null;
62
+ for (const comment of comments ?? []) {
63
+ if (!isEngine(comment.author)) continue;
64
+ const revert = parseRevert(comment.body);
65
+ if (revert?.label === label) best = { ...revert, commentId: comment.id };
66
+ }
67
+ return best;
68
+ }
69
+
70
+ export const renderRestart = ({ at, kind, actor }) =>
71
+ `<!-- factory:restart${VERSION_TOKEN} at=${at} kind=${kind} actor=${plain(actor)} -->\nThe Factory took a ${kind} by ${plain(actor)} as a Human move: its Claims are released and its Attempts start again.`;
72
+
73
+ /** The restart markers the engine wrote: `[{ commentId, at, kind }]`, oldest first. */
74
+ export function restartsOf(comments, isEngine) {
75
+ const out = [];
76
+ for (const comment of comments ?? []) {
77
+ if (!isEngine(comment.author)) continue;
78
+ const m = RESTART.exec(String(comment.body ?? ""));
79
+ if (m) out.push({ commentId: comment.id, at: m[1], kind: m[2] });
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /** The refusal of Trigger labels, naming them. */
85
+ export const renderTriggerRefused = (labels) =>
86
+ `${TRIGGER_REFUSED_MARKER}\nThis issue carries a Factory label, so the Factory runs its Stages itself and takes a pipeline Trigger label off: ${labels.map((l) => `\`${l}\``).join(", ")} was removed and started nothing here. ` +
87
+ "To run a pipeline flow by hand, use an issue without a `factory:*` label.";
@@ -0,0 +1,72 @@
1
+ // Who moved a label, read from the issue timeline (ADR 0038): never from the
2
+ // waking event's sender. The read gives each issue `timeline`, its labeled and
3
+ // unlabeled events, oldest first: `{ kind: "labeled" | "unlabeled", label,
4
+ // actor, at }`. Pure.
5
+
6
+ import { PAUSED_LABEL, stateOfLabel } from "../sweep/states.mjs";
7
+
8
+ const BURST_MS = 120_000;
9
+
10
+ const byTime = (a, b) => Date.parse(a.at) - Date.parse(b.at);
11
+
12
+ /**
13
+ * The latest move of each state label now on the issue: who added it, when, and
14
+ * the state label that was in force just before (`from`, or null when there was
15
+ * none: a person who removes the old label in the web UI and then adds the new
16
+ * one, within two minutes, still moved from the old).
17
+ * @returns {Map<string, { actor: string, at: string, from: string | null }>}
18
+ */
19
+ export function stateMoves(timeline) {
20
+ const events = [...(timeline ?? [])].sort(byTime);
21
+ const inForce = new Set();
22
+ const moves = new Map();
23
+ const removed = [];
24
+ for (const event of events) {
25
+ if (stateOfLabel(event.label) === null) continue;
26
+ if (event.kind === "unlabeled") {
27
+ inForce.delete(event.label);
28
+ removed.push(event);
29
+ continue;
30
+ }
31
+ const others = [...inForce].filter((l) => l !== event.label);
32
+ let from = others.length ? others[others.length - 1] : null;
33
+ if (from === null) {
34
+ const recent = removed
35
+ .filter(
36
+ (r) =>
37
+ r.label !== event.label &&
38
+ r.actor === event.actor &&
39
+ Date.parse(event.at) - Date.parse(r.at) <= BURST_MS &&
40
+ Date.parse(event.at) >= Date.parse(r.at),
41
+ )
42
+ .at(-1);
43
+ from = recent?.label ?? null;
44
+ }
45
+ inForce.add(event.label);
46
+ moves.set(event.label, { actor: event.actor, at: event.at, from });
47
+ }
48
+ return moves;
49
+ }
50
+
51
+ /** The latest `factory:paused` event: `{ kind, actor, at }`, or null. */
52
+ export function pausedMove(timeline) {
53
+ return (
54
+ [...(timeline ?? [])]
55
+ .filter((e) => e.label === PAUSED_LABEL)
56
+ .sort(byTime)
57
+ .at(-1) ?? null
58
+ );
59
+ }
60
+
61
+ /** The distinct logins of the people whose permission a sweep must read for this issue. */
62
+ export function moverLogins(issue) {
63
+ const logins = new Set();
64
+ const moves = stateMoves(issue.timeline);
65
+ for (const label of issue.labels ?? []) {
66
+ const move = moves.get(label);
67
+ if (move?.actor) logins.add(move.actor);
68
+ }
69
+ const paused = pausedMove(issue.timeline);
70
+ if (paused?.actor) logins.add(paused.actor);
71
+ return [...logins];
72
+ }
@@ -0,0 +1,59 @@
1
+ // Evidence last edited by someone other than its trusted writer is void
2
+ // (ADR 0038). The read carries each comment's `editor` (the last person to
3
+ // edit it); a comment the engine wrote is trusted only while the engine is also
4
+ // its last editor. Pure.
5
+ //
6
+ // a Claim comment -> kept, flagged `voided`: the sweep reads it as expired
7
+ // a Plan comment -> kept with its header block removed: it reads as a plan
8
+ // the sweep cannot read, one failed Attempt
9
+ // any other comment of the engine's (a Decision Request, a release comment,
10
+ // a note) -> dropped: it is not there
11
+ // a reply carrying `A<n>:` answers, edited by someone other than its author
12
+ // -> dropped: the answer counts only as its writer left it
13
+
14
+ import { parseAnswers } from "../decision/answers.mjs";
15
+ import { parsePlanComment } from "../plan/comment.mjs";
16
+ import { parseClaim } from "../sweep/markers.mjs";
17
+
18
+ const baseLogin = (login) =>
19
+ String(login ?? "")
20
+ .replace(/\[bot\]$/, "")
21
+ .toLowerCase();
22
+
23
+ /** Whether someone other than `author` was the last to edit the comment. */
24
+ export const editedByOther = (comment) =>
25
+ Boolean(comment.editor) && baseLogin(comment.editor) !== baseLogin(comment.author);
26
+
27
+ /**
28
+ * The issue with its voided evidence applied. A read with no `editor` anywhere
29
+ * comes back unchanged.
30
+ * @param {{ comments?: object[] }} issue
31
+ * @param {(login: string) => boolean} isEngine
32
+ */
33
+ export function applyVoid(issue, isEngine) {
34
+ const comments = [];
35
+ let changed = false;
36
+ for (const comment of issue.comments ?? []) {
37
+ if (!editedByOther(comment)) {
38
+ comments.push(comment);
39
+ continue;
40
+ }
41
+ changed = true;
42
+ if (isEngine(comment.author)) {
43
+ if (parseClaim(comment.body)) {
44
+ comments.push({ ...comment, voided: true });
45
+ } else if (parsePlanComment(comment.body)) {
46
+ const first = String(comment.body).split("\n", 1)[0];
47
+ comments.push({
48
+ ...comment,
49
+ voided: true,
50
+ body: `${first}\nVoided: edited by someone else.`,
51
+ });
52
+ }
53
+ continue;
54
+ }
55
+ if (parseAnswers(comment.body).size > 0) continue;
56
+ comments.push(comment);
57
+ }
58
+ return changed ? { ...issue, comments } : issue;
59
+ }