@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
@@ -10,6 +10,77 @@
10
10
  * @module pipeline/scripts/_cost
11
11
  */
12
12
 
13
+ import { readFileSync } from "node:fs";
14
+ import { basename, dirname, join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ const HERE = dirname(fileURLToPath(import.meta.url));
18
+
19
+ /**
20
+ * Read a JSON file beside this one, or null.
21
+ *
22
+ * Read rather than imported, deliberately. This module is the arithmetic and
23
+ * nothing else, and it is copied on its own into sandboxes and audited trees;
24
+ * an import of a sibling module turns every one of those into a
25
+ * module-not-found before the first line runs. A file that is not there leaves
26
+ * the answer to the caller instead.
27
+ */
28
+ const beside = (...p) => {
29
+ try {
30
+ return JSON.parse(readFileSync(join(HERE, ...p), "utf8"));
31
+ } catch {
32
+ return null;
33
+ }
34
+ };
35
+
36
+ /** The rate catalog. Empty when the table is not installed beside this file. */
37
+ const PRICES = beside("cost-table.json")?.prices ?? {};
38
+
39
+ /** The host registry, for the ceiling an unpriced phase is billed at. */
40
+ const HOSTS = beside("..", "schemas", "hosts.json");
41
+
42
+ /** Which host this copy sits in, read from its own path. Null in a checkout. */
43
+ function hostHere() {
44
+ const segment = basename(dirname(HERE));
45
+ const hosts = HOSTS?.hosts ?? {};
46
+ return Object.keys(hosts).find((id) => hosts[id]?.detect?.rootSegment === segment) ?? null;
47
+ }
48
+
49
+ /**
50
+ * The rung an unpriced phase is billed at: this host's most expensive one.
51
+ *
52
+ * Billing every host at the Anthropic top tier over-charged one host and
53
+ * under-charged another, and only the under-charge is dangerous - a ceiling
54
+ * that trips late has already spent the money.
55
+ *
56
+ * @type {string}
57
+ */
58
+ export const CONSERVATIVE_RUNG = conservativeRung();
59
+
60
+ /**
61
+ * This host's ceiling, unless that ceiling costs nothing.
62
+ *
63
+ * A host whose own models are free prices every unknown phase at zero, and a
64
+ * ceiling of zero bounds nothing: a tracker written by another host, or a phase
65
+ * that fell back to a paid rung, would be billed at nothing and no budget check
66
+ * would ever trip. In that one case the most expensive row in the table answers
67
+ * instead, which is the direction an estimate is allowed to be wrong in.
68
+ *
69
+ * @param {Record<string, object>} [prices]
70
+ * @param {string} [hostId]
71
+ * @returns {string}
72
+ */
73
+ export function conservativeRung(prices = PRICES, hostId = hostHere()) {
74
+ const dearest = Object.entries(prices ?? {}).sort(
75
+ (a, b) => (b[1].outPerMtok ?? 0) - (a[1].outPerMtok ?? 0),
76
+ )[0]?.[0];
77
+ const key = HOSTS?.hosts?.[hostId ?? HOSTS?.order?.[0]]?.pricing?.ceilingKey;
78
+ if (!key) return dearest ?? "fable";
79
+ const row = prices?.[key];
80
+ if (row && (row.inPerMtok > 0 || row.outPerMtok > 0)) return key;
81
+ return dearest ?? key;
82
+ }
83
+
13
84
  /**
14
85
  * USD cost for a token trio given a rate object.
15
86
  *
@@ -38,8 +109,9 @@ export function costUsd(rate, tokensIn = 0, tokensOut = 0, tokensCached = 0) {
38
109
  /**
39
110
  * USD for one run from the per-phase token counts its tracker-state.json
40
111
  * recorded (`phases` as a list or a map). A phase whose model the price table
41
- * does not name is priced at `fallbackRung`: an over-estimate stops a spend
42
- * ceiling early, an under-estimate stops it late. Null, never 0, when no phase
112
+ * does not name is priced at `fallbackRung`, which defaults to this host's own
113
+ * most expensive rung: an over-estimate stops a spend ceiling early, an
114
+ * under-estimate stops it late. Null, never 0, when no phase
43
115
  * recorded a token or there is no price table, so "cost nothing" and "cost is
44
116
  * not known" stay apart.
45
117
  *
@@ -48,7 +120,7 @@ export function costUsd(rate, tokensIn = 0, tokensOut = 0, tokensCached = 0) {
48
120
  * @param {string} [fallbackRung]
49
121
  * @returns {number|null}
50
122
  */
51
- export function trackerUsd(tracker, prices, fallbackRung = "fable") {
123
+ export function trackerUsd(tracker, prices, fallbackRung = CONSERVATIVE_RUNG) {
52
124
  if (!tracker || !prices) return null;
53
125
  let usd = 0;
54
126
  let tokens = 0;
@@ -84,7 +84,7 @@ import { ArgsError, parseArgs as parseArgv } from "../lib/args.mjs";
84
84
 
85
85
  exitOnHelp(import.meta.url);
86
86
 
87
- export const CONTRACT_VERSION = "1.4.0";
87
+ export const CONTRACT_VERSION = "1.5.0";
88
88
  export const RECENT_MS = 10 * 60_000;
89
89
 
90
90
  export const ROLES = JSON.parse(
@@ -875,6 +875,9 @@ const MAX_TASKS = 20;
875
875
  const TASK_STATES = new Set(["pending", "in_progress", "completed"]);
876
876
  const fraction = (v) =>
877
877
  typeof v === "number" && v >= 0 && v <= 1 ? Math.round(v * 100) / 100 : null;
878
+ // runs-index keeps `subs` as the count an older reader already decodes and the
879
+ // steps themselves as `subList`, so the list is read from there.
880
+ const subRows = (p) => (Array.isArray(p?.subList) ? p.subList : []);
878
881
  // The command a table runs, named the way a user types it.
879
882
  // The commands installed beside this script; a mode with no command of its
880
883
  // own (dev, short, dev-local) is a /multi-agent run.
@@ -1026,10 +1029,33 @@ function renderTable(team, clean, now) {
1026
1029
  name: phaseRow?.name || phaseName(runType, shownPhase),
1027
1030
  last: LAST_PHASE,
1028
1031
  },
1032
+ // The office shows what the terminal surfaces show, from the same record:
1033
+ // which model is spending, what the phase is doing right now, and how far
1034
+ // through its own steps it is. Without these the page can only name the
1035
+ // phase, which is the one thing a reader already knows.
1029
1036
  phaseHistory: phases.map((p) => ({
1030
1037
  id: Number.isFinite(Number(p.id)) ? Number(p.id) : null,
1031
1038
  name: clean(p.name, 60) ?? "",
1032
1039
  status: String(p.status ?? "pending"),
1040
+ model: clean(p.model, 40) ?? null,
1041
+ // Only a phase that is working, or stopped where it was working, has a
1042
+ // current action; on any other status it would describe a past moment.
1043
+ // Falling back to the step in progress keeps the card from going blank
1044
+ // on a phase that moved without writing a line.
1045
+ now:
1046
+ p.status === "in_progress" || p.status === "failed"
1047
+ ? (clean(p.now, 60) ??
1048
+ clean(subRows(p).find((x) => x?.status === "in_progress")?.name, 60) ??
1049
+ null)
1050
+ : null,
1051
+ tokens: Number(p.tokens?.in ?? 0) + Number(p.tokens?.out ?? 0) || null,
1052
+ subs: subRows(p)
1053
+ .slice(0, MAX_TASKS)
1054
+ .map((sb) => ({
1055
+ id: clean(String(sb?.id ?? ""), 12) ?? "",
1056
+ name: clean(sb?.name, 60) ?? "",
1057
+ status: TASK_STATES.has(sb?.status) ? sb.status : "pending",
1058
+ })),
1033
1059
  startedAt: p.startedAt ?? null,
1034
1060
  completedAt: p.completedAt ?? null,
1035
1061
  progress: fraction(p.progress),
@@ -36,7 +36,7 @@ import { readFileSync, writeFileSync } from "node:fs";
36
36
  import { spawnSync } from "node:child_process";
37
37
  import { join } from "node:path";
38
38
 
39
- import { resolveToken } from "../lib/credential-resolve.mjs";
39
+ import { resolveSecretAsync } from "../lib/service-account.mjs";
40
40
  import { runMain } from "../lib/fatal.mjs";
41
41
  import { exitOnHelp } from "../lib/cli-help.mjs";
42
42
 
@@ -140,13 +140,30 @@ async function swaggerPrint(s) {
140
140
  }
141
141
  }
142
142
 
143
+ /**
144
+ * A token for this base URL, or nothing.
145
+ *
146
+ * Fingerprinting is best effort: a source nobody can read is reported
147
+ * unchecked, which is also the right answer when the base URL points at a host
148
+ * no account covers. The refusal is not an error here, it is the absence of a
149
+ * token - and the request then goes out without one rather than with someone
150
+ * else's.
151
+ */
152
+ async function maybeSecret(service, base) {
153
+ if (!base) return null;
154
+ const answer = await resolveSecretAsync({ service, url: base });
155
+ return answer.ok ? answer.secret : null;
156
+ }
157
+
143
158
  async function fingerprints(spec) {
144
159
  const ev = spec.evidence || {};
160
+ const figmaBase = (process.env.FIGMA_API_BASE || "https://api.figma.com").replace(/\/+$/, "");
161
+ const confluenceBase = (process.env.CONFLUENCE_BASE_URL || "").replace(/\/+$/, "");
145
162
  const ctx = {
146
- figmaBase: (process.env.FIGMA_API_BASE || "https://api.figma.com").replace(/\/+$/, ""),
147
- figmaToken: resolveToken("figma", "FIGMA_TOKEN"),
148
- confluenceBase: (process.env.CONFLUENCE_BASE_URL || "").replace(/\/+$/, ""),
149
- confluenceToken: resolveToken("confluence", "CONFLUENCE_TOKEN"),
163
+ figmaBase,
164
+ figmaToken: await maybeSecret("figma", figmaBase),
165
+ confluenceBase,
166
+ confluenceToken: await maybeSecret("confluence", confluenceBase),
150
167
  };
151
168
  return Promise.all([
152
169
  ...(ev.figma || []).map((f) => figmaPrint(f, ctx)),
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * analysis-unattended.mjs - the intake answers an unattended analysis run
4
+ * takes, and the questions it refuses to answer for anyone.
5
+ *
6
+ * `/multi-agent:analysis <ref> autopilot` has nobody to ask, so every Phase 0
7
+ * question is either derived from evidence the run already holds or parked with
8
+ * the reason. The rules are here rather than in prose because "derived, not
9
+ * guessed" is only true if the derivation is the same every time, and because a
10
+ * run that would have to guess has to stop in a way a test can exercise.
11
+ *
12
+ * The caller collects the evidence - the queued item, the repo it came from,
13
+ * the preferences - and hands it in as one document:
14
+ *
15
+ * { "ref": "PROJ-123", "source": "jira" | "github",
16
+ * "title": "the item's own summary",
17
+ * "profiles": ["global"], // prefs.global.analysisProfiles
18
+ * "outline": "/path/outline.md", // only when the profile is custom
19
+ * "repos": [{ "name": "acme/app", "path": "/p", "platform": "ios" }],
20
+ * "links": [{ "type": "figma", "url": "..." }],
21
+ * "outputDir": "/abs/dir the run may write" }
22
+ *
23
+ * `derive` answers with the resolved intake (`state.analysisSpec.*` shape), one
24
+ * decision per answer for `decisions[]`, or a park verdict naming the question
25
+ * and what would settle it.
26
+ *
27
+ * Nothing here fetches, writes a document or publishes: the destination it
28
+ * resolves is the run's own directory, because an unattended run posts nothing
29
+ * outside the machine (`features/unattended-security.md`, Phase 5 and channels).
30
+ *
31
+ * Usage:
32
+ * analysis-unattended.mjs derive --evidence <file.json> [--state <agent-state.json>] [--json]
33
+ *
34
+ * Exit: 0 every question answered · 2 the evidence document is unusable ·
35
+ * 3 usage · 4 park, the verdict names the question and the reason.
36
+ *
37
+ * @module pipeline/scripts/analysis-unattended
38
+ */
39
+
40
+ import { existsSync, readFileSync } from "node:fs";
41
+
42
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
43
+ import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
44
+ import { exitOnHelp } from "../lib/cli-help.mjs";
45
+ import { decisionEntry, withDecision } from "../lib/decisions.mjs";
46
+ import { updateState } from "./gate-ledger.mjs";
47
+
48
+ exitOnHelp(import.meta.url);
49
+
50
+ /** The profiles Phase 0 Step 1b can resolve to. */
51
+ export const PROFILES = Object.freeze(["global", "corporate", "custom"]);
52
+
53
+ /**
54
+ * The coverage opt-ins of Phase 0 Step 5a. Each one widens the document, and an
55
+ * unattended run takes the lighter side of every one of them: a section nobody
56
+ * asked for is added by re-running analysis, and a section nobody asked for
57
+ * costs the reader attention the evidence did not earn.
58
+ */
59
+ export const COVERAGE_DEFAULTS = Object.freeze({
60
+ uiTests: false,
61
+ a11yDepth: "basic",
62
+ redesign: false,
63
+ });
64
+
65
+ class UsageError extends Error {}
66
+ class EvidenceError extends Error {}
67
+
68
+ const text = (v) => (typeof v === "string" ? v.trim() : "");
69
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
70
+
71
+ /** The evidence document's own shape, as a list of problems. Empty passes. */
72
+ export function evidenceProblems(doc) {
73
+ if (!isObject(doc)) return ["not a JSON object"];
74
+ const problems = [];
75
+ if (!text(doc.ref)) problems.push("ref is empty");
76
+ if (!["jira", "github"].includes(text(doc.source))) {
77
+ problems.push('source must be "jira" or "github"');
78
+ }
79
+ if (!text(doc.outputDir)) problems.push("outputDir is empty");
80
+ if (doc.profiles !== undefined && !Array.isArray(doc.profiles)) {
81
+ problems.push("profiles must be an array");
82
+ }
83
+ if (doc.repos !== undefined && !Array.isArray(doc.repos)) {
84
+ problems.push("repos must be an array");
85
+ }
86
+ if (doc.links !== undefined && !Array.isArray(doc.links)) {
87
+ problems.push("links must be an array");
88
+ }
89
+ return problems;
90
+ }
91
+
92
+ /** A park verdict: the question, why evidence could not settle it, and the fix. */
93
+ const park = (question, reason, fix) => ({ question, reason, fix });
94
+
95
+ /**
96
+ * The analysis name, from the item's own summary. A tracker item without a
97
+ * summary is the one shape where nothing in the run can name the document, so
98
+ * it parks instead of inventing a title the reader would have to correct.
99
+ */
100
+ export function deriveName(doc) {
101
+ const title = text(doc.title);
102
+ if (!title) {
103
+ return {
104
+ park: park(
105
+ "analysis-name",
106
+ `${text(doc.ref)} carries no summary, and the analysis name is what the document and every file it writes are named after`,
107
+ "give the item a summary, or run the analysis by hand with a name",
108
+ ),
109
+ };
110
+ }
111
+ return {
112
+ value: title,
113
+ decision: {
114
+ what: `Named the analysis "${title}"`,
115
+ why: `the summary of ${text(doc.ref)}`,
116
+ costIfWrong:
117
+ "the document and its file names carry the ticket's wording and are renamed by hand",
118
+ },
119
+ };
120
+ }
121
+
122
+ /**
123
+ * The profile, from `prefs.global.analysisProfiles`. One available profile is
124
+ * an answer; more than one is a question, and it is the question an unattended
125
+ * run must never answer for anyone - the profile selects the template, so the
126
+ * whole document is written against it (Locked 31). A guess here produces a
127
+ * document in the wrong standard, which is not a section to add later.
128
+ */
129
+ export function deriveProfile(doc) {
130
+ const offered = Array.isArray(doc.profiles)
131
+ ? doc.profiles.map(text).filter((p) => PROFILES.includes(p))
132
+ : [...PROFILES];
133
+ const unique = [...new Set(offered)];
134
+ if (unique.length !== 1) {
135
+ return {
136
+ park: park(
137
+ "analysis-profile",
138
+ unique.length
139
+ ? `${unique.length} analysis profiles are available (${unique.join(", ")}), and the profile decides which template the whole document is written against`
140
+ : "no analysis profile is available",
141
+ "list exactly one profile in prefs.global.analysisProfiles, or run the analysis by hand and pick one",
142
+ ),
143
+ };
144
+ }
145
+ const [profile] = unique;
146
+ if (profile === "custom" && !text(doc.outline)) {
147
+ return {
148
+ park: park(
149
+ "analysis-outline",
150
+ "the custom profile renders against an outline file and none is configured",
151
+ "set the outline path in the evidence, or list a profile that ships its own template",
152
+ ),
153
+ };
154
+ }
155
+ return {
156
+ value: profile,
157
+ decision: {
158
+ what: `Rendered against the ${profile} profile`,
159
+ why: "the only profile prefs.global.analysisProfiles offers",
160
+ costIfWrong:
161
+ "the document follows the wrong standard and is re-rendered against the other one",
162
+ },
163
+ };
164
+ }
165
+
166
+ /**
167
+ * The repos and the platforms, from the item's own checkout. An item is queued
168
+ * for the repo whose label it carries, so the repo set is not a question. The
169
+ * platforms are the distinct stack tags of those repos, which is what the
170
+ * attended step derives before it offers to ask.
171
+ *
172
+ * No repo and no tag is a real answer, not a gap: Locked 34 keeps the run going
173
+ * without a target repository and records in Section 20 that the development
174
+ * layer awaits one.
175
+ */
176
+ export function deriveRepos(doc) {
177
+ const repos = (Array.isArray(doc.repos) ? doc.repos : [])
178
+ .filter(isObject)
179
+ .map((r) => ({
180
+ name: text(r.name),
181
+ path: text(r.path),
182
+ platform: text(r.platform).toLowerCase(),
183
+ canPush: r.canPush === true,
184
+ }))
185
+ .filter((r) => r.name && r.path);
186
+ const platforms = [...new Set(repos.map((r) => r.platform).filter(Boolean))];
187
+ return {
188
+ repos,
189
+ platforms,
190
+ decision: {
191
+ what: platforms.length
192
+ ? `Analysed ${platforms.join(", ")} from ${repos.map((r) => r.name).join(", ")}`
193
+ : "Analysed with no platform layer",
194
+ why: platforms.length
195
+ ? "the stack tags of the repo the item was queued for"
196
+ : "the item's repo carries no stack tag, so Locked 34 defers the development layer",
197
+ costIfWrong: platforms.length
198
+ ? "a platform the item also touches has no document and is added by re-running analysis"
199
+ : "the development layer is missing and is added once a repo is selected",
200
+ },
201
+ };
202
+ }
203
+
204
+ /**
205
+ * The seven source questions, from the links the item's own text carries. An
206
+ * empty set is an answer and not a gap: a ticket that names no design and no
207
+ * contract is a ticket whose analysis has none, and Phase 3.3 still searches
208
+ * the repo before anything is recorded as open.
209
+ *
210
+ * Standards and Firebase resolve to their own auto-detect option when a repo is
211
+ * present, which is the attended picker's second option rather than a default
212
+ * invented here.
213
+ */
214
+ export function deriveSources(doc, repos) {
215
+ const links = (Array.isArray(doc.links) ? doc.links : []).filter(isObject);
216
+ const probe = repos.length ? "auto" : "none";
217
+ return {
218
+ contextLinks: links,
219
+ standards: probe,
220
+ firebase: probe,
221
+ decision: {
222
+ what: links.length
223
+ ? `Took ${links.length} source link(s) from the item itself`
224
+ : "Took no source links: the item names none",
225
+ why: "the only sources an unattended run has are the ones the item carries",
226
+ costIfWrong: "a source nobody linked on the item is missing and the document records the gap",
227
+ },
228
+ };
229
+ }
230
+
231
+ /**
232
+ * The destination. Local only, and local means the run's own directory: an
233
+ * unattended run publishes nothing outside the machine, and the repo working
234
+ * tree is not its to write into.
235
+ */
236
+ export function deriveOutput(doc) {
237
+ return {
238
+ requested: ["local"],
239
+ dir: text(doc.outputDir),
240
+ decision: {
241
+ what: `Wrote the document to ${text(doc.outputDir)} and published nowhere else`,
242
+ why: "an unattended run posts nothing outside the machine",
243
+ costIfWrong: "the document has to be published by hand from the run directory",
244
+ },
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Every intake answer, or the first question evidence cannot settle. The order
250
+ * is the attended chain's own, so the question a park names is the question the
251
+ * person would have been asked first.
252
+ *
253
+ * @param {object} doc the evidence document
254
+ * @returns {{resolved: object|null, decisions: object[], park: object|null}}
255
+ */
256
+ export function derive(doc) {
257
+ const problems = evidenceProblems(doc);
258
+ if (problems.length) throw new EvidenceError(problems.join("; "));
259
+
260
+ const decisions = [];
261
+ const name = deriveName(doc);
262
+ if (name.park) return { resolved: null, decisions, park: name.park };
263
+ decisions.push(name.decision);
264
+
265
+ const profile = deriveProfile(doc);
266
+ if (profile.park) return { resolved: null, decisions, park: profile.park };
267
+ decisions.push(profile.decision);
268
+
269
+ const { repos, platforms, decision: reposDecision } = deriveRepos(doc);
270
+ decisions.push(reposDecision);
271
+
272
+ const sources = deriveSources(doc, repos);
273
+ decisions.push(sources.decision);
274
+
275
+ const output = deriveOutput(doc);
276
+ decisions.push(output.decision);
277
+
278
+ return {
279
+ resolved: {
280
+ featureName: name.value,
281
+ profile: profile.value,
282
+ ...(profile.value === "custom" ? { outline: text(doc.outline) } : {}),
283
+ platforms,
284
+ repos,
285
+ contextLinks: sources.contextLinks,
286
+ autoDetect: { standards: sources.standards, firebase: sources.firebase },
287
+ options: { ...COVERAGE_DEFAULTS },
288
+ outputs: { requested: output.requested, dir: output.dir },
289
+ },
290
+ decisions,
291
+ park: null,
292
+ };
293
+ }
294
+
295
+ function readEvidence(path) {
296
+ if (!path) throw new UsageError("--evidence is required");
297
+ if (!existsSync(path)) throw new UsageError(`no file at ${path}`);
298
+ try {
299
+ return JSON.parse(readFileSync(path, "utf8"));
300
+ } catch (err) {
301
+ throw new UsageError(`unreadable: ${err.message}`);
302
+ }
303
+ }
304
+
305
+ async function run(sub, flags, emit) {
306
+ if (sub !== "derive") throw unknownSubcommand(sub, ["derive"]);
307
+ const doc = readEvidence(flags.evidence);
308
+ let out;
309
+ try {
310
+ out = derive(doc);
311
+ } catch (err) {
312
+ if (!(err instanceof EvidenceError)) throw err;
313
+ process.stderr.write(`analysis-unattended: evidence is unusable: ${err.message}\n`);
314
+ return 2;
315
+ }
316
+ if (out.park) {
317
+ emit(
318
+ { ok: false, park: out.park },
319
+ `park ${out.park.question}: ${out.park.reason}\n ${out.park.fix}`,
320
+ );
321
+ return 4;
322
+ }
323
+ if (flags.state) {
324
+ await updateState(flags.state, (s) =>
325
+ out.decisions.reduce((acc, d) => withDecision(acc, decisionEntry({ ...d, phase: 0 })), s),
326
+ );
327
+ }
328
+ emit(
329
+ { ok: true, resolved: out.resolved, decisions: out.decisions },
330
+ out.decisions.map((d) => ` - ${d.what} (${d.why})`).join("\n"),
331
+ );
332
+ return 0;
333
+ }
334
+
335
+ export async function main(argv = process.argv.slice(2)) {
336
+ const [sub, ...rest] = argv;
337
+ let flags;
338
+ try {
339
+ ({ flags } = parseArgs(rest, {
340
+ booleans: ["json"],
341
+ strings: ["evidence", "state"],
342
+ unknown: "error",
343
+ positionals: false,
344
+ }));
345
+ } catch (e) {
346
+ if (!(e instanceof ArgsError)) throw e;
347
+ process.stderr.write(`analysis-unattended: ${e.message}\n`);
348
+ return 3;
349
+ }
350
+ const emit = (obj, line) =>
351
+ process.stdout.write(`${flags.json ? JSON.stringify(obj, null, 2) : line}\n`);
352
+ try {
353
+ return await run(sub, flags, emit);
354
+ } catch (e) {
355
+ process.stderr.write(`analysis-unattended: ${e.message}\n`);
356
+ return 3;
357
+ }
358
+ }
359
+
360
+ if (invokedDirectly(import.meta.url)) main().then((code) => process.exit(code));
@@ -43,6 +43,7 @@
43
43
 
44
44
  import { readFileSync, writeFileSync } from "node:fs";
45
45
  import { pathToFileURL } from "node:url";
46
+ import { FAMILIES, familyOf } from "../lib/reviewer-families.mjs";
46
47
 
47
48
  const IDENTITY_KEYS = [
48
49
  "reviewer",
@@ -167,13 +168,8 @@ export function anonymize(input, { seed } = {}) {
167
168
  return { findings: tagged, map: { seed: seedText, labelToModel, malformed } };
168
169
  }
169
170
 
170
- const FAMILIES = ["fable", "opus", "sonnet", "gpt"];
171
-
172
- /** The reviewer family a map entry names, or null for a model outside the four. */
173
- export function familyOf(model) {
174
- const m = String(model ?? "").toLowerCase();
175
- return FAMILIES.find((f) => m.includes(f)) ?? null;
176
- }
171
+ // Derived from the host registry so a rung added there needs no second edit.
172
+ export { FAMILIES, familyOf };
177
173
 
178
174
  /**
179
175
  * The triage document with `reviewer` set on every finding whose `foundBy`
@@ -26,8 +26,8 @@
26
26
  *
27
27
  * Readable, not only recorded. `probe` asks every credential the configured
28
28
  * repos need whether it can be read right now without a prompt: `gh auth
29
- * status` for GitHub, and `credential-store.sh probe` for the logical keys a
30
- * source reads from `prefs.global.keychainMapping` (Jira today). The value is
29
+ * status` for GitHub, and `credential-store.sh probe` for the item the account
30
+ * resolver names for a source (Jira today). The value is
31
31
  * never read into this process - the store answers one word. autopilot-on runs
32
32
  * it before the schedule is offered, and every tick runs the item's own half
33
33
  * through `check --probe`, because a tick runs in the background session, where
@@ -60,6 +60,7 @@ import { configRefusal } from "./_autopilot-config.mjs";
60
60
  import { hostCommand, messages as languageHalf } from "../lib/user-facing.mjs";
61
61
  import { PREFS_ENV, prefsPath } from "../lib/prefs-value.mjs";
62
62
  import { exitOnHelp } from "../lib/cli-help.mjs";
63
+ import { selectAccount } from "../lib/service-account.mjs";
63
64
 
64
65
  exitOnHelp(import.meta.url);
65
66
 
@@ -100,9 +101,9 @@ const MESSAGES = {
100
101
  ghUnauth: () =>
101
102
  "GitHub: gh is not authenticated for a non-interactive session - run gh auth login",
102
103
  unmapped: (key, cmd) =>
103
- `credential "${key}": prefs.global.keychainMapping.${key} is not set - save the token with ${cmd}`,
104
+ `credential "${key}": no ${key} account is configured - save the token with ${cmd}`,
104
105
  noHost: (key, cmd) =>
105
- `credential "${key}": prefs.global.hosts.${key} is not set - record the host with ${cmd}`,
106
+ `credential "${key}": the ${key} account does not say which host it is for - record it with ${cmd}`,
106
107
  missing: (key, item, cmd) =>
107
108
  `credential "${key}" (stored as "${item}") is not in the credential store - save it with ${cmd}`,
108
109
  locked: (key) =>
@@ -129,9 +130,9 @@ const MESSAGES = {
129
130
  ghMissing: () => "GitHub: gh kurulu değil - kur, sonra gh auth login çalıştır",
130
131
  ghUnauth: () => "GitHub: gh etkileşimsiz oturum için giriş yapmamış - gh auth login çalıştır",
131
132
  unmapped: (key, cmd) =>
132
- `"${key}" kimlik bilgisi: prefs.global.keychainMapping.${key} tanımlı değil - token'ı ${cmd} ile kaydet`,
133
+ `"${key}" kimlik bilgisi: ${key} hesabı tanımlı değil - token'ı ${cmd} ile kaydet`,
133
134
  noHost: (key, cmd) =>
134
- `"${key}" kimlik bilgisi: prefs.global.hosts.${key} tanımlı değil - host'u ${cmd} ile kaydet`,
135
+ `"${key}" kimlik bilgisi: ${key} hesabı hangi host için olduğunu söylemiyor - ${cmd} ile kaydet`,
135
136
  missing: (key, item, cmd) =>
136
137
  `"${key}" kimlik bilgisi ("${item}" adıyla) kimlik deposunda yok - ${cmd} ile kaydet`,
137
138
  locked: (key) =>
@@ -272,12 +273,20 @@ export function probeService(service, { prefs, env = process.env, language = "en
272
273
  }
273
274
  const key = service;
274
275
  const setup = hostCommand("setup");
275
- const item = prefs?.global?.keychainMapping?.[key];
276
- if (typeof item !== "string" || !item.trim()) {
276
+ // Which account answers, and which store item it names, is the resolver's
277
+ // question. Asking it here also answers the host one: an account that cannot
278
+ // say where it may be sent is not an account this check will pass.
279
+ const chosen = selectAccount({ service }, { prefs });
280
+ if (!chosen.ok) {
281
+ const status = chosen.reason === "not-configured" ? "unmapped" : "no-host";
282
+ const message = status === "unmapped" ? m.unmapped(key, setup) : m.noHost(key, setup);
283
+ return { service, key, status, message };
284
+ }
285
+ const item = chosen.account.secrets?.[chosen.account.slots?.[0] ?? "token"] ?? "";
286
+ if (!String(item).trim()) {
277
287
  return { service, key, status: "unmapped", message: m.unmapped(key, setup) };
278
288
  }
279
- const host = prefs?.global?.hosts?.[key];
280
- if (typeof host !== "string" || !host.trim()) {
289
+ if (!chosen.account.hosts?.length) {
281
290
  return { service, key, status: "no-host", message: m.noHost(key, setup) };
282
291
  }
283
292
  const r = spawnSync("bash", [STORE, "probe", key], {