@mmerterden/multi-agent-pipeline 23.3.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 (224) hide show
  1. package/CHANGELOG.md +44 -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 +5 -5
  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 +223 -155
  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/graph/SKILL.md +57 -24
  21. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  22. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  23. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  24. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  25. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  26. package/pipeline/contract/CHANGELOG.md +49 -0
  27. package/pipeline/contract/build.mjs +13 -1
  28. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  29. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  30. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  31. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  32. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  33. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  34. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  35. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  36. package/pipeline/contract/fixtures/runs-running.json +4 -1
  37. package/pipeline/contract/manifest.json +28 -15
  38. package/pipeline/contract/types/index.d.ts +55 -3
  39. package/pipeline/lib/detach-self.mjs +95 -0
  40. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  41. package/pipeline/lib/rotated-log.mjs +93 -0
  42. package/pipeline/lib/tls-trust.mjs +29 -0
  43. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  44. package/pipeline/lib/usage-names.generated.mjs +614 -0
  45. package/pipeline/lib/usage-run-key.mjs +235 -0
  46. package/pipeline/lib/usage-vocab.mjs +210 -0
  47. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  48. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  49. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  50. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  51. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  52. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  53. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  54. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  55. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  56. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  57. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  58. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  59. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  60. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  61. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  62. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  63. package/pipeline/multi-agent-refs/help/en.md +3 -2
  64. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  65. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  66. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  67. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  68. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  69. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  70. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  71. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  72. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  73. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  74. package/pipeline/office/index.html +1207 -233
  75. package/pipeline/office/toolkit.json +1 -1
  76. package/pipeline/rules/outside-the-pipeline.md +1 -1
  77. package/pipeline/schemas/activity.schema.json +23 -0
  78. package/pipeline/schemas/agent-state.schema.json +6 -1
  79. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  80. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  81. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  82. package/pipeline/schemas/code-graph.schema.json +2 -2
  83. package/pipeline/schemas/examples/design-check-config.json +27 -0
  84. package/pipeline/schemas/learning-curve.schema.json +67 -0
  85. package/pipeline/schemas/office-jobs.json +69 -2
  86. package/pipeline/schemas/office-jobs.schema.json +8 -1
  87. package/pipeline/schemas/phases.json +5 -0
  88. package/pipeline/schemas/phases.schema.json +8 -0
  89. package/pipeline/schemas/prefs.schema.json +46 -12
  90. package/pipeline/schemas/runs-index.schema.json +17 -0
  91. package/pipeline/schemas/toolkit-path-params.json +84 -8
  92. package/pipeline/scripts/README.md +1 -0
  93. package/pipeline/scripts/_code-graph.mjs +184 -103
  94. package/pipeline/scripts/_contract-core.mjs +1 -1
  95. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  96. package/pipeline/scripts/_diff-impact.mjs +21 -2
  97. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  98. package/pipeline/scripts/_http-post.mjs +103 -115
  99. package/pipeline/scripts/_safe-read.mjs +57 -0
  100. package/pipeline/scripts/_skill-practices.mjs +26 -0
  101. package/pipeline/scripts/_strip-code.mjs +380 -0
  102. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  103. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  104. package/pipeline/scripts/call-graph/index.mjs +78 -0
  105. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  106. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  107. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  108. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  109. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  110. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  111. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  112. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  113. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  114. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  115. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  116. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  117. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  118. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  119. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  120. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  121. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  122. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  123. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  124. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  125. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  126. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  127. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  128. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  129. package/pipeline/scripts/contract-server.mjs +1 -0
  130. package/pipeline/scripts/feedback-send.mjs +26 -26
  131. package/pipeline/scripts/gate-ledger.mjs +2 -1
  132. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  133. package/pipeline/scripts/graph-affected.mjs +109 -20
  134. package/pipeline/scripts/graph-build.mjs +95 -15
  135. package/pipeline/scripts/graph-export.mjs +272 -0
  136. package/pipeline/scripts/graph-hint.mjs +15 -2
  137. package/pipeline/scripts/graph-query.mjs +305 -26
  138. package/pipeline/scripts/graph-report.mjs +187 -1
  139. package/pipeline/scripts/health-report.mjs +3 -4
  140. package/pipeline/scripts/infra/docs.mjs +317 -0
  141. package/pipeline/scripts/infra/extract.mjs +998 -0
  142. package/pipeline/scripts/infra/graph.mjs +245 -0
  143. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  144. package/pipeline/scripts/job-launch.mjs +67 -2
  145. package/pipeline/scripts/learning-curve.mjs +288 -178
  146. package/pipeline/scripts/log-metric.sh +10 -1
  147. package/pipeline/scripts/note-agent-event.mjs +3 -4
  148. package/pipeline/scripts/note-command-use.mjs +333 -0
  149. package/pipeline/scripts/note-command-use.sh +126 -0
  150. package/pipeline/scripts/note-mcp-call.sh +89 -0
  151. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  152. package/pipeline/scripts/note-session.sh +62 -3
  153. package/pipeline/scripts/note-skill-use.mjs +58 -2
  154. package/pipeline/scripts/office-build.mjs +115 -1
  155. package/pipeline/scripts/office-memory.mjs +14 -5
  156. package/pipeline/scripts/pair.mjs +333 -0
  157. package/pipeline/scripts/pre-push-check.sh +1 -1
  158. package/pipeline/scripts/remote/cbor.mjs +128 -0
  159. package/pipeline/scripts/remote/contract.mjs +98 -0
  160. package/pipeline/scripts/remote/handler.mjs +317 -0
  161. package/pipeline/scripts/remote/handles.mjs +57 -0
  162. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  163. package/pipeline/scripts/remote/listener.mjs +204 -0
  164. package/pipeline/scripts/remote/lockout.mjs +103 -0
  165. package/pipeline/scripts/remote/nonces.mjs +61 -0
  166. package/pipeline/scripts/remote/pairing.mjs +519 -0
  167. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  168. package/pipeline/scripts/remote/store.mjs +188 -0
  169. package/pipeline/scripts/remote/transport.mjs +211 -0
  170. package/pipeline/scripts/remote/verbs.json +70 -0
  171. package/pipeline/scripts/remote/verbs.mjs +217 -0
  172. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  173. package/pipeline/scripts/remote/wire.mjs +364 -0
  174. package/pipeline/scripts/remote-listener.mjs +83 -0
  175. package/pipeline/scripts/route-learn.mjs +4 -4
  176. package/pipeline/scripts/run-kill.mjs +1 -1
  177. package/pipeline/scripts/run-write.mjs +13 -2
  178. package/pipeline/scripts/runs-index.mjs +30 -3
  179. package/pipeline/scripts/search-logs.sh +9 -0
  180. package/pipeline/scripts/session-brief.mjs +458 -0
  181. package/pipeline/scripts/session-brief.sh +130 -0
  182. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  183. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  184. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  185. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  186. package/pipeline/scripts/token-budget-report.mjs +3 -2
  187. package/pipeline/scripts/uninstall.mjs +29 -0
  188. package/pipeline/scripts/usage-access.mjs +16 -31
  189. package/pipeline/scripts/usage-health.mjs +31 -62
  190. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  191. package/pipeline/scripts/usage-register.mjs +39 -29
  192. package/pipeline/scripts/usage-report.mjs +579 -178
  193. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  194. package/pipeline/scripts/write-state.mjs +39 -0
  195. package/pipeline/skills/.skill-manifest.json +21 -17
  196. package/pipeline/skills/.skills-index.json +13 -2
  197. package/pipeline/skills/shared/README.md +5 -4
  198. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  199. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  200. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  201. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  202. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  203. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  204. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  205. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  206. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  207. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  208. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  209. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  210. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  211. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  212. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  213. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  214. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  215. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  216. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  219. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  220. package/pipeline/skills/skills-index.md +3 -2
  221. package/docs/FIGMA_PIPELINE.md +0 -137
  222. package/pipeline/lib/identifier-scan.mjs +0 -156
  223. package/pipeline/scripts/publish-staged.mjs +0 -324
  224. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,333 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * note-command-use.mjs - count which /multi-agent commands are typed.
4
+ *
5
+ * note-command-use.sh, a UserPromptSubmit hook, appends one line to
6
+ * `cmd-calls.log` for a prompt whose first token is `/multi-agent:<name>` (or
7
+ * `/multi-agent <name>` for a shipped name): the shipped command name, or the
8
+ * constant `other`. This module folds those lines into a per-command counter
9
+ * and hands the counts to the usage report as the `cmds` field.
10
+ *
11
+ * Nothing else about a prompt is read or stored: no arguments, no text, no
12
+ * length, no time. A name is kept only when it is on the shipped command list
13
+ * (lib/usage-names.generated.mjs); any other name counts as `other`.
14
+ *
15
+ * The counter, `cmd-counts.json`, holds `pending` (counts not yet offered) and
16
+ * `inflight` (the batch a sender claimed and has not acknowledged). Everything
17
+ * that changes it, the fold of the log included, runs under the file's lock, so
18
+ * concurrent reports take turns: a claim moves the pending counts into one
19
+ * batch with an id; while that batch is out, no other claim is handed it; an
20
+ * acknowledgement with the batch id clears it, a release makes it available
21
+ * again, and a batch nobody answered for CLAIM_TTL_MS is offered again, with
22
+ * the same id and the same counts. A count is therefore sent once per accepted
23
+ * send, kept when a send fails, and a resend can be told from a new batch.
24
+ *
25
+ * Counting has its own switches: it is on only while usageLog.enabled is true,
26
+ * usageLog.optOut is not, and the preferences parse. The hook is a shell
27
+ * script that cannot parse them, so it works from a marker file
28
+ * (`cmd-counting-on`) written here with a real parser, and stops the moment
29
+ * the preferences are newer than the marker. When counting is off the log and
30
+ * the counter are emptied.
31
+ *
32
+ * @module pipeline/scripts/note-command-use
33
+ */
34
+
35
+ import {
36
+ closeSync,
37
+ constants,
38
+ openSync,
39
+ readdirSync,
40
+ renameSync,
41
+ unlinkSync,
42
+ writeSync,
43
+ } from "node:fs";
44
+ import { randomBytes } from "node:crypto";
45
+ import { join } from "node:path";
46
+
47
+ import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
48
+ import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
49
+ import { readRegularFile } from "../lib/regular-file.mjs";
50
+ import { mkdirSafe } from "../lib/safe-write.mjs";
51
+ import { SHIPPED_COMMANDS } from "../lib/usage-names.generated.mjs";
52
+ import { DEADLINE_MS, logDir } from "./note-skill-use.mjs";
53
+ import { exitOnHelp } from "../lib/cli-help.mjs";
54
+
55
+ exitOnHelp(import.meta.url);
56
+
57
+ export const COMMAND_LOG = "cmd-calls.log";
58
+ export const COMMAND_FILE = "cmd-counts.json";
59
+ export const COMMAND_SENTINEL = "cmd-counting-on";
60
+ export const MAX_CMDS = SHIPPED_COMMANDS.length + 1;
61
+ export const MAX_CMD_COUNT = 9999;
62
+ export const CLAIM_TTL_MS = 10 * 60 * 1000;
63
+ const STORE_MAX = 1_000_000;
64
+ const OTHER = "other";
65
+ const SHIPPED = new Set(SHIPPED_COMMANDS);
66
+
67
+ const plain = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
68
+ const lockOpts = (env) => ({
69
+ fallback: {},
70
+ mode: 0o600,
71
+ timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS),
72
+ });
73
+
74
+ /** True while commands are counted: reporting on, not opted out, preferences readable. */
75
+ export function commandCountEnabled(env = process.env) {
76
+ const found = findPrefs(env);
77
+ if (found && found.status !== "ok") return false;
78
+ if (globalPref("usageLog.optOut", false, env) === true) return false;
79
+ return globalPref("usageLog.enabled", false, env) === true;
80
+ }
81
+
82
+ /** The counted name for a log line: a shipped name, `other` for any well-formed other name, else null. */
83
+ function nameOf(line) {
84
+ if (!/^[a-z0-9-]{1,40}$/.test(line)) return null;
85
+ return SHIPPED.has(line) ? line : OTHER;
86
+ }
87
+
88
+ function counterPath(env) {
89
+ return join(logDir(env), COMMAND_FILE);
90
+ }
91
+
92
+ /** Read and delete the log files into `into`, a plain name-to-count object. Runs under the counter lock. */
93
+ function drainLogs(env, into, enabled) {
94
+ const dir = logDir(env);
95
+ const log = join(dir, COMMAND_LOG);
96
+ const mine = `${log}.proc.${process.pid}`;
97
+ try {
98
+ renameSync(log, mine);
99
+ } catch {
100
+ /* no new lines */
101
+ }
102
+ let names;
103
+ try {
104
+ names = readdirSync(dir).filter((f) => f.startsWith(`${COMMAND_LOG}.proc.`));
105
+ } catch {
106
+ return;
107
+ }
108
+ for (const f of names) {
109
+ const file = join(dir, f);
110
+ let text = "";
111
+ try {
112
+ if (enabled) text = readRegularFile(file, { maxBytes: 4 * 1024 * 1024, within: [dir] });
113
+ } catch {
114
+ /* unreadable: dropped with the file */
115
+ }
116
+ for (const line of text.split("\n")) {
117
+ const name = nameOf(line);
118
+ if (name) into[name] = Math.min((into[name] ?? 0) + 1, STORE_MAX);
119
+ }
120
+ try {
121
+ unlinkSync(file);
122
+ } catch {
123
+ /* already gone */
124
+ }
125
+ }
126
+ }
127
+
128
+ function hasLogs(env) {
129
+ try {
130
+ return readdirSync(logDir(env)).some(
131
+ (f) => f === COMMAND_LOG || f.startsWith(`${COMMAND_LOG}.proc.`),
132
+ );
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ const merge = (a, b) => {
139
+ const out = { ...a };
140
+ for (const [k, v] of Object.entries(b)) out[k] = Math.min((out[k] ?? 0) + v, STORE_MAX);
141
+ return out;
142
+ };
143
+
144
+ const counts = (obj) =>
145
+ Object.entries(plain(obj))
146
+ .filter(([n, k]) => (n === OTHER || SHIPPED.has(n)) && Number.isInteger(k) && k > 0)
147
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
148
+ .slice(0, MAX_CMDS)
149
+ .map(([n, k]) => ({ n, k: Math.min(k, MAX_CMD_COUNT) }));
150
+
151
+ function normalize(current) {
152
+ const inflight = plain(current?.inflight);
153
+ const hasBatch = typeof inflight.id === "string" && Object.keys(plain(inflight.counts)).length;
154
+ return {
155
+ pending: { ...plain(current?.pending) },
156
+ inflight: hasBatch
157
+ ? { id: inflight.id, at: Number(inflight.at) || 0, counts: { ...plain(inflight.counts) } }
158
+ : null,
159
+ };
160
+ }
161
+
162
+ /** Run `change(state, enabled)` on the counter under its lock, after folding the log into `pending`. */
163
+ function withCounter(env, change) {
164
+ let result = null;
165
+ try {
166
+ const enabled = commandCountEnabled(env);
167
+ if (hasLogs(env) || enabled) mkdirSafe(logDir(env), { mode: 0o700, env });
168
+ updateJsonFileSync(
169
+ counterPath(env),
170
+ (current) => {
171
+ const state = normalize(current);
172
+ drainLogs(env, state.pending, enabled);
173
+ const out = change(state);
174
+ result = out.result;
175
+ return { v: 1, pending: state.pending, inflight: state.inflight, ...out.patch };
176
+ },
177
+ lockOpts(env),
178
+ );
179
+ } catch {
180
+ /* the counter is bookkeeping */
181
+ }
182
+ return result;
183
+ }
184
+
185
+ /** What a send would carry now, without taking it: the pending counts and any batch in flight. */
186
+ export function peekCommands(env = process.env) {
187
+ if (!commandCountEnabled(env)) return [];
188
+ const out = withCounter(env, (state) => ({
189
+ result: counts(merge(state.pending, state.inflight?.counts ?? {})),
190
+ patch: {},
191
+ }));
192
+ return out ?? [];
193
+ }
194
+
195
+ /**
196
+ * Split counts into the part one batch may carry (each count at most
197
+ * MAX_CMD_COUNT) and the rest, which stays for a later batch.
198
+ */
199
+ function capped(all) {
200
+ const batch = {};
201
+ const rest = {};
202
+ for (const [n, k] of Object.entries(all)) {
203
+ batch[n] = Math.min(k, MAX_CMD_COUNT);
204
+ if (k > MAX_CMD_COUNT) rest[n] = k - MAX_CMD_COUNT;
205
+ }
206
+ return { batch, rest };
207
+ }
208
+
209
+ /**
210
+ * Take the counts for one send. Returns { id, cmds }; `cmds` is empty and `id`
211
+ * null when counting is off, nothing is pending, or another sender's batch is
212
+ * in flight.
213
+ *
214
+ * `id` is the batch id sent to the server as `cb`: 16 lowercase hex characters
215
+ * from crypto.randomBytes, made when the pending counts become a batch. A batch
216
+ * that was released or never answered is handed out again unchanged, with its
217
+ * id and its counts, so the server can recognise the resend; whatever was typed
218
+ * since waits in `pending` for the next batch. No count in a batch is above
219
+ * MAX_CMD_COUNT; the remainder stays pending.
220
+ */
221
+ export function claimCommands(env = process.env, now = Date.now()) {
222
+ const none = { id: null, cmds: [] };
223
+ if (!commandCountEnabled(env)) return none;
224
+ const out = withCounter(env, (state) => {
225
+ if (state.inflight) {
226
+ if (now - state.inflight.at < CLAIM_TTL_MS && state.inflight.at > 0) {
227
+ return { result: none, patch: {} };
228
+ }
229
+ const { batch, rest } = capped(state.inflight.counts);
230
+ const cmds = counts(batch);
231
+ if (cmds.length) {
232
+ return {
233
+ result: { id: state.inflight.id, cmds },
234
+ patch: {
235
+ pending: merge(state.pending, rest),
236
+ inflight: { id: state.inflight.id, at: now, counts: batch },
237
+ },
238
+ };
239
+ }
240
+ }
241
+ const { batch, rest } = capped(state.pending);
242
+ const cmds = counts(batch);
243
+ if (!cmds.length) return { result: none, patch: { pending: {}, inflight: null } };
244
+ const id = randomBytes(8).toString("hex");
245
+ return {
246
+ result: { id, cmds },
247
+ patch: { pending: rest, inflight: { id, at: now, counts: batch } },
248
+ };
249
+ });
250
+ return out ?? none;
251
+ }
252
+
253
+ /** The batch `id` was accepted: forget it. Another claim's batch is left alone. */
254
+ export function ackCommands(id, env = process.env) {
255
+ if (typeof id !== "string") return;
256
+ withCounter(env, (state) => ({
257
+ result: null,
258
+ patch: { inflight: state.inflight?.id === id ? null : state.inflight },
259
+ }));
260
+ }
261
+
262
+ /** The send of batch `id` failed: make it available to the next claim at once. */
263
+ export function releaseCommands(id, env = process.env) {
264
+ if (typeof id !== "string") return;
265
+ withCounter(env, (state) => ({
266
+ result: null,
267
+ patch: {
268
+ inflight: state.inflight?.id === id ? { ...state.inflight, at: 0 } : state.inflight,
269
+ },
270
+ }));
271
+ }
272
+
273
+ /** Forget every count: the hook's log, any leftover, the pending counts and the batch in flight. Never throws. */
274
+ export function discardCommands(env = process.env) {
275
+ try {
276
+ const dir = logDir(env);
277
+ const names = readdirSync(dir);
278
+ for (const f of names) {
279
+ if (f === COMMAND_LOG || f.startsWith(`${COMMAND_LOG}.proc.`)) {
280
+ try {
281
+ unlinkSync(join(dir, f));
282
+ } catch {
283
+ /* already gone */
284
+ }
285
+ }
286
+ }
287
+ if (names.includes(COMMAND_FILE)) {
288
+ updateJsonFileSync(
289
+ counterPath(env),
290
+ () => ({ v: 1, pending: {}, inflight: null }),
291
+ lockOpts(env),
292
+ );
293
+ }
294
+ } catch {
295
+ /* nothing counted, nothing to forget */
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Write the marker the hook tests (and renew its time), or remove it and
301
+ * discard the counts when counting is off. Never throws.
302
+ *
303
+ * @returns {boolean} whether counting is on
304
+ */
305
+ export function syncCommandSentinel(env = process.env) {
306
+ try {
307
+ const dir = logDir(env);
308
+ const file = join(dir, COMMAND_SENTINEL);
309
+ if (!commandCountEnabled(env)) {
310
+ try {
311
+ unlinkSync(file);
312
+ } catch {
313
+ /* not there */
314
+ }
315
+ discardCommands(env);
316
+ return false;
317
+ }
318
+ mkdirSafe(dir, { mode: 0o700, env });
319
+ const fd = openSync(
320
+ file,
321
+ constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
322
+ 0o600,
323
+ );
324
+ try {
325
+ writeSync(fd, "on\n");
326
+ } finally {
327
+ closeSync(fd);
328
+ }
329
+ return true;
330
+ } catch {
331
+ return false;
332
+ }
333
+ }
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env bash
2
+ # note-command-use.sh - UserPromptSubmit hook: count which /multi-agent
3
+ # commands are typed, by name only.
4
+ #
5
+ # A prompt counts when its first token is `/multi-agent:<name>`, or when it is
6
+ # `/multi-agent <name>` and <name> is a shipped command. <name> is looked up in
7
+ # the shipped command list (lib/usage-names.generated.mjs, SHIPPED_COMMANDS);
8
+ # the line appended to <log root>/cmd-calls.log is that shipped name, or the
9
+ # constant `other` for a colon-form name that is not on the list. Nothing else
10
+ # of the prompt is read past its first two tokens, and nothing else is stored:
11
+ # no arguments, no text, no length, no time. The log is folded into
12
+ # cmd-counts.json under a lock by note-command-use.mjs when a report is built.
13
+ #
14
+ # It starts no node process and parses no JSON beyond a depth-aware scan of the
15
+ # first 8 KiB of the payload for the top-level `hook_event_name` and `prompt`
16
+ # keys (a `prompt` inside any nested object is never read; the depth is kept
17
+ # across the lines of a payload that is not on one line). Off, with nothing
18
+ # read or written, unless the marker file <log root>/cmd-counting-on exists, is
19
+ # not a symlink, and is not older than the preferences file; the marker is
20
+ # written with a real parser by note-command-use.mjs (syncCommandSentinel) only
21
+ # while usageLog.enabled is true and usageLog.optOut is not, and removed
22
+ # otherwise. One short append is atomic, so concurrent prompts need no lock; the
23
+ # fold takes the counter lock.
24
+ #
25
+ # Never blocks the prompt: no output, exit 0 on every path. The log stops
26
+ # growing at 1 MiB until the next report folds it.
27
+
28
+ set -u
29
+
30
+ PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
31
+ DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
32
+ MARKER="$DIR/cmd-counting-on"
33
+ [ -f "$MARKER" ] || exit 0
34
+ [ -L "$MARKER" ] && exit 0
35
+ [ -f "$PREFS" ] || exit 0
36
+ [ "$PREFS" -nt "$MARKER" ] && exit 0
37
+
38
+ HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd)" || exit 0
39
+ LIST="$HERE/../lib/usage-names.generated.mjs"
40
+ [ -f "$LIST" ] || exit 0
41
+
42
+ HEAD="$(head -c 8192 2>/dev/null)" || exit 0
43
+
44
+ TOKENS="$(printf '%s' "$HEAD" | awk '
45
+ BEGIN { d = 0; st = 0 }
46
+ {
47
+ s = $0; n = length(s); i = 1
48
+ while (i <= n) {
49
+ c = substr(s, i, 1)
50
+ if (c == "\"") {
51
+ j = i + 1; str = ""
52
+ while (j <= n) {
53
+ ch = substr(s, j, 1)
54
+ if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
55
+ if (ch == "\"") break
56
+ str = str ch; j++
57
+ }
58
+ if (d == 1) {
59
+ if (st == 0) { key = str; st = 1 }
60
+ else if (st == 2) {
61
+ if (key == "hook_event_name") event = str
62
+ else if (key == "prompt" && !seen) {
63
+ seen = 1
64
+ first = str; rest = ""
65
+ if (match(str, /[ \\]/)) {
66
+ first = substr(str, 1, RSTART - 1)
67
+ if (substr(str, RSTART, 1) == " ") rest = substr(str, RSTART + 1)
68
+ }
69
+ second = rest
70
+ if (match(rest, /[ \\]/)) second = substr(rest, 1, RSTART - 1)
71
+ }
72
+ st = 3
73
+ }
74
+ }
75
+ i = j + 1; continue
76
+ }
77
+ if (c == ":" && d == 1) st = 2
78
+ else if (c == "," && d == 1) st = 0
79
+ else if (c == "{" || c == "[") d++
80
+ else if (c == "}" || c == "]") d--
81
+ i++
82
+ }
83
+ }
84
+ END { print event; print first; print second }')" || exit 0
85
+
86
+ {
87
+ IFS= read -r EVENT
88
+ IFS= read -r FIRST
89
+ IFS= read -r SECOND
90
+ } <<EOF
91
+ $TOKENS
92
+ EOF
93
+
94
+ [ "$EVENT" = "UserPromptSubmit" ] || exit 0
95
+
96
+ NAME="" COLON=0
97
+ case "$FIRST" in
98
+ /multi-agent:*) NAME="${FIRST#/multi-agent:}"; COLON=1 ;;
99
+ /multi-agent) NAME="$SECOND" ;;
100
+ *) exit 0 ;;
101
+ esac
102
+ printf '%s' "$NAME" | grep -Eq '^[a-z0-9-]{1,40}$' || exit 0
103
+
104
+ SHIPPED="$(awk -v n="$NAME" '
105
+ /SHIPPED_COMMANDS = / { on = 1; next }
106
+ on && /^\]\)/ { exit }
107
+ on { gsub(/^[ \t]*"|",?[ \t]*$/, ""); if ($0 == n) { print "yes"; exit } }
108
+ ' "$LIST" 2>/dev/null)"
109
+
110
+ if [ "$SHIPPED" = "yes" ]; then
111
+ COUNTED="$NAME"
112
+ elif [ "$COLON" = "1" ]; then
113
+ COUNTED="other"
114
+ else
115
+ exit 0
116
+ fi
117
+
118
+ LOG="$DIR/cmd-calls.log"
119
+ ( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
120
+ [ -L "$LOG" ] && exit 0
121
+ if [ -f "$LOG" ]; then
122
+ SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
123
+ [ "${SIZE:-0}" -ge 1048576 ] 2>/dev/null && exit 0
124
+ fi
125
+ ( umask 077; printf '%s\n' "$COUNTED" >> "$LOG" ) 2>/dev/null
126
+ exit 0
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env bash
2
+ # note-mcp-call.sh - PostToolUse hook on MCP tools (mcp__.*), registered async.
3
+ #
4
+ # Counts a successful MCP call for the usage record's `tools` field by appending
5
+ # one short line, `<session id> <tool name>`, to <log root>/mcp-calls.log. It
6
+ # starts no node process and parses no JSON: it reads the first 8 KiB of the
7
+ # payload (the host writes session_id, hook_event_name and tool_name before the
8
+ # tool's input and response, so a large tool_response is never read), takes the
9
+ # first occurrence of each of the three keys, and appends. The report folds the
10
+ # log into per-session counts (note-mcp-failure.mjs foldCalls).
11
+ #
12
+ # Off, with nothing read or written, unless the marker file
13
+ # <log root>/mcp-counting-on exists and the preferences file is not newer than
14
+ # it. A shell script cannot parse the preferences reliably, so it never tries:
15
+ # the marker is written (and its time renewed) by note-mcp-failure.mjs
16
+ # syncCountingSentinel with a real parser, only while usageLog.enabled is true
17
+ # and neither usageLog.optOut nor mcpFailures.enabled false is set, and removed
18
+ # otherwise. Any change to the preferences makes the marker older than them, so
19
+ # an edit that opts out stops the hook at once, and counting resumes when the
20
+ # next report or failure hook renews the marker.
21
+ #
22
+ # The log stops growing at 2 MiB until the next report folds it. Exits 0 on every
23
+ # path with no output: bookkeeping never holds a tool call.
24
+
25
+ set -u
26
+
27
+ PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
28
+ DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
29
+ MARKER="$DIR/mcp-counting-on"
30
+ [ -f "$MARKER" ] || exit 0
31
+ [ -L "$MARKER" ] && exit 0
32
+ [ -f "$PREFS" ] || exit 0
33
+ [ "$PREFS" -nt "$MARKER" ] && exit 0
34
+
35
+ HEAD="$(head -c 8192 2>/dev/null)" || exit 0
36
+ SID="" EVENT="" TOOL=""
37
+ while IFS='=' read -r key value; do
38
+ case "$key" in
39
+ session_id) SID="$value" ;;
40
+ hook_event_name) EVENT="$value" ;;
41
+ tool_name) TOOL="$value" ;;
42
+ esac
43
+ done <<EOF
44
+ $(printf '%s' "$HEAD" | awk '
45
+ {
46
+ s = $0; n = length(s); d = 0; st = 0; i = 1
47
+ while (i <= n) {
48
+ c = substr(s, i, 1)
49
+ if (c == "\"") {
50
+ j = i + 1; str = ""
51
+ while (j <= n) {
52
+ ch = substr(s, j, 1)
53
+ if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
54
+ if (ch == "\"") break
55
+ str = str ch; j++
56
+ }
57
+ if (d == 1) {
58
+ if (st == 0) { key = str; st = 1 }
59
+ else if (st == 2) {
60
+ if ((key == "session_id" || key == "hook_event_name" || key == "tool_name") && !(key in seen)) {
61
+ seen[key] = 1; print key "=" str
62
+ }
63
+ st = 3
64
+ }
65
+ }
66
+ i = j + 1; continue
67
+ }
68
+ if (c == ":" && d == 1) st = 2
69
+ else if (c == "," && d == 1) st = 0
70
+ else if (c == "{" || c == "[") d++
71
+ else if (c == "}" || c == "]") d--
72
+ i++
73
+ }
74
+ }')
75
+ EOF
76
+
77
+ [ "$EVENT" = "PostToolUse" ] || exit 0
78
+ printf '%s' "$SID" | grep -Eq '^[A-Za-z0-9_-]{8,64}$' || exit 0
79
+ printf '%s' "$TOOL" | grep -Eq '^mcp__[A-Za-z0-9_-]{1,100}$' || exit 0
80
+
81
+ LOG="$DIR/mcp-calls.log"
82
+ ( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
83
+ [ -L "$LOG" ] && exit 0
84
+ if [ -f "$LOG" ]; then
85
+ SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
86
+ [ "${SIZE:-0}" -ge 2097152 ] 2>/dev/null && exit 0
87
+ fi
88
+ ( umask 077; printf '%s %s\n' "$SID" "$TOOL" >> "$LOG" ) 2>/dev/null
89
+ exit 0