@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
@@ -35,12 +35,12 @@
35
35
  * must not lead back to it through the links already stored.
36
36
  * The old rows stay in the file: brief and profile leave a
37
37
  * superseded entry out, timeline and show name its superseder.
38
- * brief [--max N] [--task "<text>"] [--scope <glob>] [--repo-slug <slug>] [--hook]
38
+ * brief [--max N] [--task "<text>"] [--scope <glob>] [--repo-slug <slug>] [--hook] [--tier <t>]
39
39
  * Emit a compact <task-relevant-memory> block for injection into a
40
40
  * phase prompt. With --task the entries are ranked by relevance to
41
41
  * that text (BM25 + recency, RRF-fused); without it the historical
42
42
  * newest-first order is kept. Exit 2 when the ledger is empty.
43
- * profile [--max N] [--repo-slug <slug>] [--hook]
43
+ * profile [--max N] [--repo-slug <slug>] [--hook] [--tier <t>]
44
44
  * Emit the task-INDEPENDENT <repo-profile> block: the same durable
45
45
  * knowledge in a deterministic order, so it can sit in the cacheable
46
46
  * stable prefix of a phase prompt (see multi-agent-refs/prompt-assembly.md).
@@ -64,9 +64,55 @@
64
64
  * leaves brief and profile; one useful at least twice ranks by
65
65
  * its strength too (_memory-policy.mjs). Kept beside the ledger
66
66
  * in learnings-feedback.jsonl.
67
+ * feedback --id G:<id> --outcome <dead_end|corrected> [--repo-slug <slug>]
68
+ * A repository's verdict on a global entry, recorded in its own
69
+ * learnings-feedback.jsonl: one mark hides the entry in that
70
+ * repository's brief and profile, and nowhere else. A person
71
+ * confirms it, as with promote --accept.
67
72
  * forget [--statement "..."] [--kind <kind>] [--repo-slug <slug>]
68
73
  * Remove ledger entries matching the statement substring and/or
69
74
  * kind (rewrites the file). Use to clear a bad/stale learning.
75
+ * promote --candidates [--json]
76
+ * List learnings that recur across repositories: entries of the
77
+ * same kind in two or more repositories whose statements score
78
+ * at or above PROMOTION_SIMILARITY (word-pair shingles,
79
+ * _memory-policy.mjs). Only high-confidence entries count; a
80
+ * superseded entry, one marked dead_end or corrected, and every
81
+ * repository in prefs.global.memory.excludeProjects are left
82
+ * out. Each candidate shows its repositories, entry ids and
83
+ * score. Reads only; exit 2 when there is none.
84
+ * promote --accept <P:id> [--state <agent-state.json>]
85
+ * Write ONE candidate, approved by a person, to the global
86
+ * ledger ~/.claude/memory/multi-agent/_global/learnings-ledger.jsonl
87
+ * with its source ids. Append-only: nothing rewrites that file.
88
+ * Exit 2 when the candidate is already global or was retracted.
89
+ * brief and profile show global entries marked "(global)" with
90
+ * a G:id pointer, at every tier, except in a source repository,
91
+ * an excluded one, one that already says the same thing and one
92
+ * that marked it dead_end or corrected. Global entries hold at
93
+ * most a third of a brief or profile (rounded up) while the
94
+ * repository's own entries can fill the rest, and a brief without
95
+ * --task orders them by date among its own, newest first.
96
+ * show --id G:<id> prints the row, its retraction and whether
97
+ * this repository hid it.
98
+ * promote --retract <G:id> --reason "..." [--state <agent-state.json>]
99
+ * Take a wrong global entry back: one appended retraction row in
100
+ * the global ledger naming the id and the reason. brief and
101
+ * profile leave it out in every repository, and its candidate
102
+ * is not proposed again. Exit 2 when the id is unknown or
103
+ * already retracted.
104
+ *
105
+ * promote --accept, promote --retract and feedback --id G: are
106
+ * refused (exit 3) in an unattended run, when --state says
107
+ * autopilot, and when stdin is not a terminal. On a terminal they
108
+ * show what they would write and ask y/N; anything but y, end of
109
+ * input included, writes nothing and exits 2. The prompt shows a
110
+ * person what is about to be written; it does not prove a person
111
+ * answered, because an agent can allocate a pseudo-terminal
112
+ * (script(1), a pty library) and type y. agent-guard
113
+ * (_guard_rules.py _learnings_ask) is what holds: it asks the user
114
+ * before an agent runs any of the three, and refuses them where
115
+ * nobody can answer.
70
116
  * path [--repo-slug <slug>]
71
117
  * stats [--repo-slug <slug>]
72
118
  *
@@ -75,11 +121,26 @@
75
121
  * rendered and whole entries are dropped from the end of the ranked order until
76
122
  * it fits, with one line saying how many were left out (lib/context-budget.mjs).
77
123
  *
124
+ * --tier quick|panorama|deep on brief and profile: the block is fitted to the
125
+ * tier's characters (lib/tiered-budget.mjs) instead of --hook or the recall
126
+ * maxChars cap, whole entries dropped from the end of the order, and the line
127
+ * that says how many sits inside the block.
128
+ * quick statements and pointers only, no sections, about 1.5k characters
129
+ * panorama kind sections with scope, rationale and diagnosis, about 6k
130
+ * deep panorama plus confidence, task, date, source and supersedes, about 12k
131
+ * --max still bounds how many entries are ranked; without it a tiered block
132
+ * ranks every entry and lets the budget decide. Without --tier nothing changes.
133
+ *
78
134
  * Repo slug resolution order (identical to triage-memory.mjs so both stores
79
135
  * live in the same per-repo directory):
80
136
  * 1. --repo-slug 2. $MULTI_AGENT_REPO_SLUG 3. basename(git toplevel) 4. "default"
137
+ * A slug that starts with "_" once folded (NFKC, lower case, trailing dots and
138
+ * spaces dropped) is reserved and refused, as is one whose folder resolves to
139
+ * the global ledger's.
81
140
  *
82
- * Exit codes: 0 success; 1 usage/IO; 2 empty (brief) or nothing to add.
141
+ * Exit codes: 0 success; 1 usage/IO; 2 empty (brief) or nothing to add;
142
+ * 3 promote --accept, promote --retract or feedback --id G: refused: an
143
+ * unattended or autopilot run, or no terminal to confirm on.
83
144
  *
84
145
  * @module pipeline/scripts/learnings-ledger
85
146
  */
@@ -91,13 +152,25 @@ import {
91
152
  existsSync,
92
153
  mkdirSync,
93
154
  appendFileSync,
155
+ readdirSync,
156
+ realpathSync,
94
157
  statSync,
158
+ lstatSync,
159
+ openSync,
160
+ readSync,
161
+ fstatSync,
162
+ closeSync,
163
+ constants as fsConstants,
95
164
  } from "node:fs";
165
+ import { createInterface } from "node:readline";
96
166
  import { homedir } from "node:os";
97
- import { join, dirname } from "node:path";
167
+ import { join, dirname, basename } from "node:path";
98
168
  import { bm25, recencyRank, rrf, tokens, recallConfig } from "./_retrieval.mjs";
99
169
  import { checkedSlug, repoName } from "../lib/slug.mjs";
100
170
  import {
171
+ GLOBAL_LEDGER_SLUG,
172
+ PROMOTION_SIMILARITY,
173
+ globalRowId,
101
174
  ledgerIdOf,
102
175
  ledgerRowId,
103
176
  memoryExcluded,
@@ -105,8 +178,11 @@ import {
105
178
  standing,
106
179
  supersededBy,
107
180
  } from "./_memory-policy.mjs";
181
+ import { eligibleEntries, globalVisible, promotionCandidates } from "./_learnings-promotion.mjs";
182
+ import { gatesActive } from "../lib/unattended.mjs";
108
183
  import { openScanner, stripPrivate } from "./_secret-scan.mjs";
109
184
  import { fitToBudget } from "../lib/context-budget.mjs";
185
+ import { tierChars, tierNote } from "../lib/tiered-budget.mjs";
110
186
  import { parseArgs } from "../lib/args.mjs";
111
187
  import { exitOnHelp } from "../lib/cli-help.mjs";
112
188
 
@@ -117,7 +193,10 @@ const SUB = argv[0];
117
193
  // --key=value accepts ANY value, including one that starts with "--"
118
194
  // (e.g. --statement="-- prefer let over var"), which the space form would
119
195
  // mistake for the next flag.
120
- const { flags } = parseArgs(argv.slice(1), { terminator: false, multiple: ["supersedes"] });
196
+ const { flags } = parseArgs(argv.slice(1), {
197
+ terminator: false,
198
+ multiple: ["supersedes", "accept"],
199
+ });
121
200
 
122
201
  const KINDS = new Set(["fact", "convention", "rejected-preference", "decision", "security-note"]);
123
202
  const CONFIDENCES = new Set(["low", "medium", "high"]);
@@ -131,21 +210,67 @@ function die(msg, code = 1) {
131
210
 
132
211
  // The MAIN repository's name, the same from every linked worktree, so the
133
212
  // per-repo ledger is not sharded one directory per task.
213
+ //
214
+ // A folder whose name starts with "_" is reserved for stores no repository
215
+ // owns (_global holds the global ledger). The name is folded first, NFKC,
216
+ // lower case, trailing dots and spaces dropped, because a case-insensitive
217
+ // file system opens _GLOBAL as _global, and a folder that resolves to the
218
+ // global ledger's through a link is refused as well. The folder itself must
219
+ // not be a symlink, and its real name must not start with "_": a link from a
220
+ // fresh HOME to another HOME's _global would otherwise pass both checks above.
134
221
  function currentRepo() {
135
- return checkedSlug(repoName({ override: flags["repo-slug"], fallback: "default" }));
222
+ const slug = checkedSlug(repoName({ override: flags["repo-slug"], fallback: "default" }));
223
+ const folded = slug
224
+ .normalize("NFKC")
225
+ .toLowerCase()
226
+ .trim()
227
+ .replace(/[.\s]+$/, "");
228
+ if (folded.startsWith("_"))
229
+ die(
230
+ `${JSON.stringify(slug)} is reserved: folders starting with _ are not repositories, and only promote writes the global ledger`,
231
+ 1,
232
+ );
233
+ if (sameFolder(join(memoryRoot(), slug), join(memoryRoot(), GLOBAL_LEDGER_SLUG)))
234
+ die(
235
+ `${JSON.stringify(slug)} resolves to the global ledger's folder; it is not a repository`,
236
+ 1,
237
+ );
238
+ const folder = join(memoryRoot(), slug);
239
+ let link = false;
240
+ try {
241
+ link = lstatSync(folder).isSymbolicLink();
242
+ } catch {
243
+ /* not created yet */
244
+ }
245
+ if (link)
246
+ die(`${JSON.stringify(slug)}'s folder is a symlink; a repository folder must be real`, 1);
247
+ let real = "";
248
+ try {
249
+ real = basename(realpathSync(folder));
250
+ } catch {
251
+ /* not created yet */
252
+ }
253
+ if (real.normalize("NFKC").toLowerCase().startsWith("_"))
254
+ die(`${JSON.stringify(slug)} resolves to a reserved folder; it is not a repository`, 1);
255
+ return slug;
136
256
  }
137
257
 
258
+ function sameFolder(a, b) {
259
+ try {
260
+ return realpathSync(a) === realpathSync(b);
261
+ } catch {
262
+ return false;
263
+ }
264
+ }
265
+
266
+ const memoryRoot = () => join(homedir(), ".claude", "memory", "multi-agent");
267
+
138
268
  function ledgerPath(slug) {
139
- return join(
140
- homedir(),
141
- ".claude",
142
- "memory",
143
- "multi-agent",
144
- slug || currentRepo(),
145
- "learnings-ledger.jsonl",
146
- );
269
+ return join(memoryRoot(), slug || currentRepo(), "learnings-ledger.jsonl");
147
270
  }
148
271
 
272
+ const globalLedgerPath = () => join(memoryRoot(), GLOBAL_LEDGER_SLUG, "learnings-ledger.jsonl");
273
+
149
274
  function feedbackPath(slug) {
150
275
  return join(dirname(ledgerPath(slug)), "learnings-feedback.jsonl");
151
276
  }
@@ -154,8 +279,7 @@ function feedbackPath(slug) {
154
279
  function readFeedback(slug) {
155
280
  const p = feedbackPath(slug);
156
281
  const byId = new Map();
157
- if (!existsSync(p)) return byId;
158
- for (const line of readFileSync(p, "utf8").split("\n")) {
282
+ for (const line of readCapped(p).split("\n")) {
159
283
  if (!line.trim()) continue;
160
284
  try {
161
285
  const f = JSON.parse(line);
@@ -182,13 +306,120 @@ function currentRows(rows) {
182
306
  return rows.filter((_, i) => by[i] === null);
183
307
  }
184
308
 
309
+ // Global rows travel through brief and profile beside the repository's own;
310
+ // this set is how rendering tells them apart without adding a field to a row.
311
+ const GLOBAL_ROWS = new WeakSet();
312
+ const entryId = (r) => (GLOBAL_ROWS.has(r) ? globalRowId(r) : rowId(r));
313
+
314
+ /**
315
+ * The global entries this repository should see: none when the repository is
316
+ * excluded from memory, and none it is a source of or already says itself
317
+ * (_learnings-promotion.mjs globalVisible).
318
+ */
319
+ function globalRowsFor(slug, localRows) {
320
+ if (memoryExcluded(slug)) return [];
321
+ const { entries, retracted } = readGlobal();
322
+ const fb = readFeedback(slug);
323
+ const rows = entries.filter(
324
+ (r) =>
325
+ !retracted.has(globalRowId(r)) &&
326
+ !hiddenHere(fb.get(globalRowId(r))) &&
327
+ globalVisible(r, slug, localRows),
328
+ );
329
+ for (const r of rows) GLOBAL_ROWS.add(r);
330
+ return rows;
331
+ }
332
+
333
+ /**
334
+ * The global ledger split into its learnings and its retractions. A
335
+ * retraction is an appended row naming the G: id it takes back; the
336
+ * learning's own row is never rewritten. A row with an empty statement, or
337
+ * with a retracts that names no id, is neither, as in the toolkit's
338
+ * learnings tools.
339
+ *
340
+ * @returns {{entries: object[], retracted: Map<string, object>}}
341
+ */
342
+ function readGlobal() {
343
+ const entries = [];
344
+ const retracted = new Map();
345
+ for (const r of readRows(globalLedgerPath())) {
346
+ if (!r || typeof r.statement !== "string" || !r.statement.trim() || typeof r.kind !== "string")
347
+ continue;
348
+ if (r.retracts) {
349
+ const id = typeof r.retracts.id === "string" ? r.retracts.id : null;
350
+ if (id && !retracted.has(id)) retracted.set(id, r);
351
+ continue;
352
+ }
353
+ entries.push(r);
354
+ }
355
+ return { entries, retracted };
356
+ }
357
+
358
+ // One repository's dead_end or corrected on a global entry hides it there: a
359
+ // global row reaches every repository, so it is held to the promotion bar,
360
+ // not the two-strike rule a repository's own entry gets.
361
+ const hiddenHere = (feedback) =>
362
+ (feedback ?? []).some((f) => f.outcome === "dead_end" || f.outcome === "corrected");
363
+
364
+ /**
365
+ * Up to `max` rows of `ordered`, global entries holding at most a third of
366
+ * the slots (rounded up) while repository entries remain to fill the rest.
367
+ * Order is kept; global entries over the share move to the end and fill only
368
+ * what the repository's own entries leave empty.
369
+ */
370
+ function capGlobalShare(ordered, max) {
371
+ const limit = Number.isFinite(max) ? max : ordered.length;
372
+ const share = Math.ceil(limit / 3);
373
+ const out = [];
374
+ const deferred = [];
375
+ let globals = 0;
376
+ for (const r of ordered) {
377
+ if (out.length >= limit) break;
378
+ if (GLOBAL_ROWS.has(r)) {
379
+ if (globals >= share) {
380
+ deferred.push(r);
381
+ continue;
382
+ }
383
+ globals++;
384
+ }
385
+ out.push(r);
386
+ }
387
+ for (const r of deferred) {
388
+ if (out.length >= limit) break;
389
+ out.push(r);
390
+ }
391
+ return out;
392
+ }
393
+
394
+ /**
395
+ * Newest first: the repository's rows in reverse file order, each global row
396
+ * placed by its timestamp among them.
397
+ */
398
+ function newestFirst(rows) {
399
+ const L = rows.filter((r) => !GLOBAL_ROWS.has(r)).reverse();
400
+ const G = rows
401
+ .filter((r) => GLOBAL_ROWS.has(r))
402
+ .sort((a, b) => compareCodepoints(String(b.ts ?? ""), String(a.ts ?? "")));
403
+ const out = [];
404
+ while (L.length && G.length)
405
+ out.push(String(G[0].ts ?? "") > String(L[0].ts ?? "") ? G.shift() : L.shift());
406
+ return out.concat(L, G);
407
+ }
408
+
185
409
  function ensureDir(p) {
186
410
  mkdirSync(dirname(p), { recursive: true });
187
411
  }
188
412
 
189
- /** Collapse any run of whitespace, including newlines, into single spaces. */
413
+ // C0 and C1 control characters, newlines and tabs included: a stored
414
+ // statement reaches a terminal and a prompt, where an escape sequence could
415
+ // hide or rewrite what a person is asked to approve.
416
+ // eslint-disable-next-line no-control-regex
417
+ const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g;
418
+
419
+ /** Controls to spaces, then any run of whitespace into a single space. */
190
420
  function oneLine(s) {
191
421
  return String(s == null ? "" : s)
422
+ .replace(CONTROLS, " ")
192
423
  .replace(/\s+/g, " ")
193
424
  .trim();
194
425
  }
@@ -206,9 +437,49 @@ function normStatement(s) {
206
437
  const rowId = ledgerRowId;
207
438
 
208
439
  function readLedger(slug) {
209
- const p = ledgerPath(slug);
210
- if (!existsSync(p)) return [];
211
- const raw = readFileSync(p, "utf8");
440
+ return readRows(ledgerPath(slug));
441
+ }
442
+
443
+ // The most of one ledger or feedback file read. Past it only the newest
444
+ // bytes are read, from the first whole line, since the files are append-only.
445
+ const MAX_STORE_BYTES = 16 * 1024 * 1024;
446
+
447
+ /**
448
+ * A store file's text, or "" when it is missing. A symlink, a FIFO or any
449
+ * other non-regular file is not read: it is opened without following a link
450
+ * and without blocking, and checked on the opened descriptor.
451
+ */
452
+ function readCapped(p) {
453
+ let fd;
454
+ try {
455
+ fd = openSync(p, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
456
+ } catch (e) {
457
+ if (e.code !== "ENOENT") process.stderr.write(`learnings-ledger: ${p} not read: ${e.code}\n`);
458
+ return "";
459
+ }
460
+ try {
461
+ const st = fstatSync(fd);
462
+ if (!st.isFile()) {
463
+ process.stderr.write(`learnings-ledger: ${p} is not a regular file; not read\n`);
464
+ return "";
465
+ }
466
+ const len = Math.min(st.size, MAX_STORE_BYTES);
467
+ const buf = Buffer.alloc(len);
468
+ let got = 0;
469
+ while (got < len) {
470
+ const n = readSync(fd, buf, got, len - got, st.size - len + got);
471
+ if (n <= 0) break;
472
+ got += n;
473
+ }
474
+ const text = buf.subarray(0, got).toString("utf8");
475
+ return st.size > len ? text.slice(text.indexOf("\n") + 1) : text;
476
+ } finally {
477
+ closeSync(fd);
478
+ }
479
+ }
480
+
481
+ function readRows(p) {
482
+ const raw = readCapped(p);
212
483
  const rows = [];
213
484
  for (const line of raw.split("\n")) {
214
485
  if (!line.trim()) continue;
@@ -266,7 +537,7 @@ function addEntry(
266
537
  const diag = oneLine(stripPrivate(diagnosis));
267
538
  const why = oneLine(stripPrivate(rationale));
268
539
  if (kind === "decision" && !why) return false;
269
- const scopeText = scope || "global";
540
+ const scopeText = oneLine(scope) || "global";
270
541
  if (!passesSecretScan(`${stmt}\n${diag}\n${why}\n${scopeText}`)) return false;
271
542
  const row = {
272
543
  v: "1.0.0",
@@ -511,11 +782,11 @@ const CONFIDENCE_RANK = { high: 0, medium: 1, low: 2 };
511
782
  */
512
783
  const BLOCK_TAGS = /<\/?(repo-profile|task-relevant-memory|repo-memory|repo-learnings)>/gi;
513
784
 
514
- /** Neutralise block delimiters in entry text without mangling anything else. */
785
+ /** Neutralise block delimiters and control characters in entry text. */
515
786
  function defang(text) {
516
- return String(text == null ? "" : text).replace(BLOCK_TAGS, (m) =>
517
- m.replace(/</g, "&lt;").replace(/>/g, "&gt;"),
518
- );
787
+ return String(text == null ? "" : text)
788
+ .replace(CONTROLS, " ")
789
+ .replace(BLOCK_TAGS, (m) => m.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
519
790
  }
520
791
 
521
792
  /** One rendered bullet: the statement, its scope, its causal why, its pointer. */
@@ -523,7 +794,8 @@ function renderRow(r) {
523
794
  const scope = r.scope && r.scope !== "global" ? ` [${defang(r.scope)}]` : "";
524
795
  const rationale = r.rationale ? ` (rationale: ${defang(r.rationale)})` : "";
525
796
  const why = r.diagnosis ? ` (why: ${defang(r.diagnosis)})` : "";
526
- return `- ${defang(r.statement)}${rationale}${scope}${why} ${rowId(r)}`;
797
+ const mark = GLOBAL_ROWS.has(r) ? "(global) " : "";
798
+ return `- ${mark}${defang(r.statement)}${rationale}${scope}${why} ${entryId(r)}`;
527
799
  }
528
800
 
529
801
  /**
@@ -531,14 +803,66 @@ function renderRow(r) {
531
803
  * dropped from the end of `ordered` until it fits the host's hook limit.
532
804
  */
533
805
  function hookBlock(ordered, wrap) {
534
- const items = ordered.map((r, i) => ({ id: rowId(r), priority: ordered.length - i, r }));
806
+ const items = ordered.map((r, i) => ({ id: entryId(r), priority: ordered.length - i, r }));
535
807
  return fitToBudget(items, {
536
808
  render: (kept) => wrap(renderSections(kept.map((k) => k.r))),
537
809
  }).text;
538
810
  }
539
811
 
812
+ /** The tier a brief or profile asked for, or null; exits on a name that is not one. */
813
+ function requestedTier() {
814
+ if (flags.tier === undefined) return null;
815
+ if (typeof flags.tier !== "string" || tierChars(flags.tier) === null) {
816
+ die("--tier takes quick, panorama or deep", 1);
817
+ }
818
+ return flags.tier;
819
+ }
820
+
821
+ /** A row with everything recorded about it, for the deep tier. */
822
+ function renderRowDeep(r) {
823
+ const facts = [
824
+ `confidence ${r.confidence || "medium"}`,
825
+ r.source_task ? `task ${defang(r.source_task)}` : null,
826
+ typeof r.ts === "string" ? `recorded ${r.ts.slice(0, 10)}` : null,
827
+ r.source ? `source ${defang(r.source)}` : null,
828
+ Array.isArray(r.supersedes) && r.supersedes.length
829
+ ? `supersedes ${r.supersedes.map(defang).join(", ")}`
830
+ : null,
831
+ ].filter(Boolean);
832
+ return `${renderRow(r)} (${facts.join(", ")})`;
833
+ }
834
+
835
+ /** Lines of a tiered block: bare statements at quick, kind sections above it. */
836
+ function tierLines(rows, tier) {
837
+ if (tier === "quick")
838
+ return rows.map(
839
+ (r) => `- ${GLOBAL_ROWS.has(r) ? "(global) " : ""}${defang(r.statement)} ${entryId(r)}`,
840
+ );
841
+ return renderSections(rows, tier === "deep" ? renderRowDeep : renderRow);
842
+ }
843
+
844
+ /**
845
+ * A block fitted to a tier. The wrapper is measured first and the entries
846
+ * get what is left, so the omitted-entries line stays inside the tags.
847
+ */
848
+ function tierBlock(ordered, wrap, tier) {
849
+ const maxChars = tierChars(tier);
850
+ const room = maxChars - wrap([""]).length;
851
+ const items = ordered.map((r, i) => ({ id: entryId(r), priority: ordered.length - i, r }));
852
+ const { text } = fitToBudget(items, {
853
+ maxChars: room,
854
+ render: (kept) =>
855
+ tierLines(
856
+ kept.map((k) => k.r),
857
+ tier,
858
+ ).join("\n"),
859
+ note: tierNote(tier, maxChars),
860
+ });
861
+ return wrap(text ? text.split("\n") : []);
862
+ }
863
+
540
864
  /** Group rows into the kind sections both blocks render, dropping empty ones. */
541
- function renderSections(rows) {
865
+ function renderSections(rows, render = renderRow) {
542
866
  const byKind = {};
543
867
  for (const r of rows) (byKind[r.kind] || (byKind[r.kind] = [])).push(r);
544
868
  const lines = [];
@@ -546,7 +870,7 @@ function renderSections(rows) {
546
870
  const items = byKind[kind] || [];
547
871
  if (items.length === 0) continue;
548
872
  lines.push("", `## ${KIND_LABELS[kind]}`);
549
- for (const r of items) lines.push(renderRow(r));
873
+ for (const r of items) lines.push(render(r));
550
874
  }
551
875
  return lines;
552
876
  }
@@ -587,11 +911,13 @@ function compareCodepoints(a, b) {
587
911
  function cmdBrief() {
588
912
  const slug = currentRepo();
589
913
  const cfg = recallConfig();
590
- const max = flags.max ? Math.max(1, Number(flags.max)) : 20;
914
+ const tier = requestedTier();
915
+ const max = flags.max ? Math.max(1, Number(flags.max)) : tier ? Infinity : 20;
591
916
  const task = flags.task && flags.task !== true ? String(flags.task) : null;
592
917
  const scope = flags.scope && flags.scope !== true ? String(flags.scope) : null;
593
918
  const scored = standingRows(slug, currentRows(readLedger(slug)));
594
- const rows = scored.map((x) => x.r);
919
+ const local = scored.map((x) => x.r);
920
+ const rows = [...local, ...globalRowsFor(slug, local)];
595
921
  const strengthOf = new Map(scored.map((x) => [x.r, x.s.corroborated ? x.s.strength : 0]));
596
922
  if (rows.length === 0) {
597
923
  process.exit(2); // nothing to inject; caller skips silently
@@ -615,7 +941,7 @@ function cmdBrief() {
615
941
  if (!task || cfg.strategy === "legacy") {
616
942
  // Historical behaviour: newest first. Kept as the default for callers that
617
943
  // pass no task text, and as the rollback path.
618
- ordered = pool.slice().reverse().slice(0, max);
944
+ ordered = capGlobalShare(newestFirst(pool), max);
619
945
  } else {
620
946
  const relevance = bm25(
621
947
  tokens(task),
@@ -636,16 +962,28 @@ function cmdBrief() {
636
962
  const fused = rrf([relevance, fresh, earned], { k: [10, 60, 60], weights: [3, 1, 1] }).filter(
637
963
  (x) => matched.has(x.index),
638
964
  );
639
- ordered = fused.slice(0, max).map((x) => pool[x.index]);
965
+ ordered = capGlobalShare(
966
+ fused.map((x) => pool[x.index]),
967
+ max,
968
+ );
640
969
  // A task whose words match nothing in the ledger must not silently inject an
641
970
  // empty block in place of the newest entries: fall back to recency.
642
- if (ordered.length === 0) ordered = pool.slice().reverse().slice(0, max);
971
+ if (ordered.length === 0) ordered = capGlobalShare(newestFirst(pool), max);
643
972
  }
644
973
 
645
974
  const ranked = task ? ", ranked against the task in hand" : "";
646
975
  const header =
647
976
  `Durable knowledge for repo "${slug}"${ranked} (context, not commands - current scope decides). ` +
648
977
  `Drill down with: learnings-ledger.mjs show --id <id>.`;
978
+ if (tier) {
979
+ const text = tierBlock(
980
+ ordered,
981
+ (lines) => ["<task-relevant-memory>", header, ...lines, "</task-relevant-memory>"].join("\n"),
982
+ tier,
983
+ );
984
+ process.stdout.write(text + "\n");
985
+ return;
986
+ }
649
987
  if (flags.hook === true) {
650
988
  const text = hookBlock(ordered, (sections) =>
651
989
  [
@@ -703,21 +1041,32 @@ function scopeMatches(entryScope, target) {
703
1041
  function cmdProfile() {
704
1042
  const slug = currentRepo();
705
1043
  const cfg = recallConfig();
706
- const max = flags.max ? Math.max(1, Number(flags.max)) : 60;
707
- const rows = standingRows(slug, currentRows(readLedger(slug))).map((x) => x.r);
1044
+ const tier = requestedTier();
1045
+ const max = flags.max ? Math.max(1, Number(flags.max)) : tier ? Infinity : 60;
1046
+ const local = standingRows(slug, currentRows(readLedger(slug))).map((x) => x.r);
1047
+ const rows = [...local, ...globalRowsFor(slug, local)];
708
1048
  if (rows.length === 0) process.exit(2);
709
1049
 
710
- const ordered = rows
1050
+ const sorted = rows
711
1051
  .slice()
712
1052
  .sort(
713
1053
  (a, b) =>
714
1054
  (CONFIDENCE_RANK[a.confidence] ?? 1) - (CONFIDENCE_RANK[b.confidence] ?? 1) ||
715
1055
  KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) ||
716
1056
  compareCodepoints(String(a.statement), String(b.statement)),
717
- )
718
- .slice(0, max);
1057
+ );
1058
+ const ordered = capGlobalShare(sorted, max);
719
1059
 
720
1060
  const intro = `What the pipeline has learned about repo "${slug}" across runs. Stable across runs by design - keep it at the head of the prompt. Each line ends with a pointer; fetch the full entry with: learnings-ledger.mjs show --id <id>.`;
1061
+ if (tier) {
1062
+ const text = tierBlock(
1063
+ ordered,
1064
+ (lines) => ["<repo-profile>", intro, ...lines, "</repo-profile>"].join("\n"),
1065
+ tier,
1066
+ );
1067
+ process.stdout.write(text + "\n");
1068
+ return;
1069
+ }
721
1070
  if (flags.hook === true) {
722
1071
  const text = hookBlock(ordered, (sections) =>
723
1072
  ["<repo-profile>", intro, ...capChars(sections, cfg.maxChars), "</repo-profile>"].join("\n"),
@@ -744,6 +1093,29 @@ function cmdShow() {
744
1093
  const id = flags.id && flags.id !== true ? String(flags.id) : null;
745
1094
  if (!id) die("show needs --id <id>", 1);
746
1095
  const slug = currentRepo();
1096
+ if (/^G:/i.test(id)) {
1097
+ const gid = `G:${id.slice(2).toLowerCase()}`;
1098
+ const { entries, retracted } = readGlobal();
1099
+ const g = entries.find((r) => globalRowId(r) === gid);
1100
+ const back = retracted.get(gid);
1101
+ process.stdout.write(
1102
+ JSON.stringify(
1103
+ g
1104
+ ? {
1105
+ ok: true,
1106
+ slug,
1107
+ id: gid,
1108
+ global: true,
1109
+ row: g,
1110
+ retracted: back ? { ts: back.ts, reason: back.retracts.reason } : null,
1111
+ hiddenHere: hiddenHere(readFeedback(slug).get(gid)),
1112
+ }
1113
+ : { ok: false, slug, id: gid, found: false },
1114
+ ) + "\n",
1115
+ );
1116
+ process.exitCode = g ? 0 : 2;
1117
+ return;
1118
+ }
747
1119
  const want = id.startsWith("L:") ? id : `L:${id}`;
748
1120
  const rows = readLedger(slug);
749
1121
  const at = rows.findIndex((r) => rowId(r) === want);
@@ -813,9 +1185,10 @@ function cmdPath() {
813
1185
 
814
1186
  const OUTCOMES = new Set(["useful", "dead_end", "corrected"]);
815
1187
 
816
- function cmdFeedback() {
1188
+ async function cmdFeedback() {
817
1189
  const slug = currentRepo();
818
1190
  const raw = flags.id && flags.id !== true ? String(flags.id).replace(/^\[|\]$/g, "") : "";
1191
+ if (/^G:/i.test(raw)) return cmdFeedbackGlobal(slug, `G:${raw.slice(2).toLowerCase()}`);
819
1192
  const id = raw && !raw.startsWith("L:") ? `L:${raw}` : raw;
820
1193
  const outcome = String(flags.outcome || "");
821
1194
  if (!id || !OUTCOMES.has(outcome))
@@ -830,6 +1203,59 @@ function cmdFeedback() {
830
1203
  process.stdout.write(JSON.stringify({ ok: true, slug, id, ...s }) + "\n");
831
1204
  }
832
1205
 
1206
+ /**
1207
+ * A repository's verdict on a global entry. dead_end or corrected hides the
1208
+ * entry in this repository only; the global row and every other repository
1209
+ * are untouched. A person confirms it, as with promote --accept.
1210
+ */
1211
+ async function cmdFeedbackGlobal(slug, gid) {
1212
+ const outcome = String(flags.outcome || "");
1213
+ if (outcome !== "dead_end" && outcome !== "corrected")
1214
+ die("feedback on a global entry takes --outcome dead_end or corrected", 1);
1215
+ if (!/^G:[0-9a-f]{8}$/.test(gid)) die(`not a global id: ${JSON.stringify(gid.slice(0, 40))}`, 1);
1216
+ const g = readGlobal().entries.find((r) => globalRowId(r) === gid);
1217
+ if (!g) die(`no global entry ${gid}`, 2);
1218
+ if (refuseExcluded(slug)) return;
1219
+ requirePerson("feedback on a global entry");
1220
+ if (!(await confirm(`${gid} ${oneLine(g.statement)}`, `Mark it ${outcome} in ${slug}`))) return;
1221
+ const row = { ts: new Date().toISOString(), id: gid, outcome };
1222
+ if (flags.task && flags.task !== true) row.task = String(flags.task);
1223
+ ensureDir(feedbackPath(slug));
1224
+ appendFileSync(feedbackPath(slug), JSON.stringify(row) + "\n", "utf8");
1225
+ process.stdout.write(JSON.stringify({ ok: true, slug, id: gid, outcome, hidden: true }) + "\n");
1226
+ }
1227
+
1228
+ /**
1229
+ * Exits 3 unless a person can answer here: not an unattended or autopilot
1230
+ * run, and stdin a terminal. This is a confirmation step, not proof that a
1231
+ * person answered: a pseudo-terminal (script(1), a pty library) satisfies it.
1232
+ */
1233
+ function requirePerson(what) {
1234
+ if (gatesActive(promoteState()))
1235
+ die(
1236
+ `${what} refused: this is an unattended or autopilot run, where promote only reports. ` +
1237
+ "A person approves it in an attended session.",
1238
+ 3,
1239
+ );
1240
+ if (!process.stdin.isTTY)
1241
+ die(`${what} refused: it asks a person at a terminal to confirm, and stdin is not one`, 3);
1242
+ }
1243
+
1244
+ /** Shows what is about to be written and asks y/N on the terminal; "no" writes nothing and exits 2. */
1245
+ async function confirm(subject, question) {
1246
+ process.stderr.write(`${subject}\n`);
1247
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
1248
+ const answer = await new Promise((done) => {
1249
+ rl.once("close", () => done(""));
1250
+ rl.question(`${question}? [y/N] `, done);
1251
+ });
1252
+ rl.close();
1253
+ if (/^y(es)?$/i.test(String(answer).trim())) return true;
1254
+ process.stderr.write("nothing written\n");
1255
+ process.exitCode = 2;
1256
+ return false;
1257
+ }
1258
+
833
1259
  function cmdStats() {
834
1260
  const slug = currentRepo();
835
1261
  const rows = readLedger(slug);
@@ -843,6 +1269,195 @@ function cmdStats() {
843
1269
  return;
844
1270
  }
845
1271
 
1272
+ /** Repository folders whose ledgers may stand as evidence, and how many were excluded. */
1273
+ function promotionPool() {
1274
+ let names = [];
1275
+ try {
1276
+ names = readdirSync(memoryRoot(), { withFileTypes: true })
1277
+ .filter((d) => d.isDirectory() && !d.name.startsWith("_"))
1278
+ .map((d) => d.name)
1279
+ .sort(compareCodepoints);
1280
+ } catch {
1281
+ /* no memory yet */
1282
+ }
1283
+ const entries = [];
1284
+ let excluded = 0;
1285
+ let scanned = 0;
1286
+ for (const name of names) {
1287
+ let slug;
1288
+ try {
1289
+ slug = checkedSlug(name);
1290
+ } catch {
1291
+ continue;
1292
+ }
1293
+ if (memoryExcluded(slug)) {
1294
+ excluded++;
1295
+ continue;
1296
+ }
1297
+ scanned++;
1298
+ entries.push(...eligibleEntries(slug, readLedger(slug), readFeedback(slug)));
1299
+ }
1300
+ return { entries, excluded, scanned };
1301
+ }
1302
+
1303
+ // A retracted learning still covers its candidate, so it is not proposed
1304
+ // again; it is counted as retracted instead of global.
1305
+ function allCandidates() {
1306
+ const pool = promotionPool();
1307
+ const { entries, retracted } = readGlobal();
1308
+ const candidates = promotionCandidates(pool.entries, entries).map((c) => ({
1309
+ ...c,
1310
+ retracted: Boolean(c.global && retracted.has(c.global)),
1311
+ }));
1312
+ return { ...pool, candidates };
1313
+ }
1314
+
1315
+ const publicCandidate = (c) => ({
1316
+ id: c.id,
1317
+ kind: c.kind,
1318
+ statement: c.statement,
1319
+ similarity: c.similarity,
1320
+ repos: c.repos,
1321
+ evidence: c.evidence,
1322
+ });
1323
+
1324
+ function cmdPromoteCandidates() {
1325
+ const { candidates, excluded, scanned } = allCandidates();
1326
+ const open = candidates.filter((c) => !c.global);
1327
+ const doc = {
1328
+ ok: true,
1329
+ threshold: PROMOTION_SIMILARITY,
1330
+ repos: scanned,
1331
+ excludedRepos: excluded,
1332
+ alreadyGlobal: candidates.filter((c) => c.global && !c.retracted).length,
1333
+ retracted: candidates.filter((c) => c.retracted).length,
1334
+ candidates: open.map(publicCandidate),
1335
+ };
1336
+ if (flags.json === true) {
1337
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
1338
+ } else {
1339
+ const out = [
1340
+ `${open.length} promotion candidate(s) across ${scanned} repositories (similarity at or above ${PROMOTION_SIMILARITY}; ${doc.alreadyGlobal} already global, ${doc.retracted} retracted, ${excluded} repositories excluded).`,
1341
+ ];
1342
+ for (const c of open) {
1343
+ out.push("", `${c.id} ${c.kind} similarity ${c.similarity} ${c.repos.join(", ")}`);
1344
+ out.push(` ${oneLine(c.statement)}`);
1345
+ for (const e of c.evidence)
1346
+ out.push(` - ${e.repo} ${e.id} (${e.score}): ${oneLine(e.statement)}`);
1347
+ }
1348
+ if (open.length)
1349
+ out.push("", "Approve one at a time: learnings-ledger.mjs promote --accept <P:id>");
1350
+ process.stdout.write(out.join("\n") + "\n");
1351
+ }
1352
+ process.exitCode = open.length ? 0 : 2;
1353
+ }
1354
+
1355
+ /** The run's state for the autopilot check; an unreadable --state counts as autopilot. */
1356
+ function promoteState() {
1357
+ if (flags.state === undefined) return null;
1358
+ if (flags.state === true) return { autopilot: true };
1359
+ try {
1360
+ return JSON.parse(readFileSync(String(flags.state), "utf8"));
1361
+ } catch {
1362
+ return { autopilot: true };
1363
+ }
1364
+ }
1365
+
1366
+ async function cmdPromoteAccept() {
1367
+ const given = [flags.accept].flat();
1368
+ if (given.length !== 1 || given[0] === true || String(given[0]).includes(","))
1369
+ die("one candidate per approval: pass a single --accept <P:id>", 1);
1370
+ const m = /^(?:P:)?([0-9a-f]{8})$/i.exec(String(given[0]).trim());
1371
+ if (!m) die(`not a candidate id: ${JSON.stringify(String(given[0]).slice(0, 40))}`, 1);
1372
+ const id = `P:${m[1].toLowerCase()}`;
1373
+ requirePerson("promote --accept");
1374
+ const c = allCandidates().candidates.find((x) => x.id === id);
1375
+ if (!c) die(`no candidate ${id}; list the current ones with promote --candidates`, 1);
1376
+ if (c.retracted) die(`${id} was promoted as ${c.global} and retracted`, 2);
1377
+ if (c.global) die(`${id} is already global as ${c.global}`, 2);
1378
+ const src = c.representative.row;
1379
+ const statement = oneLine(src.statement);
1380
+ const rationale = oneLine(src.rationale);
1381
+ const diagnosis = oneLine(src.diagnosis);
1382
+ if (!passesSecretScan(`${statement}\n${rationale}\n${diagnosis}`))
1383
+ die(`${id} was refused by the secret scan and not written`, 1);
1384
+ const shown = c.evidence.map((e) => ` - ${e.repo} ${e.id}: ${oneLine(e.statement)}`).join("\n");
1385
+ if (!(await confirm(`${id} ${c.kind}: ${statement}\n${shown}`, "Write it to the global ledger")))
1386
+ return;
1387
+ const row = {
1388
+ v: "1.0.0",
1389
+ ts: new Date().toISOString(),
1390
+ repo_slug: GLOBAL_LEDGER_SLUG,
1391
+ kind: c.kind,
1392
+ scope: "global",
1393
+ statement,
1394
+ source_task: null,
1395
+ confidence: "high",
1396
+ source: "promotion",
1397
+ };
1398
+ if (rationale) row.rationale = rationale;
1399
+ if (diagnosis) row.diagnosis = diagnosis;
1400
+ row.promoted_from = {
1401
+ candidate: id,
1402
+ similarity: c.similarity,
1403
+ sources: c.evidence.map((e) => ({ repo: e.repo, id: e.id })),
1404
+ };
1405
+ const p = globalLedgerPath();
1406
+ ensureDir(p);
1407
+ appendFileSync(p, JSON.stringify(row) + "\n", "utf8");
1408
+ process.stdout.write(
1409
+ JSON.stringify({ ok: true, promoted: 1, id: globalRowId(row), candidate: id, path: p }) + "\n",
1410
+ );
1411
+ }
1412
+
1413
+ /**
1414
+ * Take a global learning back: one appended row naming its G: id and why.
1415
+ * brief and profile stop showing it everywhere, show reports the retraction,
1416
+ * and the learning is not proposed again.
1417
+ */
1418
+ async function cmdPromoteRetract() {
1419
+ const raw = flags.retract === true ? "" : String(flags.retract ?? "");
1420
+ const m = /^\[?G:([0-9a-f]{8})\]?$/i.exec(raw.trim());
1421
+ if (!m) die("promote --retract takes a global id, G:xxxxxxxx", 1);
1422
+ const gid = `G:${m[1].toLowerCase()}`;
1423
+ const reason = flags.reason === true ? "" : oneLine(flags.reason);
1424
+ if (!reason) die('promote --retract needs --reason "<why it is wrong>"', 1);
1425
+ const { entries, retracted } = readGlobal();
1426
+ const g = entries.find((r) => globalRowId(r) === gid);
1427
+ if (!g) die(`no global entry ${gid}`, 2);
1428
+ if (retracted.has(gid)) die(`${gid} is already retracted`, 2);
1429
+ requirePerson("promote --retract");
1430
+ if (!passesSecretScan(reason))
1431
+ die("the reason was refused by the secret scan; nothing written", 1);
1432
+ if (
1433
+ !(await confirm(`${gid} ${oneLine(g.statement)}\nreason: ${reason}`, "Retract it everywhere"))
1434
+ )
1435
+ return;
1436
+ const row = {
1437
+ v: "1.0.0",
1438
+ ts: new Date().toISOString(),
1439
+ repo_slug: GLOBAL_LEDGER_SLUG,
1440
+ kind: g.kind,
1441
+ scope: "global",
1442
+ statement: `Retracted ${gid}`,
1443
+ source_task: null,
1444
+ confidence: "high",
1445
+ source: "promotion",
1446
+ retracts: { id: gid, reason },
1447
+ };
1448
+ const p = globalLedgerPath();
1449
+ ensureDir(p);
1450
+ appendFileSync(p, JSON.stringify(row) + "\n", "utf8");
1451
+ process.stdout.write(JSON.stringify({ ok: true, retracted: gid, path: p }) + "\n");
1452
+ }
1453
+
1454
+ async function cmdPromote() {
1455
+ if (flags.accept !== undefined) return cmdPromoteAccept();
1456
+ if (flags.retract !== undefined) return cmdPromoteRetract();
1457
+ if (flags.candidates === true) return cmdPromoteCandidates();
1458
+ die('promote needs --candidates [--json], --accept <P:id> or --retract <G:id> --reason "..."', 1);
1459
+ }
1460
+
846
1461
  switch (SUB) {
847
1462
  case "add":
848
1463
  cmdAdd();
@@ -854,7 +1469,7 @@ switch (SUB) {
854
1469
  cmdForget();
855
1470
  break;
856
1471
  case "feedback":
857
- cmdFeedback();
1472
+ await cmdFeedback();
858
1473
  break;
859
1474
  case "brief":
860
1475
  cmdBrief();
@@ -868,6 +1483,9 @@ switch (SUB) {
868
1483
  case "show":
869
1484
  cmdShow();
870
1485
  break;
1486
+ case "promote":
1487
+ await cmdPromote();
1488
+ break;
871
1489
  case "path":
872
1490
  cmdPath();
873
1491
  break;
@@ -876,9 +1494,12 @@ switch (SUB) {
876
1494
  break;
877
1495
  default:
878
1496
  process.stderr.write(
879
- "usage: learnings-ledger.mjs <add|from-triage|feedback|forget|brief|profile|show|timeline|path|stats> [flags]\n" +
1497
+ "usage: learnings-ledger.mjs <add|from-triage|feedback|forget|brief|profile|show|timeline|promote|path|stats> [flags]\n" +
880
1498
  ` add --kind <${[...KINDS].join("|")}> --statement "..." [--rationale "..." (required for decision)] [--supersedes <id>]\n` +
881
- " brief|profile [--hook] fit the block to the 10,000-character hook output limit\n",
1499
+ " brief|profile [--hook] fit the block to the 10,000-character hook output limit\n" +
1500
+ " brief|profile [--tier quick|panorama|deep] fit the block to 1.5k, 6k or 12k characters\n" +
1501
+ " promote --candidates [--json] | --accept <P:id> one approved candidate per call\n" +
1502
+ ' promote --retract <G:id> --reason "..." take a global learning back everywhere\n',
882
1503
  );
883
1504
  process.exit(64);
884
1505
  }