@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
@@ -16,7 +16,14 @@
16
16
  * "validation", then an HTTP status, then fixed wording
17
17
  * patterns; the text itself is never stored
18
18
  *
19
- * A name part outside NAME_PART (a strict charset and length) or carrying a
19
+ * Successful calls are counted by note-mcp-call.sh, a shell hook that appends one
20
+ * short line (`<session id> <tool name>`) to <log dir>/mcp-calls.log and starts no
21
+ * node process. This module folds that log into <log dir>/mcp-calls.json at
22
+ * report time (foldCalls): `<server>:<tool>` (lowercase, a name that fits
23
+ * CALL_KEY) and a count per host session, owner-only. Nothing else about a call is
24
+ * read or kept.
25
+ *
26
+ A name part outside NAME_PART (a strict charset and length) or carrying a
20
27
  * credential pattern drops the whole call. The tool's arguments, its output
21
28
  * and the error text are never written. No server is probed: the counter
22
29
  * only sees the calls the session already made.
@@ -44,6 +51,15 @@
44
51
  * @module pipeline/scripts/note-mcp-failure
45
52
  */
46
53
 
54
+ import {
55
+ closeSync,
56
+ constants,
57
+ openSync,
58
+ readdirSync,
59
+ renameSync,
60
+ unlinkSync,
61
+ writeSync,
62
+ } from "node:fs";
47
63
  import { join } from "node:path";
48
64
 
49
65
  import { parseArgs } from "../lib/args.mjs";
@@ -51,14 +67,23 @@ import { exitOnHelp } from "../lib/cli-help.mjs";
51
67
  import { installFatalHandlers } from "../lib/fatal.mjs";
52
68
  import { claimHookEvent } from "../lib/hook-once.mjs";
53
69
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
70
+ import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
54
71
  import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
55
72
  import { redact } from "../lib/redact.mjs";
56
73
  import { readRegularFile } from "../lib/regular-file.mjs";
74
+ import { mkdirSafe } from "../lib/safe-write.mjs";
57
75
  import { DEADLINE_MS, MAX_LOG_BYTES, appendLogRow, logDir } from "./note-skill-use.mjs";
76
+ import { syncCommandSentinel } from "./note-command-use.mjs";
58
77
 
59
78
  exitOnHelp(import.meta.url);
60
79
 
61
80
  export const LOG_FILE = "mcp-failures.jsonl";
81
+ export const CALLS_FILE = "mcp-calls.json";
82
+ export const CALLS_LOG = "mcp-calls.log";
83
+ export const CALLS_MAX_NAMES = 200;
84
+ export const CALLS_MAX_COUNT = 1_000_000;
85
+ const CALL_KEY = /^[A-Za-z0-9_-]{1,40}:[a-z0-9_]{1,64}$/;
86
+ export const COUNTING_SENTINEL = "mcp-counting-on";
62
87
  export const ROW_VERSION = "1.0.0";
63
88
  export const WINDOW_HOURS = 24;
64
89
  export const REPEAT_AT = 5;
@@ -218,6 +243,251 @@ export function record(payload, env = process.env) {
218
243
  return appendLogRow(LOG_FILE, row, env) ? row : null;
219
244
  }
220
245
 
246
+ /** Where the success counter lives: the same log directory the failure log uses. */
247
+ export const mcpCallsPath = (env = process.env) => join(logDir(env), CALLS_FILE);
248
+
249
+ const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
250
+ export const CALLS_MAX_SESSIONS = 20;
251
+
252
+ const plain = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
253
+
254
+ function newestFirst(map, keep) {
255
+ return Object.fromEntries(
256
+ Object.entries(map)
257
+ .sort((a, b) => (Date.parse(b[1]?.t) || 0) - (Date.parse(a[1]?.t) || 0))
258
+ .slice(0, keep),
259
+ );
260
+ }
261
+
262
+ /** The counter document, tolerant of a missing, damaged or older file. */
263
+ export function readCalls(env = process.env) {
264
+ let doc = null;
265
+ try {
266
+ doc = JSON.parse(readRegularFile(mcpCallsPath(env), { maxBytes: 4 * 1024 * 1024 }));
267
+ } catch {
268
+ /* missing or damaged: nothing counted yet */
269
+ }
270
+ return { v: 2, sessions: plain(doc?.sessions), bases: plain(doc?.bases) };
271
+ }
272
+
273
+ /**
274
+ * The counter turned into a run's own numbers: the host session's total minus
275
+ * what the session had counted when the run was first reported. The base is
276
+ * written the first time a run is seen (`establish`), so an earlier run in the
277
+ * same session is not counted again. Only the 20 newest sessions and runs are
278
+ * kept.
279
+ *
280
+ * @returns {Record<string, number>} `<server>:<tool>` to calls for this run
281
+ */
282
+ export function runCalls({ runId, sessionId, env = process.env, establish = false }) {
283
+ if (!runId || !SESSION_ID.test(String(sessionId ?? ""))) return {};
284
+ const delta = (doc) => {
285
+ const total = doc.sessions[sessionId]?.calls ?? {};
286
+ const base = doc.bases[runId]?.sid === sessionId ? (doc.bases[runId].calls ?? {}) : {};
287
+ const out = {};
288
+ for (const [name, n] of Object.entries(total)) {
289
+ const d = Number(n) - (Number(base[name]) || 0);
290
+ if (Number.isInteger(d) && d > 0) out[name] = d;
291
+ }
292
+ return out;
293
+ };
294
+ if (!establish) return delta(readCalls(env));
295
+ let result = {};
296
+ try {
297
+ updateJsonFileSync(
298
+ mcpCallsPath(env),
299
+ (current) => {
300
+ const doc = {
301
+ v: 2,
302
+ sessions: { ...plain(current?.sessions) },
303
+ bases: { ...plain(current?.bases) },
304
+ };
305
+ if (doc.bases[runId]?.sid !== sessionId) {
306
+ doc.bases[runId] = {
307
+ sid: sessionId,
308
+ t: new Date().toISOString(),
309
+ calls: { ...(doc.sessions[sessionId]?.calls ?? {}) },
310
+ };
311
+ doc.bases = newestFirst(doc.bases, CALLS_MAX_SESSIONS);
312
+ }
313
+ result = delta(doc);
314
+ return doc;
315
+ },
316
+ { fallback: {}, mode: 0o600, timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS) },
317
+ );
318
+ } catch {
319
+ result = delta(readCalls(env));
320
+ }
321
+ return result;
322
+ }
323
+
324
+ /** True when successful calls are counted: the failure-log switches, plus usage reporting on. */
325
+ export function callCountEnabled(env = process.env) {
326
+ return captureEnabled(env) && globalPref("usageLog.enabled", false, env) === true;
327
+ }
328
+
329
+ /** `<server>:<tool>` for a tool name, or null when it is not one to count. */
330
+ export function callKeyOf(toolName) {
331
+ const names = splitToolName(toolName);
332
+ if (!names) return null;
333
+ const key = `${names.server}:${names.tool.toLowerCase()}`;
334
+ return CALL_KEY.test(key) ? key : null;
335
+ }
336
+
337
+ /**
338
+ * Keep the marker the PostToolUse hook tests before it writes anything. The
339
+ * hook is a shell script with no JSON parser, so it cannot read the opt-out
340
+ * from the preferences reliably; it appends only while this file exists and the
341
+ * preferences are not newer than it. The file is created (or its time renewed)
342
+ * here, with the real parser, when counting is on, and removed when it is off.
343
+ * Never throws.
344
+ */
345
+ export function syncCountingSentinel(env = process.env) {
346
+ syncCommandSentinel(env);
347
+ try {
348
+ const dir = logDir(env);
349
+ const file = join(dir, COUNTING_SENTINEL);
350
+ if (!callCountEnabled(env)) {
351
+ try {
352
+ unlinkSync(file);
353
+ } catch {
354
+ /* not there */
355
+ }
356
+ discardCounted(env);
357
+ return false;
358
+ }
359
+ mkdirSafe(dir, { mode: 0o700, env });
360
+ const fd = openSync(
361
+ file,
362
+ constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
363
+ 0o600,
364
+ );
365
+ try {
366
+ writeSync(fd, "on\n");
367
+ } finally {
368
+ closeSync(fd);
369
+ }
370
+ return true;
371
+ } catch {
372
+ return false;
373
+ }
374
+ }
375
+
376
+ /** Where the hook appends. */
377
+ export const mcpCallsLogPath = (env = process.env) => join(logDir(env), CALLS_LOG);
378
+
379
+ /**
380
+ * Fold what note-mcp-call.sh appended into the per-session counter. Everything
381
+ * happens under the counter file's lock: the log is renamed (so the hook starts
382
+ * a fresh file), the renamed file and any leftover of an interrupted fold are
383
+ * read, their lines added to the counter, the files deleted and the counter
384
+ * written. Folds that run at the same time therefore take turns and never read
385
+ * the same lines; a line written by a hook that had the old file open in the
386
+ * instant of the rename is lost, which is the same kind of undercount as a call
387
+ * made before the run was reported. Lines that do not fit `<session id> <mcp
388
+ * tool name>` are skipped. Off, and the lines discarded, when the counter is
389
+ * off. Never throws.
390
+ *
391
+ * @returns {number} lines counted
392
+ */
393
+ export function foldCalls(env = process.env) {
394
+ let counted = 0;
395
+ try {
396
+ const dir = logDir(env);
397
+ const log = join(dir, CALLS_LOG);
398
+ const isPart = (f) => f === CALLS_LOG || f.startsWith(`${CALLS_LOG}.proc.`);
399
+ if (!readdirSync(dir).some(isPart)) return 0;
400
+ const enabled = callCountEnabled(env);
401
+ mkdirSafe(dir, { mode: 0o700, env });
402
+ updateJsonFileSync(
403
+ mcpCallsPath(env),
404
+ (current) => {
405
+ const mine = `${log}.proc.${process.pid}`;
406
+ try {
407
+ renameSync(log, mine);
408
+ } catch {
409
+ /* no new lines */
410
+ }
411
+ const files = readdirSync(dir)
412
+ .filter((f) => f.startsWith(`${CALLS_LOG}.proc.`))
413
+ .map((f) => join(dir, f));
414
+ const bySession = new Map();
415
+ for (const file of files) {
416
+ let text = "";
417
+ try {
418
+ if (enabled) text = readRegularFile(file, { maxBytes: 4 * 1024 * 1024, within: [dir] });
419
+ } catch {
420
+ /* unreadable: dropped with the file */
421
+ }
422
+ for (const line of text.split("\n")) {
423
+ const [sid, tool, extra] = line.split(" ");
424
+ if (extra !== undefined || !SESSION_ID.test(sid ?? "")) continue;
425
+ const key = callKeyOf(tool);
426
+ if (!key) continue;
427
+ const calls = bySession.get(sid) ?? new Map();
428
+ calls.set(key, (calls.get(key) ?? 0) + 1);
429
+ bySession.set(sid, calls);
430
+ }
431
+ try {
432
+ unlinkSync(file);
433
+ } catch {
434
+ /* already gone */
435
+ }
436
+ }
437
+ if (!bySession.size) return undefined;
438
+ const sessions = { ...plain(current?.sessions) };
439
+ const bases = { ...plain(current?.bases) };
440
+ for (const [sid, add] of bySession) {
441
+ const calls = { ...plain(plain(sessions[sid]).calls) };
442
+ for (const [key, n] of add) {
443
+ if (!Object.hasOwn(calls, key) && Object.keys(calls).length >= CALLS_MAX_NAMES)
444
+ continue;
445
+ const prior = Number.isInteger(calls[key]) && calls[key] > 0 ? calls[key] : 0;
446
+ calls[key] = Math.min(prior + n, CALLS_MAX_COUNT);
447
+ counted += n;
448
+ }
449
+ sessions[sid] = { t: new Date().toISOString(), calls };
450
+ }
451
+ return { v: 2, sessions: newestFirst(sessions, CALLS_MAX_SESSIONS), bases };
452
+ },
453
+ { fallback: {}, mode: 0o600, timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS) },
454
+ );
455
+ } catch {
456
+ /* the counter is bookkeeping */
457
+ }
458
+ return counted;
459
+ }
460
+
461
+ /**
462
+ * Forget every call counted so far: the hook's log and any leftover of a fold,
463
+ * and the counter's sessions and per-run bases. Called when counting is off, so
464
+ * what was seen while it was off can never be sent after it is turned back on.
465
+ * Never throws.
466
+ */
467
+ export function discardCounted(env = process.env) {
468
+ try {
469
+ const dir = logDir(env);
470
+ for (const f of readdirSync(dir)) {
471
+ if (f === CALLS_LOG || f.startsWith(`${CALLS_LOG}.proc.`)) {
472
+ try {
473
+ unlinkSync(join(dir, f));
474
+ } catch {
475
+ /* already gone */
476
+ }
477
+ }
478
+ }
479
+ if (readdirSync(dir).includes(CALLS_FILE)) {
480
+ updateJsonFileSync(mcpCallsPath(env), () => ({ v: 2, sessions: {}, bases: {} }), {
481
+ fallback: {},
482
+ mode: 0o600,
483
+ timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS),
484
+ });
485
+ }
486
+ } catch {
487
+ /* nothing counted, nothing to forget */
488
+ }
489
+ }
490
+
221
491
  /**
222
492
  * Every readable row of the log and its previous generation, oldest first. A
223
493
  * generation that is not a regular file, resolves outside the log directory,
@@ -346,6 +616,7 @@ async function hookMain() {
346
616
  return;
347
617
  }
348
618
  if (!claimHookEvent("note-mcp-failure", payload)) return;
619
+ syncCountingSentinel();
349
620
  record(payload);
350
621
  }
351
622
 
@@ -67,7 +67,7 @@ OUT="$OUT_DIR/session-notes.jsonl"
67
67
 
68
68
  TRANSCRIPT="$TRANSCRIPT" REPO_SLUG="$REPO_SLUG" OUT="$OUT" DRY="$DRY" JSON="$JSON" \
69
69
  python3 - <<'PY'
70
- import json, os, re, sys
70
+ import json, os, re, sys, time
71
71
  from collections import Counter
72
72
  from datetime import datetime, timezone
73
73
 
@@ -177,8 +177,67 @@ if os.environ.get("DRY") == "1":
177
177
  sys.exit(0)
178
178
 
179
179
  out = os.environ["OUT"]
180
- os.makedirs(os.path.dirname(out), exist_ok=True)
181
- with open(out, "a", encoding="utf-8") as fh:
180
+ os.makedirs(os.path.dirname(out), mode=0o700, exist_ok=True)
181
+ MAX_LOG_BYTES = 1024 * 1024
182
+ LOCK_STALE_S = 10
183
+ LOCK_WAIT_S = 0.2
184
+
185
+
186
+ def full():
187
+ try:
188
+ return os.path.getsize(out) > MAX_LOG_BYTES
189
+ except OSError:
190
+ return False
191
+
192
+
193
+ def rotate_locked():
194
+ """Move a full log to .1 under <out>.lock, the lock note-skill-use.mjs takes
195
+ for the same file, and re-read the size once it is held, so a second writer
196
+ that saw the same full log does not move the fresh one over .1."""
197
+ if not full():
198
+ return
199
+ lock = out + ".lock"
200
+ deadline = time.time() + LOCK_WAIT_S
201
+ held = False
202
+ while True:
203
+ try:
204
+ lock_fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
205
+ os.close(lock_fd)
206
+ held = True
207
+ break
208
+ except FileExistsError:
209
+ try:
210
+ if time.time() - os.lstat(lock).st_mtime > LOCK_STALE_S:
211
+ os.unlink(lock)
212
+ continue
213
+ except OSError:
214
+ pass
215
+ if time.time() > deadline:
216
+ break
217
+ time.sleep(0.005)
218
+ except OSError:
219
+ break
220
+ if not held:
221
+ return
222
+ try:
223
+ if full():
224
+ os.replace(out, out + ".1")
225
+ except OSError:
226
+ pass
227
+ finally:
228
+ try:
229
+ os.unlink(lock)
230
+ except OSError:
231
+ pass
232
+
233
+
234
+ rotate_locked()
235
+ fd = os.open(out, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
236
+ try:
237
+ os.fchmod(fd, 0o600)
238
+ except OSError:
239
+ pass
240
+ with os.fdopen(fd, "a", encoding="utf-8") as fh:
182
241
  fh.write(json.dumps(row, ensure_ascii=False) + "\n")
183
242
 
184
243
  print(json.dumps({"status": "written", "path": out, "errors": errors,
@@ -42,7 +42,16 @@
42
42
  * @module pipeline/scripts/note-skill-use
43
43
  */
44
44
 
45
- import { existsSync, readFileSync, statSync } from "node:fs";
45
+ import {
46
+ closeSync,
47
+ constants,
48
+ existsSync,
49
+ fchmodSync,
50
+ fstatSync,
51
+ openSync,
52
+ readFileSync,
53
+ statSync,
54
+ } from "node:fs";
46
55
  import { homedir } from "node:os";
47
56
  import { basename, dirname, join, resolve } from "node:path";
48
57
 
@@ -213,6 +222,45 @@ function takeLock(lock, opts, now = Date.now()) {
213
222
  return false;
214
223
  }
215
224
 
225
+ /**
226
+ * Run `fn` while holding <file>.lock, the lock every writer of the local logs
227
+ * takes before a rotation. Waits up to LOCK_WAIT_MS; when the lock stays busy
228
+ * `fn` is not run and undefined is returned, since the holder is rotating.
229
+ */
230
+ export function withRotationLock(file, opts, fn) {
231
+ const lock = `${file}.lock`;
232
+ let held = takeLock(lock, opts);
233
+ for (let waited = 0; !held && waited < LOCK_WAIT_MS; waited += LOCK_POLL_MS) {
234
+ pause(LOCK_POLL_MS);
235
+ held = takeLock(lock, opts);
236
+ }
237
+ if (!held) return undefined;
238
+ try {
239
+ return fn();
240
+ } finally {
241
+ unlinkSafe(lock, opts);
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Make an existing log owner-only. A log created by an older version, or by a
247
+ * shell redirect under a permissive umask, can be 0644; the first write after
248
+ * this change tightens it. Opened without following a link, so a link planted
249
+ * at the name is left alone. Never throws.
250
+ */
251
+ export function tightenMode(file) {
252
+ let fd;
253
+ try {
254
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
255
+ const st = fstatSync(fd);
256
+ if (st.isFile() && (st.mode & 0o077) !== 0) fchmodSync(fd, 0o600);
257
+ } catch {
258
+ /* absent, a link, or not ours to change */
259
+ } finally {
260
+ if (fd !== undefined) closeSync(fd);
261
+ }
262
+ }
263
+
216
264
  /**
217
265
  * Move a full log to .1. One writer rotates at a time, under an O_EXCL lock,
218
266
  * and re-reads the size once it holds it, so a writer that saw the full log
@@ -275,10 +323,18 @@ function rotateIfFull(file, opts) {
275
323
  * write failure, a linked directory on the way included.
276
324
  */
277
325
  export function appendLogRow(name, row, env = process.env) {
278
- const dir = logDir(env);
326
+ return appendRowIn(logDir(env), name, row, env);
327
+ }
328
+
329
+ /**
330
+ * appendLogRow for a log that lives in another directory (the per-repo
331
+ * session notes): the same cap, generation, lock and link refusal.
332
+ */
333
+ export function appendRowIn(dir, name, row, env = process.env) {
279
334
  mkdirSafe(dir, { mode: 0o700, env });
280
335
  const file = join(dir, name);
281
336
  if (!rotateIfFull(file, { env })) return false;
337
+ tightenMode(file);
282
338
  try {
283
339
  appendFileSafe(file, JSON.stringify(row) + "\n", { mode: 0o600, env });
284
340
  return true;
@@ -24,12 +24,14 @@
24
24
  */
25
25
 
26
26
  import { createHash } from "node:crypto";
27
- import { readFileSync, readdirSync, writeFileSync } from "node:fs";
27
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
28
28
  import { deflateSync, inflateSync } from "node:zlib";
29
29
  import { basename, join } from "node:path";
30
30
  import { pathToFileURL } from "node:url";
31
+ import vm from "node:vm";
31
32
 
32
33
  import { APP_ICON_SIZES, THEME_COLOR } from "./office-webapp.mjs";
34
+ import { catalog, commandsDir } from "./commands.mjs";
33
35
 
34
36
  const ROOT = join(import.meta.dirname, "..");
35
37
  const SRC = join(ROOT, "office-src");
@@ -886,6 +888,7 @@ export const APP_MODULES = [
886
888
  "panel-server.js",
887
889
  "panel-archive.js",
888
890
  "demo.js",
891
+ "progress-draft.js",
889
892
  "start.js",
890
893
  ];
891
894
  // The /* global */ and /* exported */ lines that tell the linter what a module
@@ -901,7 +904,117 @@ export function appSource() {
901
904
  ).join("\n\n");
902
905
  }
903
906
 
907
+ // --- how the office handles each command ---------------------------------------
908
+ // office-src/command-routes.json names every command: "start" (a job in
909
+ // schemas/office-jobs.json runs it), "window:<id>" or "terminal:<reason>".
910
+ // Nothing is defaulted: a command without an entry, or an entry without a
911
+ // command, fails the build, so a new command is a decision and not a silent
912
+ // terminal-only.
913
+
914
+ export const TERMINAL_REASONS = ["approval", "device", "freeform", "machine", "self"];
915
+ const ROOT_COMMAND = "multi-agent";
916
+
917
+ /** The page's own first-listed-wins job lookup, run from core.js so there is one definition. */
918
+ export function pageJobByCommand(jobs) {
919
+ const core = readFileSync(join(SRC, "app", "core.js"), "utf8");
920
+ const start = core.indexOf("function jobByCommand(");
921
+ const end = core.indexOf("\n}\n", start);
922
+ if (start < 0 || end < 0) throw new Error("core.js has no jobByCommand function");
923
+ const ctx = vm.createContext({});
924
+ vm.runInContext(`${core.slice(start, end + 3)}\nthis.fn = jobByCommand;`, ctx);
925
+ return ctx.fn(jobs);
926
+ }
927
+
928
+ /** Every command the office can be asked about: the catalog plus the root command. */
929
+ export function commandIds(dir) {
930
+ const cat = catalog(dir);
931
+ if (!cat) return [];
932
+ const ids = cat.commands.map((c) => c.id);
933
+ if (existsSync(join(commandsDir(dir), "SKILL.md")) && !ids.includes(ROOT_COMMAND))
934
+ ids.unshift(ROOT_COMMAND);
935
+ return ids;
936
+ }
937
+
938
+ /** The windows the page can open: every `loaders.<id> =` its modules assign. */
939
+ export function windowIds() {
940
+ const ids = new Set();
941
+ for (const m of appSource().matchAll(/\bloaders\.([A-Za-z]\w*)\s*=/g)) ids.add(m[1]);
942
+ return ids;
943
+ }
944
+
945
+ /** Keys that appear more than once in a JSON object text; JSON.parse keeps the last silently. */
946
+ export function duplicateKeys(text) {
947
+ const seen = new Set();
948
+ const twice = [];
949
+ for (const m of text.matchAll(/"((?:[^"\\]|\\.)*)"\s*:/g)) {
950
+ if (seen.has(m[1]) && !twice.includes(m[1])) twice.push(m[1]);
951
+ seen.add(m[1]);
952
+ }
953
+ return twice;
954
+ }
955
+
956
+ /** The routes table and what is wrong with its text. */
957
+ export function readRoutes(file) {
958
+ const text = readFileSync(file, "utf8");
959
+ return {
960
+ routes: JSON.parse(text).commands,
961
+ problems: duplicateKeys(text).map(
962
+ (id) => `command-routes.json names "${id}" more than once; only the last would count`,
963
+ ),
964
+ };
965
+ }
966
+
967
+ const has = (table, key) => Object.hasOwn(table, key);
968
+
969
+ /** What is wrong with a routes table next to the command list, the jobs and the windows. */
970
+ export function routeProblems({ ids, routes, jobs, windows = windowIds() }) {
971
+ const problems = [];
972
+ const known = new Set(ids);
973
+ const byCommand = pageJobByCommand(jobs);
974
+ for (const id of ids) {
975
+ if (!has(routes, id)) {
976
+ problems.push(`command-routes.json has no entry for the command "${id}"`);
977
+ continue;
978
+ }
979
+ const r = routes[id];
980
+ const window = /^window:(\w+)$/.exec(r);
981
+ const terminal = /^terminal:(\w+)$/.exec(r);
982
+ if (r === "start") {
983
+ if (!byCommand.has(id))
984
+ problems.push(`"${id}" is routed "start" but no job in office-jobs.json runs it`);
985
+ } else if (window || terminal) {
986
+ if (byCommand.has(id))
987
+ problems.push(
988
+ `"${id}" has a job in office-jobs.json, so its route must be "start", not "${r}"`,
989
+ );
990
+ if (terminal && !TERMINAL_REASONS.includes(terminal[1]))
991
+ problems.push(`"${id}" has the unknown terminal reason "${terminal[1]}"`);
992
+ if (window && !windows.has(window[1]))
993
+ problems.push(`"${id}" opens the window "${window[1]}", which the page does not have`);
994
+ } else
995
+ problems.push(`"${id}" has the route "${r}"; use start, window:<id> or terminal:<reason>`);
996
+ }
997
+ for (const id of Object.keys(routes))
998
+ if (!known.has(id))
999
+ problems.push(`command-routes.json has an entry for "${id}", which is not a command`);
1000
+ for (const id of byCommand.keys())
1001
+ if (!known.has(id)) problems.push(`office-jobs.json runs "${id}", which is not a command`);
1002
+ return problems;
1003
+ }
1004
+
1005
+ /** The routes problems for the repository's own command tree; empty when it has none. */
1006
+ export function repoRouteProblems() {
1007
+ const tree = join(ROOT, "commands", "multi-agent");
1008
+ if (!existsSync(tree)) return [];
1009
+ const ids = commandIds(tree);
1010
+ const { routes, problems } = readRoutes(join(SRC, "command-routes.json"));
1011
+ const jobs = JSON.parse(readFileSync(join(ROOT, "schemas", "office-jobs.json"), "utf8")).jobs;
1012
+ return [...problems, ...routeProblems({ ids, routes, jobs })];
1013
+ }
1014
+
904
1015
  export function build() {
1016
+ const problems = repoRouteProblems();
1017
+ if (problems.length) throw new Error(`command-routes.json: ${problems.join("; ")}`);
905
1018
  const read = (f) => readFileSync(join(SRC, f), "utf8");
906
1019
  const strings = JSON.parse(read("strings.json"));
907
1020
  const sprites = atlas();
@@ -913,6 +1026,7 @@ export function build() {
913
1026
  `const ATLAS = ${JSON.stringify(sprites)};`,
914
1027
  `const STRINGS = ${JSON.stringify(strings)};`,
915
1028
  `const EMPLOYEES = ${JSON.stringify(staff.people)};`,
1029
+ `const COMMAND_ROUTES = ${JSON.stringify(JSON.parse(read("command-routes.json")))};`,
916
1030
  'const spriteUrl = (name) => "/office/assets/" + name + ".png";',
917
1031
  read("world.js").trim(),
918
1032
  appSource(),
@@ -122,6 +122,15 @@ export async function store(path, maxBytes) {
122
122
  }
123
123
  }
124
124
 
125
+ /**
126
+ * A store that rotates to `<path>.1`: both generations as one store, the
127
+ * previous one first, so the count and the tail run across a rotation.
128
+ */
129
+ export async function rotatedStore(path, maxBytes) {
130
+ const [older, current] = await Promise.all([store(`${path}.1`, maxBytes), store(path, maxBytes)]);
131
+ return { count: older.count + current.count, tail: [...older.tail, ...current.tail] };
132
+ }
133
+
125
134
  const ms = (v) => {
126
135
  const t = Date.parse(v ?? "");
127
136
  return Number.isFinite(t) ? t : null;
@@ -140,11 +149,11 @@ async function shelf(name, r, now, R, maxBytes) {
140
149
  sizeKb: Math.round(st.size / 1024),
141
150
  };
142
151
  }
143
- const [learnings, findings, notes] = await Promise.all(
144
- ["learnings-ledger.jsonl", "triage-corpus.jsonl", "session-notes.jsonl"].map((f) =>
145
- store(join(dir, f), maxBytes),
146
- ),
147
- );
152
+ const [learnings, findings, notes] = await Promise.all([
153
+ store(join(dir, "learnings-ledger.jsonl"), maxBytes),
154
+ store(join(dir, "triage-corpus.jsonl"), maxBytes),
155
+ rotatedStore(join(dir, "session-notes.jsonl"), maxBytes),
156
+ ]);
148
157
  const times = [...learnings.tail, ...findings.tail, ...notes.tail]
149
158
  .map((x) => ms(x.ts))
150
159
  .filter((t) => t !== null);