@mmerterden/multi-agent-pipeline 23.6.0 → 24.0.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 (167) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/README.md +61 -27
  3. package/README.tr.md +46 -12
  4. package/SECURITY.md +3 -3
  5. package/docs/architecture.md +47 -8
  6. package/docs/ecosystem.md +20 -18
  7. package/docs/engineering.md +1 -1
  8. package/docs/facts.json +8 -6
  9. package/docs/features.md +59 -15
  10. package/install/_codex-agents.mjs +13 -8
  11. package/install/_common.mjs +24 -0
  12. package/install/_dev-only-files.mjs +4 -0
  13. package/install/_mcp-register.mjs +6 -2
  14. package/install/_rewrite-tree.mjs +197 -0
  15. package/install/codex.mjs +96 -180
  16. package/install/copilot.mjs +24 -54
  17. package/install/index.mjs +29 -11
  18. package/install/templates/codex-instructions.md +21 -5
  19. package/install/templates/copilot-instructions.md +21 -14
  20. package/manifest.json +2082 -0
  21. package/package.json +6 -2
  22. package/pipeline/commands/multi-agent/SKILL.md +7 -5
  23. package/pipeline/commands/multi-agent/analysis/SKILL.md +4 -0
  24. package/pipeline/commands/multi-agent/autopilot-on/SKILL.md +31 -3
  25. package/pipeline/commands/multi-agent/autopilot-status/SKILL.md +5 -1
  26. package/pipeline/commands/multi-agent/channels/SKILL.md +16 -8
  27. package/pipeline/commands/multi-agent/log/SKILL.md +2 -0
  28. package/pipeline/commands/multi-agent/resume/SKILL.md +2 -0
  29. package/pipeline/commands/multi-agent/review-rounds/SKILL.md +94 -0
  30. package/pipeline/commands/multi-agent/stack/SKILL.md +1 -1
  31. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  32. package/pipeline/contract/manifest.json +1 -1
  33. package/pipeline/contract/types/index.d.ts +1 -0
  34. package/pipeline/lib/_jira-auth.sh +50 -78
  35. package/pipeline/lib/_service-account.sh +191 -0
  36. package/pipeline/lib/credential-inventory.sh +49 -37
  37. package/pipeline/lib/credential-store.sh +48 -3
  38. package/pipeline/lib/fetch-confluence.sh +76 -92
  39. package/pipeline/lib/fetch-crashlytics.sh +30 -59
  40. package/pipeline/lib/fetch-figma-annotations.sh +9 -9
  41. package/pipeline/lib/fetch-fortify.sh +77 -81
  42. package/pipeline/lib/fetch-graylog.sh +38 -77
  43. package/pipeline/lib/figma-mcp-refresh.sh +23 -4
  44. package/pipeline/lib/figma-screenshot.sh +7 -8
  45. package/pipeline/lib/figma-token.sh +39 -46
  46. package/pipeline/lib/host.mjs +138 -0
  47. package/pipeline/lib/host.sh +48 -0
  48. package/pipeline/lib/issue-fetcher.sh +25 -41
  49. package/pipeline/lib/jira-publish.sh +23 -21
  50. package/pipeline/lib/local-model.mjs +93 -0
  51. package/pipeline/lib/md2confluence-v3.py +37 -30
  52. package/pipeline/lib/model-dispatch.sh +41 -4
  53. package/pipeline/lib/model-resolve.mjs +58 -0
  54. package/pipeline/lib/post-pr-review.sh +38 -53
  55. package/pipeline/lib/reviewer-families.mjs +70 -0
  56. package/pipeline/lib/service-account.mjs +2131 -0
  57. package/pipeline/lib/service-account.sh +35 -0
  58. package/pipeline/lib/usage-names.generated.mjs +3 -0
  59. package/pipeline/lib/usage-token.mjs +64 -24
  60. package/pipeline/lib/usage-vocab.mjs +1 -1
  61. package/pipeline/lib/user-facing.mjs +11 -3
  62. package/pipeline/lib/vercel-deploy.sh +17 -26
  63. package/pipeline/multi-agent-refs/_entry-picker.md +62 -0
  64. package/pipeline/multi-agent-refs/_input-parser.md +1 -1
  65. package/pipeline/multi-agent-refs/analysis/intake.md +2 -0
  66. package/pipeline/multi-agent-refs/analysis/reusable-refs.md +1 -0
  67. package/pipeline/multi-agent-refs/analysis/unattended.md +135 -0
  68. package/pipeline/multi-agent-refs/autopilot-on/details.md +16 -0
  69. package/pipeline/multi-agent-refs/channels/generator.md +10 -2
  70. package/pipeline/multi-agent-refs/channels/menu.md +3 -1
  71. package/pipeline/multi-agent-refs/channels/preview.md +3 -1
  72. package/pipeline/multi-agent-refs/channels/reference.md +16 -2
  73. package/pipeline/multi-agent-refs/channels/report-file.md +188 -0
  74. package/pipeline/multi-agent-refs/component-dispatch.md +2 -2
  75. package/pipeline/multi-agent-refs/cross-cli-contract.md +38 -30
  76. package/pipeline/multi-agent-refs/features/autopilot-circuit-breaker.md +4 -4
  77. package/pipeline/multi-agent-refs/features/doctor.md +37 -11
  78. package/pipeline/multi-agent-refs/features/free-models.md +3 -3
  79. package/pipeline/multi-agent-refs/features/local-model.md +87 -0
  80. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -10
  81. package/pipeline/multi-agent-refs/features/product-context.md +6 -5
  82. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  83. package/pipeline/multi-agent-refs/features/review-rounds.md +40 -0
  84. package/pipeline/multi-agent-refs/features/rework-escalation.md +5 -4
  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 +31 -2
  88. package/pipeline/multi-agent-refs/help/tr.md +31 -2
  89. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +3 -2
  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/operations.md +1 -1
  93. package/pipeline/multi-agent-refs/phases/phase-0-init.md +1 -1
  94. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  95. package/pipeline/multi-agent-refs/phases/phase-3-review.md +7 -3
  96. package/pipeline/multi-agent-refs/phases/phase-5-report.md +12 -10
  97. package/pipeline/multi-agent-refs/phases.md +4 -3
  98. package/pipeline/multi-agent-refs/resume/details.md +2 -0
  99. package/pipeline/multi-agent-refs/review/panel.md +30 -18
  100. package/pipeline/multi-agent-refs/setup/discovery.md +17 -5
  101. package/pipeline/multi-agent-refs/setup/token-save-flow.md +21 -2
  102. package/pipeline/multi-agent-refs/sync/overview.md +11 -5
  103. package/pipeline/multi-agent-refs/tracker-contract.md +28 -10
  104. package/pipeline/office/index.html +4 -4
  105. package/pipeline/schemas/agent-state.schema.json +19 -1
  106. package/pipeline/schemas/autopilot-config.schema.json +29 -4
  107. package/pipeline/schemas/hosts.json +512 -0
  108. package/pipeline/schemas/hosts.schema.json +310 -0
  109. package/pipeline/schemas/launch.json +22 -2
  110. package/pipeline/schemas/launch.schema.json +2 -1
  111. package/pipeline/schemas/phases.json +21 -3
  112. package/pipeline/schemas/phases.schema.json +8 -0
  113. package/pipeline/schemas/prefs.schema.json +346 -7
  114. package/pipeline/schemas/token-budget.json +2 -2
  115. package/pipeline/scripts/.doctor-mut.47076.mjs +2253 -0
  116. package/pipeline/scripts/_autopilot-config.mjs +67 -4
  117. package/pipeline/scripts/_autopilot-item.mjs +67 -0
  118. package/pipeline/scripts/_autopilot-outcomes.mjs +6 -0
  119. package/pipeline/scripts/_cost.mjs +75 -3
  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 +16 -13
  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 +146 -38
  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/report-file.mjs +285 -0
  145. package/pipeline/scripts/review-rounds.mjs +592 -0
  146. package/pipeline/scripts/rework-escalation.mjs +26 -7
  147. package/pipeline/scripts/service-read.mjs +19 -17
  148. package/pipeline/scripts/skill-siblings.mjs +17 -1
  149. package/pipeline/scripts/status-overview.mjs +20 -10
  150. package/pipeline/scripts/uninstall.mjs +145 -57
  151. package/pipeline/scripts/usage-register.mjs +34 -11
  152. package/pipeline/scripts/usage-report.mjs +31 -26
  153. package/pipeline/scripts/validate-state.mjs +19 -11
  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 +11 -7
  158. package/pipeline/skills/.skills-index.json +13 -2
  159. package/pipeline/skills/shared/README.md +4 -3
  160. package/pipeline/skills/shared/core/multi-agent/SKILL.md +14 -6
  161. package/pipeline/skills/shared/core/multi-agent-analysis/SKILL.md +2 -0
  162. package/pipeline/skills/shared/core/multi-agent-channels/SKILL.md +11 -8
  163. package/pipeline/skills/shared/core/multi-agent-resume/SKILL.md +1 -1
  164. package/pipeline/skills/shared/core/multi-agent-review-rounds/SKILL.md +92 -0
  165. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  166. package/pipeline/skills/skills-index.md +2 -1
  167. package/pipeline/lib/credential-resolve.mjs +0 -75
@@ -10,14 +10,17 @@
10
10
  *
11
11
  * The package ships without dependencies, so this is a small validator for the
12
12
  * keywords the schema uses: type, const, enum, minimum, maximum, pattern,
13
- * required, properties, additionalProperties, items and uniqueItems. `format`,
14
- * `default` and the annotations are not assertions and are not checked.
13
+ * required, properties, additionalProperties, items and uniqueItems. `format`
14
+ * and the annotations are not assertions and are not checked; `default` is
15
+ * read only to resolve what an unset field means for the cross-field rules
16
+ * below, which the schema cannot express.
15
17
  *
16
18
  * @module pipeline/scripts/_autopilot-config
17
19
  */
18
20
 
19
21
  import { readFileSync } from "node:fs";
20
22
  import { join } from "node:path";
23
+ import { KIND, queuedKinds } from "./_autopilot-item.mjs";
21
24
 
22
25
  const SCHEMA_PATH = join(import.meta.dirname, "..", "schemas", "autopilot-config.schema.json");
23
26
 
@@ -97,8 +100,65 @@ function check(node, v, path, out) {
97
100
  }
98
101
 
99
102
  /**
100
- * Every way `config` breaks the schema, as one readable line each. Empty means
101
- * valid.
103
+ * The label pairs that have to stay apart: one tracker's development queue and
104
+ * its analysis queue. The two kinds run different commands and are recorded
105
+ * under different keys, so a label that means both would make the kind of a
106
+ * picked item depend on which query returned it first.
107
+ */
108
+ const LABEL_PAIRS = [
109
+ ["githubLabel", "analysisGithubLabel"],
110
+ ["jiraLabel", "analysisJiraLabel"],
111
+ ];
112
+
113
+ /** The repo property definitions, which carry the defaults a repo leaves unset. */
114
+ function repoProperties(doc) {
115
+ return doc?.properties?.repos?.items?.properties || {};
116
+ }
117
+
118
+ /**
119
+ * The value a repo actually queues by, default included. The schema's own
120
+ * `default` is read rather than repeated here, so the two cannot drift.
121
+ */
122
+ function effectiveLabel(repo, field, props) {
123
+ const set = repo[field];
124
+ return typeof set === "string" && set.trim() ? set.trim() : props[field]?.default;
125
+ }
126
+
127
+ /**
128
+ * Repos whose analysis label is their development label. Refused rather than
129
+ * resolved: picking one of the two kinds for the operator would run work they
130
+ * did not ask for, in a repo they can write to.
131
+ *
132
+ * Only a repo that is actually in both queues can collide. A repo that never
133
+ * said yes to analysis work has no analysis label in play, so its development
134
+ * label may be named whatever the operator likes - refusing it there would
135
+ * block the whole queue over a second queue the repo is not in.
136
+ *
137
+ * @returns {string[]}
138
+ */
139
+ function labelCollisions(doc, config) {
140
+ const props = repoProperties(doc);
141
+ const out = [];
142
+ for (const repo of config?.repos || []) {
143
+ if (!repo || typeof repo !== "object" || Array.isArray(repo)) continue;
144
+ if (!queuedKinds(repo).includes(KIND.ANALYSIS)) continue;
145
+ const name = repo.nameWithOwner || "a repo with no nameWithOwner";
146
+ for (const [development, analysis] of LABEL_PAIRS) {
147
+ const dev = effectiveLabel(repo, development, props);
148
+ const ana = effectiveLabel(repo, analysis, props);
149
+ if (dev === undefined || dev !== ana) continue;
150
+ out.push(
151
+ `${name}: ${development} and ${analysis} are both ${JSON.stringify(dev)}, ` +
152
+ `and one label cannot queue both kinds of work - give ${analysis} a name of its own`,
153
+ );
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /**
160
+ * Every way `config` breaks the schema, plus the cross-field rules the schema
161
+ * cannot express, as one readable line each. Empty means valid.
102
162
  *
103
163
  * @param {unknown} config
104
164
  * @returns {string[]}
@@ -112,6 +172,9 @@ export function configProblems(config) {
112
172
  }
113
173
  const out = [];
114
174
  check(doc, config, "", out);
175
+ // Only when the shape itself held: a collision line about a field the schema
176
+ // already refused would name a value that is not a label in the first place.
177
+ if (!out.length) out.push(...labelCollisions(doc, config));
115
178
  return out;
116
179
  }
117
180
 
@@ -0,0 +1,67 @@
1
+ /**
2
+ * _autopilot-item.mjs - what a queued item is, for every reader of the queue.
3
+ *
4
+ * An item is a tracker reference plus the kind of work the label it carries
5
+ * asked for: `development`, which runs the pipeline and stops at a pull
6
+ * request, or `analysis`, which runs the analysis command and stops at a
7
+ * document. Intake builds items, the runner launches and records them, and
8
+ * both fold attempted.jsonl under the key defined here - so one ticket can be
9
+ * analysed once and developed once without either run reading the other's row
10
+ * as its own.
11
+ *
12
+ * Zero runtime dependencies (ADR-0004).
13
+ *
14
+ * @module pipeline/scripts/_autopilot-item
15
+ */
16
+
17
+ /** The kinds of work a label queues. */
18
+ export const KIND = Object.freeze({
19
+ DEVELOPMENT: "development",
20
+ ANALYSIS: "analysis",
21
+ });
22
+
23
+ /**
24
+ * The kinds of work one repo is queued for.
25
+ *
26
+ * Development is what selecting a repo has always meant, so every configured
27
+ * repo carries it. Analysis is said separately, because the two deliver
28
+ * different things for the same run: `analysisQueue: true` from the arming
29
+ * picker, or an analysis label the operator wrote themselves, which is the same
30
+ * yes said another way. A repo that said neither is never queried for analysis
31
+ * work and never has its analysis labels read.
32
+ *
33
+ * @param {{analysisQueue?: boolean, analysisGithubLabel?: string, analysisJiraLabel?: string}} repo
34
+ * @returns {string[]}
35
+ */
36
+ export function queuedKinds(repo) {
37
+ const named = (v) => typeof v === "string" && v.trim() !== "";
38
+ const analysis =
39
+ repo?.analysisQueue === true ||
40
+ named(repo?.analysisGithubLabel) ||
41
+ named(repo?.analysisJiraLabel);
42
+ return analysis ? [KIND.DEVELOPMENT, KIND.ANALYSIS] : [KIND.DEVELOPMENT];
43
+ }
44
+
45
+ /**
46
+ * Is this item - or this ledger row - analysis work? A row written before the
47
+ * analysis kind existed carries no `kind` and is development, which is what
48
+ * keeps every existing attempted.jsonl row meaning what it meant.
49
+ *
50
+ * @param {{kind?: string}|null|undefined} item
51
+ * @returns {boolean}
52
+ */
53
+ export function isAnalysis(item) {
54
+ return item?.kind === KIND.ANALYSIS;
55
+ }
56
+
57
+ /**
58
+ * The key an item's attempts are recorded and read under. Development keeps
59
+ * the bare `source:id` every existing row carries; analysis carries the
60
+ * `#analysis` suffix, which is the whole of what holds the two apart.
61
+ *
62
+ * @param {{source?: string, id?: string, kind?: string}} item
63
+ * @returns {string}
64
+ */
65
+ export function historyKey(item) {
66
+ return `${item?.source}:${item?.id}${isAnalysis(item) ? "#analysis" : ""}`;
67
+ }
@@ -25,6 +25,7 @@ export const OUTCOME = Object.freeze({
25
25
  PR_OPENED: "pr-opened",
26
26
  PUSHED_AWAITING_PR: "pushed-awaiting-pr",
27
27
  MERGED: "merged",
28
+ DOC_DELIVERED: "doc-delivered",
28
29
  SKIPPED: "skipped",
29
30
  COMPLETED_NO_PR: "completed-no-pr",
30
31
  STOPPED_INCOMPLETE: "stopped-incomplete",
@@ -55,11 +56,16 @@ export const OUTCOME = Object.freeze({
55
56
  * person's, which touches neither the worktree nor the queue: a retry would
56
57
  * push the same work again, and parking would hold the repo for a step that
57
58
  * does not need it.
59
+ *
60
+ * `doc-delivered` is what an analysis item delivers instead of a pull request:
61
+ * the run wrote its document and stopped there, which is the whole of what the
62
+ * analysis command does, so the item is finished with us.
58
63
  */
59
64
  export const TERMINAL = new Set([
60
65
  OUTCOME.PR_OPENED,
61
66
  OUTCOME.PUSHED_AWAITING_PR,
62
67
  OUTCOME.MERGED,
68
+ OUTCOME.DOC_DELIVERED,
63
69
  OUTCOME.SKIPPED,
64
70
  OUTCOME.COMPLETED_NO_PR,
65
71
  ]);
@@ -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;
@@ -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));