@mmerterden/multi-agent-pipeline 23.3.0 → 23.5.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 (239) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +27 -8
  3. package/README.tr.md +28 -9
  4. package/SECURITY.md +16 -0
  5. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  6. package/docs/adr/0010-own-code-graph.md +299 -8
  7. package/docs/architecture.md +3 -3
  8. package/docs/ecosystem.md +10 -10
  9. package/docs/engineering.md +4 -4
  10. package/docs/facts.json +8 -8
  11. package/docs/features.md +5 -5
  12. package/docs/performance.md +17 -17
  13. package/install/_dev-only-files.mjs +9 -0
  14. package/install/_platform-filter.mjs +2 -55
  15. package/install/claude.mjs +28 -2
  16. package/install/codex.mjs +1 -3
  17. package/install/copilot.mjs +4 -8
  18. package/install/templates/claude-hooks.json +32 -1
  19. package/manifest.json +236 -167
  20. package/package.json +11 -3
  21. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  22. package/pipeline/commands/multi-agent/design-check/SKILL.md +3 -2
  23. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  24. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  25. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  26. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  27. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  28. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  29. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  30. package/pipeline/contract/CHANGELOG.md +63 -0
  31. package/pipeline/contract/README.md +1 -0
  32. package/pipeline/contract/build.mjs +13 -1
  33. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  34. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  35. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  36. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  37. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  38. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  39. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  40. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  41. package/pipeline/contract/fixtures/runs-running.json +4 -1
  42. package/pipeline/contract/manifest.json +41 -15
  43. package/pipeline/contract/types/index.d.ts +81 -3
  44. package/pipeline/lib/detach-self.mjs +95 -0
  45. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  46. package/pipeline/lib/rotated-log.mjs +93 -0
  47. package/pipeline/lib/stack-detect.sh +1 -1
  48. package/pipeline/lib/tls-trust.mjs +29 -0
  49. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  50. package/pipeline/lib/usage-names.generated.mjs +613 -0
  51. package/pipeline/lib/usage-run-key.mjs +235 -0
  52. package/pipeline/lib/usage-vocab.mjs +210 -0
  53. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  54. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  55. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  56. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  57. package/pipeline/multi-agent-refs/design-check/init-inventory.md +11 -1
  58. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  59. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  60. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  61. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  62. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  63. package/pipeline/multi-agent-refs/features/remote-control.md +253 -0
  64. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  65. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  66. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  67. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  68. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  69. package/pipeline/multi-agent-refs/features/usage-reporting.md +255 -27
  70. package/pipeline/multi-agent-refs/help/en.md +3 -2
  71. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  72. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  73. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -2
  74. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  75. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  76. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  77. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  78. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  79. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  80. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  81. package/pipeline/office/index.html +1309 -236
  82. package/pipeline/office/toolkit.json +1 -1
  83. package/pipeline/rules/outside-the-pipeline.md +1 -1
  84. package/pipeline/schemas/activity.schema.json +23 -0
  85. package/pipeline/schemas/agent-state.schema.json +6 -1
  86. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  87. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  88. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  89. package/pipeline/schemas/code-graph.schema.json +2 -2
  90. package/pipeline/schemas/examples/design-check-config.json +27 -0
  91. package/pipeline/schemas/learning-curve.schema.json +67 -0
  92. package/pipeline/schemas/mcp-health.schema.json +96 -0
  93. package/pipeline/schemas/office-jobs.json +69 -2
  94. package/pipeline/schemas/office-jobs.schema.json +8 -1
  95. package/pipeline/schemas/phases.json +5 -0
  96. package/pipeline/schemas/phases.schema.json +8 -0
  97. package/pipeline/schemas/prefs.schema.json +46 -12
  98. package/pipeline/schemas/runs-index.schema.json +17 -0
  99. package/pipeline/schemas/toolkit-path-params.json +78 -8
  100. package/pipeline/scripts/README.md +1 -0
  101. package/pipeline/scripts/_code-graph.mjs +184 -103
  102. package/pipeline/scripts/_contract-core.mjs +1 -1
  103. package/pipeline/scripts/_contract-routes-office.mjs +33 -0
  104. package/pipeline/scripts/_diff-impact.mjs +21 -2
  105. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  106. package/pipeline/scripts/_http-post.mjs +103 -115
  107. package/pipeline/scripts/_safe-read.mjs +57 -0
  108. package/pipeline/scripts/_skill-practices.mjs +26 -0
  109. package/pipeline/scripts/_strip-code.mjs +380 -0
  110. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  111. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  112. package/pipeline/scripts/build-stack-plugins.mjs +1 -47
  113. package/pipeline/scripts/call-graph/index.mjs +78 -0
  114. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  115. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  116. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  117. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  118. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  119. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  120. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  121. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  122. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  123. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  124. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  125. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  126. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  127. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  128. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  129. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  130. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  131. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  132. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  133. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  134. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  135. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  136. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  137. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  138. package/pipeline/scripts/contract-server.mjs +3 -0
  139. package/pipeline/scripts/design-check-config.mjs +205 -0
  140. package/pipeline/scripts/feedback-send.mjs +26 -26
  141. package/pipeline/scripts/gate-ledger.mjs +2 -1
  142. package/pipeline/scripts/gen-facts.mjs +1 -2
  143. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  144. package/pipeline/scripts/graph-affected.mjs +109 -20
  145. package/pipeline/scripts/graph-build.mjs +95 -15
  146. package/pipeline/scripts/graph-export.mjs +272 -0
  147. package/pipeline/scripts/graph-hint.mjs +15 -2
  148. package/pipeline/scripts/graph-query.mjs +305 -26
  149. package/pipeline/scripts/graph-report.mjs +187 -1
  150. package/pipeline/scripts/health-report.mjs +3 -4
  151. package/pipeline/scripts/infra/docs.mjs +317 -0
  152. package/pipeline/scripts/infra/extract.mjs +998 -0
  153. package/pipeline/scripts/infra/graph.mjs +245 -0
  154. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  155. package/pipeline/scripts/job-launch.mjs +67 -2
  156. package/pipeline/scripts/learning-curve.mjs +288 -178
  157. package/pipeline/scripts/log-metric.sh +10 -1
  158. package/pipeline/scripts/mcp-health.mjs +309 -0
  159. package/pipeline/scripts/note-agent-event.mjs +3 -4
  160. package/pipeline/scripts/note-command-use.mjs +333 -0
  161. package/pipeline/scripts/note-command-use.sh +126 -0
  162. package/pipeline/scripts/note-mcp-call.sh +89 -0
  163. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  164. package/pipeline/scripts/note-session.sh +62 -3
  165. package/pipeline/scripts/note-skill-use.mjs +58 -2
  166. package/pipeline/scripts/office-build.mjs +115 -1
  167. package/pipeline/scripts/office-memory.mjs +14 -5
  168. package/pipeline/scripts/pair.mjs +333 -0
  169. package/pipeline/scripts/pre-push-check.sh +1 -1
  170. package/pipeline/scripts/remote/cbor.mjs +128 -0
  171. package/pipeline/scripts/remote/contract.mjs +98 -0
  172. package/pipeline/scripts/remote/handler.mjs +330 -0
  173. package/pipeline/scripts/remote/handles.mjs +57 -0
  174. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  175. package/pipeline/scripts/remote/listener.mjs +204 -0
  176. package/pipeline/scripts/remote/lockout.mjs +103 -0
  177. package/pipeline/scripts/remote/nonces.mjs +61 -0
  178. package/pipeline/scripts/remote/pairing.mjs +519 -0
  179. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  180. package/pipeline/scripts/remote/store.mjs +191 -0
  181. package/pipeline/scripts/remote/transport.mjs +211 -0
  182. package/pipeline/scripts/remote/verbs.json +70 -0
  183. package/pipeline/scripts/remote/verbs.mjs +217 -0
  184. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  185. package/pipeline/scripts/remote/wire.mjs +364 -0
  186. package/pipeline/scripts/remote-listener.mjs +83 -0
  187. package/pipeline/scripts/route-learn.mjs +4 -4
  188. package/pipeline/scripts/run-kill.mjs +1 -1
  189. package/pipeline/scripts/run-write.mjs +13 -2
  190. package/pipeline/scripts/runs-index.mjs +30 -3
  191. package/pipeline/scripts/search-logs.sh +9 -0
  192. package/pipeline/scripts/session-brief.mjs +458 -0
  193. package/pipeline/scripts/session-brief.sh +130 -0
  194. package/pipeline/scripts/skill-usage.mjs +16 -5
  195. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  196. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  197. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  198. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  199. package/pipeline/scripts/token-budget-report.mjs +3 -2
  200. package/pipeline/scripts/uninstall.mjs +29 -0
  201. package/pipeline/scripts/usage-access.mjs +16 -31
  202. package/pipeline/scripts/usage-health.mjs +31 -62
  203. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  204. package/pipeline/scripts/usage-register.mjs +39 -29
  205. package/pipeline/scripts/usage-report.mjs +579 -178
  206. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  207. package/pipeline/scripts/write-state.mjs +39 -0
  208. package/pipeline/skills/.skill-manifest.json +21 -17
  209. package/pipeline/skills/.skills-index.json +13 -2
  210. package/pipeline/skills/shared/README.md +5 -4
  211. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  212. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  213. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  214. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  215. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  216. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  219. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  220. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  221. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  222. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  223. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  224. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  225. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  226. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  227. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  228. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  229. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  230. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  231. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  232. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  233. package/pipeline/skills/skills-index.md +3 -2
  234. package/docs/FIGMA_PIPELINE.md +0 -137
  235. package/pipeline/lib/identifier-scan.mjs +0 -156
  236. package/pipeline/scripts/_renamed-skills.mjs +0 -164
  237. package/pipeline/scripts/publish-staged.mjs +0 -324
  238. package/pipeline/skills/renamed.json +0 -30
  239. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -8,8 +8,9 @@
8
8
  * id (`taskId`), upserted at every phase transition and at completion, halt
9
9
  * and park, fire-and-forget - never throws, never delays a run.
10
10
  * Only coarse run metadata is included; never prompts, code, diffs, token
11
- * values, or absolute paths. The task title and the PR URL are sent only when
12
- * usageLog.includeTitle / usageLog.includePrUrl are true. The optional
11
+ * values, or absolute paths. A summary of the task title (word count, ticket
12
+ * shape, language; never the title) and the PR URL of a known code host are
13
+ * sent only when usageLog.includeTitle / usageLog.includePrUrl are true. The optional
13
14
  * `health` summary comes from usage-health.mjs, which bounds its own wait.
14
15
  *
15
16
  * Enable + configure via prefs.global.usageLog:
@@ -36,40 +37,127 @@
36
37
  *
37
38
  * node usage-report.mjs --lifecycle (report the installed version when it changed)
38
39
  * --event phase | completed | halted | parked (default: derived from state)
40
+ * --register-first run the quiet registration in this process before sending, so the
41
+ * first report on an unregistered machine finds its token
42
+ * --detach hand the run to a detached copy and return at once, so a phase
43
+ * document's call never waits on the network
39
44
  *
40
45
  * @module pipeline/scripts/usage-report
41
46
  */
42
47
 
43
48
  import { postJson } from "./_http-post.mjs";
44
- import {
45
- readFileSync,
46
- existsSync,
47
- readdirSync,
48
- appendFileSync,
49
- mkdirSync,
50
- renameSync,
51
- writeFileSync,
52
- } from "fs";
53
- import { DEFAULT_ENDPOINT, canonicalEndpoint } from "../lib/usage-endpoint.mjs";
49
+ import { readFileSync, existsSync, readdirSync, mkdirSync, renameSync, writeFileSync } from "fs";
50
+ import { DEFAULT_ENDPOINT, canonicalEndpoint, registerUrlAllowed } from "../lib/usage-endpoint.mjs";
54
51
  import { homedir, platform } from "os";
55
52
  import { dirname, join } from "path";
56
53
  import { fileURLToPath, pathToFileURL } from "url";
57
54
  import { execFileSync } from "child_process";
58
- import { createHash } from "crypto";
55
+ import { randomBytes } from "crypto";
59
56
  import { costUsd } from "./_cost.mjs";
60
57
  import { defaultPrefsPath, identityHidden, resolveReportingLogin } from "./usage-identity.mjs";
61
58
  import { installedVersion, lifecycleEvent } from "../lib/usage-lifecycle.mjs";
62
59
  import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
63
- import { KNOWN_STACKS, pluginsForStacks } from "./_stack-routing.mjs";
60
+ import { ALWAYS_ON, KNOWN_STACKS, STACK_PLUGIN_ALIAS } from "./_stack-routing.mjs";
64
61
  import { exitOnHelp } from "../lib/cli-help.mjs";
62
+ import { detachSelf, shouldDetach } from "../lib/detach-self.mjs";
63
+ import { isPublicMcpServer, publicServerName } from "../lib/public-mcp-servers.mjs";
64
+ import { MCP_SERVER_ID } from "../lib/mcp-rename.mjs";
65
+ import { SHIPPED_COMMANDS, SHIPPED_SKILLS, TOOLKIT_TOOLS } from "../lib/usage-names.generated.mjs";
66
+ import { foldCalls, runCalls, syncCountingSentinel } from "./note-mcp-failure.mjs";
67
+ import {
68
+ MAX_CMDS,
69
+ MAX_CMD_COUNT,
70
+ ackCommands,
71
+ claimCommands,
72
+ peekCommands,
73
+ releaseCommands,
74
+ } from "./note-command-use.mjs";
75
+ import {
76
+ CLIS,
77
+ INPUT_TYPES,
78
+ LANGUAGES,
79
+ OPERATING_SYSTEMS,
80
+ PHASE_STATUSES,
81
+ REMOTE_KINDS,
82
+ PR_URL_HOSTS,
83
+ TASK_TYPES,
84
+ TITLE_WORDS,
85
+ boundedSec,
86
+ floorMinute,
87
+ isoMs,
88
+ isoTimestamp,
89
+ nowMinute,
90
+ oneOf,
91
+ spanMs,
92
+ spanSec,
93
+ versionOrUnknown,
94
+ } from "../lib/usage-vocab.mjs";
95
+ import { loadRunKey, repoDigest, runIdDigest as keyedRunIdDigest } from "../lib/usage-run-key.mjs";
65
96
  import { parseArgs as parseArgv } from "../lib/args.mjs";
66
97
  import { machineHealth } from "./usage-health.mjs";
98
+ import { appendLogRow } from "./note-skill-use.mjs";
67
99
 
68
100
  exitOnHelp(import.meta.url);
69
101
 
70
102
  const __dirname = dirname(fileURLToPath(import.meta.url));
71
103
  const TIMEOUT_MS = 6000;
72
104
 
105
+ /** First readable shipped file among the install tree next to this script and the host trees. */
106
+ function shippedJson(...parts) {
107
+ for (const p of [join(__dirname, "..", ...parts), hostFile(...parts)]) {
108
+ const doc = p ? readJson(p) : null;
109
+ if (doc) return doc;
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /**
115
+ * The credential names the pipeline itself documents: the properties of
116
+ * `global.keychainMapping` in prefs.schema.json. A mapped name outside the list
117
+ * is somebody's own (a person's name, a ticket key, an address) and is never
118
+ * sent as written.
119
+ */
120
+ function knownCredentialKeys() {
121
+ const props = shippedJson("schemas", "prefs.schema.json")?.properties?.global?.properties
122
+ ?.keychainMapping?.properties;
123
+ return new Set(props && typeof props === "object" ? Object.keys(props) : []);
124
+ }
125
+
126
+ /** The model ids the cost table knows: rung names, their wire ids, legacy ids and the model map. */
127
+ function knownModelIds() {
128
+ const t =
129
+ shippedJson("scripts", "cost-table.json") ?? readJson(join(__dirname, "cost-table.json"));
130
+ const ids = new Set();
131
+ for (const [rung, row] of Object.entries(t?.prices ?? {})) {
132
+ ids.add(rung);
133
+ if (typeof row?.modelId === "string") ids.add(row.modelId);
134
+ if (typeof row?.copilotModelId === "string") ids.add(row.copilotModelId);
135
+ }
136
+ for (const k of Object.keys(t?.legacy ?? {})) ids.add(k);
137
+ for (const k of Object.keys(t?.models ?? {})) ids.add(k);
138
+ return ids;
139
+ }
140
+
141
+ /** Phase numbers the pipeline has ever had: 0 up to the highest id in phases.json (current or `was`). */
142
+ function knownPhaseIds() {
143
+ const phases = shippedJson("schemas", "phases.json")?.phases;
144
+ let max = 7;
145
+ if (Array.isArray(phases)) {
146
+ const all = phases.flatMap((p) => [p?.id, ...(Array.isArray(p?.was) ? p.was : [])]);
147
+ const nums = all.filter((n) => Number.isInteger(n) && n >= 0);
148
+ if (nums.length) max = Math.max(...nums);
149
+ }
150
+ return new Set(Array.from({ length: max + 1 }, (_, i) => i));
151
+ }
152
+
153
+ /** The phase number for a tracker or state id, or null when it is not a known number. */
154
+ function phaseNumber(raw, ids = knownPhaseIds()) {
155
+ const text = typeof raw === "number" ? String(raw) : typeof raw === "string" ? raw.trim() : "";
156
+ if (!/^\d{1,2}$/.test(text)) return null;
157
+ const n = Number(text);
158
+ return ids.has(n) ? n : null;
159
+ }
160
+
73
161
  // The emitter ships verbatim into ~/.claude, ~/.copilot and ~/.codex, so it must
74
162
  // never hard-code one host's tree: a Copilot- or Codex-only install has no
75
163
  // ~/.claude/lib. Resolve each helper across every installed host root.
@@ -102,8 +190,10 @@ function parseArgs(argv) {
102
190
  "dry-run": "dryRun",
103
191
  lifecycle: "lifecycle",
104
192
  "print-state": "printState",
193
+ detach: "detach",
194
+ "register-first": "registerFirst",
105
195
  };
106
- const booleans = ["dry-run", "lifecycle", "print-state"];
196
+ const booleans = ["dry-run", "lifecycle", "print-state", "detach", "register-first"];
107
197
  parseArgv(argv, {
108
198
  values: ["state", "task-id", "phase", "status", "event"],
109
199
  booleans,
@@ -183,7 +273,7 @@ function readEnabledPluginNames(settings) {
183
273
  // `private` says that one was enabled.
184
274
  function enabledPlugins(state, { publicPlugins, home } = {}) {
185
275
  const root = state.projectRoot || process.cwd();
186
- const pub = publicPlugins ?? publicToolkits();
276
+ const pub = publicPlugins ?? PUBLIC_PLUGINS;
187
277
  const names = new Set();
188
278
  for (const s of [
189
279
  readJson(join(root, ".claude", "settings.json")),
@@ -200,7 +290,10 @@ function enabledPlugins(state, { publicPlugins, home } = {}) {
200
290
  function integrationTags(state) {
201
291
  const apps = new Set();
202
292
  if (state.jiraId) apps.add("jira");
203
- if (state.remoteType) apps.add(String(state.remoteType).toLowerCase());
293
+ if (state.remoteType) {
294
+ const remote = String(state.remoteType).toLowerCase();
295
+ apps.add(REMOTE_KINDS.includes(remote) ? remote : "private");
296
+ }
204
297
  if (state.githubIssue) apps.add("github");
205
298
  if (state.confluenceSpace) apps.add("confluence");
206
299
  if (state.figmaAccess?.tier) apps.add("figma");
@@ -208,30 +301,113 @@ function integrationTags(state) {
208
301
  const tool = String(call?.tool || "");
209
302
  // Server segment may contain hyphens (mcp__multi-agent__ios_tap), so the
210
303
  // class must accept them or "multi-agent" collapses to "multi".
211
- const m = tool.match(/^mcp__([a-z0-9_-]+?)__/i) || tool.match(/^mcp__([a-z0-9_-]+)/i);
212
- if (m) apps.add(m[1].replace(/_/g, "-").toLowerCase());
304
+ const m = tool.match(/^mcp__([A-Za-z0-9_-]+?)__/) || tool.match(/^mcp__([A-Za-z0-9_-]+)/);
305
+ if (m) apps.add(publicServerName(m[1]));
213
306
  }
214
307
  return Array.from(apps).slice(0, 20);
215
308
  }
216
309
 
310
+ const MAX_TOOLS = 40;
311
+ const MAX_TOOL_COUNT = 9999;
312
+ const SERVER_PART = /^[A-Za-z0-9_-]{1,40}$/;
313
+ const TOOL_PART = /^[A-Za-z0-9_]{1,64}$/;
314
+ const TOOLKIT_TOOL_SET = new Set(TOOLKIT_TOOLS);
315
+
316
+ /** `[server, tool]` from the host's `mcp__<server>__<tool>` name, or null. */
317
+ function splitMcpName(raw) {
318
+ const m = /^mcp__(.+?)__(.+)$/.exec(String(raw || ""));
319
+ return m && SERVER_PART.test(m[1]) && TOOL_PART.test(m[2]) ? [m[1], m[2]] : null;
320
+ }
321
+
322
+ /**
323
+ * What a tool call is called in the record. A server is named only by its exact
324
+ * registered name from the shipped public list; any other server is one
325
+ * `private:private` row. A tool is named only when it is on the shipped tool
326
+ * list of its server, which exists for this product's own server; every other
327
+ * tool of a public server is `<server>:other`. A private server registered
328
+ * under a public name is therefore counted as that public server with the tool
329
+ * `other`, which reveals nothing.
330
+ */
331
+ export function toolLabel(server, tool) {
332
+ if (!isPublicMcpServer(server)) return "private:private";
333
+ return server === MCP_SERVER_ID && TOOLKIT_TOOL_SET.has(tool)
334
+ ? `${server}:${tool}`
335
+ : `${server}:other`;
336
+ }
337
+
338
+ /**
339
+ * Names and call counts of the MCP tools one run used: the run's own record,
340
+ * and the machine counter note-mcp-failure.mjs keeps per host session, reduced
341
+ * to this run (the session's total minus its base). Where both name a tool the
342
+ * larger count is used, since the hook sees the calls the record lists too.
343
+ * Only names from the shipped lists (toolLabel) and counts; never arguments or
344
+ * results.
345
+ */
346
+ function toolCounts(state) {
347
+ const counts = new Map();
348
+ for (const call of state.telemetry?.mcpCalls ?? []) {
349
+ const parts = splitMcpName(call?.tool);
350
+ if (!parts) continue;
351
+ const key = `${parts[0]}:${parts[1]}`;
352
+ counts.set(key, (counts.get(key) ?? 0) + 1);
353
+ }
354
+ const delta = runCalls({
355
+ runId: runId(state),
356
+ sessionId: state.hostSessionId,
357
+ });
358
+ for (const [name, n] of Object.entries(delta)) {
359
+ const at = name.indexOf(":");
360
+ const k = Number(n);
361
+ if (at < 1 || !Number.isInteger(k)) continue;
362
+ if (!SERVER_PART.test(name.slice(0, at)) || !TOOL_PART.test(name.slice(at + 1))) continue;
363
+ if (k > (counts.get(name) ?? 0)) counts.set(name, k);
364
+ }
365
+ const shown = new Map();
366
+ for (const [name, k] of counts) {
367
+ const at = name.indexOf(":");
368
+ const label = toolLabel(name.slice(0, at), name.slice(at + 1));
369
+ shown.set(label, (shown.get(label) ?? 0) + k);
370
+ }
371
+ return [...shown]
372
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
373
+ .slice(0, MAX_TOOLS)
374
+ .map(([n, k]) => ({ n, k: Math.min(k, MAX_TOOL_COUNT) }));
375
+ }
376
+
377
+ const SVC_RANK = { ok: 0, fail: 1, expired: 2 };
378
+
379
+ /**
380
+ * Which credentials are onboarded and whether their last check passed. A
381
+ * credential is named only when it is one of the pipeline's own documented
382
+ * logical keys; every other mapped name is folded into `private` (one entry in
383
+ * `on`, one row in `svc` carrying the worst status, and `np` for how many).
384
+ */
217
385
  function credHealth() {
218
386
  const g = resolveGlobalPrefs();
219
- const mapping = g.keychainMapping ?? {};
220
- const on = Object.entries(mapping)
387
+ const known = knownCredentialKeys();
388
+ const mapping =
389
+ g.keychainMapping && typeof g.keychainMapping === "object" ? g.keychainMapping : {};
390
+ const mapped = Object.entries(mapping)
221
391
  .filter(([, v]) => typeof v === "string" && v.trim())
222
- .map(([k]) => k)
223
- .slice(0, 40);
392
+ .map(([k]) => k);
393
+ const on = [...new Set(mapped.map((k) => (known.has(k) ? k : "private")))].slice(0, 40);
394
+ const np = mapped.filter((k) => !known.has(k)).length;
224
395
 
225
396
  const svc = {};
226
397
  for (const [name, st] of Object.entries(g.serviceStatus ?? {})) {
227
398
  const err = String(st?.error || "").toLowerCase();
228
399
  const expired = /401|403|expired|unauthor|revoked|invalid.token/.test(err);
229
- svc[name] = {
400
+ const row = {
230
401
  s: st?.ok ? "ok" : expired ? "expired" : "fail",
231
- at: st?.checkedAt || null,
402
+ at: isoTimestamp(st?.checkedAt),
232
403
  };
404
+ const label = known.has(name) ? name : "private";
405
+ const prior = svc[label];
406
+ if (!prior || SVC_RANK[row.s] > SVC_RANK[prior.s])
407
+ svc[label] = { s: row.s, at: row.at ?? prior?.at ?? null };
408
+ else if (row.at && (!prior.at || row.at > prior.at)) prior.at = row.at;
233
409
  }
234
- return { on, svc };
410
+ return { on, svc, np };
235
411
  }
236
412
 
237
413
  export const MAX_SERVICES = 40;
@@ -245,26 +421,37 @@ function serverNames(config) {
245
421
  }
246
422
 
247
423
  /**
248
- * Which apps this machine is connected to, by name only: every onboarded
249
- * credential's logical key (kind "token"; connected while it is mapped and its
250
- * last service check did not fail) and every MCP server registered with
251
- * Claude Code (user scope and each project) or Copilot CLI (kind "mcp").
252
- * Mapping values, server configs and paths are never read into the result,
253
- * and a name that is not a plain identifier is dropped, so nothing but the
254
- * key itself can leave. A missing or unparsable config adds nothing.
424
+ * Which apps this machine is connected to: every onboarded credential (kind
425
+ * "token"; connected while it is mapped and its last service check did not
426
+ * fail) and every MCP server registered with Claude Code (user scope and each
427
+ * project) or Copilot CLI (kind "mcp"). A credential is named only when it is
428
+ * one of the pipeline's documented logical keys and an MCP server only when it
429
+ * is on the shipped public list; every other one is folded into a single
430
+ * `private` row of its kind, with `n` for how many. Mapping values, server
431
+ * configs and paths are never read into the result. A missing or unparsable
432
+ * config adds nothing.
255
433
  *
256
- * @returns {{name: string, kind: "token"|"mcp", connected: boolean}[]}
434
+ * @returns {{name: string, kind: "token"|"mcp", connected: boolean, n?: number}[]}
257
435
  */
258
- export function machineServices({ globalPrefs, home = homedir() } = {}) {
436
+ export function machineServices({ globalPrefs, home = homedir(), knownKeys } = {}) {
259
437
  const g = globalPrefs ?? resolveGlobalPrefs();
260
- const out = [];
261
- const seen = new Set();
438
+ const known = knownKeys ?? knownCredentialKeys();
439
+ const rows = new Map();
440
+ const seenNames = new Set();
262
441
  const add = (name, kind, connected) => {
263
442
  if (typeof name !== "string" || !SERVICE_NAME_RE.test(name)) return;
264
- const key = `${kind}:${name}`;
265
- if (seen.has(key) || out.length >= MAX_SERVICES) return;
266
- seen.add(key);
267
- out.push({ name, kind, connected });
443
+ if (seenNames.has(`${kind}:${name}`)) return;
444
+ seenNames.add(`${kind}:${name}`);
445
+ const label = kind === "token" ? (known.has(name) ? name : "private") : publicServerName(name);
446
+ const key = `${kind}:${label}`;
447
+ const row = rows.get(key);
448
+ if (!row) {
449
+ if (rows.size >= MAX_SERVICES) return;
450
+ rows.set(key, { name: label, kind, connected, ...(label === "private" ? { n: 1 } : {}) });
451
+ } else if (label === "private") {
452
+ row.n += 1;
453
+ row.connected = row.connected && connected;
454
+ }
268
455
  };
269
456
  const mapping = g?.keychainMapping;
270
457
  const status = g?.serviceStatus ?? {};
@@ -282,19 +469,40 @@ export function machineServices({ globalPrefs, home = homedir() } = {}) {
282
469
  }
283
470
  mcp.push(...serverNames(readJson(join(home, ".copilot", "mcp-config.json"))));
284
471
  for (const name of mcp) add(name, "mcp", true);
285
- return out;
472
+ return [...rows.values()];
286
473
  }
287
474
 
288
- // A repo-local skill is named by whoever owns the repo, and a fallback toolkit
289
- // that the public marketplace does not carry is somebody's private plugin:
290
- // neither name is sent. Each is replaced by a constant naming its source, so
291
- // the panel still counts that such a skill was used.
292
- function publicToolkits(manifestPath) {
293
- return new Set(pluginsForStacks(KNOWN_STACKS, manifestPath ? { manifestPath } : {}).plugins);
475
+ /**
476
+ * The plugins whose names a record may carry: the ones the pipeline's own
477
+ * marketplace publishes for its stacks. Built from the package's routing table,
478
+ * never from what is installed on the machine.
479
+ */
480
+ export const PUBLIC_PLUGINS = new Set([
481
+ ...ALWAYS_ON,
482
+ ...KNOWN_STACKS.map((s) => `ai-${STACK_PLUGIN_ALIAS[s] ?? s}-toolkit`),
483
+ ]);
484
+ const SHIPPED_COMMAND_SET = new Set(SHIPPED_COMMANDS);
485
+ const SHIPPED_SKILL_SET = new Set(SHIPPED_SKILLS);
486
+
487
+ /**
488
+ * A skill as the record names it. A skill of a public plugin is
489
+ * `<plugin>:<skill>` when the skill is one the package ships, else
490
+ * `<plugin>:other`; for the `multi-agent` namespace the name must be a command
491
+ * the package ships. A skill of any other plugin, or one with no plugin, is
492
+ * `private`, whatever the source recorded for it.
493
+ */
494
+ export function skillLabel(skill, pub = PUBLIC_PLUGINS) {
495
+ const m = /^([A-Za-z0-9._-]+):([A-Za-z0-9._-]+)$/.exec(skill);
496
+ if (!m) return "private";
497
+ if (m[1] === "multi-agent") {
498
+ return SHIPPED_COMMAND_SET.has(m[2]) ? skill : "multi-agent:other";
499
+ }
500
+ if (!pub.has(m[1])) return "private";
501
+ return SHIPPED_SKILL_SET.has(m[2]) ? skill : `${m[1]}:other`;
294
502
  }
295
503
 
296
- function invokedCalls(state, { publicPlugins, manifestPath } = {}) {
297
- let pub = publicPlugins ?? null;
504
+ export function invokedCalls(state, { publicPlugins } = {}) {
505
+ const pub = publicPlugins ?? PUBLIC_PLUGINS;
298
506
  const names = new Set();
299
507
  for (const c of state.telemetry?.skillCalls ?? []) {
300
508
  if (!c?.skill) continue;
@@ -304,12 +512,15 @@ function invokedCalls(state, { publicPlugins, manifestPath } = {}) {
304
512
  continue;
305
513
  }
306
514
  if (c.source === "marketplace-fallback") {
307
- pub ??= publicToolkits(manifestPath);
308
515
  const toolkit = String(c.toolkit || skill.split(":")[0]);
309
- names.add(pub.has(toolkit) ? skill : "marketplace-fallback");
516
+ names.add(
517
+ pub.has(toolkit)
518
+ ? skillLabel(`${toolkit}:${skill.split(":").pop()}`, pub)
519
+ : "marketplace-fallback",
520
+ );
310
521
  continue;
311
522
  }
312
- names.add(skill);
523
+ names.add(skillLabel(skill, pub));
313
524
  }
314
525
  return Array.from(names).slice(0, 30);
315
526
  }
@@ -319,12 +530,12 @@ function invokedCalls(state, { publicPlugins, manifestPath } = {}) {
319
530
  // function and the field exist because the panel groups by `os` and a row with the key
320
531
  // missing reads as "unknown host" rather than "macOS".
321
532
  function detectOs() {
322
- return platform() === "darwin" ? "macos" : platform();
533
+ return oneOf(platform() === "darwin" ? "macos" : "other", OPERATING_SYSTEMS) ?? "other";
323
534
  }
324
535
 
325
536
  function detectCli() {
326
537
  const e = process.env;
327
- if (e.MULTI_AGENT_CLI) return String(e.MULTI_AGENT_CLI).toLowerCase();
538
+ if (e.MULTI_AGENT_CLI) return oneOf(String(e.MULTI_AGENT_CLI).toLowerCase(), CLIS);
328
539
  if (e.CLAUDECODE || e.CLAUDE_CODE_ENTRYPOINT || e.ANTHROPIC_CLI) return "claude";
329
540
  if (e.CODEX_HOME || e.CODEX_SANDBOX || e.CODEX_CLI) return "codex";
330
541
  if (e.COPILOT_CLI || e.GITHUB_COPILOT_CLI || e.GH_COPILOT || e.COPILOT_AGENT_ID) {
@@ -333,18 +544,27 @@ function detectCli() {
333
544
  return null;
334
545
  }
335
546
 
547
+ /** The stacks of a run, only the ones the pipeline knows (KNOWN_STACKS). */
548
+ function stacksOf(state) {
549
+ const raw = Array.isArray(state.stacks) ? state.stacks : state.stack ? [state.stack] : [];
550
+ return [
551
+ ...new Set(
552
+ raw
553
+ .map((x) => oneOf(typeof x === "string" ? x.trim().toLowerCase() : x, KNOWN_STACKS))
554
+ .filter(Boolean),
555
+ ),
556
+ ];
557
+ }
558
+
336
559
  function deriveContext(state) {
337
560
  return {
338
- lang: resolveGlobalPrefs().outputLanguage ?? null,
561
+ lang: oneOf(resolveGlobalPrefs().outputLanguage, LANGUAGES),
339
562
  os: detectOs(),
340
563
  cli: detectCli(),
341
- stack: Array.isArray(state.stacks)
342
- ? state.stacks.slice(0, 10)
343
- : state.stack
344
- ? [String(state.stack)]
345
- : [],
564
+ stack: stacksOf(state),
346
565
  plug: enabledPlugins(state),
347
566
  apps: integrationTags(state),
567
+ tools: toolCounts(state),
348
568
  creds: credHealth(),
349
569
  services: machineServices(),
350
570
  calls: invokedCalls(state),
@@ -402,9 +622,9 @@ function packageVersion() {
402
622
  }
403
623
 
404
624
  function inputType(state) {
405
- if (state.jiraId) return "jira";
406
- if (state.githubIssue) return "github-issue";
407
- return "free-text";
625
+ if (state.jiraId) return INPUT_TYPES[0];
626
+ if (state.githubIssue) return INPUT_TYPES[1];
627
+ return INPUT_TYPES[2];
408
628
  }
409
629
 
410
630
  // The mode set is read from phases.json, which ships next to this script in
@@ -454,23 +674,31 @@ export function modeOf(state, modes = allowedModes()) {
454
674
  return has("full") ? "full" : "unknown";
455
675
  }
456
676
 
457
- // The command that was invoked, when the state names one that still ships
458
- // (`<root>/commands/multi-agent/<name>/`); otherwise the run's mode.
677
+ // The command that was invoked, when the state names one the package ships
678
+ // (SHIPPED_COMMANDS, generated when the package is packed); otherwise the run's
679
+ // mode. A routine saved on this machine is not on the list.
459
680
  function commandOf(state, mode) {
460
681
  const name = commandName(state);
461
- if (name && existsSync(join(__dirname, "..", "commands", "multi-agent", name))) {
462
- return `/multi-agent:${name}`;
463
- }
464
- return mode;
682
+ return name && SHIPPED_COMMAND_SET.has(name) ? `/multi-agent:${name}` : mode;
465
683
  }
466
684
 
467
685
  // A repository name is the user's, not ours, and the panel never needs it:
468
- // only the ability to tell one project's runs from another's. A digest keeps
469
- // the name out of the record. It is not secret: anyone who can guess a name
470
- // can hash it and compare.
471
- function projectDigest(name) {
472
- if (typeof name !== "string" || !name.trim()) return null;
473
- return `p${createHash("sha256").update(name.trim()).digest("hex").slice(0, 8)}`;
686
+ // only the ability to tell one project's runs from another's. The name is
687
+ // digested with the install's secret (usage-run-key.mjs), in a domain of its
688
+ // own, so it cannot be recovered by hashing likely names. With no secret there
689
+ // is no digest.
690
+ function projectDigest(name, key = loadRunKey()) {
691
+ return repoDigest(name, key);
692
+ }
693
+
694
+ // The run id is a ticket key in practice, which belongs to the user's tracker
695
+ // and is low entropy, so a plain hash of it could be reversed by hashing every
696
+ // plausible key. The panel only needs to tell one run from another and to join
697
+ // the events of one run, so the id leaves the machine as an HMAC under a
698
+ // per-install secret (usage-run-key.mjs). Local logs keep the raw id. With no
699
+ // secret there is no digest, and the caller skips the send.
700
+ function runIdDigest(id, key = loadRunKey()) {
701
+ return keyedRunIdDigest(id, key);
474
702
  }
475
703
 
476
704
  function resolveTracker(state) {
@@ -485,15 +713,11 @@ function resolveTracker(state) {
485
713
  }
486
714
 
487
715
  function phaseDurationSec(p) {
488
- if (Number.isFinite(Number(p?.duration_ms))) {
489
- return Math.round(Number(p.duration_ms) / 1000);
490
- }
491
- const s = p?.startedAt || p?.started_at || p?.start;
492
- const f = p?.finishedAt || p?.finished_at || p?.completed_at || p?.end;
493
- const sm = s ? Date.parse(s) : NaN;
494
- const fm = f ? Date.parse(f) : NaN;
495
- if (Number.isNaN(sm) || Number.isNaN(fm) || fm < sm) return null;
496
- return Math.round((fm - sm) / 1000);
716
+ if (Number.isFinite(Number(p?.duration_ms))) return boundedSec(Number(p.duration_ms) / 1000);
717
+ return spanSec(
718
+ p?.startedAt || p?.started_at || p?.start,
719
+ p?.finishedAt || p?.finished_at || p?.completed_at || p?.end,
720
+ );
497
721
  }
498
722
 
499
723
  function trackerSummary(state) {
@@ -505,6 +729,7 @@ function trackerSummary(state) {
505
729
  models: [],
506
730
  startedAt: null,
507
731
  endedAt: null,
732
+ durationSec: null,
508
733
  current: null,
509
734
  };
510
735
  const path = resolveTracker(state);
@@ -524,26 +749,29 @@ function trackerSummary(state) {
524
749
  const phs = [];
525
750
  const failed = [];
526
751
  const models = new Set();
527
- let startedAt =
528
- typeof tracker?.started_at === "string" && tracker.started_at ? tracker.started_at : null;
529
- let endedAt = null;
752
+ const phaseIds = knownPhaseIds();
753
+ const modelIds = knownModelIds();
754
+ let startMs = isoMs(tracker?.started_at);
755
+ let endMs = null;
530
756
  for (const p of list) {
531
- const id = p?.id != null && String(p.id) !== "" ? String(p.id) : "?";
532
- if (p?.status === "failed") failed.push(id);
533
- if (p?.model) models.add(String(p.model));
757
+ const num = phaseNumber(p?.id, phaseIds);
758
+ const status = oneOf(p?.status, PHASE_STATUSES);
759
+ if (p?.model) models.add(modelIds.has(String(p.model)) ? String(p.model) : "other");
534
760
  const pin = Number(p?.tokens_in || 0);
535
761
  const pout = Number(p?.tokens_out || 0);
536
762
  const pcache = Number(p?.tokens_cached || 0);
537
763
  tin += pin;
538
764
  tout += pout;
539
765
  tcache += pcache;
540
- const ps = p?.started_at || p?.startedAt || null;
541
- const pf = p?.completed_at || p?.finished_at || p?.finishedAt || null;
542
- if (ps && (!startedAt || ps < startedAt)) startedAt = ps;
543
- if (pf && (!endedAt || pf > endedAt)) endedAt = pf;
766
+ const ps = isoMs(p?.started_at || p?.startedAt);
767
+ const pf = isoMs(p?.completed_at || p?.finished_at || p?.finishedAt);
768
+ if (ps !== null && (startMs === null || ps < startMs)) startMs = ps;
769
+ if (pf !== null && (endMs === null || pf > endMs)) endMs = pf;
770
+ if (num === null) continue;
771
+ if (status === "failed") failed.push(num);
544
772
  phs.push({
545
- p: Number.isNaN(Number(id)) ? id : Number(id),
546
- st: p?.status || null,
773
+ p: num,
774
+ st: status,
547
775
  du: phaseDurationSec(p),
548
776
  tk: pin + pout + pcache || null,
549
777
  });
@@ -587,34 +815,44 @@ function trackerSummary(state) {
587
815
  phs: phs.length ? phs : null,
588
816
  failed,
589
817
  models: Array.from(models).slice(0, 10),
590
- startedAt,
591
- endedAt,
818
+ startedAt: startMs === null ? null : floorMinute(startMs),
819
+ endedAt: endMs === null ? null : floorMinute(endMs),
820
+ durationSec: startMs !== null && endMs !== null ? spanMs(startMs, endMs) : null,
592
821
  current,
593
822
  };
594
823
  }
595
824
 
825
+ /**
826
+ * The typed-command counts as the record carries them: `{n, k}` rows whose name
827
+ * is a shipped command or `other`, k an integer from 1 to MAX_CMD_COUNT, at
828
+ * most MAX_CMDS rows, most used first.
829
+ */
830
+ export function commandCounts(rows) {
831
+ const names = new Set([...SHIPPED_COMMANDS, "other"]);
832
+ const out = new Map();
833
+ for (const row of Array.isArray(rows) ? rows : []) {
834
+ const k = Number(row?.k);
835
+ if (!names.has(row?.n) || !Number.isInteger(k) || k < 1) continue;
836
+ out.set(row.n, Math.min((out.get(row.n) ?? 0) + k, MAX_CMD_COUNT));
837
+ }
838
+ return [...out]
839
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
840
+ .slice(0, MAX_CMDS)
841
+ .map(([n, k]) => ({ n, k }));
842
+ }
843
+
596
844
  function deriveErrors(state, failedPhases) {
597
845
  const errs = new Set();
598
846
  const halt = reasonCode(state, "halted");
599
847
  if (halt) errs.add(halt);
600
- for (const id of failedPhases ?? []) errs.add(`phase-${id}-failed`);
848
+ for (const n of failedPhases ?? []) if (Number.isInteger(n)) errs.add(`phase-${n}-failed`);
601
849
  const s = String(state.status || "").toLowerCase();
602
850
  if (s === "failed") errs.add("run-failed");
603
851
  return Array.from(errs).slice(0, 20);
604
852
  }
605
853
 
606
854
  function durationSec(state, spend) {
607
- const s = state.startedAt ? Date.parse(state.startedAt) : NaN;
608
- const f = state.finishedAt ? Date.parse(state.finishedAt) : NaN;
609
- if (!Number.isNaN(s) && !Number.isNaN(f) && f >= s) {
610
- return Math.round((f - s) / 1000);
611
- }
612
- const ts = spend?.startedAt ? Date.parse(spend.startedAt) : NaN;
613
- const tf = spend?.endedAt ? Date.parse(spend.endedAt) : NaN;
614
- if (!Number.isNaN(ts) && !Number.isNaN(tf) && tf >= ts) {
615
- return Math.round((tf - ts) / 1000);
616
- }
617
- return null;
855
+ return spanSec(state.startedAt, state.finishedAt) ?? spend?.durationSec ?? null;
618
856
  }
619
857
 
620
858
  function runId(state) {
@@ -657,29 +895,123 @@ function codeOf(raw, max = 60) {
657
895
  const ABSOLUTE_PATH = /(?:~|\/(?:Users|home|var|private|tmp|opt|etc|Volumes))\/\S*|[A-Za-z]:\\\S*/g;
658
896
 
659
897
  /**
660
- * A short machine-readable reason: the halt cause as `<phase>:<cause>` or the
661
- * step a parked run waits at. Paths are removed before the text is reduced to
662
- * [a-z0-9:_-], so a cause that quoted a file cannot carry a home directory.
898
+ * The causes a halt or a park can be reported as. A cause is never sent as
899
+ * text: free text carries ticket keys, hosts, addresses, remotes and mail
900
+ * addresses in shapes no blocklist covers, so the text is matched against the
901
+ * patterns below and only the matching code leaves the machine. The full text
902
+ * stays in the local errors ledger.
903
+ */
904
+ export const CAUSE_CODES = [
905
+ "circuit-breaker",
906
+ "retry-cap",
907
+ "stop-guard",
908
+ "research",
909
+ "reviewer-json",
910
+ "review-blocking",
911
+ "cancelled",
912
+ "disk-full",
913
+ "rate-limit",
914
+ "timeout",
915
+ "budget",
916
+ "auth",
917
+ "network",
918
+ "permission",
919
+ "conflict",
920
+ "not-found",
921
+ "dispatch",
922
+ "lock",
923
+ "verification",
924
+ "build",
925
+ "test",
926
+ "approval",
927
+ "maturity",
928
+ "channels",
929
+ "awaiting-input",
930
+ "validation",
931
+ "run-failed",
932
+ "unknown",
933
+ ];
934
+
935
+ const CAUSE_PATTERNS = [
936
+ ["circuit-breaker", /circuit.?breaker|identical.?finding/],
937
+ ["retry-cap", /retry.?cap/],
938
+ ["stop-guard", /stop.?guard|scope.?guard/],
939
+ ["research", /\bresearch/],
940
+ ["reviewer-json", /reviewer.?json|review.?output|json.?invalid/],
941
+ ["review-blocking", /review.?blocking|blocking.?finding/],
942
+ ["cancelled", /interrupt|cancel|abort|user.?stop/],
943
+ ["disk-full", /enospc|disk.?full|no space/],
944
+ ["rate-limit", /rate.?limit|\b429\b|too many requests/],
945
+ ["timeout", /time.?out|timed.?out|deadline/],
946
+ ["budget", /budget|\bcost\b/],
947
+ ["auth", /\b40[13]\b|unauthori|forbidden|credential|token|expired|login|\bauth/],
948
+ [
949
+ "network",
950
+ /network|connect|\bdns\b|\breach|unreachable|offline|econn|socket|\bssl\b|\btls\b|certificate|refused|\bhost\b/,
951
+ ],
952
+ ["permission", /denied|permission|not permitted|read.?only/],
953
+ ["conflict", /conflict|rebase|\bmerge|diverged/],
954
+ ["not-found", /not found|no such|missing|\b404\b|does not exist/],
955
+ ["dispatch", /subagent|dispatch|no agent/],
956
+ ["lock", /\block/],
957
+ ["verification", /verif/],
958
+ ["build", /\bbuild/],
959
+ ["test", /\btests?\b|\bfailing\b/],
960
+ ["approval", /approv/],
961
+ ["maturity", /maturity/],
962
+ ["channels", /channels?/],
963
+ ["awaiting-input", /question|clarif|awaiting|waiting|input|attended/],
964
+ ["validation", /validat|schema|invalid|malformed|parse/],
965
+ ];
966
+
967
+ /** The cause code for a piece of text, or `fallback` when no pattern matches. */
968
+ export function causeCode(text, fallback = "unknown") {
969
+ const t = String(text ?? "").toLowerCase();
970
+ for (const [code, re] of CAUSE_PATTERNS) if (re.test(t)) return code;
971
+ return fallback;
972
+ }
973
+
974
+ /**
975
+ * A halt as `<phase>:<cause>` (or the cause alone when the reason names no
976
+ * phase), a park as the cause the run waits on. Always a value of CAUSE_CODES
977
+ * behind an optional phase number: nothing from the reason text is sent.
663
978
  */
664
979
  function reasonCode(state, status) {
665
980
  if (status === "halted" || status === "failed") {
666
- const hr =
667
- typeof state.haltReason === "string" ? state.haltReason.replace(ABSOLUTE_PATH, " ") : "";
981
+ const hr = typeof state.haltReason === "string" ? state.haltReason : "";
668
982
  if (!hr.trim()) return status === "failed" ? "run-failed" : null;
669
- const m = hr.match(/^\s*(\d+)\s*:(.*)$/);
670
- if (m) {
671
- const cause = codeOf(m[2], 40);
672
- return cause ? `${m[1]}:${cause}` : m[1];
673
- }
674
- return codeOf(hr, 48);
983
+ const m = hr.match(/^\s*(\d{1,2})\s*:(.*)$/s);
984
+ if (m) return `${m[1]}:${causeCode(m[2])}`;
985
+ return causeCode(hr);
675
986
  }
676
987
  if (status === "parked") {
677
- return codeOf(state.waitingFor) || codeOf(state.status) || "awaiting-input";
988
+ return causeCode(state.waitingFor ?? state.status, "awaiting-input");
678
989
  }
679
990
  return null;
680
991
  }
681
992
 
682
- /** Opt-in: a one-line task title with paths, markup and code spans removed. */
993
+ // A ticket-key shape: letters then digits, joined by a hyphen, an underscore,
994
+ // a space or nothing, or a `#number` reference.
995
+ const TICKET_SHAPE = /(?:\p{L}{2,}[-_ ]?\d{2,})|(?:#\d+)/u;
996
+
997
+ /** The text with percent-escapes decoded (a mail address written `a%40b.example` is still one). */
998
+ function safeDecode(text) {
999
+ try {
1000
+ return decodeURIComponent(text);
1001
+ } catch {
1002
+ return text;
1003
+ }
1004
+ }
1005
+
1006
+ /**
1007
+ * Opt-in (`usageLog.includeTitle`): a summary of the task title, never the
1008
+ * title. Free text cannot be scrubbed reliably, so none of it is sent: the
1009
+ * title is normalised (NFKC, so fullwidth and compatibility forms fold to the
1010
+ * plain ones) and reduced to three closed values, `w` the number of words (at
1011
+ * most 99), `k` whether it has a ticket-key shape (letters, then digits, with
1012
+ * a hyphen, underscore, space or nothing between, or a `#number`), and `l` the
1013
+ * language by the shipped common-word lists (`en`, `tr` or `other`).
1014
+ */
683
1015
  export function titleSummary(state, prefs) {
684
1016
  if (prefs?.includeTitle !== true) return null;
685
1017
  const candidates = [
@@ -693,24 +1025,31 @@ export function titleSummary(state, prefs) {
693
1025
  ];
694
1026
  const raw = candidates.find((c) => typeof c === "string" && c.trim());
695
1027
  if (!raw) return null;
696
- const clean = raw
697
- .replace(/`[^`]*`/g, " ")
698
- .replace(ABSOLUTE_PATH, " ")
699
- .replace(/[<>{}[\]`]/g, " ")
700
- .replace(/\s+/g, " ")
701
- .trim();
702
- if (!clean) return null;
703
- return clean.length > 80 ? `${clean.slice(0, 79)}...` : clean;
1028
+ const text = safeDecode(raw).normalize("NFKC");
1029
+ const words = text.split(/\s+/).filter((t) => /[\p{L}\p{N}]/u.test(t));
1030
+ if (!words.length) return null;
1031
+ const bare = words.map((w) => w.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""));
1032
+ const hits = (list) => bare.filter((w) => list.includes(w)).length;
1033
+ const turkishLetters = (text.match(/[ğüşöçıİĞÜŞÖÇ]/g) ?? []).length;
1034
+ const en = hits(TITLE_WORDS.en);
1035
+ const tr = hits(TITLE_WORDS.tr) + turkishLetters;
1036
+ return {
1037
+ w: Math.min(words.length, 99),
1038
+ k: TICKET_SHAPE.test(text),
1039
+ l: tr > en ? "tr" : en > tr ? "en" : "other",
1040
+ };
704
1041
  }
705
1042
 
706
- /** Opt-in: the PR URL, https only. */
1043
+ /** Opt-in: the PR URL, only for a known code host (PR_URL_HOSTS), without credentials, query or fragment. */
707
1044
  export function prUrlOf(state, prefs) {
708
1045
  if (prefs?.includePrUrl !== true) return null;
709
1046
  const url = typeof state.pr === "string" ? state.pr : state.pr?.url;
710
1047
  if (typeof url !== "string") return null;
711
1048
  try {
712
1049
  const u = new URL(url.trim());
713
- return u.protocol === "https:" ? u.href.slice(0, 200) : null;
1050
+ if (u.protocol !== "https:" || u.port || !PR_URL_HOSTS.includes(u.hostname)) return null;
1051
+ const out = `https://${u.hostname}${u.pathname}`;
1052
+ return /^https:\/\/[a-z.]+\/[A-Za-z0-9._~/-]*$/.test(out) && out.length <= 200 ? out : null;
714
1053
  } catch {
715
1054
  return null;
716
1055
  }
@@ -722,25 +1061,28 @@ function hasPr(state) {
722
1061
  }
723
1062
 
724
1063
  function eventTimestamp(state, status) {
725
- if (status === "completed" && state.finishedAt) return state.finishedAt;
726
- return new Date().toISOString();
1064
+ const finished = status === "completed" ? isoTimestamp(state.finishedAt) : null;
1065
+ return finished ?? nowMinute();
727
1066
  }
728
1067
 
729
- function appendErrorLedger(event) {
1068
+ function appendErrorLedger(event, login, rawId, reason) {
730
1069
  if (!event.errs || event.errs.length === 0) return;
731
- const path = join(homedir(), ".claude", "logs", "multi-agent", "errors-ledger.jsonl");
732
1070
  const row = {
733
1071
  t: event.t,
734
- id: event.id,
735
- u: event.u,
1072
+ id: rawId,
1073
+ u: login,
736
1074
  c: event.c,
737
1075
  rp: event.rp,
738
1076
  ph: event.ph,
739
1077
  v: event.v,
740
1078
  errs: event.errs,
1079
+ ...(typeof reason === "string" && reason.trim() ? { reason: reason.slice(0, 500) } : {}),
741
1080
  };
742
1081
  try {
743
- appendFileSync(path, JSON.stringify(row) + "\n");
1082
+ appendLogRow("errors-ledger.jsonl", row, {
1083
+ ...process.env,
1084
+ LOGS_ROOT: join(homedir(), ".claude", "logs", "multi-agent"),
1085
+ });
744
1086
  } catch {
745
1087
  /* logs dir missing or unwritable - never break the run */
746
1088
  }
@@ -754,31 +1096,33 @@ function resolveUser(opts = {}) {
754
1096
  return resolveReportingLogin(opts).login;
755
1097
  }
756
1098
 
757
- function buildEvent(state, { event = null, login = null, health = null } = {}) {
1099
+ const BATCH_ID = /^[0-9a-f]{16}$/;
1100
+
1101
+ function buildEvent(
1102
+ state,
1103
+ { event = null, health = null, runKey = loadRunKey(), cmds = [], cb = null } = {},
1104
+ ) {
1105
+ const cmdRows = commandCounts(cmds);
758
1106
  const spend = trackerSummary(state);
759
1107
  const ctx = deriveContext(state);
760
1108
  const prefs = resolvePrefs();
761
1109
  const st = runStatus(state, event);
762
1110
  const rc = reasonCode(state, st);
763
1111
  const mode = modeOf(state);
764
- const phase =
765
- typeof state.currentPhase === "number" && !Number.isNaN(state.currentPhase)
766
- ? state.currentPhase
767
- : null;
1112
+ const phase = phaseNumber(state.currentPhase);
768
1113
  return {
769
- id: runId(state),
1114
+ id: runIdDigest(runId(state), runKey),
770
1115
  ev: EVENT_KINDS.includes(event) ? event : null,
771
1116
  t: eventTimestamp(state, st),
772
- t0: state.startedAt || spend.startedAt || null,
773
- u: login,
1117
+ t0: isoTimestamp(state.startedAt) ?? spend.startedAt ?? null,
774
1118
  c: commandOf(state, mode),
775
1119
  m: mode,
776
- tt: codeOf(state.taskType, 30),
1120
+ tt: oneOf(state.taskType, TASK_TYPES),
777
1121
  ap: Boolean(state.autopilot),
778
1122
  lo: Boolean(state.localMode),
779
1123
  in: inputType(state),
780
- rp: projectDigest(state.project),
781
- ph: state._phaseOverride ?? spend.current ?? phase,
1124
+ rp: projectDigest(state.project, runKey),
1125
+ ph: phaseNumber(state._phaseOverride) ?? spend.current ?? phase,
782
1126
  st,
783
1127
  hr: st === "halted" || st === "failed" ? rc : null,
784
1128
  rc,
@@ -797,12 +1141,15 @@ function buildEvent(state, { event = null, login = null, health = null } = {}) {
797
1141
  stack: ctx.stack,
798
1142
  plug: ctx.plug,
799
1143
  apps: ctx.apps,
1144
+ tools: ctx.tools,
800
1145
  creds: ctx.creds,
801
1146
  services: ctx.services,
802
1147
  ...(health ? { health } : {}),
803
1148
  calls: ctx.calls,
1149
+ cmds: cmdRows,
1150
+ ...(cmdRows.length && BATCH_ID.test(String(cb)) ? { cb } : {}),
804
1151
  errs: deriveErrors(state, spend.failed),
805
- v: packageVersion(),
1152
+ v: versionOrUnknown(packageVersion()),
806
1153
  };
807
1154
  }
808
1155
 
@@ -826,14 +1173,13 @@ async function post(endpoint, token, event) {
826
1173
  body: JSON.stringify(event),
827
1174
  timeoutMs: TIMEOUT_MS,
828
1175
  });
829
- const via = r.fetchFailure ? { transport: r.transport, fetchFailure: r.fetchFailure } : {};
830
1176
  if (r.failure) {
831
- return { outcome: "failed", reason: codeOf(String(r.failure), 40), ...via };
1177
+ return { outcome: "failed", reason: codeOf(String(r.failure), 40) };
832
1178
  }
833
1179
  if (r.status >= 300 && r.status < 400) {
834
- return { outcome: "redirected", status: r.status, location: hostOf(r.location || ""), ...via };
1180
+ return { outcome: "redirected", status: r.status, location: hostOf(r.location || "") };
835
1181
  }
836
- if (r.status < 200 || r.status >= 300) return { outcome: "rejected", status: r.status, ...via };
1182
+ if (r.status < 200 || r.status >= 300) return { outcome: "rejected", status: r.status };
837
1183
  let body = null;
838
1184
  try {
839
1185
  body = JSON.parse(r.body);
@@ -845,7 +1191,6 @@ async function post(endpoint, token, event) {
845
1191
  outcome: body?.accepted === false ? "not-accepted" : "accepted",
846
1192
  status: r.status,
847
1193
  ...(held ? { reason: "pending_approval" } : {}),
848
- ...via,
849
1194
  };
850
1195
  }
851
1196
 
@@ -888,15 +1233,26 @@ function endpointAllowed(endpoint) {
888
1233
  return false;
889
1234
  }
890
1235
 
1236
+ // The ingest token rides in the request, so the host is held to the rule
1237
+ // registration applies: the reporting site's own hosts or usageLog.trustedHosts
1238
+ // over https, loopback over http.
1239
+ function sendAllowed(endpoint, prefs) {
1240
+ return endpointAllowed(endpoint) && registerUrlAllowed(endpoint, prefs?.trustedHosts || []);
1241
+ }
1242
+
891
1243
  /**
892
1244
  * Send an install or update record when the installed version (from the
893
1245
  * installer's stamp) is not the last one reported, and move
894
1246
  * `usageLog.reportedVersion` forward once the server accepted it.
895
1247
  */
896
- async function reportInstalledVersion(endpoint, token, login, usageLog) {
1248
+ export function lifecycleBody(e) {
1249
+ return { ...e, os: detectOs(), cli: detectCli() };
1250
+ }
1251
+
1252
+ async function reportInstalledVersion(endpoint, token, usageLog) {
897
1253
  const e = lifecycleEvent({ installed: installedVersion(homedir()), usageLog });
898
1254
  if (!e) return;
899
- const r = await post(endpoint, token, { ...e, u: login, os: detectOs(), cli: detectCli() });
1255
+ const r = await post(endpoint, token, lifecycleBody(e));
900
1256
  if (r.outcome !== "accepted") return;
901
1257
  try {
902
1258
  updateJsonFileSync(
@@ -1025,6 +1381,23 @@ async function main() {
1025
1381
  if (path) process.stdout.write(`${path}\n`);
1026
1382
  return;
1027
1383
  }
1384
+ if (!args.dryRun) syncCountingSentinel(process.env);
1385
+ if (args.detach && !args.dryRun && shouldDetach(process.argv.slice(2))) {
1386
+ detachSelf(fileURLToPath(import.meta.url), process.argv.slice(2));
1387
+ return;
1388
+ }
1389
+ // On a machine that has not registered yet the first report has no token.
1390
+ // Registering here, in the same process and before anything is read, fixes
1391
+ // the order: the registration finishes, then the report goes out with the
1392
+ // token it stored. Registration honours optOut and defers in a sandbox.
1393
+ if (args.registerFirst && !args.dryRun) {
1394
+ try {
1395
+ const { register } = await import(pathToFileURL(join(__dirname, "usage-register.mjs")).href);
1396
+ await register(["--quiet"]);
1397
+ } catch {
1398
+ /* a failed registration leaves the report to skip for lack of a token */
1399
+ }
1400
+ }
1028
1401
  const prefs = resolvePrefs();
1029
1402
  const endpoint = canonicalEndpoint(prefs.endpoint || DEFAULT_ENDPOINT);
1030
1403
 
@@ -1034,7 +1407,7 @@ async function main() {
1034
1407
  if (!args.dryRun) {
1035
1408
  if (prefs.optOut === true) return;
1036
1409
  if (prefs.enabled !== true) return;
1037
- if (!endpointAllowed(endpoint)) {
1410
+ if (!sendAllowed(endpoint, prefs)) {
1038
1411
  recordSend({ id: args.taskId, outcome: "skipped", reason: "endpoint-not-allowed" });
1039
1412
  return;
1040
1413
  }
@@ -1048,7 +1421,7 @@ async function main() {
1048
1421
  if (args.lifecycle) {
1049
1422
  if (args.dryRun) return;
1050
1423
  const who = reportingLogin(prefs);
1051
- if (who.login) await reportInstalledVersion(endpoint, token, who.login, prefs);
1424
+ if (who.login) await reportInstalledVersion(endpoint, token, prefs);
1052
1425
  return;
1053
1426
  }
1054
1427
 
@@ -1085,37 +1458,65 @@ async function main() {
1085
1458
  }
1086
1459
  }
1087
1460
 
1461
+ // The machine counter is per host session; this run's share starts at the
1462
+ // counts the session had when the run was first reported. Written once per
1463
+ // run, never by a dry run.
1464
+ if (!args.dryRun) {
1465
+ foldCalls(process.env);
1466
+ runCalls({ runId: runId(state), sessionId: state.hostSessionId, establish: true });
1467
+ }
1468
+
1469
+ // A dry run never reads, creates or repairs the secret: it shows the shape of the
1470
+ // record with a throwaway one, so its id is not the id a real send would carry.
1471
+ const runKey = args.dryRun ? randomBytes(32).toString("hex") : loadRunKey();
1472
+ if (!args.dryRun && !runKey && runId(state) != null) {
1473
+ recordSend({ id: runId(state), ev: kind, outcome: "skipped", reason: "run-key-unavailable" });
1474
+ return;
1475
+ }
1476
+
1088
1477
  // A dry run reads the cached health summary only. A real send waits, at most
1089
1478
  // usage-health's WAIT_MS, only when it starts the refresh itself.
1090
1479
  const health = await machineHealth({
1091
1480
  lang: resolveGlobalPrefs().outputLanguage ?? "en",
1092
1481
  ...(args.dryRun ? { refresh: null } : {}),
1093
1482
  });
1094
- const event = buildEvent(state, { event: kind, login: who.login, health });
1483
+ // The typed-command counts ride on this send. A real send claims them (one
1484
+ // batch, handed to one sender at a time) and acknowledges the batch only once
1485
+ // the server accepted the record; a dry run only looks.
1486
+ const batch = args.dryRun
1487
+ ? { id: randomBytes(8).toString("hex"), cmds: peekCommands(process.env) }
1488
+ : claimCommands(process.env);
1489
+ const event = buildEvent(state, { event: kind, health, runKey, cmds: batch.cmds, cb: batch.id });
1095
1490
 
1096
1491
  if (args.dryRun) {
1097
1492
  process.stdout.write(JSON.stringify(event, null, 2) + "\n");
1098
1493
  return;
1099
1494
  }
1100
1495
 
1101
- if (event.st !== "in_progress") appendErrorLedger(event);
1496
+ if (event.st !== "in_progress")
1497
+ appendErrorLedger(event, who.login, runId(state), state.haltReason);
1102
1498
  let sendToken = token;
1103
- let result = await post(endpoint, sendToken, event);
1499
+ let result = { outcome: "failed" };
1104
1500
  let heal = {};
1105
- if (result.outcome === "rejected" && result.status === 401) {
1106
- const healed = await selfHeal(token);
1107
- heal = { first: { outcome: result.outcome, status: result.status }, ...healed.record };
1108
- if (healed.token) {
1109
- sendToken = healed.token;
1110
- result = await post(endpoint, sendToken, event);
1111
- heal.healed = result.outcome === "accepted";
1112
- } else {
1113
- heal.healed = false;
1501
+ try {
1502
+ result = await post(endpoint, sendToken, event);
1503
+ if (result.outcome === "rejected" && result.status === 401) {
1504
+ const healed = await selfHeal(token);
1505
+ heal = { first: { outcome: result.outcome, status: result.status }, ...healed.record };
1506
+ if (healed.token) {
1507
+ sendToken = healed.token;
1508
+ result = await post(endpoint, sendToken, event);
1509
+ heal.healed = result.outcome === "accepted";
1510
+ } else {
1511
+ heal.healed = false;
1512
+ }
1114
1513
  }
1514
+ } finally {
1515
+ if (result.outcome === "accepted") ackCommands(batch.id, process.env);
1516
+ else releaseCommands(batch.id, process.env);
1115
1517
  }
1116
- recordSend({ id: event.id, ev: event.ev, host: hostOf(endpoint), ...result, ...heal });
1117
- if (result.outcome === "accepted")
1118
- await reportInstalledVersion(endpoint, sendToken, who.login, prefs);
1518
+ recordSend({ id: runId(state), ev: event.ev, host: hostOf(endpoint), ...result, ...heal });
1519
+ if (result.outcome === "accepted") await reportInstalledVersion(endpoint, sendToken, prefs);
1119
1520
  if (result.outcome !== "accepted") {
1120
1521
  const detail = result.status ?? result.reason;
1121
1522
  const where = result.location ? ` to ${result.location}` : "";
@@ -1143,7 +1544,6 @@ if (invokedDirectly) {
1143
1544
 
1144
1545
  export {
1145
1546
  endpointAllowed,
1146
- invokedCalls,
1147
1547
  integrationTags,
1148
1548
  enabledPlugins,
1149
1549
  readEnabledPluginNames,
@@ -1152,4 +1552,5 @@ export {
1152
1552
  resolveUser,
1153
1553
  runStatus,
1154
1554
  reasonCode,
1555
+ runIdDigest,
1155
1556
  };