@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -0,0 +1,356 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file note-mcp-failure.mjs - one row per failed MCP tool call, in a local
4
+ * log, so a server that keeps failing shows up in doctor instead of being
5
+ * rediscovered call by call.
6
+ *
7
+ * Registered on PostToolUseFailure with the matcher `mcp__.*`. The row holds
8
+ * four facts and nothing else:
9
+ *
10
+ * server the MCP server, from the tool name mcp__<server>__<tool>
11
+ * tool the tool, from the same name
12
+ * ts when the hook ran
13
+ * errorClass one of ERROR_CLASSES, chosen from the error text: a JSON-RPC
14
+ * code first, then a message that opens with "invalid" or
15
+ * "validation", then an HTTP status, then fixed wording
16
+ * patterns; the text itself is never stored
17
+ *
18
+ * A name part outside NAME_PART (a strict charset and length) or carrying a
19
+ * credential pattern drops the whole call. The tool's arguments, its output
20
+ * and the error text are never written. No server is probed: the counter
21
+ * only sees the calls the session already made.
22
+ *
23
+ * The log is <LOGS_ROOT or ~/.claude/logs/multi-agent>/mcp-failures.jsonl,
24
+ * written through note-skill-use.mjs appendLogRow: the same 1 MiB cap, single
25
+ * .1 generation and O_EXCL rotation code as the skill-usage log, with its own
26
+ * lock file (mcp-failures.jsonl.lock), so the two logs never wait on each other.
27
+ *
28
+ * Off with prefs.global.mcpFailures.enabled false, with
29
+ * prefs.global.usageLog.optOut true, and while the preferences file exists
30
+ * but cannot be read or parsed, since an opt-out in it cannot be seen.
31
+ * Nothing leaves the machine either way.
32
+ *
33
+ * Fast and fail-open: stdin is read for at most DEADLINE_MS and every failure
34
+ * ends in exit 0 with no output, so the tool call is never held.
35
+ *
36
+ * note-mcp-failure.mjs hook mode, payload on stdin
37
+ * note-mcp-failure.mjs summary [--hours N] [--json]
38
+ * failures per server and per tool in the last N hours (default 24),
39
+ * and the servers that failed REPEAT_AT times or more on the server's
40
+ * side (invalid-input, denied and interrupted are the caller's or the
41
+ * user's, so they are counted as calls but not as failures)
42
+ *
43
+ * @module pipeline/scripts/note-mcp-failure
44
+ */
45
+
46
+ import { join } from "node:path";
47
+
48
+ import { parseArgs } from "../lib/args.mjs";
49
+ import { exitOnHelp } from "../lib/cli-help.mjs";
50
+ import { installFatalHandlers } from "../lib/fatal.mjs";
51
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
52
+ import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
53
+ import { redact } from "../lib/redact.mjs";
54
+ import { readRegularFile } from "../lib/regular-file.mjs";
55
+ import { DEADLINE_MS, MAX_LOG_BYTES, appendLogRow, logDir } from "./note-skill-use.mjs";
56
+
57
+ exitOnHelp(import.meta.url);
58
+
59
+ export const LOG_FILE = "mcp-failures.jsonl";
60
+ export const ROW_VERSION = "1.0.0";
61
+ export const WINDOW_HOURS = 24;
62
+ export const REPEAT_AT = 5;
63
+ export const NAME_PART = /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/;
64
+ const MAX_INPUT = 512 * 1024;
65
+ const ERROR_SCAN_MAX = 4096;
66
+ const READ_MAX = 4 * MAX_LOG_BYTES;
67
+
68
+ /** A refusal by the user or the host's permission layer, never by the server. */
69
+ const DENIED =
70
+ /doesn't want to proceed|(?:was|were) rejected by the user|permission to use \S+ (?:was|has been) denied|denied by the user|user denied/i;
71
+
72
+ /**
73
+ * JSON-RPC codes, read before any wording because a server's message text can
74
+ * say anything. -32000 and -32001 are the MCP SDK's connection-closed and
75
+ * request-timeout codes; -32002 is MCP's resource not found; the rest of the
76
+ * -32000..-32099 range is implementation-defined server error.
77
+ */
78
+ const JSONRPC_CODES = new Map([
79
+ [-32700, "invalid-input"],
80
+ [-32600, "invalid-input"],
81
+ [-32601, "not-found"],
82
+ [-32602, "invalid-input"],
83
+ [-32603, "server-error"],
84
+ [-32000, "connection"],
85
+ [-32001, "timeout"],
86
+ [-32002, "not-found"],
87
+ ]);
88
+ const JSONRPC_CODE = /(?:^|[^\w-])(-32\d{3})\b/;
89
+
90
+ /**
91
+ * An HTTP status only where the text says it is one: after HTTP, HTTP/x.y,
92
+ * status or status code, at the end of a request line (a method and a URL),
93
+ * or before a reason phrase. A bare three-digit number ("got 404", "max
94
+ * length (500)", "retry after 500") is not a status, nor is one inside a
95
+ * path or a host:port.
96
+ */
97
+ const HTTP_STATUS = [
98
+ /\bHTTP(?:\/\d(?:\.\d)?)?:?\s+([1-5]\d\d)\b/i,
99
+ /\bstatus(?:\s+code)?\s*[:=]?\s*([1-5]\d\d)\b/i,
100
+ /\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\S+\s+([1-5]\d\d)\b/,
101
+ /(?:^|\s)([1-5]\d\d)\s+(?:internal server error|bad gateway|service unavailable|gateway time-?out|unauthori[sz]ed|forbidden|not found|too many requests|bad request|unprocessable)/i,
102
+ ];
103
+
104
+ /** A message that opens by saying the input was invalid is the caller's. */
105
+ const INVALID_PREFIX = /^\s*(?:error:\s*)?(?:invalid|validation)\b/i;
106
+
107
+ function statusClass(status) {
108
+ if (status >= 500) return "server-error";
109
+ if (status === 401 || status === 403) return "auth";
110
+ if (status === 404) return "not-found";
111
+ if (status === 408) return "timeout";
112
+ if (status === 429) return "rate-limit";
113
+ if (status === 400 || status === 422) return "invalid-input";
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Wording, read only when no code or status decided. First match wins, and a
119
+ * server-side class comes before invalid-input: a message that names both is
120
+ * the server failing, and invalid-input is not counted against a server.
121
+ */
122
+ const CLASS_PATTERNS = [
123
+ ["timeout", /timed out|deadline exceeded|ETIMEDOUT|timeout (?:error|exceeded|after)/i],
124
+ ["rate-limit", /rate.?limit|too many requests/i],
125
+ ["auth", /unauthori[sz]ed|forbidden|authenticat|expired token|token expired|invalid token/i],
126
+ [
127
+ "connection",
128
+ /connection (?:closed|refused|reset)|ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|socket hang up|not connected|disconnected|failed to (?:start|connect)/i,
129
+ ],
130
+ [
131
+ "server-error",
132
+ /internal (?:server )?error|server error|service unavailable|bad gateway|is unavailable/i,
133
+ ],
134
+ ["not-found", /not found|no such tool|unknown tool/i],
135
+ [
136
+ "invalid-input",
137
+ /invalid (?:params|parameters?|arguments?|input|request)|validation (?:error|failed)|failed validation|does not match (?:the )?schema|is required|must be/i,
138
+ ],
139
+ ];
140
+
141
+ export const ERROR_CLASSES = Object.freeze([
142
+ "denied",
143
+ ...CLASS_PATTERNS.map(([c]) => c),
144
+ "interrupted",
145
+ "other",
146
+ ]);
147
+
148
+ /** Classes that say nothing about the server's health. */
149
+ export const CALLER_SIDE = new Set(["invalid-input", "denied", "interrupted"]);
150
+
151
+ /** {server, tool} for an MCP tool name, or null when it is not one to keep. */
152
+ export function splitToolName(name) {
153
+ if (typeof name !== "string" || !name.startsWith("mcp__")) return null;
154
+ const rest = name.slice(5);
155
+ const at = rest.indexOf("__");
156
+ if (at <= 0) return null;
157
+ const server = rest.slice(0, at);
158
+ const tool = rest.slice(at + 2);
159
+ for (const part of [server, tool]) {
160
+ if (!NAME_PART.test(part) || redact(part) !== part) return null;
161
+ }
162
+ return { server, tool };
163
+ }
164
+
165
+ /** The closed class of a failure payload; the error text is read, never kept. */
166
+ export function errorClass(payload) {
167
+ if (payload?.is_interrupt === true) return "interrupted";
168
+ const text = typeof payload?.error === "string" ? payload.error.slice(0, ERROR_SCAN_MAX) : "";
169
+ if (DENIED.test(text)) return "denied";
170
+ const code = JSONRPC_CODE.exec(text);
171
+ if (code) {
172
+ const n = Number(code[1]);
173
+ const cls = JSONRPC_CODES.get(n) ?? (n >= -32099 && n <= -32000 ? "server-error" : null);
174
+ if (cls) return cls;
175
+ }
176
+ if (INVALID_PREFIX.test(text)) return "invalid-input";
177
+ for (const re of HTTP_STATUS) {
178
+ const m = re.exec(text);
179
+ const cls = m && statusClass(Number(m[1]));
180
+ if (cls) return cls;
181
+ }
182
+ for (const [cls, re] of CLASS_PATTERNS) if (re.test(text)) return cls;
183
+ return "other";
184
+ }
185
+
186
+ /** The row for one hook payload, or null when it is not an MCP failure to keep. */
187
+ export function rowFor(payload, now = Date.now()) {
188
+ if (payload?.hook_event_name !== "PostToolUseFailure") return null;
189
+ const names = splitToolName(payload.tool_name);
190
+ if (!names) return null;
191
+ return {
192
+ v: ROW_VERSION,
193
+ ts: new Date(now).toISOString(),
194
+ server: names.server,
195
+ tool: names.tool,
196
+ errorClass: errorClass(payload),
197
+ };
198
+ }
199
+
200
+ /** False when the user turned the counter off. */
201
+ export function captureEnabled(env = process.env) {
202
+ const found = findPrefs(env);
203
+ if (found && found.status !== "ok") return false;
204
+ if (globalPref("mcpFailures.enabled", true, env) === false) return false;
205
+ return globalPref("usageLog.optOut", false, env) !== true;
206
+ }
207
+
208
+ /** Build and append the row for a payload. Returns the row written, or null. */
209
+ export function record(payload, env = process.env) {
210
+ const row = rowFor(payload);
211
+ if (!row || !captureEnabled(env)) return null;
212
+ return appendLogRow(LOG_FILE, row, env) ? row : null;
213
+ }
214
+
215
+ /**
216
+ * Every readable row of the log and its previous generation, oldest first. A
217
+ * generation that is not a regular file, resolves outside the log directory,
218
+ * or is past READ_MAX, is skipped.
219
+ */
220
+ export function readFailures(env = process.env) {
221
+ const dir = logDir(env);
222
+ const file = join(dir, LOG_FILE);
223
+ const out = [];
224
+ for (const p of [`${file}.1`, file]) {
225
+ let text;
226
+ try {
227
+ text = readRegularFile(p, { maxBytes: READ_MAX, within: [dir] });
228
+ } catch {
229
+ continue;
230
+ }
231
+ for (const line of text.split("\n")) {
232
+ if (!line.startsWith("{")) continue;
233
+ try {
234
+ const r = JSON.parse(line);
235
+ if (typeof r.server === "string" && typeof r.tool === "string") out.push(r);
236
+ } catch {
237
+ /* a torn line */
238
+ }
239
+ }
240
+ }
241
+ return out;
242
+ }
243
+
244
+ /**
245
+ * Calls and server-side failures per server inside the window, most failures
246
+ * first, and the servers whose failures reached `repeatAt`.
247
+ */
248
+ export function failureSummary(
249
+ rows,
250
+ { now = Date.now(), hours = WINDOW_HOURS, repeatAt = REPEAT_AT } = {},
251
+ ) {
252
+ const since = now - hours * 3600_000;
253
+ const by = new Map();
254
+ for (const r of rows) {
255
+ const t = Date.parse(r.ts);
256
+ if (!(t >= since && t <= now)) continue;
257
+ if (!by.has(r.server)) {
258
+ by.set(r.server, {
259
+ server: r.server,
260
+ calls: 0,
261
+ failures: 0,
262
+ tools: new Map(),
263
+ classes: new Map(),
264
+ last: null,
265
+ });
266
+ }
267
+ const s = by.get(r.server);
268
+ const cls = ERROR_CLASSES.includes(r.errorClass) ? r.errorClass : "other";
269
+ s.calls++;
270
+ if (!CALLER_SIDE.has(cls)) s.failures++;
271
+ s.tools.set(r.tool, (s.tools.get(r.tool) ?? 0) + 1);
272
+ s.classes.set(cls, (s.classes.get(cls) ?? 0) + 1);
273
+ if (!s.last || r.ts > s.last) s.last = r.ts;
274
+ }
275
+ const sortKeys = (m) => Object.fromEntries([...m].sort(([a], [b]) => (a < b ? -1 : 1)));
276
+ const servers = [...by.values()]
277
+ .map((s) => ({ ...s, tools: sortKeys(s.tools), classes: sortKeys(s.classes) }))
278
+ .sort((a, b) => b.failures - a.failures || (a.server < b.server ? -1 : 1));
279
+ return {
280
+ hours,
281
+ repeatAt,
282
+ servers,
283
+ repeated: servers.filter((s) => s.failures >= repeatAt).map((s) => s.server),
284
+ };
285
+ }
286
+
287
+ function summaryMain(argv) {
288
+ const { flags } = parseArgs(argv);
289
+ const hours = Number(flags.hours) > 0 ? Number(flags.hours) : WINDOW_HOURS;
290
+ const s = failureSummary(readFailures(), { hours });
291
+ if (flags.json === true) {
292
+ process.stdout.write(JSON.stringify({ enabled: captureEnabled(), ...s }, null, 2) + "\n");
293
+ return;
294
+ }
295
+ if (!s.servers.length) {
296
+ process.stdout.write(`no MCP failures recorded in the last ${hours} hours\n`);
297
+ return;
298
+ }
299
+ for (const v of s.servers) {
300
+ const classes = Object.entries(v.classes)
301
+ .map(([c, n]) => `${c} ${n}`)
302
+ .join(", ");
303
+ process.stdout.write(
304
+ `${v.server}: ${v.failures} server-side failures of ${v.calls} failed calls (${classes})\n`,
305
+ );
306
+ }
307
+ }
308
+
309
+ /** stdin as text, or null once DEADLINE_MS passes or it grows past MAX_INPUT. */
310
+ function readStdin() {
311
+ return new Promise((resolve) => {
312
+ const parts = [];
313
+ let size = 0;
314
+ const done = (value) => {
315
+ clearTimeout(timer);
316
+ process.stdin.removeAllListeners();
317
+ process.stdin.destroy();
318
+ resolve(value);
319
+ };
320
+ const timer = setTimeout(() => done(null), DEADLINE_MS);
321
+ process.stdin.on("data", (chunk) => {
322
+ size += chunk.length;
323
+ if (size > MAX_INPUT) return done(null);
324
+ parts.push(chunk);
325
+ });
326
+ process.stdin.on("end", () => done(Buffer.concat(parts).toString("utf8")));
327
+ process.stdin.on("error", () => done(null));
328
+ });
329
+ }
330
+
331
+ async function hookMain() {
332
+ const stop = setTimeout(() => process.exit(0), DEADLINE_MS * 2);
333
+ stop.unref();
334
+ const raw = await readStdin();
335
+ if (!raw) return;
336
+ let payload;
337
+ try {
338
+ payload = JSON.parse(raw);
339
+ } catch {
340
+ return;
341
+ }
342
+ record(payload);
343
+ }
344
+
345
+ if (invokedDirectly(import.meta.url)) {
346
+ const argv = process.argv.slice(2);
347
+ if (argv[0] === "summary") {
348
+ installFatalHandlers({ name: "note-mcp-failure" });
349
+ summaryMain(argv.slice(1));
350
+ } else {
351
+ installFatalHandlers({ name: "note-mcp-failure", code: 0 });
352
+ hookMain()
353
+ .catch(() => {})
354
+ .finally(() => process.exit(0));
355
+ }
356
+ }
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env bash
2
+ # note-mcp-failure.sh - PostToolUseFailure hook on MCP tools (mcp__.*).
3
+ #
4
+ # Appends the server, the tool, the time and a closed error class to the local
5
+ # MCP failure log. The logic is in note-mcp-failure.mjs; this wrapper exists
6
+ # because every hook the pipeline registers is a
7
+ # `bash "$HOME/.<host>/scripts/<name>"` command.
8
+ #
9
+ # Exits 0 on every path with no output: bookkeeping never holds a tool call.
10
+
11
+ set -u
12
+
13
+ HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
14
+ CORE="$HERE/note-mcp-failure.mjs"
15
+ [ -f "$CORE" ] || exit 0
16
+ command -v node >/dev/null 2>&1 || exit 0
17
+
18
+ node "$CORE" >/dev/null 2>&1 || true
19
+ exit 0
@@ -22,9 +22,14 @@
22
22
  * The log is <LOGS_ROOT or ~/.claude/logs/multi-agent>/skill-usage.jsonl. Past
23
23
  * MAX_LOG_BYTES it moves to skill-usage.jsonl.1, replacing the generation
24
24
  * before it, the same single-generation cap the office's audit logs use. One
25
- * writer rotates at a time, under skill-usage.jsonl.lock (O_EXCL; a lock older
26
- * than LOCK_STALE_MS is taken over); a writer that finds it held appends
27
- * without rotating.
25
+ * writer rotates at a time, under skill-usage.jsonl.lock (O_EXCL; a lock file
26
+ * older than LOCK_STALE_MS is taken over, and a link or other non-file at the
27
+ * lock's name is never a live lock and is unlinked itself). A writer that
28
+ * finds the lock held waits up to LOCK_WAIT_MS for the rotation; when the log
29
+ * is still full after that, or cannot rotate because .1 is a directory, the
30
+ * row is dropped, so the log never grows past the cap. A .1 that is a
31
+ * symlink, a FIFO or another non-regular file is replaced by the rename, so
32
+ * rotation never writes through it.
28
33
  *
29
34
  * Off with prefs.global.skillUsage.enabled false, and with
30
35
  * prefs.global.usageLog.optOut true: an opt-out from passive collection covers
@@ -67,6 +72,9 @@ export const SKILL_NAME_MAX = 96;
67
72
  export const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*(?::[A-Za-z0-9][A-Za-z0-9._-]*){0,2}$/;
68
73
  const MAX_INPUT = 512 * 1024;
69
74
  const LOCK_STALE_MS = 10_000;
75
+ const LOCK_WAIT_MS = 200;
76
+ const LOCK_POLL_MS = 5;
77
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
70
78
 
71
79
  /** The log directory: LOGS_ROOT, else ~/.claude/logs/multi-agent. */
72
80
  export const logDir = (env = process.env) =>
@@ -155,13 +163,28 @@ async function rowRepo(cwd, env) {
155
163
  }
156
164
  }
157
165
 
158
- /** The log's size; a link or anything but a regular file there throws. */
159
- const sizeOf = (file, opts) => statSafe(file, opts)?.size ?? 0;
166
+ /**
167
+ * The log's size: 0 when nothing is there, null when a link, a FIFO, a
168
+ * directory or anything but a regular file stands at the name.
169
+ */
170
+ function logSize(file, opts) {
171
+ try {
172
+ return statSafe(file, opts)?.size ?? 0;
173
+ } catch (e) {
174
+ if (e.code === "ENOTREG" || e.code === "ELINKED") return null;
175
+ throw e;
176
+ }
177
+ }
178
+
179
+ /** Errors an append gives for a path that is not a regular file: the row is dropped. */
180
+ const NOT_REGULAR = new Set(["ELOOP", "EMLINK", "ENXIO", "EISDIR", "ENOTDIR", "ENOTREG"]);
181
+ /** Errors a rename onto a .1 that is a directory gives: the log cannot rotate. */
182
+ const ROTATE_BLOCKED = new Set(["EISDIR", "ENOTEMPTY", "EEXIST"]);
160
183
 
161
184
  /**
162
- * The rotation lock, or false when another writer holds a live one. The lock
163
- * is a file made with O_EXCL in the pinned log directory; a link, FIFO or
164
- * other non-file at its name is never a live lock and is unlinked itself.
185
+ * Take the rotation lock; false when another writer holds a live one. The
186
+ * lock is a file made with O_EXCL in the pinned log directory; a link, FIFO
187
+ * or other non-file at its name is never a live lock and is unlinked itself.
165
188
  */
166
189
  function takeLock(lock, opts, now = Date.now()) {
167
190
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -191,33 +214,81 @@ function takeLock(lock, opts, now = Date.now()) {
191
214
  /**
192
215
  * Move a full log to .1. One writer rotates at a time, under an O_EXCL lock,
193
216
  * and re-reads the size once it holds it, so a writer that saw the full log
194
- * just before another rotated it does not move the fresh log over .1. The
195
- * log root is one an unattended run writes, so the size, the lock and the
196
- * rename go through safe-write: nothing is followed through a link.
217
+ * just before another rotated it does not move the fresh log over .1. A
218
+ * writer that finds the lock held waits up to LOCK_WAIT_MS for the rotation.
219
+ * The log root is one an unattended run writes, so the size, the lock and
220
+ * the rename go through safe-write: nothing is followed through a link, and a
221
+ * link or FIFO at .1 is replaced by the rename, never written through.
222
+ *
223
+ * Returns whether the log is a regular file (or absent) under the cap now, so
224
+ * the caller may append.
197
225
  */
198
226
  function rotateIfFull(file, opts) {
199
- if (sizeOf(file, opts) <= MAX_LOG_BYTES) return;
227
+ const state = () => {
228
+ const size = logSize(file, opts);
229
+ if (size === null) return "irregular";
230
+ return size > MAX_LOG_BYTES ? "full" : "ok";
231
+ };
232
+ let now = state();
233
+ if (now !== "full") return now === "ok";
200
234
  const lock = `${file}.lock`;
201
- if (!takeLock(lock, opts)) return;
235
+ let held = takeLock(lock, opts);
236
+ for (let waited = 0; !held && waited < LOCK_WAIT_MS; waited += LOCK_POLL_MS) {
237
+ pause(LOCK_POLL_MS);
238
+ now = state();
239
+ if (now !== "full") return now === "ok";
240
+ held = takeLock(lock, opts);
241
+ }
242
+ if (!held) return state() === "ok";
202
243
  try {
203
- if (sizeOf(file, opts) > MAX_LOG_BYTES) renameSafe(file, `${basename(file)}.1`, opts);
244
+ now = state();
245
+ if (now !== "full") return now === "ok";
246
+ try {
247
+ renameSafe(file, `${basename(file)}.1`, opts);
248
+ } catch (e) {
249
+ if (ROTATE_BLOCKED.has(e.code)) return false;
250
+ throw e;
251
+ }
252
+ return true;
204
253
  } finally {
205
254
  unlinkSafe(lock, opts);
206
255
  }
207
256
  }
208
257
 
209
258
  /**
210
- * Append one row, rotating a full log first. Throws on a write failure. The
211
- * log root is one an unattended run writes and this hook runs outside the
259
+ * Append one row to a log in the log directory, rotating it first when full.
260
+ * Shared with the other local counters (note-mcp-failure.mjs), so every log
261
+ * here has the same cap, generation and rotation code, each under its own
262
+ * <file>.lock.
263
+ *
264
+ * The log root is one an unattended run writes and this hook runs outside the
212
265
  * sandbox, so the directory is made and the row appended through safe-write:
213
- * a link at the log or on the way to it is refused, never followed.
266
+ * a link on the way to the log is refused, never followed. A link, a FIFO, a
267
+ * device or a directory planted at the log path drops the row instead of
268
+ * redirecting it or holding the hook, and a full log that could not rotate
269
+ * drops the row rather than grow past the cap.
270
+ *
271
+ * Returns true when the row was written, false when it was dropped for a path
272
+ * that is not a regular file or a log that stayed full. Throws on any other
273
+ * write failure, a linked directory on the way included.
214
274
  */
215
- export function appendRow(row, env = process.env) {
275
+ export function appendLogRow(name, row, env = process.env) {
216
276
  const dir = logDir(env);
217
277
  mkdirSafe(dir, { mode: 0o700, env });
218
- const file = join(dir, LOG_FILE);
219
- rotateIfFull(file, { env });
220
- appendFileSafe(file, JSON.stringify(row) + "\n", { mode: 0o600, env });
278
+ const file = join(dir, name);
279
+ if (!rotateIfFull(file, { env })) return false;
280
+ try {
281
+ appendFileSafe(file, JSON.stringify(row) + "\n", { mode: 0o600, env });
282
+ return true;
283
+ } catch (e) {
284
+ if (NOT_REGULAR.has(e.code)) return false;
285
+ throw e;
286
+ }
287
+ }
288
+
289
+ /** Append one row to the skill-usage log; false when the row was dropped. */
290
+ export function appendRow(row, env = process.env) {
291
+ return appendLogRow(LOG_FILE, row, env);
221
292
  }
222
293
 
223
294
  /** Build and append the row for a payload. Returns the row written, or null. */
@@ -225,8 +296,7 @@ export async function record(payload, env = process.env) {
225
296
  const row = rowFor(payload);
226
297
  if (!row || !captureEnabled(env)) return null;
227
298
  row.repo = await rowRepo(payload.cwd, env);
228
- appendRow(row, env);
229
- return row;
299
+ return appendRow(row, env) ? row : null;
230
300
  }
231
301
 
232
302
  /** stdin as text, or null once DEADLINE_MS passes or it grows past MAX_INPUT. */
@@ -13,6 +13,10 @@
13
13
  * is left out and counted, as brief and profile leave it;
14
14
  * so is an entry a later one superseded (its `supersedes`
15
15
  * list), counted on its own.
16
+ * global ledger ~/.claude/memory/multi-agent/_global/learnings-ledger.jsonl
17
+ * (learnings-ledger.mjs promote --accept): learnings that
18
+ * recur across repositories, on a shelf of their own under
19
+ * `global`, null until one is promoted. Never a repository.
16
20
  * graph report ~/.claude/knowledge/<repo>/GRAPH_REPORT.md
17
21
  * (graph-report.mjs), when present: architectural hubs,
18
22
  * clusters, surprising connections and the questions worth
@@ -41,7 +45,7 @@ import { join } from "node:path";
41
45
 
42
46
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
43
47
  import { messages } from "../lib/user-facing.mjs";
44
- import { ledgerRowId, standing, supersededBy } from "./_memory-policy.mjs";
48
+ import { GLOBAL_LEDGER_SLUG, ledgerRowId, standing, supersededBy } from "./_memory-policy.mjs";
45
49
  import { dirsOf, roots, store } from "./office-memory.mjs";
46
50
  import { createRedactor } from "./transcript-index.mjs";
47
51
  import { exitOnHelp } from "../lib/cli-help.mjs";
@@ -230,8 +234,14 @@ export async function officeArchive({
230
234
  } = {}) {
231
235
  const r = roots(env);
232
236
  const R = createRedactor();
233
- const names = [...new Set([...dirsOf(r.memory), ...dirsOf(r.knowledge)])].sort();
237
+ const names = [...new Set([...dirsOf(r.memory), ...dirsOf(r.knowledge)])]
238
+ .filter((n) => n !== GLOBAL_LEDGER_SLUG)
239
+ .sort();
234
240
  const read = await Promise.all(names.map((n) => shelf(n, r, now, R, maxBytes).catch(() => null)));
241
+ const promoted = await shelf(GLOBAL_LEDGER_SLUG, r, now, R, maxBytes).catch(() => null);
242
+ const c = promoted?.counts;
243
+ const global =
244
+ c && c.decisions + c.securityNotes + c.learnings > 0 ? { ...promoted, graph: null } : null;
235
245
  const latest = (s) =>
236
246
  [...s.decisions, ...s.securityNotes, ...s.learnings]
237
247
  .map((x) => x.at ?? "")
@@ -242,7 +252,12 @@ export async function officeArchive({
242
252
  .filter(Boolean)
243
253
  .sort((a, b) => latest(b).localeCompare(latest(a)) || a.repo.localeCompare(b.repo))
244
254
  .slice(0, MAX_REPOS);
245
- return { contractVersion: CONTRACT_VERSION, generatedAt: new Date(now).toISOString(), repos };
255
+ return {
256
+ contractVersion: CONTRACT_VERSION,
257
+ generatedAt: new Date(now).toISOString(),
258
+ repos,
259
+ global,
260
+ };
246
261
  }
247
262
 
248
263
  if (invokedDirectly(import.meta.url)) {
@@ -252,16 +267,14 @@ if (invokedDirectly(import.meta.url)) {
252
267
  process.exit(2);
253
268
  }
254
269
  const doc = await officeArchive();
270
+ const line = (s) =>
271
+ `${s.repo}: ${s.counts.decisions} decisions, ${s.counts.securityNotes} security notes, ${s.counts.learnings} learnings, graph ${s.graph ? "report" : "none"}`;
272
+ const shelves = [...(doc.global ? [doc.global] : []), ...doc.repos];
255
273
  process.stdout.write(
256
274
  args.includes("--json")
257
275
  ? JSON.stringify(doc) + "\n"
258
- : doc.repos.length === 0
276
+ : shelves.length === 0
259
277
  ? messages(NOTHING_RECORDED) + "\n"
260
- : doc.repos
261
- .map(
262
- (s) =>
263
- `${s.repo}: ${s.counts.decisions} decisions, ${s.counts.securityNotes} security notes, ${s.counts.learnings} learnings, graph ${s.graph ? "report" : "none"}`,
264
- )
265
- .join("\n") + "\n",
278
+ : shelves.map(line).join("\n") + "\n",
266
279
  );
267
280
  }
@@ -51,10 +51,13 @@ export const roots = (env) => ({
51
51
  knowledge: env.MA_KNOWLEDGE_ROOT || join(homedir(), ".claude", "knowledge"),
52
52
  });
53
53
 
54
+ // A folder whose name starts with "_" sits beside the repositories but is not
55
+ // one, as in the ledger and the toolkit; office-archive gives the global
56
+ // ledger its own shelf.
54
57
  export const dirsOf = (root) => {
55
58
  try {
56
59
  return readdirSync(root, { withFileTypes: true })
57
- .filter((d) => d.isDirectory() && REPO.test(d.name))
60
+ .filter((d) => d.isDirectory() && REPO.test(d.name) && !d.name.startsWith("_"))
58
61
  .map((d) => d.name);
59
62
  } catch {
60
63
  return [];