@mmerterden/multi-agent-pipeline 23.7.0 → 24.1.0

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 (162) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +59 -24
  3. package/README.tr.md +43 -8
  4. package/SECURITY.md +3 -3
  5. package/docs/architecture.md +41 -4
  6. package/docs/ecosystem.md +15 -13
  7. package/docs/facts.json +5 -4
  8. package/docs/features.md +67 -15
  9. package/install/_codex-agents.mjs +13 -8
  10. package/install/_common.mjs +24 -0
  11. package/install/_dev-only-files.mjs +5 -0
  12. package/install/_mcp-register.mjs +6 -2
  13. package/install/_rewrite-tree.mjs +197 -0
  14. package/install/codex.mjs +96 -180
  15. package/install/copilot.mjs +24 -54
  16. package/install/index.mjs +29 -11
  17. package/install/templates/codex-instructions.md +21 -5
  18. package/install/templates/copilot-instructions.md +21 -14
  19. package/manifest.json +2083 -0
  20. package/package.json +8 -2
  21. package/pipeline/commands/multi-agent/SKILL.md +5 -4
  22. package/pipeline/commands/multi-agent/analysis/SKILL.md +5 -1
  23. package/pipeline/commands/multi-agent/autopilot-on/SKILL.md +31 -3
  24. package/pipeline/commands/multi-agent/autopilot-status/SKILL.md +5 -1
  25. package/pipeline/commands/multi-agent/channels/SKILL.md +16 -8
  26. package/pipeline/commands/multi-agent/log/SKILL.md +2 -0
  27. package/pipeline/commands/multi-agent/stack/SKILL.md +1 -1
  28. package/pipeline/contract/CHANGELOG.md +15 -0
  29. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  30. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  31. package/pipeline/contract/fixtures/runs-awaiting-question.json +6 -1
  32. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  33. package/pipeline/contract/fixtures/runs-failed.json +21 -1
  34. package/pipeline/contract/fixtures/runs-old-schema.json +18 -3
  35. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +31 -1
  36. package/pipeline/contract/fixtures/runs-pr-opened.json +31 -1
  37. package/pipeline/contract/fixtures/runs-running.json +16 -1
  38. package/pipeline/contract/manifest.json +14 -14
  39. package/pipeline/contract/types/index.d.ts +20 -1
  40. package/pipeline/lib/_jira-auth.sh +50 -78
  41. package/pipeline/lib/_service-account.sh +191 -0
  42. package/pipeline/lib/credential-inventory.sh +49 -37
  43. package/pipeline/lib/credential-store.sh +48 -3
  44. package/pipeline/lib/fetch-confluence.sh +76 -92
  45. package/pipeline/lib/fetch-crashlytics.sh +30 -59
  46. package/pipeline/lib/fetch-figma-annotations.sh +9 -9
  47. package/pipeline/lib/fetch-fortify.sh +77 -81
  48. package/pipeline/lib/fetch-graylog.sh +38 -77
  49. package/pipeline/lib/figma-mcp-refresh.sh +23 -4
  50. package/pipeline/lib/figma-screenshot.sh +7 -8
  51. package/pipeline/lib/figma-token.sh +39 -46
  52. package/pipeline/lib/host.mjs +138 -0
  53. package/pipeline/lib/host.sh +48 -0
  54. package/pipeline/lib/issue-fetcher.sh +25 -41
  55. package/pipeline/lib/jira-publish.sh +23 -21
  56. package/pipeline/lib/local-model.mjs +93 -0
  57. package/pipeline/lib/md2confluence-v3.py +37 -30
  58. package/pipeline/lib/model-dispatch.sh +41 -4
  59. package/pipeline/lib/model-resolve.mjs +58 -0
  60. package/pipeline/lib/post-pr-review.sh +38 -53
  61. package/pipeline/lib/reviewer-families.mjs +70 -0
  62. package/pipeline/lib/service-account.mjs +2131 -0
  63. package/pipeline/lib/service-account.sh +35 -0
  64. package/pipeline/lib/usage-token.mjs +64 -24
  65. package/pipeline/lib/usage-vocab.mjs +1 -1
  66. package/pipeline/lib/user-facing.mjs +11 -3
  67. package/pipeline/lib/vercel-deploy.sh +17 -26
  68. package/pipeline/multi-agent-refs/_entry-picker.md +62 -0
  69. package/pipeline/multi-agent-refs/analysis/intake.md +2 -0
  70. package/pipeline/multi-agent-refs/analysis/render.md +12 -1
  71. package/pipeline/multi-agent-refs/analysis/reusable-refs.md +1 -0
  72. package/pipeline/multi-agent-refs/analysis/unattended.md +135 -0
  73. package/pipeline/multi-agent-refs/autopilot-on/details.md +16 -0
  74. package/pipeline/multi-agent-refs/channels/generator.md +10 -2
  75. package/pipeline/multi-agent-refs/channels/menu.md +3 -1
  76. package/pipeline/multi-agent-refs/channels/preview.md +3 -1
  77. package/pipeline/multi-agent-refs/channels/reference.md +16 -2
  78. package/pipeline/multi-agent-refs/channels/report-file.md +188 -0
  79. package/pipeline/multi-agent-refs/cross-cli-contract.md +35 -27
  80. package/pipeline/multi-agent-refs/features/doctor.md +37 -11
  81. package/pipeline/multi-agent-refs/features/free-models.md +3 -3
  82. package/pipeline/multi-agent-refs/features/local-model.md +87 -0
  83. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -10
  84. package/pipeline/multi-agent-refs/features/product-context.md +6 -5
  85. package/pipeline/multi-agent-refs/features/service-accounts.md +233 -0
  86. package/pipeline/multi-agent-refs/features/unattended-security.md +10 -1
  87. package/pipeline/multi-agent-refs/help/en.md +36 -1
  88. package/pipeline/multi-agent-refs/help/tr.md +34 -1
  89. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +2 -1
  90. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -1
  91. package/pipeline/multi-agent-refs/phases/modes.md +20 -1
  92. package/pipeline/multi-agent-refs/phases/phase-0-init.md +1 -0
  93. package/pipeline/multi-agent-refs/phases/phase-4-commit.md +1 -0
  94. package/pipeline/multi-agent-refs/phases/phase-5-report.md +13 -11
  95. package/pipeline/multi-agent-refs/phases.md +4 -3
  96. package/pipeline/multi-agent-refs/review/panel.md +30 -18
  97. package/pipeline/multi-agent-refs/setup/discovery.md +17 -5
  98. package/pipeline/multi-agent-refs/setup/token-save-flow.md +21 -2
  99. package/pipeline/multi-agent-refs/sync/overview.md +11 -5
  100. package/pipeline/multi-agent-refs/tracker-contract.md +64 -20
  101. package/pipeline/office/index.html +77 -4
  102. package/pipeline/schemas/activity.schema.json +63 -4
  103. package/pipeline/schemas/autopilot-config.schema.json +29 -4
  104. package/pipeline/schemas/hosts.json +512 -0
  105. package/pipeline/schemas/hosts.schema.json +310 -0
  106. package/pipeline/schemas/launch.json +22 -2
  107. package/pipeline/schemas/launch.schema.json +2 -1
  108. package/pipeline/schemas/now-lines.json +103 -0
  109. package/pipeline/schemas/now-lines.schema.json +42 -0
  110. package/pipeline/schemas/phases.json +19 -1
  111. package/pipeline/schemas/phases.schema.json +8 -0
  112. package/pipeline/schemas/prefs.schema.json +331 -4
  113. package/pipeline/schemas/runs-index.schema.json +22 -1
  114. package/pipeline/scripts/_autopilot-config.mjs +67 -4
  115. package/pipeline/scripts/_autopilot-item.mjs +67 -0
  116. package/pipeline/scripts/_autopilot-outcomes.mjs +6 -0
  117. package/pipeline/scripts/_contract-core.mjs +1 -1
  118. package/pipeline/scripts/_cost.mjs +75 -3
  119. package/pipeline/scripts/activity-snapshot.mjs +27 -1
  120. package/pipeline/scripts/analysis-sources.mjs +22 -5
  121. package/pipeline/scripts/analysis-unattended.mjs +360 -0
  122. package/pipeline/scripts/anonymize-findings.mjs +3 -7
  123. package/pipeline/scripts/autopilot-arming.mjs +19 -10
  124. package/pipeline/scripts/autopilot-intake.mjs +124 -27
  125. package/pipeline/scripts/autopilot-menubar.swift +7 -0
  126. package/pipeline/scripts/autopilot-runner.mjs +77 -48
  127. package/pipeline/scripts/autopilot-status.sh +32 -9
  128. package/pipeline/scripts/bulk-read.sh +37 -5
  129. package/pipeline/scripts/confluence-readback.mjs +15 -7
  130. package/pipeline/scripts/cost-table.json +65 -25
  131. package/pipeline/scripts/doctor.mjs +119 -32
  132. package/pipeline/scripts/entry-mode.mjs +101 -0
  133. package/pipeline/scripts/estimate.mjs +30 -16
  134. package/pipeline/scripts/feedback-send.mjs +11 -8
  135. package/pipeline/scripts/gen-facts.mjs +7 -9
  136. package/pipeline/scripts/jira-attach.sh +23 -28
  137. package/pipeline/scripts/jira-search.sh +5 -21
  138. package/pipeline/scripts/launch-request.mjs +15 -9
  139. package/pipeline/scripts/migrate-prefs.mjs +56 -0
  140. package/pipeline/scripts/phase-tracker.sh +226 -50
  141. package/pipeline/scripts/priority-review.mjs +14 -7
  142. package/pipeline/scripts/product-context.mjs +26 -7
  143. package/pipeline/scripts/prune-logs.sh +4 -2
  144. package/pipeline/scripts/render-work-summary.sh +51 -1
  145. package/pipeline/scripts/report-file.mjs +285 -0
  146. package/pipeline/scripts/rework-escalation.mjs +19 -4
  147. package/pipeline/scripts/runs-index.mjs +2 -1
  148. package/pipeline/scripts/service-read.mjs +19 -17
  149. package/pipeline/scripts/skill-siblings.mjs +17 -1
  150. package/pipeline/scripts/status-overview.mjs +20 -10
  151. package/pipeline/scripts/uninstall.mjs +145 -57
  152. package/pipeline/scripts/usage-register.mjs +34 -11
  153. package/pipeline/scripts/usage-report.mjs +31 -26
  154. package/pipeline/scripts/validate-triage.mjs +11 -1
  155. package/pipeline/scripts/work-items.mjs +25 -28
  156. package/pipeline/scripts/write-store-config.mjs +37 -11
  157. package/pipeline/skills/.skill-manifest.json +4 -4
  158. package/pipeline/skills/.skills-index.json +1 -1
  159. package/pipeline/skills/shared/core/multi-agent/SKILL.md +11 -3
  160. package/pipeline/skills/shared/core/multi-agent-analysis/SKILL.md +2 -0
  161. package/pipeline/skills/shared/core/multi-agent-channels/SKILL.md +11 -8
  162. package/pipeline/lib/credential-resolve.mjs +0 -75
@@ -7,6 +7,15 @@
7
7
  * keeping the two apart is what makes the ordering testable without a network,
8
8
  * a simulator, or a willingness to open a real PR while a gate runs.
9
9
  *
10
+ * KINDS. Each repo has two labels per tracker: the development label, whose
11
+ * items run the pipeline and stop at a pull request, and the analysis label,
12
+ * whose items run the analysis command and stop at a document. Each is its own
13
+ * query, each item carries its `kind`, and the ledger keys them apart
14
+ * (_autopilot-item.mjs), so one ticket can be analysed and later developed. A
15
+ * repo whose two labels are equal is refused (_autopilot-config.mjs), and a
16
+ * repo that never said yes to analysis work is never queried for it
17
+ * (`analysisEnrolled`).
18
+ *
10
19
  * ORDER (descending precedence). Deterministic, no model call:
11
20
  *
12
21
  * 1. explicit rank from the label (`agent-queue:1` ... `agent-queue:9`)
@@ -43,6 +52,7 @@ import { join, dirname } from "node:path";
43
52
  import { homedir } from "node:os";
44
53
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
45
54
  import { OUTCOME, isParked, isRetryable, isTerminal } from "./_autopilot-outcomes.mjs";
55
+ import { KIND, historyKey, isAnalysis, queuedKinds } from "./_autopilot-item.mjs";
46
56
  import { configRefusal } from "./_autopilot-config.mjs";
47
57
  import { exitOnHelp } from "../lib/cli-help.mjs";
48
58
 
@@ -75,12 +85,76 @@ export function priorityScore(name) {
75
85
  return PRIORITY[String(name).trim().toLowerCase()] ?? 0;
76
86
  }
77
87
 
88
+ /**
89
+ * The shape a queue label may take.
90
+ *
91
+ * The label is operator-configured, and it is read into three different
92
+ * languages: a regular expression here, a JQL string literal in the Jira
93
+ * query, and a GitHub search term. Rather than escaping it three ways, it is
94
+ * checked once against what a label can actually be - a tracker label is a
95
+ * short name, and nothing that fits this pattern means anything in any of the
96
+ * three.
97
+ */
98
+ const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,48}$/;
99
+
100
+ /** The configured label, or null when it is not a label at all. */
101
+ export function checkedLabel(value, fallback) {
102
+ const text = String(value ?? "").trim() || fallback;
103
+ return LABEL_RE.test(text) ? text : null;
104
+ }
105
+
106
+ /**
107
+ * The label each kind is queued by when the repo names none. The schema
108
+ * carries the same two defaults, and test/autopilot-intake.test.mjs fails when
109
+ * they drift.
110
+ */
111
+ export const DEFAULT_LABELS = Object.freeze({
112
+ [KIND.DEVELOPMENT]: "agent-queue",
113
+ [KIND.ANALYSIS]: "agent-analysis",
114
+ });
115
+
116
+ /** Is this repo in the analysis queue at all? One owner: `queuedKinds`. */
117
+ export function analysisEnrolled(repo) {
118
+ return queuedKinds(repo).includes(KIND.ANALYSIS);
119
+ }
120
+
121
+ /**
122
+ * The label one repo queues `kind` work by on one tracker, or null when the
123
+ * configured value is not a label. Every query below is built from this and
124
+ * from nothing else, so an unchecked value never reaches a JQL string literal
125
+ * or a search term.
126
+ *
127
+ * @param {object} repo
128
+ * @param {"github"|"jira"} tracker
129
+ * @param {string} kind
130
+ * @returns {string|null}
131
+ */
132
+ export function labelFor(repo, tracker, kind = KIND.DEVELOPMENT) {
133
+ const analysis = kind === KIND.ANALYSIS;
134
+ const configured =
135
+ tracker === "jira"
136
+ ? analysis
137
+ ? repo.analysisJiraLabel
138
+ : repo.jiraLabel
139
+ : analysis
140
+ ? repo.analysisGithubLabel
141
+ : repo.githubLabel;
142
+ return checkedLabel(configured, DEFAULT_LABELS[kind]);
143
+ }
144
+
78
145
  /** `agent-queue:3` -> 3. Any other label shape -> null (ordered by the rules). */
79
146
  export function rankFromLabels(labels, base) {
147
+ const checked = checkedLabel(base, "");
148
+ if (!checked) return null;
149
+ // Escaped even though the pattern above already excludes every character
150
+ // that means anything here: the two checks answer to different callers, and
151
+ // the one that is only correct because of the other is the one that breaks
152
+ // when either moves.
153
+ const re = new RegExp(`^${checked.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&")}:([1-9])$`);
80
154
  for (const l of labels || []) {
81
155
  const name = typeof l === "string" ? l : l?.name;
82
156
  if (!name) continue;
83
- const m = new RegExp(`^${base}:([1-9])$`).exec(name);
157
+ const m = re.exec(name);
84
158
  if (m) return Number(m[1]);
85
159
  }
86
160
  return null;
@@ -160,7 +234,7 @@ export function foldAttempts(lines) {
160
234
  } catch {
161
235
  continue; // a truncated last line is normal on an append-only log
162
236
  }
163
- const key = `${rec.source}:${rec.id}`;
237
+ const key = historyKey(rec);
164
238
  const cur = byKey.get(key) || { attempts: 0, last: null, usd: 0, at: 0, runs: new Set() };
165
239
  if (isRetryable(rec.outcome)) {
166
240
  if (!rec.taskId) cur.attempts += 1;
@@ -188,6 +262,7 @@ export function foldAttempts(lines) {
188
262
  * leaving the item alone, never toward running it twice.
189
263
  */
190
264
  function legacyKey(c) {
265
+ if (isAnalysis(c)) return null; // no analysis row was ever written under the old id
191
266
  if (c?.source !== "github" || typeof c.id !== "string") return null;
192
267
  const m = /^[^/#]+\/([^/#]+)#(\d+)$/.exec(c.id);
193
268
  return m ? `github:${m[1]}#${m[2]}` : null;
@@ -203,7 +278,7 @@ export function selectable(candidates, history, { maxAttempts = 2 } = {}) {
203
278
  const awaiting = [];
204
279
  const dropped = [];
205
280
  for (const c of candidates) {
206
- const h = history.get(`${c.source}:${c.id}`) ?? history.get(legacyKey(c));
281
+ const h = history.get(historyKey(c)) ?? history.get(legacyKey(c));
207
282
  if (!h) {
208
283
  queued.push(c);
209
284
  continue;
@@ -255,8 +330,9 @@ function sh(cmd, args, opts = {}) {
255
330
  * anyone who opens an issue, and an unattended run acts on the issue's text.
256
331
  * `githubAssignee: "*"` lists every labelled issue.
257
332
  */
258
- export function githubListArgs(repo) {
259
- const label = repo.githubLabel || "agent-queue";
333
+ export function githubListArgs(repo, kind = KIND.DEVELOPMENT) {
334
+ const label = labelFor(repo, "github", kind);
335
+ if (!label) return null;
260
336
  const assignee = repo.githubAssignee || "@me";
261
337
  const args = ["issue", "list", "--repo", repo.nameWithOwner, "--label", label];
262
338
  if (assignee !== "*") args.push("--assignee", assignee);
@@ -264,15 +340,17 @@ export function githubListArgs(repo) {
264
340
  return args;
265
341
  }
266
342
 
267
- function fetchGitHub(repo) {
268
- const out = sh("gh", githubListArgs(repo));
343
+ function fetchGitHub(repo, kind = KIND.DEVELOPMENT) {
344
+ const args = githubListArgs(repo, kind);
345
+ if (!args) return [];
346
+ const out = sh("gh", args);
269
347
  let rows;
270
348
  try {
271
349
  rows = JSON.parse(out || "[]");
272
350
  } catch {
273
351
  return [];
274
352
  }
275
- return githubCandidates(repo, rows);
353
+ return githubCandidates(repo, rows, kind);
276
354
  }
277
355
 
278
356
  /**
@@ -281,13 +359,14 @@ function fetchGitHub(repo) {
281
359
  * would let one repo's finished issue drop the other's. `ref` stays short -
282
360
  * the run is launched in the repo's own checkout, which names the repo.
283
361
  */
284
- export function githubCandidates(repo, rows) {
285
- const label = repo.githubLabel || "agent-queue";
362
+ export function githubCandidates(repo, rows, kind = KIND.DEVELOPMENT) {
363
+ const label = labelFor(repo, "github", kind);
286
364
  const short = repo.nameWithOwner.split("/").pop();
287
365
  return (rows || []).map((r) => ({
288
366
  source: "github",
289
367
  id: `${repo.nameWithOwner}#${r.number}`,
290
368
  ref: `${short}#${r.number}`,
369
+ kind,
291
370
  repo: repo.nameWithOwner,
292
371
  localPath: repo.localPath,
293
372
  title: r.title,
@@ -305,10 +384,17 @@ export function githubCandidates(repo, rows) {
305
384
  }));
306
385
  }
307
386
 
308
- function fetchJira(repo) {
309
- const label = repo.jiraLabel || "agent-queue";
387
+ function fetchJira(repo, kind = KIND.DEVELOPMENT) {
388
+ // A label that is not a label never reaches the query: it would be a quote
389
+ // inside a JQL string literal, which is a different query than the one this
390
+ // line reads as.
391
+ const label = labelFor(repo, "jira", kind);
392
+ if (!label) return [];
393
+ // `jiraJql` is the development queue's own search; analysis work is picked
394
+ // up by its label whatever that search says, so a repo with a custom JQL
395
+ // does not silently lose the analysis queue.
310
396
  const jql =
311
- repo.jiraJql ||
397
+ (kind === KIND.ANALYSIS ? null : repo.jiraJql) ||
312
398
  `assignee = currentUser() AND labels = "${label}" AND resolution = EMPTY ` +
313
399
  `AND status not in (Done, Closed, Cancelled) ORDER BY priority DESC, created ASC`;
314
400
  // One helper owns Jira search: URL encoding and JQL injection are already
@@ -327,15 +413,16 @@ function fetchJira(repo) {
327
413
  } catch {
328
414
  return [];
329
415
  }
330
- return jiraCandidates(repo, rows);
416
+ return jiraCandidates(repo, rows, kind);
331
417
  }
332
418
 
333
419
  /** Queue items from a Jira search's `issues`. The issue key is the id. */
334
- export function jiraCandidates(repo, issues) {
420
+ export function jiraCandidates(repo, issues, kind = KIND.DEVELOPMENT) {
335
421
  return (issues || []).map((i) => ({
336
422
  source: "jira",
337
423
  id: i.key,
338
424
  ref: i.key,
425
+ kind,
339
426
  repo: repo.nameWithOwner,
340
427
  localPath: repo.localPath,
341
428
  title: i.fields?.summary,
@@ -354,6 +441,8 @@ export function jiraCandidates(repo, issues) {
354
441
  * repo with Jira on would queue - and run, and open a PR for - the same issue.
355
442
  * The first repo in config order takes it; each other match is returned in
356
443
  * `duplicates` with the reason, so the queue says why it is not listed twice.
444
+ * That holds per kind: the analysis queue and the development queue each pick
445
+ * one owner, and an issue in both is two items, not a duplicate.
357
446
  *
358
447
  * @returns {{items: object[], duplicates: object[]}}
359
448
  */
@@ -366,18 +455,26 @@ export function gather(
366
455
  const jiraOwner = new Map();
367
456
  for (const repo of config.repos || []) {
368
457
  const sources = repo.sources || ["github"];
369
- if (sources.includes("github")) items.push(...gh(repo));
370
- if (!sources.includes("jira")) continue;
371
- for (const it of jira(repo)) {
372
- const owner = jiraOwner.get(it.id);
373
- if (owner === undefined) {
374
- jiraOwner.set(it.id, it.repo);
375
- items.push(it);
376
- } else if (owner !== it.repo) {
377
- duplicates.push({
378
- ...it,
379
- reason: `also matched for ${owner}, queued there - give each repo a jiraJql that matches only its own issues`,
380
- });
458
+ // One pass per kind, because the two labels are two separate queries. The
459
+ // same ticket may answer both, and then it is two items: one analysed, one
460
+ // developed, each with its own key in the ledger. The analysis pass runs
461
+ // only for a repo enrolled in that queue, so a repo picked for development
462
+ // never starts spending runs on documents nobody asked for.
463
+ for (const kind of queuedKinds(repo)) {
464
+ if (sources.includes("github")) items.push(...gh(repo, kind));
465
+ if (!sources.includes("jira")) continue;
466
+ for (const it of jira(repo, kind)) {
467
+ const key = historyKey(it);
468
+ const owner = jiraOwner.get(key);
469
+ if (owner === undefined) {
470
+ jiraOwner.set(key, it.repo);
471
+ items.push(it);
472
+ } else if (owner !== it.repo) {
473
+ duplicates.push({
474
+ ...it,
475
+ reason: `also matched for ${owner}, queued there - give each repo a jiraJql that matches only its own issues`,
476
+ });
477
+ }
381
478
  }
382
479
  }
383
480
  }
@@ -35,6 +35,7 @@ struct Item: Decodable {
35
35
  let stack: String?
36
36
  let startedAt: Double?
37
37
  let state: String? // running | queued | awaiting-answer | blocked
38
+ let kind: String? // development | analysis - what the item delivers
38
39
  let url: String? // the ticket, so a row is clickable
39
40
  }
40
41
 
@@ -135,6 +136,7 @@ struct Strings {
135
136
  let idle: String
136
137
  let queuedHeading: String
137
138
  let queuedMore: String
139
+ let analysisSuffix: String
138
140
  let awaitingHeading: String
139
141
  let reportsHeading: String
140
142
  let todayCount: String
@@ -159,6 +161,7 @@ func strings(for language: Language) -> Strings {
159
161
  idle: "on, nothing queued",
160
162
  queuedHeading: "Queued (%d)",
161
163
  queuedMore: " ... %d more",
164
+ analysisSuffix: "analysis",
162
165
  awaitingHeading: "Waiting for an answer (%d)",
163
166
  reportsHeading: "Reports (%d)",
164
167
  todayCount: "today: %d",
@@ -179,6 +182,7 @@ func strings(for language: Language) -> Strings {
179
182
  idle: "açık, sırada iş yok",
180
183
  queuedHeading: "Sırada (%d)",
181
184
  queuedMore: " ... %d tane daha",
185
+ analysisSuffix: "analiz",
182
186
  awaitingHeading: "Cevap bekliyor (%d)",
183
187
  reportsHeading: "Raporlar (%d)",
184
188
  todayCount: "bugün %d madde",
@@ -281,6 +285,9 @@ final class Controller: NSObject {
281
285
  }
282
286
  if i.startedAt != nil { line += " · \(elapsed(since: i.startedAt, ui))" }
283
287
  if let s = i.stack, !s.isEmpty { line += " · \(s)" }
288
+ // An analysis item ends at a document, not at a pull request. Without
289
+ // this the row reads as work that will produce a PR and never does.
290
+ if i.kind == "analysis" { line += " · \(ui.analysisSuffix)" }
284
291
 
285
292
  let m = NSMenuItem(title: line, action: nil, keyEquivalent: "")
286
293
  // The ticket title is long and would push every row's shape around, so
@@ -22,6 +22,11 @@
22
22
  * else leaves it parked. Bounded by config `maxAskRounds`.
23
23
  * 6. RECORD attempted.jsonl, clear the pid file, refresh status.json.
24
24
  *
25
+ * The item's KIND decides what step 5 runs and where it ends: a development
26
+ * item runs the pipeline and stops at a draft PR, an analysis item runs
27
+ * `/multi-agent:analysis` and stops at a document, skips the publish step
28
+ * entirely and is recorded as `doc-delivered`.
29
+ *
25
30
  * Around the run, three operations (_autopilot-ops.mjs): a sleep inhibitor held
26
31
  * from the launch to the end of the tick; `maxParallelAgents`, a ceiling on
27
32
  * runner-launched sessions working at once; and two jobs at most once per
@@ -101,7 +106,7 @@ import {
101
106
  resolveRunFile,
102
107
  runDirCandidates,
103
108
  } from "./_run-paths.mjs";
104
- import { trackerUsd } from "./_cost.mjs";
109
+ import { CONSERVATIVE_RUNG, trackerUsd } from "./_cost.mjs";
105
110
  import { configRefusal } from "./_autopilot-config.mjs";
106
111
  import {
107
112
  OUTCOME,
@@ -111,6 +116,7 @@ import {
111
116
  isTerminal,
112
117
  rateLimited,
113
118
  } from "./_autopilot-outcomes.mjs";
119
+ import { historyKey, isAnalysis } from "./_autopilot-item.mjs";
114
120
  import {
115
121
  SESSION_ID_RE,
116
122
  prRequestsDir,
@@ -282,9 +288,6 @@ const GUARD_MATCHERS = [
282
288
  // the script path can run anything and still look registered.
283
289
  const GUARD_COMMAND = 'bash "$HOME/.claude/scripts/agent-guard.sh"';
284
290
  const MANAGED_SETTINGS = "/Library/Application Support/ClaudeCode/managed-settings.json";
285
- // A phase record without a model is priced at the most expensive tier: an
286
- // over-estimate stops the spend ceiling early, an under-estimate stops it late.
287
- const CONSERVATIVE_PRICE = "fable";
288
291
  // What the queue says when the arming script answers nothing at all. Read by a
289
292
  // person in the menu bar and in the terminal, so it renders in the same
290
293
  // preference every other line does.
@@ -303,14 +306,24 @@ const RATE_LIMITED_MSG = {
303
306
  * scripts in every install, as runs-index.mjs reads it; a host tree without it
304
307
  * shows the number alone rather than failing the tick.
305
308
  */
306
- const PHASES = (() => {
309
+ const PHASE_CONTRACT = (() => {
307
310
  try {
308
- return JSON.parse(readFileSync(new URL("../schemas/phases.json", import.meta.url), "utf-8"))
309
- .phases;
311
+ return JSON.parse(readFileSync(new URL("../schemas/phases.json", import.meta.url), "utf-8"));
310
312
  } catch {
311
- return [];
313
+ return { phases: [], modes: {} };
312
314
  }
313
315
  })();
316
+ const PHASES = PHASE_CONTRACT.phases || [];
317
+
318
+ /**
319
+ * A phase's name in the item's own mode. An analysis item runs the same six
320
+ * slots under its own step names, so its row says Synthesis where a development
321
+ * row says Dev - the name a reader checks the queue for.
322
+ */
323
+ function phaseLabel(item, id) {
324
+ const names = isAnalysis(item) ? PHASE_CONTRACT.modes?.["analysis-autopilot"]?.names : null;
325
+ return names?.[String(id)] ?? PHASES.find((p) => p.id === id)?.name ?? null;
326
+ }
314
327
 
315
328
  const log = (m) => process.stdout.write(`autopilot-runner: ${m}\n`);
316
329
 
@@ -353,6 +366,14 @@ function writeState(name, obj) {
353
366
  renameSync(tmp, p);
354
367
  }
355
368
 
369
+ /**
370
+ * The identity every ledger row carries, so a row is folded under the key of
371
+ * the item that produced it and not under the other kind's.
372
+ */
373
+ function rowItem(item) {
374
+ return { source: item?.source, id: item?.id, ...(item?.kind ? { kind: item.kind } : {}) };
375
+ }
376
+
356
377
  function record(entry) {
357
378
  ensureRoot();
358
379
  const p = join(ROOT, "attempted.jsonl");
@@ -536,13 +557,13 @@ export function compactAttempted(
536
557
  const since = now - keepSec;
537
558
  const newest = new Map();
538
559
  rows.forEach((r, i) => {
539
- const key = `${r.source}:${r.id}`;
560
+ const key = historyKey(r);
540
561
  const cur = newest.get(key);
541
562
  if (!cur || Number(r.at || 0) >= Number(rows[cur].at || 0)) newest.set(key, i);
542
563
  });
543
564
  return rows.filter((r, i) => {
544
565
  if (Number(r.at || 0) >= since) return true;
545
- const key = `${r.source}:${r.id}`;
566
+ const key = historyKey(r);
546
567
  const last = newest.get(key);
547
568
  if (last === i) return true;
548
569
  if (isTerminal(rows[last].outcome)) return false;
@@ -763,7 +784,7 @@ export function runUsd(runTaskId, statePath) {
763
784
  if (!trackerPath) return null;
764
785
  const tracker = readJson(trackerPath, null);
765
786
  const prices = readJson(join(import.meta.dirname, "cost-table.json"), null)?.prices;
766
- return trackerUsd(tracker, prices, CONSERVATIVE_PRICE);
787
+ return trackerUsd(tracker, prices, CONSERVATIVE_RUNG);
767
788
  }
768
789
 
769
790
  /**
@@ -783,13 +804,12 @@ async function retire(holder) {
783
804
  const pub = await publishStep(holder.sessionId, holder.statePath, item);
784
805
  const state = holder.statePath ? readJson(holder.statePath, null) : null;
785
806
  const prUrl = prFromState(state);
786
- const ended = pub.outcome || outcomeFor({ reason: "gone" }, state, prUrl);
807
+ const ended = pub.outcome || outcomeFor({ reason: "gone" }, state, prUrl, item);
787
808
  const usd = runUsd(holder.runTaskId, holder.statePath);
788
809
 
789
810
  if (holder.parked || isParked(ended)) {
790
811
  record({
791
- source: item.source,
792
- id: item.id,
812
+ ...rowItem(item),
793
813
  taskId: holder.taskId,
794
814
  outcome: ended,
795
815
  usd,
@@ -834,8 +854,7 @@ async function retire(holder) {
834
854
 
835
855
  if (isTerminal(ended)) {
836
856
  record({
837
- source: item.source,
838
- id: item.id,
857
+ ...rowItem(item),
839
858
  taskId: holder.taskId,
840
859
  outcome: ended,
841
860
  prUrl,
@@ -861,8 +880,7 @@ async function retire(holder) {
861
880
  }
862
881
 
863
882
  record({
864
- source: item.source,
865
- id: item.id,
883
+ ...rowItem(item),
866
884
  taskId: holder.taskId,
867
885
  outcome: OUTCOME.DIED,
868
886
  keptWorktree: kept,
@@ -891,11 +909,10 @@ async function reconcileParked() {
891
909
  const pub = DRY ? { outcome: null } : await publishStep(e.sessionId, e.statePath, e);
892
910
  const st = e.statePath ? readJson(e.statePath, null) : null;
893
911
  const prUrl = prFromState(st);
894
- const outcome = pub.outcome || outcomeFor({ reason: "gone" }, st, prUrl);
912
+ const outcome = pub.outcome || outcomeFor({ reason: "gone" }, st, prUrl, e);
895
913
  if (!isParked(outcome) && !DRY) {
896
914
  record({
897
- source: e.source,
898
- id: e.id,
915
+ ...rowItem(e),
899
916
  taskId: e.taskId,
900
917
  outcome,
901
918
  prUrl,
@@ -983,6 +1000,10 @@ function releaseSlot(id, pidPath, queue = { queued: [], running: [] }) {
983
1000
  */
984
1001
  async function publishStep(sessionId, statePath, item) {
985
1002
  if (!sessionId || !statePath || !item?.repo) return { outcome: null };
1003
+ // An analysis run delivers a document and touches no branch, so there is no
1004
+ // request to verify and nothing to push. Reaching the publish step at all
1005
+ // would be the one way an analysis item could end at a pull request.
1006
+ if (isAnalysis(item)) return { outcome: null };
986
1007
  const config = readJson(join(ROOT, "config.json"), null);
987
1008
  let pub;
988
1009
  try {
@@ -1154,6 +1175,10 @@ export function prFromState(state) {
1154
1175
  * unattended run's own gate rejected its work, before a plain `failed`:
1155
1176
  * retrying repeats the same work into the same rejection.
1156
1177
  *
1178
+ * An analysis item ends at `doc-delivered` where a development item ends at
1179
+ * `completed-no-pr`: its mode ends at the document, which is delivery, and the
1180
+ * same completion contract decides whether the state earned it.
1181
+ *
1157
1182
  * "finished with no PR" is deliberately not "failed": a run can stop
1158
1183
  * legitimately without opening one, and calling that a failure would put a
1159
1184
  * healthy item into the retry path. It is only that when the state earns it
@@ -1161,7 +1186,7 @@ export function prFromState(state) {
1161
1186
  * without Phase 4 evidence or without a plan-coverage verdict is
1162
1187
  * `stopped-incomplete`, which is retried, not filed as finished.
1163
1188
  */
1164
- export function outcomeFor(supervised, state, prUrl) {
1189
+ export function outcomeFor(supervised, state, prUrl, item = null) {
1165
1190
  if (prUrl) return OUTCOME.PR_OPENED;
1166
1191
  if (state?.publish?.outcome === OUTCOME.PUSHED_AWAITING_PR) return OUTCOME.PUSHED_AWAITING_PR;
1167
1192
  if (state && (state.waitingFor || state.status === "awaiting_input")) {
@@ -1174,7 +1199,8 @@ export function outcomeFor(supervised, state, prUrl) {
1174
1199
  if (state && state.verificationFailed) return OUTCOME.VERIFICATION_FAILED;
1175
1200
  const status = state && state.status;
1176
1201
  if (status === "complete" || status === "completed") {
1177
- return completionGaps(state).length ? OUTCOME.STOPPED_INCOMPLETE : OUTCOME.COMPLETED_NO_PR;
1202
+ if (completionGaps(state).length) return OUTCOME.STOPPED_INCOMPLETE;
1203
+ return isAnalysis(item) ? OUTCOME.DOC_DELIVERED : OUTCOME.COMPLETED_NO_PR;
1178
1204
  }
1179
1205
  if (status === "failed") return OUTCOME.FAILED;
1180
1206
  return state ? `stopped-${status || "unknown"}` : OUTCOME.NO_STATE;
@@ -1183,13 +1209,17 @@ export function outcomeFor(supervised, state, prUrl) {
1183
1209
  /**
1184
1210
  * The `claude` arguments for one item. The shape - background, a session id
1185
1211
  * this runner chose, no permission prompts, the unattended permission profile
1186
- * as an extra settings file, one unattended `/multi-agent` item as the
1187
- * positional prompt (`--bg` refuses `--print`: the prompt is the positional,
1188
- * and the CLI prints the session id and returns) - is pending a live launch
1189
- * trial; everything that launches or describes a launch derives from here so
1190
- * a correction is one edit. `print` starts the same launch in print mode,
1191
- * which waits for the run to end: autopilot-loop judges each iteration from
1192
- * the state the finished run left.
1212
+ * as an extra settings file, one unattended item as the positional prompt
1213
+ * (`--bg` refuses `--print`: the prompt is the positional, and the CLI prints
1214
+ * the session id and returns) - is pending a live launch trial; everything
1215
+ * that launches or describes a launch derives from here so a correction is one
1216
+ * edit. `print` starts the same launch in print mode, which waits for the run
1217
+ * to end: autopilot-loop judges each iteration from the state the finished run
1218
+ * left.
1219
+ *
1220
+ * The item's kind decides the command. An analysis item runs
1221
+ * `/multi-agent:analysis`, which writes a document and stops: no worktree, no
1222
+ * commit, no pull request, and so nothing for the publish step to verify.
1193
1223
  */
1194
1224
  export function launchArgv(
1195
1225
  item,
@@ -1205,7 +1235,7 @@ export function launchArgv(
1205
1235
  "none",
1206
1236
  "--settings",
1207
1237
  settingsFile,
1208
- `/multi-agent ${item.ref || item.id} autopilot`,
1238
+ `${isAnalysis(item) ? "/multi-agent:analysis" : "/multi-agent"} ${item.ref || item.id} autopilot`,
1209
1239
  ];
1210
1240
  }
1211
1241
 
@@ -1603,7 +1633,7 @@ export function researchRoute(state, prUrl, { roundsUsed = 0, maxAskRounds = 2 }
1603
1633
  export function researchRoundsUsed(lines, item) {
1604
1634
  let n = 0;
1605
1635
  for (const row of lines || []) {
1606
- if (!row || row.source !== item?.source || row.id !== item?.id) continue;
1636
+ if (!row || historyKey(row) !== historyKey(item)) continue;
1607
1637
  const r = Number(row.researchRounds || 0);
1608
1638
  if (Number.isFinite(r) && r > 0) n += r;
1609
1639
  }
@@ -1845,7 +1875,7 @@ function trackRunState(claim) {
1845
1875
  }
1846
1876
 
1847
1877
  /** Mirror the run's current phase onto its `running` entry, which the status line renders. */
1848
- function trackProgress(claim, id) {
1878
+ function trackProgress(claim, item) {
1849
1879
  if (!claim.statePath) return;
1850
1880
  const st = readJson(claim.statePath, null);
1851
1881
  const phase = st && Number.isInteger(st.currentPhase) ? st.currentPhase : null;
@@ -1854,11 +1884,11 @@ function trackProgress(claim, id) {
1854
1884
  const q = readJson(join(ROOT, "queue.json"), null);
1855
1885
  if (!q) return;
1856
1886
  const last = PHASES.length ? PHASES[PHASES.length - 1].id : null;
1857
- const phaseName = PHASES.find((p) => p.id === phase)?.name ?? null;
1887
+ const phaseName = phaseLabel(item, phase);
1858
1888
  writeState("queue.json", {
1859
1889
  ...q,
1860
1890
  running: (q.running || []).map((r) =>
1861
- r.id === id ? { ...r, phase, phaseName, phaseTotal: last } : r,
1891
+ r.id === item.id ? { ...r, phase, phaseName, phaseTotal: last } : r,
1862
1892
  ),
1863
1893
  });
1864
1894
  refreshStatus();
@@ -1914,7 +1944,7 @@ function supervise(sessionId, claim, item) {
1914
1944
  sawLive = true;
1915
1945
  lastRow = row;
1916
1946
  trackRunState(claim);
1917
- trackProgress(claim, item.id);
1947
+ trackProgress(claim, item);
1918
1948
  if (row.status === "busy" || row.status === "running") sawBusy = true;
1919
1949
  if (row.status === "waiting") {
1920
1950
  // Only terminal once the run has actually been working. A session can
@@ -1990,10 +2020,10 @@ function nextItem(queue, busyRepos, attempts) {
1990
2020
  for (const i of queue.queued || []) {
1991
2021
  if (busyRepos.has(i.repo)) continue;
1992
2022
  if (i.localPath && existsSync(i.localPath)) return i;
1993
- const prev = attempts.findLast((a) => a.source === i.source && a.id === i.id);
2023
+ const prev = attempts.findLast((a) => historyKey(a) === historyKey(i));
1994
2024
  log(`${i.id}: no checkout at ${i.localPath || "(none configured)"} - not launched`);
1995
2025
  if (!DRY && prev?.outcome !== OUTCOME.BLOCKED_NO_PATH) {
1996
- record({ source: i.source, id: i.id, outcome: OUTCOME.BLOCKED_NO_PATH });
2026
+ record({ ...rowItem(i), outcome: OUTCOME.BLOCKED_NO_PATH });
1997
2027
  }
1998
2028
  }
1999
2029
  return null;
@@ -2271,7 +2301,7 @@ async function main() {
2271
2301
  if (!arm.armed) {
2272
2302
  log(`not armed: ${arm.reason}`);
2273
2303
  if (!DRY) {
2274
- record({ source: next.source, id: next.id, outcome: `blocked-${arm.blockedBy}` });
2304
+ record({ ...rowItem(next), outcome: `blocked-${arm.blockedBy}` });
2275
2305
  writeState("queue.json", { ...queue, blockedReason: arm.reason });
2276
2306
  refreshStatus();
2277
2307
  }
@@ -2290,7 +2320,7 @@ async function main() {
2290
2320
  `not launching: ${guard.reason} (install registers it; see features/unattended-security.md)`,
2291
2321
  );
2292
2322
  if (!DRY) {
2293
- record({ source: next.source, id: next.id, outcome: OUTCOME.BLOCKED_GUARD_MISSING });
2323
+ record({ ...rowItem(next), outcome: OUTCOME.BLOCKED_GUARD_MISSING });
2294
2324
  writeState("queue.json", { ...queue, blockedReason: guard.reason });
2295
2325
  refreshStatus();
2296
2326
  }
@@ -2306,7 +2336,7 @@ async function main() {
2306
2336
  if (!sandbox.ok) {
2307
2337
  log(`not launching: ${sandbox.reason} (see features/unattended-security.md)`);
2308
2338
  if (!DRY) {
2309
- record({ source: next.source, id: next.id, outcome: OUTCOME.BLOCKED_SANDBOX_UNAVAILABLE });
2339
+ record({ ...rowItem(next), outcome: OUTCOME.BLOCKED_SANDBOX_UNAVAILABLE });
2310
2340
  writeState("queue.json", { ...queue, blockedReason: sandbox.reason });
2311
2341
  refreshStatus();
2312
2342
  }
@@ -2325,7 +2355,7 @@ async function main() {
2325
2355
  const reason = `installed v${local || "?"} is below the required v${required || "?"}; run the update`;
2326
2356
  log(`not launching: ${reason}`);
2327
2357
  if (!DRY) {
2328
- record({ source: next.source, id: next.id, outcome: OUTCOME.BLOCKED_VERSION_FLOOR });
2358
+ record({ ...rowItem(next), outcome: OUTCOME.BLOCKED_VERSION_FLOOR });
2329
2359
  writeState("queue.json", { ...queue, blockedReason: reason });
2330
2360
  refreshStatus();
2331
2361
  }
@@ -2367,6 +2397,7 @@ async function main() {
2367
2397
  ...running,
2368
2398
  {
2369
2399
  id: next.id,
2400
+ kind: next.kind,
2370
2401
  repo: next.repo,
2371
2402
  stack: next.stack,
2372
2403
  startedAt: claim.startedAt,
@@ -2376,7 +2407,7 @@ async function main() {
2376
2407
  taskId,
2377
2408
  },
2378
2409
  ],
2379
- queued: (queue.queued || []).filter((i) => i.id !== next.id),
2410
+ queued: (queue.queued || []).filter((i) => historyKey(i) !== historyKey(next)),
2380
2411
  });
2381
2412
  refreshStatus();
2382
2413
 
@@ -2399,8 +2430,7 @@ async function main() {
2399
2430
  const why = (child.stderr || child.error?.message || "").trim().slice(0, 300);
2400
2431
  // Nothing ran, so nothing was spent: 0 here is a measurement, not a guess.
2401
2432
  record({
2402
- source: next.source,
2403
- id: next.id,
2433
+ ...rowItem(next),
2404
2434
  taskId,
2405
2435
  outcome: OUTCOME.LAUNCH_FAILED,
2406
2436
  note: why,
@@ -2459,10 +2489,9 @@ async function main() {
2459
2489
  // ---- 6. RECORD ---------------------------------------------------------
2460
2490
  // From the run's own state file, not from the child's exit code and not from
2461
2491
  // its stdout - with `--bg` the stdout is a session id and nothing else.
2462
- const outcome = pub.outcome || outcomeFor(supervised, stateNow, prNow);
2492
+ const outcome = pub.outcome || outcomeFor(supervised, stateNow, prNow, next);
2463
2493
  record({
2464
- source: next.source,
2465
- id: next.id,
2494
+ ...rowItem(next),
2466
2495
  taskId,
2467
2496
  outcome,
2468
2497
  prUrl: prNow,