@mmerterden/multi-agent-pipeline 23.2.0 → 23.4.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 (230) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +6 -6
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +229 -161
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/fable-status/SKILL.md +1 -1
  21. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  22. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  23. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  24. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  25. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  26. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  27. package/pipeline/contract/CHANGELOG.md +49 -0
  28. package/pipeline/contract/build.mjs +13 -1
  29. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  30. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  31. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  32. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  33. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  34. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  35. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  36. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  37. package/pipeline/contract/fixtures/runs-running.json +4 -1
  38. package/pipeline/contract/manifest.json +28 -15
  39. package/pipeline/contract/types/index.d.ts +55 -3
  40. package/pipeline/lib/detach-self.mjs +95 -0
  41. package/pipeline/lib/model-rung.sh +1 -1
  42. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  43. package/pipeline/lib/rotated-log.mjs +93 -0
  44. package/pipeline/lib/tls-trust.mjs +29 -0
  45. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  46. package/pipeline/lib/usage-names.generated.mjs +614 -0
  47. package/pipeline/lib/usage-run-key.mjs +235 -0
  48. package/pipeline/lib/usage-vocab.mjs +210 -0
  49. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  50. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  51. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  52. package/pipeline/multi-agent-refs/cross-cli-contract.md +4 -4
  53. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  54. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  55. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  56. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  57. package/pipeline/multi-agent-refs/features/model-fallback.md +9 -7
  58. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  59. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  60. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  61. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  62. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  63. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  64. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  65. package/pipeline/multi-agent-refs/help/en.md +3 -2
  66. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  67. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  68. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +1 -1
  69. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  70. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  71. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  72. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  73. package/pipeline/multi-agent-refs/phases/phase-3-review.md +5 -3
  74. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  75. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  76. package/pipeline/multi-agent-refs/review/panel.md +1 -1
  77. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  78. package/pipeline/office/index.html +1207 -233
  79. package/pipeline/office/toolkit.json +1 -1
  80. package/pipeline/rules/outside-the-pipeline.md +1 -1
  81. package/pipeline/schemas/activity.schema.json +23 -0
  82. package/pipeline/schemas/agent-state.schema.json +6 -1
  83. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  84. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  85. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  86. package/pipeline/schemas/code-graph.schema.json +2 -2
  87. package/pipeline/schemas/examples/design-check-config.json +27 -0
  88. package/pipeline/schemas/learning-curve.schema.json +67 -0
  89. package/pipeline/schemas/office-jobs.json +69 -2
  90. package/pipeline/schemas/office-jobs.schema.json +8 -1
  91. package/pipeline/schemas/phases.json +5 -0
  92. package/pipeline/schemas/phases.schema.json +8 -0
  93. package/pipeline/schemas/prefs.schema.json +46 -12
  94. package/pipeline/schemas/runs-index.schema.json +17 -0
  95. package/pipeline/schemas/toolkit-path-params.json +84 -8
  96. package/pipeline/scripts/README.md +1 -0
  97. package/pipeline/scripts/_code-graph.mjs +184 -103
  98. package/pipeline/scripts/_contract-core.mjs +1 -1
  99. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  100. package/pipeline/scripts/_diff-impact.mjs +21 -2
  101. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  102. package/pipeline/scripts/_http-post.mjs +103 -115
  103. package/pipeline/scripts/_safe-read.mjs +57 -0
  104. package/pipeline/scripts/_skill-practices.mjs +26 -0
  105. package/pipeline/scripts/_strip-code.mjs +380 -0
  106. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  107. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  108. package/pipeline/scripts/call-graph/index.mjs +78 -0
  109. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  110. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  111. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  112. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  113. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  114. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  115. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  116. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  117. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  118. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  119. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  120. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  121. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  122. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  123. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  124. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  125. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  126. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  127. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  128. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  129. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  130. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  131. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  132. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  133. package/pipeline/scripts/contract-server.mjs +1 -0
  134. package/pipeline/scripts/cost-table.json +6 -5
  135. package/pipeline/scripts/feedback-send.mjs +26 -26
  136. package/pipeline/scripts/gate-ledger.mjs +2 -1
  137. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  138. package/pipeline/scripts/graph-affected.mjs +109 -20
  139. package/pipeline/scripts/graph-build.mjs +95 -15
  140. package/pipeline/scripts/graph-export.mjs +272 -0
  141. package/pipeline/scripts/graph-hint.mjs +15 -2
  142. package/pipeline/scripts/graph-query.mjs +305 -26
  143. package/pipeline/scripts/graph-report.mjs +187 -1
  144. package/pipeline/scripts/health-report.mjs +3 -4
  145. package/pipeline/scripts/infra/docs.mjs +317 -0
  146. package/pipeline/scripts/infra/extract.mjs +998 -0
  147. package/pipeline/scripts/infra/graph.mjs +245 -0
  148. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  149. package/pipeline/scripts/job-launch.mjs +67 -2
  150. package/pipeline/scripts/learning-curve.mjs +288 -178
  151. package/pipeline/scripts/log-metric.sh +10 -1
  152. package/pipeline/scripts/note-agent-event.mjs +3 -4
  153. package/pipeline/scripts/note-command-use.mjs +333 -0
  154. package/pipeline/scripts/note-command-use.sh +126 -0
  155. package/pipeline/scripts/note-mcp-call.sh +89 -0
  156. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  157. package/pipeline/scripts/note-session.sh +62 -3
  158. package/pipeline/scripts/note-skill-use.mjs +58 -2
  159. package/pipeline/scripts/office-build.mjs +115 -1
  160. package/pipeline/scripts/office-memory.mjs +14 -5
  161. package/pipeline/scripts/pair.mjs +333 -0
  162. package/pipeline/scripts/pre-push-check.sh +1 -1
  163. package/pipeline/scripts/remote/cbor.mjs +128 -0
  164. package/pipeline/scripts/remote/contract.mjs +98 -0
  165. package/pipeline/scripts/remote/handler.mjs +317 -0
  166. package/pipeline/scripts/remote/handles.mjs +57 -0
  167. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  168. package/pipeline/scripts/remote/listener.mjs +204 -0
  169. package/pipeline/scripts/remote/lockout.mjs +103 -0
  170. package/pipeline/scripts/remote/nonces.mjs +61 -0
  171. package/pipeline/scripts/remote/pairing.mjs +519 -0
  172. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  173. package/pipeline/scripts/remote/store.mjs +188 -0
  174. package/pipeline/scripts/remote/transport.mjs +211 -0
  175. package/pipeline/scripts/remote/verbs.json +70 -0
  176. package/pipeline/scripts/remote/verbs.mjs +217 -0
  177. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  178. package/pipeline/scripts/remote/wire.mjs +364 -0
  179. package/pipeline/scripts/remote-listener.mjs +83 -0
  180. package/pipeline/scripts/route-learn.mjs +4 -4
  181. package/pipeline/scripts/run-kill.mjs +1 -1
  182. package/pipeline/scripts/run-write.mjs +13 -2
  183. package/pipeline/scripts/runs-index.mjs +30 -3
  184. package/pipeline/scripts/search-logs.sh +9 -0
  185. package/pipeline/scripts/session-brief.mjs +458 -0
  186. package/pipeline/scripts/session-brief.sh +130 -0
  187. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  188. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  189. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  190. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  191. package/pipeline/scripts/token-budget-report.mjs +3 -2
  192. package/pipeline/scripts/uninstall.mjs +29 -0
  193. package/pipeline/scripts/usage-access.mjs +16 -31
  194. package/pipeline/scripts/usage-health.mjs +31 -62
  195. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  196. package/pipeline/scripts/usage-register.mjs +39 -29
  197. package/pipeline/scripts/usage-report.mjs +579 -178
  198. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  199. package/pipeline/scripts/write-state.mjs +39 -0
  200. package/pipeline/skills/.skill-manifest.json +22 -18
  201. package/pipeline/skills/.skills-index.json +13 -2
  202. package/pipeline/skills/shared/README.md +5 -4
  203. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  204. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  205. package/pipeline/skills/shared/core/multi-agent-fable-status/SKILL.md +1 -1
  206. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  207. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  208. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  209. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  210. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  211. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  212. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  213. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  214. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  215. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  216. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  217. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  218. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  219. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  220. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  221. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  222. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  223. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  224. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  225. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  226. package/pipeline/skills/skills-index.md +3 -2
  227. package/docs/FIGMA_PIPELINE.md +0 -137
  228. package/pipeline/lib/identifier-scan.mjs +0 -156
  229. package/pipeline/scripts/publish-staged.mjs +0 -324
  230. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -19,204 +19,314 @@
19
19
  //
20
20
  // Exit: 0 always (advisory; empty/missing metrics -> friendly note).
21
21
 
22
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
22
+ import { writeFileSync } from "node:fs";
23
23
  import { homedir } from "node:os";
24
24
  import { join } from "node:path";
25
25
 
26
- const args = process.argv.slice(2);
27
- const opts = { json: false, markdown: false, since: null, bucketDays: 7 };
28
- for (const a of args) {
29
- if (a === "--json") opts.json = true;
30
- else if (a === "--markdown" || a === "--md") opts.markdown = true;
31
- else if (a.startsWith("--since=")) opts.since = a.slice(8);
32
- else if (a.startsWith("--bucket=")) opts.bucketDays = Math.max(1, parseInt(a.slice(9), 10) || 7);
33
- else if (a === "--help" || a === "-h") {
34
- console.log("Usage: learning-curve.mjs [--bucket=<days>] [--since=ISO] [--json|--markdown]");
35
- process.exit(0);
36
- }
37
- }
26
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
27
+ import { DEFAULT_MAX_BYTES, RegularFileError, readRegularFile } from "../lib/regular-file.mjs";
28
+ import { rotatedPaths, signature } from "../lib/rotated-log.mjs";
38
29
 
39
- const METRICS_FILE =
30
+ export const CONTRACT_VERSION = "1.1.0";
31
+
32
+ const DEFAULT_METRICS_FILE = () =>
40
33
  process.env.METRICS_FILE || join(homedir(), ".claude", "logs", "multi-agent", "metrics.jsonl");
41
34
 
42
- // Called from module scope and has to stop the script, so the write goes to
43
- // fd 1 synchronously: console.log would still be in the pipe when process.exit
44
- // tore the process down.
45
- function emitEmpty(reason) {
46
- if (opts.json) writeFileSync(1, `${JSON.stringify({ ok: false, reason, buckets: [] })}\n`);
47
- else console.error(`learning-curve: ${reason}`);
48
- process.exit(0);
35
+ /**
36
+ * The metrics log's text, previous generation first: each generation is a
37
+ * regular file no larger than `maxBytes`, read through the bounded reader so a
38
+ * link, a FIFO or a huge file cannot stall or exhaust the process that serves
39
+ * the curve. A generation over the cap is skipped and named in `skipped`
40
+ * ("previous" or "current"); the read only fails as too large when no
41
+ * generation could be read. This is the one place the log is read.
42
+ *
43
+ * @param {string} file
44
+ * @param {number} [maxBytes]
45
+ * @returns {{text: string, skipped: string[]}}
46
+ * @throws {RegularFileError}
47
+ */
48
+ export function readMetricsText(file, maxBytes = DEFAULT_MAX_BYTES) {
49
+ const generations = rotatedPaths(file);
50
+ if (generations.length === 0) {
51
+ return { text: readRegularFile(file, { maxBytes, noFollow: true }), skipped: [] };
52
+ }
53
+ const texts = [];
54
+ const skipped = [];
55
+ let refusal = null;
56
+ for (const p of generations) {
57
+ try {
58
+ texts.push(readRegularFile(p, { maxBytes, noFollow: true }));
59
+ } catch (err) {
60
+ if (!(err instanceof RegularFileError) || err.code !== "too-large") throw err;
61
+ refusal = err;
62
+ skipped.push(p === file ? "current" : "previous");
63
+ }
64
+ }
65
+ if (texts.length === 0) throw refusal;
66
+ return { text: texts.join("\n"), skipped };
49
67
  }
50
68
 
51
- if (!existsSync(METRICS_FILE)) emitEmpty(`no metrics file at ${METRICS_FILE}`);
69
+ const REFUSALS = { missing: "no-metrics", "too-large": "too-large" };
52
70
 
53
- const events = [];
54
- for (const line of readFileSync(METRICS_FILE, "utf-8").split("\n")) {
55
- if (!line.trim()) continue;
71
+ /**
72
+ * The curve over a metrics file: one bucket per window of days, and the first
73
+ * to last trend. `ok` is false, with `code` and `reason`, when there is
74
+ * nothing to fold; the CLI prints the reason, a server answers with the code.
75
+ *
76
+ * @param {{metricsFile?: string, bucketDays?: number, since?: string|null}} [opts]
77
+ */
78
+ export function learningCurve({
79
+ metricsFile = DEFAULT_METRICS_FILE(),
80
+ bucketDays = 7,
81
+ since = null,
82
+ maxBytes = DEFAULT_MAX_BYTES,
83
+ } = {}) {
84
+ let text;
85
+ let skipped;
56
86
  try {
57
- const e = JSON.parse(line);
58
- if (opts.since && e.ts && e.ts < opts.since) continue;
59
- events.push(e);
60
- } catch {
61
- /* skip corrupted line */
87
+ ({ text, skipped } = readMetricsText(metricsFile, maxBytes));
88
+ } catch (err) {
89
+ if (!(err instanceof RegularFileError)) throw err;
90
+ const code = REFUSALS[err.code] ?? "no-metrics";
91
+ const reason =
92
+ code === "too-large"
93
+ ? `the metrics file is larger than ${maxBytes} bytes: ${metricsFile}`
94
+ : `no metrics file at ${metricsFile}`;
95
+ return { ok: false, code, reason, buckets: [] };
62
96
  }
63
- }
64
- if (events.length === 0) emitEmpty("no metrics events in range");
65
-
66
- // Fold events into per-task aggregates.
67
- const num = (v) => (typeof v === "number" ? v : Number(v)) || 0;
68
- const tasks = new Map();
69
- for (const e of events) {
70
- const id = e.task_id;
71
- if (!id) continue;
72
- let t = tasks.get(id);
73
- if (!t) {
74
- t = {
75
- firstTs: e.ts,
76
- reviewCycles: null,
77
- rework: 0,
78
- tokensIn: 0,
79
- tokensOut: 0,
80
- tokensCached: 0,
81
- memInjected: 0,
82
- memUsed: 0,
83
- minedLessons: 0,
84
- offloadSaved: 0,
97
+
98
+ const events = [];
99
+ for (const line of text.split("\n")) {
100
+ if (!line.trim()) continue;
101
+ try {
102
+ const e = JSON.parse(line);
103
+ if (since && e.ts && e.ts < since) continue;
104
+ events.push(e);
105
+ } catch {
106
+ /* skip corrupted line */
107
+ }
108
+ }
109
+ if (events.length === 0)
110
+ return { ok: false, code: "no-events", reason: "no metrics events in range", buckets: [] };
111
+
112
+ // Fold events into per-task aggregates.
113
+ const num = (v) => (typeof v === "number" ? v : Number(v)) || 0;
114
+ const tasks = new Map();
115
+ for (const e of events) {
116
+ const id = e.task_id;
117
+ if (!id) continue;
118
+ let t = tasks.get(id);
119
+ if (!t) {
120
+ t = {
121
+ firstTs: e.ts,
122
+ reviewCycles: null,
123
+ rework: 0,
124
+ tokensIn: 0,
125
+ tokensOut: 0,
126
+ tokensCached: 0,
127
+ memInjected: 0,
128
+ memUsed: 0,
129
+ minedLessons: 0,
130
+ offloadSaved: 0,
131
+ };
132
+ tasks.set(id, t);
133
+ }
134
+ if (e.ts && (!t.firstTs || e.ts < t.firstTs)) t.firstTs = e.ts;
135
+ const d = e.details || {};
136
+ // The review step's review.completed event carries no cycle count. Phase 4
137
+ // runs the review again, and logs its own review.completed, once per rework
138
+ // cycle, so a task's cycle count is how many review.completed events share
139
+ // its task_id (aggregate-metrics.mjs derives it the same way).
140
+ if (e.event === "review.completed") t.reviewCycles = (t.reviewCycles ?? 0) + 1;
141
+ if (e.event === "rework.started") t.rework += 1;
142
+ // Recall precision: how much of the memory a run was given it actually used.
143
+ // Without this pair the ranking is unfalsifiable - a change that injects
144
+ // better-ranked rows and a change that injects noise both look like "5 hits".
145
+ if (e.event === "memory.injected") t.memInjected += num(d.rows);
146
+ // Phase 4 records "zero cited" as a legitimate answer, so a present rows=0
147
+ // counts as zero hits; only an absent rows field means one hit (the event
148
+ // itself happened).
149
+ if (e.event === "memory.hit") t.memUsed += d.rows === undefined ? 1 : num(d.rows);
150
+ // Mined lessons and offloaded bytes are counted apart from the
151
+ // model-written lessons: a machine-mined path correction and a model's
152
+ // architectural claim are different evidence, so one combined number would
153
+ // hide which half moves.
154
+ if (e.event === "learning.mined") t.minedLessons += d.rows === undefined ? 1 : num(d.rows);
155
+ if (e.event === "offload.crushed") t.offloadSaved += num(d.saved_bytes);
156
+ t.tokensIn += num(d.tokens_in);
157
+ t.tokensOut += num(d.tokens_out);
158
+ t.tokensCached += num(d.tokens_cached);
159
+ }
160
+
161
+ // Bucket tasks by the local calendar day of their first event. A window of
162
+ // whole weeks starts on a Monday (epoch day 4 is a Monday); any other window
163
+ // counts from the epoch. The bucket is named by the local date it starts on.
164
+ const DAY = 86400000;
165
+ const origin = bucketDays % 7 === 0 ? 4 : 0;
166
+ const bucketOf = (ts) => {
167
+ const ms = Date.parse(ts);
168
+ if (Number.isNaN(ms)) return null;
169
+ const local = ms - new Date(ms).getTimezoneOffset() * 60000;
170
+ const dayIndex = Math.floor(local / DAY);
171
+ const b = origin + Math.floor((dayIndex - origin) / bucketDays) * bucketDays;
172
+ return new Date(b * DAY).toISOString().slice(0, 10);
173
+ };
174
+
175
+ const byBucket = new Map();
176
+ for (const t of tasks.values()) {
177
+ const key = bucketOf(t.firstTs);
178
+ if (!key) continue;
179
+ if (!byBucket.has(key)) byBucket.set(key, []);
180
+ byBucket.get(key).push(t);
181
+ }
182
+
183
+ const round = (n, p = 2) => Math.round(n * 10 ** p) / 10 ** p;
184
+ const buckets = [...byBucket.keys()].sort().map((start) => {
185
+ const list = byBucket.get(start);
186
+ const n = list.length;
187
+ const withReview = list.filter((t) => t.reviewCycles != null);
188
+ const firstPassClean = withReview.filter((t) => t.reviewCycles <= 1).length;
189
+ const totIn = list.reduce((s, t) => s + t.tokensIn, 0);
190
+ const totOut = list.reduce((s, t) => s + t.tokensOut, 0);
191
+ const totCached = list.reduce((s, t) => s + t.tokensCached, 0);
192
+ const totInjected = list.reduce((s, t) => s + t.memInjected, 0);
193
+ const totUsed = list.reduce((s, t) => s + t.memUsed, 0);
194
+ const totMined = list.reduce((s, t) => s + t.minedLessons, 0);
195
+ const totSaved = list.reduce((s, t) => s + t.offloadSaved, 0);
196
+ return {
197
+ bucketStart: start,
198
+ tasks: n,
199
+ firstPassCleanRate: withReview.length ? round(firstPassClean / withReview.length) : null,
200
+ avgReviewCycles: withReview.length
201
+ ? round(withReview.reduce((s, t) => s + t.reviewCycles, 0) / withReview.length)
202
+ : null,
203
+ reworkPerTask: round(list.reduce((s, t) => s + t.rework, 0) / n),
204
+ tokensPerTask: Math.round((totIn + totOut) / n),
205
+ cacheRatio: totIn + totCached ? round(totCached / (totIn + totCached)) : null,
206
+ memoryPrecision: totInjected ? round(totUsed / totInjected) : null,
207
+ // null, not 0, when nothing was recorded: "no data" and "measured zero" are
208
+ // different answers, and a chart draws them differently.
209
+ minedLessonsPerTask: totMined ? round(totMined / n) : null,
210
+ offloadBytesSavedPerTask: totSaved ? Math.round(totSaved / n) : null,
211
+ };
212
+ });
213
+
214
+ // first->last trend for the headline KPIs (only when >=2 buckets).
215
+ let trend = null;
216
+ if (buckets.length >= 2) {
217
+ const a = buckets[0];
218
+ const z = buckets[buckets.length - 1];
219
+ const delta = (x, y) => (x == null || y == null ? null : round(y - x));
220
+ trend = {
221
+ from: a.bucketStart,
222
+ to: z.bucketStart,
223
+ firstPassCleanRate: delta(a.firstPassCleanRate, z.firstPassCleanRate),
224
+ avgReviewCycles: delta(a.avgReviewCycles, z.avgReviewCycles),
225
+ tokensPerTask: a.tokensPerTask && z.tokensPerTask ? z.tokensPerTask - a.tokensPerTask : null,
226
+ cacheRatio: delta(a.cacheRatio, z.cacheRatio),
227
+ memoryPrecision: delta(a.memoryPrecision, z.memoryPrecision),
85
228
  };
86
- tasks.set(id, t);
87
229
  }
88
- if (e.ts && (!t.firstTs || e.ts < t.firstTs)) t.firstTs = e.ts;
89
- const d = e.details || {};
90
- // phase-3-review.md's actual review.completed emission (raw_count=/
91
- // accepted=/deferred=/rejected=/approved=/duration_ms=) carries no
92
- // review_cycles field - that name only appears on Phase 5's task.completed
93
- // summary event, which this never matched. Phase 4 re-runs (and logs its
94
- // own review.completed) once per rework cycle, so the cycle count for a
95
- // task is how many review.completed events share its task_id - the same
96
- // derivation aggregate-metrics.mjs already uses for this metric.
97
- if (e.event === "review.completed") t.reviewCycles = (t.reviewCycles ?? 0) + 1;
98
- if (e.event === "rework.started") t.rework += 1;
99
- // Recall precision: how much of the memory a run was given it actually used.
100
- // Without this pair the ranking is unfalsifiable - a change that injects
101
- // better-ranked rows and a change that injects noise both look like "5 hits".
102
- if (e.event === "memory.injected") t.memInjected += num(d.rows);
103
- // `num(d.rows) || 1` turned an explicit rows=0 into one hit, and phase-4
104
- // documents zero-cited as a legitimate answer - so the metric lied in exactly
105
- // the case the instruction invites. An ABSENT rows field still means one hit
106
- // (the event happened); a present zero means zero.
107
- if (e.event === "memory.hit") t.memUsed += d.rows === undefined ? 1 : num(d.rows);
108
- // Two things the loop learned to count once the pipeline started producing
109
- // them. They are kept apart from the model-written lessons on purpose: a
110
- // machine-mined path correction and a model's architectural claim are
111
- // different evidence, and a single "lessons learned" number can climb while
112
- // the half that actually helps stays flat.
113
- if (e.event === "learning.mined") t.minedLessons += d.rows === undefined ? 1 : num(d.rows);
114
- if (e.event === "offload.crushed") t.offloadSaved += num(d.saved_bytes);
115
- t.tokensIn += num(d.tokens_in);
116
- t.tokensOut += num(d.tokens_out);
117
- t.tokensCached += num(d.tokens_cached);
118
- }
119
230
 
120
- // Bucket tasks by first-seen day / bucketDays window (UTC).
121
- const DAY = 86400000;
122
- const bucketOf = (ts) => {
123
- const ms = Date.parse(ts);
124
- if (Number.isNaN(ms)) return null;
125
- const dayIndex = Math.floor(ms / DAY);
126
- const b = Math.floor(dayIndex / opts.bucketDays) * opts.bucketDays;
127
- return new Date(b * DAY).toISOString().slice(0, 10);
128
- };
129
-
130
- const byBucket = new Map();
131
- for (const t of tasks.values()) {
132
- const key = bucketOf(t.firstTs);
133
- if (!key) continue;
134
- if (!byBucket.has(key)) byBucket.set(key, []);
135
- byBucket.get(key).push(t);
231
+ return { ok: true, bucketDays, buckets, trend, ...(skipped.length ? { skipped } : {}) };
136
232
  }
137
233
 
138
- const round = (n, p = 2) => Math.round(n * 10 ** p) / 10 ** p;
139
- const buckets = [...byBucket.keys()].sort().map((start) => {
140
- const list = byBucket.get(start);
141
- const n = list.length;
142
- const withReview = list.filter((t) => t.reviewCycles != null);
143
- const firstPassClean = withReview.filter((t) => t.reviewCycles <= 1).length;
144
- const totIn = list.reduce((s, t) => s + t.tokensIn, 0);
145
- const totOut = list.reduce((s, t) => s + t.tokensOut, 0);
146
- const totCached = list.reduce((s, t) => s + t.tokensCached, 0);
147
- const totInjected = list.reduce((s, t) => s + t.memInjected, 0);
148
- const totUsed = list.reduce((s, t) => s + t.memUsed, 0);
149
- const totMined = list.reduce((s, t) => s + t.minedLessons, 0);
150
- const totSaved = list.reduce((s, t) => s + t.offloadSaved, 0);
151
- return {
152
- bucketStart: start,
153
- tasks: n,
154
- firstPassCleanRate: withReview.length ? round(firstPassClean / withReview.length) : null,
155
- avgReviewCycles: withReview.length
156
- ? round(withReview.reduce((s, t) => s + t.reviewCycles, 0) / withReview.length)
157
- : null,
158
- reworkPerTask: round(list.reduce((s, t) => s + t.rework, 0) / n),
159
- tokensPerTask: Math.round((totIn + totOut) / n),
160
- cacheRatio: totIn + totCached ? round(totCached / (totIn + totCached)) : null,
161
- memoryPrecision: totInjected ? round(totUsed / totInjected) : null,
162
- // null, not 0, when nothing was recorded: "no data" and "measured zero" are
163
- // different answers, and a chart that draws them the same way invites the
164
- // wrong conclusion about a feature that was simply never switched on.
165
- minedLessonsPerTask: totMined ? round(totMined / n) : null,
166
- offloadBytesSavedPerTask: totSaved ? Math.round(totSaved / n) : null,
167
- };
168
- });
169
-
170
- // first->last trend for the headline KPIs (only when >=2 buckets).
171
- let trend = null;
172
- if (buckets.length >= 2) {
173
- const a = buckets[0];
174
- const z = buckets[buckets.length - 1];
175
- const delta = (x, y) => (x == null || y == null ? null : round(y - x));
176
- trend = {
177
- from: a.bucketStart,
178
- to: z.bucketStart,
179
- firstPassCleanRate: delta(a.firstPassCleanRate, z.firstPassCleanRate),
180
- avgReviewCycles: delta(a.avgReviewCycles, z.avgReviewCycles),
181
- tokensPerTask: a.tokensPerTask && z.tokensPerTask ? z.tokensPerTask - a.tokensPerTask : null,
182
- cacheRatio: delta(a.cacheRatio, z.cacheRatio),
183
- memoryPrecision: delta(a.memoryPrecision, z.memoryPrecision),
184
- };
234
+ let cached = null;
235
+
236
+ /**
237
+ * learningCurve for a server that answers the same question on every request:
238
+ * the result (without its reason, which names the file) is kept while both
239
+ * generations of the log keep the inode, size and modification time they had
240
+ * and the options stay the same, and recomputed when any of them changes. A
241
+ * generation is stamped the way the reader sees it, so a link or a missing
242
+ * file stamps as empty and an answer with no readable generation is not kept.
243
+ *
244
+ * @param {Parameters<typeof learningCurve>[0]} [opts]
245
+ */
246
+ export function cachedLearningCurve(opts = {}) {
247
+ const file = opts.metricsFile ?? DEFAULT_METRICS_FILE();
248
+ const stamp = `${signature(`${file}.1`)}|${signature(file)}`;
249
+ const key = `${file}|${stamp}|${opts.bucketDays ?? 7}|${opts.since ?? ""}|${opts.maxBytes ?? ""}`;
250
+ if (cached && cached.key === key && stamp !== "|") return cached.value;
251
+ const { reason: _path, ...value } = learningCurve({ ...opts, metricsFile: file });
252
+ cached = { key, value };
253
+ return value;
185
254
  }
186
255
 
187
- const out = { ok: true, bucketDays: opts.bucketDays, buckets, trend };
188
-
189
- // else, not process.exit(0) after the write: stdout to a pipe is asynchronous
190
- // and exiting drops whatever has not drained, so the JSON arrived truncated to
191
- // anything reading it through a pipe.
192
- if (opts.json) {
193
- console.log(JSON.stringify(out, null, 2));
194
- } else {
195
- // Markdown / text (default)
196
- const arrow = (v, goodIsUp) => {
197
- if (v == null || v === 0) return "-";
198
- const up = v > 0;
199
- const good = up === goodIsUp;
200
- return `${up ? "+" : ""}${v} ${good ? "(better)" : "(worse)"}`;
256
+ function main() {
257
+ const args = process.argv.slice(2);
258
+ const opts = { json: false, markdown: false, since: null, bucketDays: 7 };
259
+ for (const a of args) {
260
+ if (a === "--json") opts.json = true;
261
+ else if (a === "--markdown" || a === "--md") opts.markdown = true;
262
+ else if (a.startsWith("--since=")) opts.since = a.slice(8);
263
+ else if (a.startsWith("--bucket="))
264
+ opts.bucketDays = Math.max(1, parseInt(a.slice(9), 10) || 7);
265
+ else if (a === "--help" || a === "-h") {
266
+ console.log("Usage: learning-curve.mjs [--bucket=<days>] [--since=ISO] [--json|--markdown]");
267
+ process.exit(0);
268
+ }
269
+ }
270
+
271
+ const result = learningCurve({
272
+ metricsFile: DEFAULT_METRICS_FILE(),
273
+ bucketDays: opts.bucketDays,
274
+ since: opts.since,
275
+ });
276
+ if (!result.ok) {
277
+ if (opts.json)
278
+ writeFileSync(
279
+ 1,
280
+ `${JSON.stringify({ contractVersion: CONTRACT_VERSION, ok: false, code: result.code, reason: result.reason, buckets: [] })}\n`,
281
+ );
282
+ else console.error(`learning-curve: ${result.reason}`);
283
+ return;
284
+ }
285
+ const { buckets, trend } = result;
286
+ const out = {
287
+ contractVersion: CONTRACT_VERSION,
288
+ ok: true,
289
+ bucketDays: result.bucketDays,
290
+ buckets,
291
+ trend,
292
+ ...(result.skipped ? { skipped: result.skipped } : {}),
201
293
  };
202
- console.log(`# Learning curve (${opts.bucketDays}-day buckets)\n`);
203
- console.log(
204
- "| Bucket | Tasks | First-pass clean | Avg review cycles | Rework/task | Tokens/task | Cache ratio | Memory precision | Mined lessons/task | Offload bytes saved/task |",
205
- );
206
- console.log("|---|---|---|---|---|---|---|---|---|---|");
207
- for (const b of buckets) {
294
+ // The function returns instead of calling process.exit(0) after the write:
295
+ // stdout to a pipe is asynchronous, and exiting early drops what has not
296
+ // drained yet.
297
+ if (opts.json) {
298
+ console.log(JSON.stringify(out, null, 2));
299
+ } else {
300
+ // Markdown / text (default)
301
+ const arrow = (v, goodIsUp) => {
302
+ if (v == null || v === 0) return "-";
303
+ const up = v > 0;
304
+ const good = up === goodIsUp;
305
+ return `${up ? "+" : ""}${v} ${good ? "(better)" : "(worse)"}`;
306
+ };
307
+ console.log(`# Learning curve (${opts.bucketDays}-day buckets)\n`);
308
+ if (result.skipped)
309
+ console.log(`Skipped, over the size cap: ${result.skipped.join(", ")} log file.\n`);
208
310
  console.log(
209
- `| ${b.bucketStart} | ${b.tasks} | ${b.firstPassCleanRate ?? "-"} | ${b.avgReviewCycles ?? "-"} | ${b.reworkPerTask} | ${b.tokensPerTask} | ${b.cacheRatio ?? "-"} | ${b.memoryPrecision ?? "-"} | ${b.minedLessonsPerTask ?? "-"} | ${b.offloadBytesSavedPerTask ?? "-"} |`,
311
+ "| Bucket | Tasks | First-pass clean | Avg review cycles | Rework/task | Tokens/task | Cache ratio | Memory precision | Mined lessons/task | Offload bytes saved/task |",
210
312
  );
211
- }
212
- if (trend) {
213
- console.log(`\n**Trend ${trend.from} -> ${trend.to}:**`);
214
- console.log(`- First-pass clean: ${arrow(trend.firstPassCleanRate, true)}`);
215
- console.log(`- Avg review cycles: ${arrow(trend.avgReviewCycles, false)}`);
216
- console.log(`- Tokens/task: ${arrow(trend.tokensPerTask, false)}`);
217
- console.log(`- Cache ratio: ${arrow(trend.cacheRatio, true)}`);
218
- console.log(`- Memory precision: ${arrow(trend.memoryPrecision, true)}`);
219
- } else {
220
- console.log("\n(need >= 2 buckets for a trend; keep running the pipeline)");
313
+ console.log("|---|---|---|---|---|---|---|---|---|---|");
314
+ for (const b of buckets) {
315
+ console.log(
316
+ `| ${b.bucketStart} | ${b.tasks} | ${b.firstPassCleanRate ?? "-"} | ${b.avgReviewCycles ?? "-"} | ${b.reworkPerTask} | ${b.tokensPerTask} | ${b.cacheRatio ?? "-"} | ${b.memoryPrecision ?? "-"} | ${b.minedLessonsPerTask ?? "-"} | ${b.offloadBytesSavedPerTask ?? "-"} |`,
317
+ );
318
+ }
319
+ if (trend) {
320
+ console.log(`\n**Trend ${trend.from} -> ${trend.to}:**`);
321
+ console.log(`- First-pass clean: ${arrow(trend.firstPassCleanRate, true)}`);
322
+ console.log(`- Avg review cycles: ${arrow(trend.avgReviewCycles, false)}`);
323
+ console.log(`- Tokens/task: ${arrow(trend.tokensPerTask, false)}`);
324
+ console.log(`- Cache ratio: ${arrow(trend.cacheRatio, true)}`);
325
+ console.log(`- Memory precision: ${arrow(trend.memoryPrecision, true)}`);
326
+ } else {
327
+ console.log("\n(need >= 2 buckets for a trend; keep running the pipeline)");
328
+ }
221
329
  }
222
330
  }
331
+
332
+ if (invokedDirectly(import.meta.url)) main();
@@ -103,14 +103,23 @@ LINE="{\"ts\":\"${TS}\",\"task_id\":\"$(json_escape "$TASK_ID")\",\"phase\":\"$(
103
103
  REDACT="$(cd "$(dirname "$0")" && pwd)/../lib/redact.mjs"
104
104
  [ -f "$REDACT" ] && LINE=$(printf '%s' "$LINE" | node "$REDACT" 2>/dev/null || printf '%s' "$LINE")
105
105
 
106
+ # The file is owner-only and, like the other local logs, moves to a single .1
107
+ # generation once it passes MAX_METRICS_BYTES.
108
+ MAX_METRICS_BYTES=1048576
109
+
106
110
  # Atomic append (one line, well under PIPE_BUF).
111
+ # Rotation takes the lock every writer of the local logs takes (run-write.mjs),
112
+ # and the first append after this version makes an older 0644 file owner-only.
107
113
  if [ "$RUN_WRITABLE" -eq 1 ]; then
114
+ ma_run_write rotate "$METRICS_FILE" --max-bytes "$MAX_METRICS_BYTES" 2>/dev/null || true
108
115
  printf '%s\n' "$LINE" | ma_run_write append "$METRICS_FILE" 2>/dev/null || {
109
116
  echo "warn: log-metric: refused or failed to write $METRICS_FILE - telemetry skipped" >&2
110
117
  exit 0
111
118
  }
112
119
  else
113
- echo "$LINE" >> "$METRICS_FILE" 2>/dev/null || {
120
+ ma_run_write rotate "$METRICS_FILE" --max-bytes "$MAX_METRICS_BYTES" 2>/dev/null || true
121
+ [ -f "$METRICS_FILE" ] && [ ! -L "$METRICS_FILE" ] && chmod 600 "$METRICS_FILE" 2>/dev/null
122
+ (umask 077; echo "$LINE" >> "$METRICS_FILE") 2>/dev/null || {
114
123
  echo "warn: log-metric: cannot write to $METRICS_FILE - telemetry skipped" >&2
115
124
  exit 0
116
125
  }
@@ -25,7 +25,7 @@
25
25
  * @module pipeline/scripts/note-agent-event
26
26
  */
27
27
 
28
- import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
28
+ import { readFileSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
 
@@ -36,6 +36,7 @@ import { memoryExcluded } from "./_memory-policy.mjs";
36
36
  import { checkedSlug, repoName } from "../lib/slug.mjs";
37
37
  import { openScanner, stripPrivate } from "./_secret-scan.mjs";
38
38
  import { exitOnHelp } from "../lib/cli-help.mjs";
39
+ import { appendRowIn } from "./note-skill-use.mjs";
39
40
 
40
41
  exitOnHelp(import.meta.url);
41
42
 
@@ -125,9 +126,7 @@ export function record(payload, env = process.env) {
125
126
  scan.close();
126
127
  }
127
128
  const out = join(env.HOME || homedir(), ".claude", "memory", "multi-agent", slug);
128
- mkdirSync(out, { recursive: true });
129
- appendFileSync(join(out, "session-notes.jsonl"), JSON.stringify(row) + "\n", "utf8");
130
- return row;
129
+ return appendRowIn(out, "session-notes.jsonl", row, env) ? row : null;
131
130
  }
132
131
 
133
132
  function main() {