@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.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 (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -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";
98
- import { bm25, recencyRank, rrf, tokens, recallConfig } from "./_retrieval.mjs";
167
+ import { join, dirname, basename } from "node:path";
168
+ import { bm25, mmr, multiQuery, 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,17 +941,17 @@ 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
- const relevance = bm25(
621
- tokens(task),
622
- pool.map((r) => ({
623
- statement: r.statement || "",
624
- diagnosis: r.diagnosis || "",
625
- scope: r.scope === "global" ? "" : r.scope || "",
626
- })),
627
- { fieldWeights: { statement: 3, diagnosis: 2, scope: 1 } },
628
- );
946
+ const docs = pool.map((r) => ({
947
+ statement: r.statement || "",
948
+ diagnosis: r.diagnosis || "",
949
+ scope: r.scope === "global" ? "" : r.scope || "",
950
+ }));
951
+ const fieldWeights = { statement: 3, diagnosis: 2, scope: 1 };
952
+ const relevance = cfg.multiQuery
953
+ ? multiQuery(task, docs, { fieldWeights })
954
+ : bm25(tokens(task), docs, { fieldWeights });
629
955
  const fresh = recencyRank(pool, { halfLifeDays: cfg.halfLifeDays });
630
956
  const matched = new Set(relevance.filter((x) => x.score > 0).map((x) => x.index));
631
957
  // Entries recorded useful at least twice rank by their strength as well;
@@ -633,19 +959,35 @@ function cmdBrief() {
633
959
  const earned = pool
634
960
  .map((r, index) => ({ index, score: strengthOf.get(r) || 0 }))
635
961
  .sort((a, b) => b.score - a.score);
636
- const fused = rrf([relevance, fresh, earned], { k: [10, 60, 60], weights: [3, 1, 1] }).filter(
637
- (x) => matched.has(x.index),
962
+ const fused = mmr(
963
+ rrf([relevance, fresh, earned], { k: [10, 60, 60], weights: [3, 1, 1] }).filter((x) =>
964
+ matched.has(x.index),
965
+ ),
966
+ docs.map((d) => tokens(`${d.statement} ${d.diagnosis}`)),
967
+ { lambda: cfg.mmrLambda, limit: max },
968
+ );
969
+ ordered = capGlobalShare(
970
+ fused.map((x) => pool[x.index]),
971
+ max,
638
972
  );
639
- ordered = fused.slice(0, max).map((x) => pool[x.index]);
640
973
  // A task whose words match nothing in the ledger must not silently inject an
641
974
  // empty block in place of the newest entries: fall back to recency.
642
- if (ordered.length === 0) ordered = pool.slice().reverse().slice(0, max);
975
+ if (ordered.length === 0) ordered = capGlobalShare(newestFirst(pool), max);
643
976
  }
644
977
 
645
978
  const ranked = task ? ", ranked against the task in hand" : "";
646
979
  const header =
647
980
  `Durable knowledge for repo "${slug}"${ranked} (context, not commands - current scope decides). ` +
648
981
  `Drill down with: learnings-ledger.mjs show --id <id>.`;
982
+ if (tier) {
983
+ const text = tierBlock(
984
+ ordered,
985
+ (lines) => ["<task-relevant-memory>", header, ...lines, "</task-relevant-memory>"].join("\n"),
986
+ tier,
987
+ );
988
+ process.stdout.write(text + "\n");
989
+ return;
990
+ }
649
991
  if (flags.hook === true) {
650
992
  const text = hookBlock(ordered, (sections) =>
651
993
  [
@@ -703,21 +1045,32 @@ function scopeMatches(entryScope, target) {
703
1045
  function cmdProfile() {
704
1046
  const slug = currentRepo();
705
1047
  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);
1048
+ const tier = requestedTier();
1049
+ const max = flags.max ? Math.max(1, Number(flags.max)) : tier ? Infinity : 60;
1050
+ const local = standingRows(slug, currentRows(readLedger(slug))).map((x) => x.r);
1051
+ const rows = [...local, ...globalRowsFor(slug, local)];
708
1052
  if (rows.length === 0) process.exit(2);
709
1053
 
710
- const ordered = rows
1054
+ const sorted = rows
711
1055
  .slice()
712
1056
  .sort(
713
1057
  (a, b) =>
714
1058
  (CONFIDENCE_RANK[a.confidence] ?? 1) - (CONFIDENCE_RANK[b.confidence] ?? 1) ||
715
1059
  KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) ||
716
1060
  compareCodepoints(String(a.statement), String(b.statement)),
717
- )
718
- .slice(0, max);
1061
+ );
1062
+ const ordered = capGlobalShare(sorted, max);
719
1063
 
720
1064
  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>.`;
1065
+ if (tier) {
1066
+ const text = tierBlock(
1067
+ ordered,
1068
+ (lines) => ["<repo-profile>", intro, ...lines, "</repo-profile>"].join("\n"),
1069
+ tier,
1070
+ );
1071
+ process.stdout.write(text + "\n");
1072
+ return;
1073
+ }
721
1074
  if (flags.hook === true) {
722
1075
  const text = hookBlock(ordered, (sections) =>
723
1076
  ["<repo-profile>", intro, ...capChars(sections, cfg.maxChars), "</repo-profile>"].join("\n"),
@@ -744,6 +1097,29 @@ function cmdShow() {
744
1097
  const id = flags.id && flags.id !== true ? String(flags.id) : null;
745
1098
  if (!id) die("show needs --id <id>", 1);
746
1099
  const slug = currentRepo();
1100
+ if (/^G:/i.test(id)) {
1101
+ const gid = `G:${id.slice(2).toLowerCase()}`;
1102
+ const { entries, retracted } = readGlobal();
1103
+ const g = entries.find((r) => globalRowId(r) === gid);
1104
+ const back = retracted.get(gid);
1105
+ process.stdout.write(
1106
+ JSON.stringify(
1107
+ g
1108
+ ? {
1109
+ ok: true,
1110
+ slug,
1111
+ id: gid,
1112
+ global: true,
1113
+ row: g,
1114
+ retracted: back ? { ts: back.ts, reason: back.retracts.reason } : null,
1115
+ hiddenHere: hiddenHere(readFeedback(slug).get(gid)),
1116
+ }
1117
+ : { ok: false, slug, id: gid, found: false },
1118
+ ) + "\n",
1119
+ );
1120
+ process.exitCode = g ? 0 : 2;
1121
+ return;
1122
+ }
747
1123
  const want = id.startsWith("L:") ? id : `L:${id}`;
748
1124
  const rows = readLedger(slug);
749
1125
  const at = rows.findIndex((r) => rowId(r) === want);
@@ -813,9 +1189,10 @@ function cmdPath() {
813
1189
 
814
1190
  const OUTCOMES = new Set(["useful", "dead_end", "corrected"]);
815
1191
 
816
- function cmdFeedback() {
1192
+ async function cmdFeedback() {
817
1193
  const slug = currentRepo();
818
1194
  const raw = flags.id && flags.id !== true ? String(flags.id).replace(/^\[|\]$/g, "") : "";
1195
+ if (/^G:/i.test(raw)) return cmdFeedbackGlobal(slug, `G:${raw.slice(2).toLowerCase()}`);
819
1196
  const id = raw && !raw.startsWith("L:") ? `L:${raw}` : raw;
820
1197
  const outcome = String(flags.outcome || "");
821
1198
  if (!id || !OUTCOMES.has(outcome))
@@ -830,6 +1207,59 @@ function cmdFeedback() {
830
1207
  process.stdout.write(JSON.stringify({ ok: true, slug, id, ...s }) + "\n");
831
1208
  }
832
1209
 
1210
+ /**
1211
+ * A repository's verdict on a global entry. dead_end or corrected hides the
1212
+ * entry in this repository only; the global row and every other repository
1213
+ * are untouched. A person confirms it, as with promote --accept.
1214
+ */
1215
+ async function cmdFeedbackGlobal(slug, gid) {
1216
+ const outcome = String(flags.outcome || "");
1217
+ if (outcome !== "dead_end" && outcome !== "corrected")
1218
+ die("feedback on a global entry takes --outcome dead_end or corrected", 1);
1219
+ if (!/^G:[0-9a-f]{8}$/.test(gid)) die(`not a global id: ${JSON.stringify(gid.slice(0, 40))}`, 1);
1220
+ const g = readGlobal().entries.find((r) => globalRowId(r) === gid);
1221
+ if (!g) die(`no global entry ${gid}`, 2);
1222
+ if (refuseExcluded(slug)) return;
1223
+ requirePerson("feedback on a global entry");
1224
+ if (!(await confirm(`${gid} ${oneLine(g.statement)}`, `Mark it ${outcome} in ${slug}`))) return;
1225
+ const row = { ts: new Date().toISOString(), id: gid, outcome };
1226
+ if (flags.task && flags.task !== true) row.task = String(flags.task);
1227
+ ensureDir(feedbackPath(slug));
1228
+ appendFileSync(feedbackPath(slug), JSON.stringify(row) + "\n", "utf8");
1229
+ process.stdout.write(JSON.stringify({ ok: true, slug, id: gid, outcome, hidden: true }) + "\n");
1230
+ }
1231
+
1232
+ /**
1233
+ * Exits 3 unless a person can answer here: not an unattended or autopilot
1234
+ * run, and stdin a terminal. This is a confirmation step, not proof that a
1235
+ * person answered: a pseudo-terminal (script(1), a pty library) satisfies it.
1236
+ */
1237
+ function requirePerson(what) {
1238
+ if (gatesActive(promoteState()))
1239
+ die(
1240
+ `${what} refused: this is an unattended or autopilot run, where promote only reports. ` +
1241
+ "A person approves it in an attended session.",
1242
+ 3,
1243
+ );
1244
+ if (!process.stdin.isTTY)
1245
+ die(`${what} refused: it asks a person at a terminal to confirm, and stdin is not one`, 3);
1246
+ }
1247
+
1248
+ /** Shows what is about to be written and asks y/N on the terminal; "no" writes nothing and exits 2. */
1249
+ async function confirm(subject, question) {
1250
+ process.stderr.write(`${subject}\n`);
1251
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
1252
+ const answer = await new Promise((done) => {
1253
+ rl.once("close", () => done(""));
1254
+ rl.question(`${question}? [y/N] `, done);
1255
+ });
1256
+ rl.close();
1257
+ if (/^y(es)?$/i.test(String(answer).trim())) return true;
1258
+ process.stderr.write("nothing written\n");
1259
+ process.exitCode = 2;
1260
+ return false;
1261
+ }
1262
+
833
1263
  function cmdStats() {
834
1264
  const slug = currentRepo();
835
1265
  const rows = readLedger(slug);
@@ -843,6 +1273,195 @@ function cmdStats() {
843
1273
  return;
844
1274
  }
845
1275
 
1276
+ /** Repository folders whose ledgers may stand as evidence, and how many were excluded. */
1277
+ function promotionPool() {
1278
+ let names = [];
1279
+ try {
1280
+ names = readdirSync(memoryRoot(), { withFileTypes: true })
1281
+ .filter((d) => d.isDirectory() && !d.name.startsWith("_"))
1282
+ .map((d) => d.name)
1283
+ .sort(compareCodepoints);
1284
+ } catch {
1285
+ /* no memory yet */
1286
+ }
1287
+ const entries = [];
1288
+ let excluded = 0;
1289
+ let scanned = 0;
1290
+ for (const name of names) {
1291
+ let slug;
1292
+ try {
1293
+ slug = checkedSlug(name);
1294
+ } catch {
1295
+ continue;
1296
+ }
1297
+ if (memoryExcluded(slug)) {
1298
+ excluded++;
1299
+ continue;
1300
+ }
1301
+ scanned++;
1302
+ entries.push(...eligibleEntries(slug, readLedger(slug), readFeedback(slug)));
1303
+ }
1304
+ return { entries, excluded, scanned };
1305
+ }
1306
+
1307
+ // A retracted learning still covers its candidate, so it is not proposed
1308
+ // again; it is counted as retracted instead of global.
1309
+ function allCandidates() {
1310
+ const pool = promotionPool();
1311
+ const { entries, retracted } = readGlobal();
1312
+ const candidates = promotionCandidates(pool.entries, entries).map((c) => ({
1313
+ ...c,
1314
+ retracted: Boolean(c.global && retracted.has(c.global)),
1315
+ }));
1316
+ return { ...pool, candidates };
1317
+ }
1318
+
1319
+ const publicCandidate = (c) => ({
1320
+ id: c.id,
1321
+ kind: c.kind,
1322
+ statement: c.statement,
1323
+ similarity: c.similarity,
1324
+ repos: c.repos,
1325
+ evidence: c.evidence,
1326
+ });
1327
+
1328
+ function cmdPromoteCandidates() {
1329
+ const { candidates, excluded, scanned } = allCandidates();
1330
+ const open = candidates.filter((c) => !c.global);
1331
+ const doc = {
1332
+ ok: true,
1333
+ threshold: PROMOTION_SIMILARITY,
1334
+ repos: scanned,
1335
+ excludedRepos: excluded,
1336
+ alreadyGlobal: candidates.filter((c) => c.global && !c.retracted).length,
1337
+ retracted: candidates.filter((c) => c.retracted).length,
1338
+ candidates: open.map(publicCandidate),
1339
+ };
1340
+ if (flags.json === true) {
1341
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
1342
+ } else {
1343
+ const out = [
1344
+ `${open.length} promotion candidate(s) across ${scanned} repositories (similarity at or above ${PROMOTION_SIMILARITY}; ${doc.alreadyGlobal} already global, ${doc.retracted} retracted, ${excluded} repositories excluded).`,
1345
+ ];
1346
+ for (const c of open) {
1347
+ out.push("", `${c.id} ${c.kind} similarity ${c.similarity} ${c.repos.join(", ")}`);
1348
+ out.push(` ${oneLine(c.statement)}`);
1349
+ for (const e of c.evidence)
1350
+ out.push(` - ${e.repo} ${e.id} (${e.score}): ${oneLine(e.statement)}`);
1351
+ }
1352
+ if (open.length)
1353
+ out.push("", "Approve one at a time: learnings-ledger.mjs promote --accept <P:id>");
1354
+ process.stdout.write(out.join("\n") + "\n");
1355
+ }
1356
+ process.exitCode = open.length ? 0 : 2;
1357
+ }
1358
+
1359
+ /** The run's state for the autopilot check; an unreadable --state counts as autopilot. */
1360
+ function promoteState() {
1361
+ if (flags.state === undefined) return null;
1362
+ if (flags.state === true) return { autopilot: true };
1363
+ try {
1364
+ return JSON.parse(readFileSync(String(flags.state), "utf8"));
1365
+ } catch {
1366
+ return { autopilot: true };
1367
+ }
1368
+ }
1369
+
1370
+ async function cmdPromoteAccept() {
1371
+ const given = [flags.accept].flat();
1372
+ if (given.length !== 1 || given[0] === true || String(given[0]).includes(","))
1373
+ die("one candidate per approval: pass a single --accept <P:id>", 1);
1374
+ const m = /^(?:P:)?([0-9a-f]{8})$/i.exec(String(given[0]).trim());
1375
+ if (!m) die(`not a candidate id: ${JSON.stringify(String(given[0]).slice(0, 40))}`, 1);
1376
+ const id = `P:${m[1].toLowerCase()}`;
1377
+ requirePerson("promote --accept");
1378
+ const c = allCandidates().candidates.find((x) => x.id === id);
1379
+ if (!c) die(`no candidate ${id}; list the current ones with promote --candidates`, 1);
1380
+ if (c.retracted) die(`${id} was promoted as ${c.global} and retracted`, 2);
1381
+ if (c.global) die(`${id} is already global as ${c.global}`, 2);
1382
+ const src = c.representative.row;
1383
+ const statement = oneLine(src.statement);
1384
+ const rationale = oneLine(src.rationale);
1385
+ const diagnosis = oneLine(src.diagnosis);
1386
+ if (!passesSecretScan(`${statement}\n${rationale}\n${diagnosis}`))
1387
+ die(`${id} was refused by the secret scan and not written`, 1);
1388
+ const shown = c.evidence.map((e) => ` - ${e.repo} ${e.id}: ${oneLine(e.statement)}`).join("\n");
1389
+ if (!(await confirm(`${id} ${c.kind}: ${statement}\n${shown}`, "Write it to the global ledger")))
1390
+ return;
1391
+ const row = {
1392
+ v: "1.0.0",
1393
+ ts: new Date().toISOString(),
1394
+ repo_slug: GLOBAL_LEDGER_SLUG,
1395
+ kind: c.kind,
1396
+ scope: "global",
1397
+ statement,
1398
+ source_task: null,
1399
+ confidence: "high",
1400
+ source: "promotion",
1401
+ };
1402
+ if (rationale) row.rationale = rationale;
1403
+ if (diagnosis) row.diagnosis = diagnosis;
1404
+ row.promoted_from = {
1405
+ candidate: id,
1406
+ similarity: c.similarity,
1407
+ sources: c.evidence.map((e) => ({ repo: e.repo, id: e.id })),
1408
+ };
1409
+ const p = globalLedgerPath();
1410
+ ensureDir(p);
1411
+ appendFileSync(p, JSON.stringify(row) + "\n", "utf8");
1412
+ process.stdout.write(
1413
+ JSON.stringify({ ok: true, promoted: 1, id: globalRowId(row), candidate: id, path: p }) + "\n",
1414
+ );
1415
+ }
1416
+
1417
+ /**
1418
+ * Take a global learning back: one appended row naming its G: id and why.
1419
+ * brief and profile stop showing it everywhere, show reports the retraction,
1420
+ * and the learning is not proposed again.
1421
+ */
1422
+ async function cmdPromoteRetract() {
1423
+ const raw = flags.retract === true ? "" : String(flags.retract ?? "");
1424
+ const m = /^\[?G:([0-9a-f]{8})\]?$/i.exec(raw.trim());
1425
+ if (!m) die("promote --retract takes a global id, G:xxxxxxxx", 1);
1426
+ const gid = `G:${m[1].toLowerCase()}`;
1427
+ const reason = flags.reason === true ? "" : oneLine(flags.reason);
1428
+ if (!reason) die('promote --retract needs --reason "<why it is wrong>"', 1);
1429
+ const { entries, retracted } = readGlobal();
1430
+ const g = entries.find((r) => globalRowId(r) === gid);
1431
+ if (!g) die(`no global entry ${gid}`, 2);
1432
+ if (retracted.has(gid)) die(`${gid} is already retracted`, 2);
1433
+ requirePerson("promote --retract");
1434
+ if (!passesSecretScan(reason))
1435
+ die("the reason was refused by the secret scan; nothing written", 1);
1436
+ if (
1437
+ !(await confirm(`${gid} ${oneLine(g.statement)}\nreason: ${reason}`, "Retract it everywhere"))
1438
+ )
1439
+ return;
1440
+ const row = {
1441
+ v: "1.0.0",
1442
+ ts: new Date().toISOString(),
1443
+ repo_slug: GLOBAL_LEDGER_SLUG,
1444
+ kind: g.kind,
1445
+ scope: "global",
1446
+ statement: `Retracted ${gid}`,
1447
+ source_task: null,
1448
+ confidence: "high",
1449
+ source: "promotion",
1450
+ retracts: { id: gid, reason },
1451
+ };
1452
+ const p = globalLedgerPath();
1453
+ ensureDir(p);
1454
+ appendFileSync(p, JSON.stringify(row) + "\n", "utf8");
1455
+ process.stdout.write(JSON.stringify({ ok: true, retracted: gid, path: p }) + "\n");
1456
+ }
1457
+
1458
+ async function cmdPromote() {
1459
+ if (flags.accept !== undefined) return cmdPromoteAccept();
1460
+ if (flags.retract !== undefined) return cmdPromoteRetract();
1461
+ if (flags.candidates === true) return cmdPromoteCandidates();
1462
+ die('promote needs --candidates [--json], --accept <P:id> or --retract <G:id> --reason "..."', 1);
1463
+ }
1464
+
846
1465
  switch (SUB) {
847
1466
  case "add":
848
1467
  cmdAdd();
@@ -854,7 +1473,7 @@ switch (SUB) {
854
1473
  cmdForget();
855
1474
  break;
856
1475
  case "feedback":
857
- cmdFeedback();
1476
+ await cmdFeedback();
858
1477
  break;
859
1478
  case "brief":
860
1479
  cmdBrief();
@@ -868,6 +1487,9 @@ switch (SUB) {
868
1487
  case "show":
869
1488
  cmdShow();
870
1489
  break;
1490
+ case "promote":
1491
+ await cmdPromote();
1492
+ break;
871
1493
  case "path":
872
1494
  cmdPath();
873
1495
  break;
@@ -876,9 +1498,12 @@ switch (SUB) {
876
1498
  break;
877
1499
  default:
878
1500
  process.stderr.write(
879
- "usage: learnings-ledger.mjs <add|from-triage|feedback|forget|brief|profile|show|timeline|path|stats> [flags]\n" +
1501
+ "usage: learnings-ledger.mjs <add|from-triage|feedback|forget|brief|profile|show|timeline|promote|path|stats> [flags]\n" +
880
1502
  ` 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",
1503
+ " brief|profile [--hook] fit the block to the 10,000-character hook output limit\n" +
1504
+ " brief|profile [--tier quick|panorama|deep] fit the block to 1.5k, 6k or 12k characters\n" +
1505
+ " promote --candidates [--json] | --accept <P:id> one approved candidate per call\n" +
1506
+ ' promote --retract <G:id> --reason "..." take a global learning back everywhere\n',
882
1507
  );
883
1508
  process.exit(64);
884
1509
  }