opencode-self-improvement 0.15.4 → 0.15.5

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 (98) hide show
  1. package/package.json +2 -2
  2. package/src/capture/candidates.ts +110 -0
  3. package/src/capture/lag.ts +18 -0
  4. package/src/capture/prompt.ts +50 -0
  5. package/src/capture/transcript.ts +59 -0
  6. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  7. package/src/{command.ts → command/ensure.ts} +2 -2
  8. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  9. package/src/consolidate/render.ts +30 -0
  10. package/src/core/cmp-ts.ts +16 -0
  11. package/src/core/config/budgets.ts +28 -0
  12. package/src/{config.ts → core/config/paths.ts} +1 -30
  13. package/src/core/logfmt/format.ts +82 -0
  14. package/src/{logfmt.ts → core/logfmt/publish.ts} +3 -92
  15. package/src/core/logfmt/read.ts +15 -0
  16. package/src/{state.ts → core/state.ts} +1 -1
  17. package/src/core/time.ts +6 -0
  18. package/src/{evidence.ts → evidence/record.ts} +7 -5
  19. package/src/{gates.ts → gate/gate.ts} +19 -21
  20. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  21. package/src/{hits.ts → hits/ledger.ts} +8 -6
  22. package/src/index.ts +64 -943
  23. package/src/init/detect.ts +144 -0
  24. package/src/init/format.ts +25 -0
  25. package/src/init/run.ts +188 -0
  26. package/src/inject/anchor.ts +43 -0
  27. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  28. package/src/inject/budget.ts +78 -0
  29. package/src/inject/digest.ts +89 -0
  30. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  31. package/src/inject/format.ts +32 -0
  32. package/src/inject/pull.ts +52 -0
  33. package/src/inject/version.ts +31 -0
  34. package/src/portable/decay.ts +20 -0
  35. package/src/portable/export.ts +194 -0
  36. package/src/portable/import.ts +173 -0
  37. package/src/recall/relevant.ts +72 -0
  38. package/src/recall/score.ts +106 -0
  39. package/src/recall/shared-terms.ts +15 -0
  40. package/src/status/format.ts +58 -0
  41. package/src/status/metrics.ts +65 -0
  42. package/src/status/payload.ts +143 -0
  43. package/src/status/report.ts +202 -0
  44. package/src/status/write.ts +102 -0
  45. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  46. package/src/store/files/append.ts +176 -0
  47. package/src/store/files/deletions.ts +31 -0
  48. package/src/store/files/load.ts +106 -0
  49. package/src/store/files/prune.ts +81 -0
  50. package/src/store/files/snapshots.ts +88 -0
  51. package/src/store/files/supersede.ts +123 -0
  52. package/src/store/files/target.ts +36 -0
  53. package/src/{lock.ts → store/lock.ts} +1 -1
  54. package/src/store/model/memory.ts +91 -0
  55. package/src/store/model/predicates.ts +12 -0
  56. package/src/store/model/visibility.ts +140 -0
  57. package/src/{prune.ts → store/prune.ts} +4 -3
  58. package/src/store/quarantine/release.ts +24 -0
  59. package/src/store/tombstones/rejection.ts +93 -0
  60. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  61. package/src/{undo.ts → store/undo.ts} +6 -3
  62. package/src/tools/consolidate.ts +42 -0
  63. package/src/tools/decay.ts +83 -0
  64. package/src/tools/deps.ts +27 -0
  65. package/src/tools/evidence.ts +48 -0
  66. package/src/tools/export.ts +27 -0
  67. package/src/tools/forget.ts +23 -0
  68. package/src/tools/import.ts +57 -0
  69. package/src/tools/init.ts +30 -0
  70. package/src/tools/list.ts +36 -0
  71. package/src/tools/merge-review.ts +138 -0
  72. package/src/tools/recall.ts +72 -0
  73. package/src/tools/registry.ts +40 -0
  74. package/src/tools/remember.ts +49 -0
  75. package/src/{schema.ts → tools/schema.ts} +3 -3
  76. package/src/tools/status-tool.ts +59 -0
  77. package/src/tools/undo.ts +57 -0
  78. package/src/tools/update.ts +342 -0
  79. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  80. package/src/viewer/mutate.ts +15 -15
  81. package/src/viewer/server.ts +10 -8
  82. package/tui.ts +1 -1
  83. package/src/capture.ts +0 -222
  84. package/src/init.ts +0 -333
  85. package/src/inject.ts +0 -471
  86. package/src/memory.ts +0 -851
  87. package/src/portable.ts +0 -379
  88. package/src/status.ts +0 -536
  89. /package/src/{sessions.ts → core/lru.ts} +0 -0
  90. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  91. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  92. /package/src/{types.ts → core/types.ts} +0 -0
  93. /package/src/{host.ts → identity/host-events.ts} +0 -0
  94. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  95. /package/src/{containment.ts → store/containment.ts} +0 -0
  96. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  97. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  98. /package/src/{secrets.ts → store/secrets.ts} +0 -0
package/src/index.ts CHANGED
@@ -9,53 +9,44 @@
9
9
  // the SDK's Plugin type using a type-only import (see the note on `plugin`).
10
10
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
11
11
  import { basename, join } from "node:path";
12
- import { frontierBudget, injectBudget, memoryRoot } from "./config.ts";
13
- import {
14
- clearSuperseded,
15
- evidenceVisibleTo,
16
- isActive,
17
- isInjectable,
18
- isVisibleTo,
19
- loadAll,
20
- malformedCount,
21
- markManySuperseded,
22
- markSuperseded,
23
- readerFromSid,
24
- resolveMemoryTarget,
25
- snapshotFiles,
26
- unresolvedWriteMessage,
27
- type Memory,
28
- } from "./memory.ts";
29
- import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
30
- import { withStoreLock } from "./lock.ts";
31
- import { isQuarantined, quarantineCandidate, quarantineReasons } from "./quarantine.ts";
32
- import { pruneMemory } from "./prune.ts";
33
- import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
34
- import { listSnapshots, restoreSnapshot } from "./undo.ts";
35
- import { SESSION_CAP, SessionLru } from "./sessions.ts";
36
- import { captureEvidenceContext, evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
37
- import { proposeConsolidations, renderProposals } from "./consolidate.ts";
38
- import { readReads } from "./hits.ts";
39
- import {
40
- compactionAnchor,
41
- contextualPull,
42
- formatMemory,
43
- pullQuery,
44
- sharedTerms,
45
- } from "./inject.ts";
46
- import { createInjectionEpochs } from "./injection-epochs.ts";
47
- import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits.ts";
48
- import { formatInit, runInit } from "./init.ts";
49
- import { ensureInitCommand, ensureMemoryReportCommand } from "./command.ts";
50
- import {
51
- blockedRecent,
52
- renderMemoryReport,
53
- type Measured,
54
- captureLag,
55
- captureLagLines,
56
- rowsPerDay,
57
- type StoreCounts,
58
- } from "./status.ts";
12
+ import { frontierBudget, injectBudget } from "./core/config/budgets.ts"
13
+ import { memoryRoot } from "./core/config/paths.ts";
14
+ import { unresolvedWriteMessage } from "./store/files/append.ts"
15
+ import { loadAll, malformedCount } from "./store/files/load.ts"
16
+ import { snapshotFiles } from "./store/files/snapshots.ts"
17
+ import { clearSuperseded, markManySuperseded, markSuperseded } from "./store/files/supersede.ts"
18
+ import { resolveMemoryTarget } from "./store/files/target.ts"
19
+ import { type Memory } from "./store/model/memory.ts"
20
+ import { isActive, isInjectable } from "./store/model/predicates.ts"
21
+ import { evidenceVisibleTo, isVisibleTo, readerFromSid } from "./store/model/visibility.ts";
22
+ import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gate/gate.ts";
23
+ import { withStoreLock } from "./store/lock.ts";
24
+ import { isQuarantined, quarantineCandidate, quarantineReasons } from "./store/quarantine/quarantine.ts";
25
+ import { pruneMemory } from "./store/prune.ts";
26
+ import { findStaleOpen } from "./portable/decay.ts"
27
+ import { exportMemories } from "./portable/export.ts"
28
+ import { importMemories } from "./portable/import.ts";
29
+ import { listSnapshots, restoreSnapshot } from "./store/undo.ts";
30
+ import { SESSION_CAP, SessionLru } from "./core/lru.ts";
31
+ import { captureEvidenceContext, evidenceFileFor, record, recordCaptureLag } from "./evidence/record.ts";
32
+ import { proposeConsolidations } from "./consolidate/propose.ts"
33
+ import { renderProposals } from "./consolidate/render.ts";
34
+ import { readReads } from "./hits/ledger.ts";
35
+ import { compactionAnchor } from "./inject/anchor.ts"
36
+ import { formatMemory } from "./inject/format.ts"
37
+ import { contextualPull } from "./inject/pull.ts"
38
+ import { pullQuery } from "./recall/relevant.ts"
39
+ import { sharedTerms } from "./recall/shared-terms.ts";
40
+ import { createInjectionEpochs } from "./inject/epochs.ts";
41
+ import { registerMemoryTools } from "./tools/registry.ts";
42
+ import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits/ledger.ts";
43
+ import { formatInit } from "./init/format.ts"
44
+ import { runInit } from "./init/run.ts";
45
+ import { ensureInitCommand, ensureMemoryReportCommand } from "./command/ensure.ts";
46
+ import { captureLag, captureLagLines, rowsPerDay } from "./status/metrics.ts"
47
+ import { type Measured, type StoreCounts } from "./status/payload.ts"
48
+ import { renderMemoryReport } from "./status/report.ts"
49
+ import { blockedRecent } from "./status/write.ts";
59
50
  import {
60
51
  afterTool,
61
52
  checkNewSession,
@@ -66,14 +57,18 @@ import {
66
57
  markFrontierTap,
67
58
  markTurn,
68
59
  onCompacting,
69
- } from "./triggers.ts";
70
- import { getCurrent, setCurrent } from "./state.ts";
71
- import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
72
- import { parseLine, readLines } from "./logfmt.ts";
73
- import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
74
- import { redactSecrets } from "./secrets.ts";
75
- import { flattenMemoryText } from "./sanitize.ts";
76
- import { bunFloorWarning } from "./runtime.ts";
60
+ } from "./capture/triggers.ts";
61
+ import { getCurrent, setCurrent } from "./core/state.ts";
62
+ import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./identity/repokey.ts";
63
+ import { parseLine } from "./core/logfmt/format.ts"
64
+ import { readLines } from "./core/logfmt/read.ts";
65
+ import { parseCandidates, parseModelRef } from "./capture/candidates.ts"
66
+ import { lagSince } from "./capture/lag.ts"
67
+ import { buildCapturePrompt } from "./capture/prompt.ts"
68
+ import { flattenTranscript } from "./capture/transcript.ts";
69
+ import { redactSecrets } from "./store/secrets.ts";
70
+ import { flattenMemoryText } from "./store/sanitize.ts";
71
+ import { bunFloorWarning } from "./core/runtime.ts";
77
72
  import {
78
73
  captureSessionID,
79
74
  sessionDirectoryFromMessages,
@@ -81,7 +76,7 @@ import {
81
76
  sessionIdentityEvent,
82
77
  sessionUsageEvent,
83
78
  toolIdentity,
84
- } from "./host.ts";
79
+ } from "./identity/host-events.ts";
85
80
 
86
81
  // Tool/input boundaries are zod schemas (src/schema.ts): the JSON Schema the
87
82
  // host sees is GENERATED from them, and raw args are re-parsed at execution.
@@ -100,21 +95,7 @@ import {
100
95
  UndoArgs,
101
96
  UpdateArgs,
102
97
  validated,
103
- } from "./schema.ts";
104
-
105
- function scoreMemory(m: Memory, q: string): number {
106
- // Same indexed fields as the injection scorer (#40): a row recalled by one of
107
- // its keywords is the same row recalled by the prose that keyword stands for.
108
- const kw = m.kw?.length ? ` ${m.kw.join(" ")}` : "";
109
- const hay = `${m.type} ${m.scope} ${m.content}${kw}`.toLowerCase();
110
- let score = 0;
111
- for (const w of q.toLowerCase().split(/\s+/).filter(Boolean)) {
112
- if (hay.includes(w)) score++;
113
- if (m.scope.toLowerCase() === w) score += 2;
114
- if (m.type.toLowerCase() === w) score += 2;
115
- }
116
- return score;
117
- }
98
+ } from "./tools/schema.ts";
118
99
 
119
100
  // --- OpenCode V2 runtime shapes (loose: we only read a few fields) ----------
120
101
  interface ToolDef {
@@ -417,878 +398,6 @@ const impl = {
417
398
  }
418
399
 
419
400
  // ---- tools --------------------------------------------------------------
420
- await ctx.tool?.transform((editor) => {
421
- const direct = { codemode: false } as const;
422
-
423
- editor.add(validated(RememberArgs, {
424
- name: "memory_remember",
425
- description:
426
- "Store a memory after the 4-gate write pipeline validates it (canonical graph, stale refs, dupes). Blocked writes record evidence instead of persisting. Add `kw` — 3-5 aliases, synonyms, verb forms or the literal command a FUTURE session would search with — to make a row findable when the wording differs; keywords are indexed, never injected.",
427
- options: direct,
428
- async execute(args, context): Promise<{ content: string }> {
429
- const { sid } = toolIds(context);
430
- const candidate: WriteCandidate = {
431
- type: args.type,
432
- scope: args.scope,
433
- content: args.content,
434
- issue: args.issue,
435
- tags: args.tags,
436
- kw: args.kw,
437
- status: args.status,
438
- repo: args.global ? "global" : undefined,
439
- };
440
- await bindSessionIdentity(sid);
441
- // An explicit global write needs no repository owner; anything else
442
- // does (#152).
443
- if (!args.global) {
444
- const ownerless = ownerlessWriter(sid);
445
- if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
446
- }
447
- const outcome = await runWriteGate(candidate, gateContext(sid));
448
- // A durable row whose audit line fell is NOT a clean success
449
- // (#155 review): the reply says what is missing where it is
450
- // missing, and the row itself stands.
451
- if (outcome.action === "promoted")
452
- return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
453
- if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
454
- return {
455
- content: `Write blocked at GATE (${outcome.reason}). ${
456
- outcome.hint ?? "Evidence recorded; inspect with memory_evidence."
457
- }`,
458
- };
459
- },
460
- }));
461
-
462
- editor.add(validated(ConsolidateArgs, {
463
- name: "memory_consolidate",
464
- description:
465
- "Propose consolidations of near-duplicate settled rows — read-only, nothing is written. Clusters same-scope same-type rows by jaccard, picks the most recently used member as canonical (#42's rule: the row retrieval keeps landing on), and proposes it ONLY when replaying the cluster's own logged reads proves the merged row catches at least as many reads as the best single member did. A cluster with no recorded reads is reported as unmeasured, never merged on resemblance. Resolve a proposal with memory_merge_review; absorbed rows stay recoverable. The merge is deterministic — the canonical row is the survivor's prose plus the absorbed rows' aliases — because this plugin ships no model and a rewritten row cannot be diffed or audited.",
466
- options: direct,
467
- async execute(args, context): Promise<{ content: string }> {
468
- const { sid } = toolIds(context);
469
- const reader = readerFromSid(sid);
470
- const all = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
471
- const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
472
- const ledger = await readLedger();
473
- const use = ledger.byRow;
474
- const reads = await readReads();
475
- const report = proposeConsolidations(rows, use, reads, {
476
- ...(args.jaccard !== undefined ? { jaccard: args.jaccard } : {}),
477
- });
478
- const shown = report.plans.slice(0, args.limit ?? 10);
479
- const out = renderProposals({ ...report, plans: shown });
480
- await record(
481
- "consolidate_propose",
482
- { clusters: shown.length, rows: report.rowsBefore, would_drop: report.rowsBefore - report.rowsAfter },
483
- false,
484
- );
485
- return { content: out };
486
- },
487
- }));
488
-
489
- editor.add(validated(InitArgs, {
490
- name: "memory_init",
491
- description:
492
- "Initialize repository memory and knowledge graph. Ensures the codebase-memory graph for this repo is indexed (one-shot `cli` spawn; no session MCP needed) and re-derives build/lint/test/typecheck command memories through the write gate, then stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
493
- options: direct,
494
- async execute(args, context): Promise<{ content: string }> {
495
- const { sid } = toolIds(context);
496
- await bindSessionIdentity(sid);
497
- const ownerless = ownerlessWriter(sid);
498
- if (ownerless) return await refuseOwnerlessWrite(ownerless, "init");
499
- const summary = await runInit({
500
- liveRoot: gateContext(sid).liveRoot,
501
- force: args.force,
502
- mode: args.mode,
503
- sessionID: sid,
504
- });
505
- return { content: formatInit(summary) };
506
- },
507
- }));
508
-
509
- editor.add(validated(RecallArgs, {
510
- name: "memory_recall",
511
- description:
512
- "Look up durable project knowledge — build/test/lint commands, decisions, patterns, preferences, blockers — BEFORE searching the repo or reading files. Use for 'how do I run X', conventions, and past decisions. By scope, type, or free-text query; with no filters it returns the most recent memories.",
513
- options: direct,
514
- async execute(args, context): Promise<{ content: string }> {
515
- const { sid, call } = toolIds(context);
516
- const reader = readerFromSid(sid);
517
- let results = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
518
- if (!results.length) return { content: "No memories found" };
519
- const total = results.length;
520
- if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
521
- if (args.type) results = results.filter((m) => m.type === args.type);
522
- if (args.query) {
523
- results = results
524
- .map((m) => ({ m, score: scoreMemory(m, args.query!) }))
525
- .filter((x) => x.score > 0)
526
- .sort((a, b) => b.score - a.score)
527
- .map((x) => x.m);
528
- }
529
- const limit = args.limit || 20;
530
- const limited = args.query ? results.slice(0, limit) : results.slice(-limit);
531
- if (!limited.length) return { content: "No matching memories" };
532
- const openIn = limited.filter((m) => m.status === "open").length;
533
- if (openIn > 0) {
534
- markFrontierTap(sid, call);
535
- await record(
536
- "frontier_tapped",
537
- {
538
- n_open: openIn,
539
- in_results: limited.length,
540
- turn: firstFrontierTap(sid)?.turn,
541
- },
542
- true,
543
- sid,
544
- );
545
- }
546
- if (args.query) await noteHits("recall", sid, limited, args.query);
547
- return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
548
- },
549
- }));
550
-
551
- editor.add(validated(UpdateArgs, {
552
- name: "memory_update",
553
- description:
554
- "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing. A prose edit carries over everything the call does not name — tags, issue, keywords, status, and the row's repository. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
555
- options: direct,
556
- async execute(args, context): Promise<{ content: string }> {
557
- const { sid } = toolIds(context);
558
- await bindSessionIdentity(sid);
559
- const ownerless = ownerlessWriter(sid);
560
- if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
561
- const reader = readerFromSid(sid);
562
- const updateGate = gateContext(sid);
563
- // The whole update — resolve, gate, supersede — runs under one
564
- // UPDATE-ORDER lock. Without it, two concurrent updates that both
565
- // resolved the same still-active target both promoted and both
566
- // claimed success: markSuperseded is first-call-wins, so one
567
- // replacement row silently survived un-superseded (measured 5/5).
568
- // This outer lock is a DISTINCT file from anything runWriteGate or
569
- // markSuperseded take (sections run flat — never re-enter a file
570
- // you hold), and the acquisition order is always update-order
571
- // then store, never the reverse, so it cannot deadlock against a
572
- // plain writer. On timeout it FAILS closed: proceeding unlocked
573
- // is exactly the race this lock exists to close. The loser then
574
- // re-resolves under the lock, finds its target already retired,
575
- // and writes nothing — the documented fail-closed contract.
576
- // Flips once a replacement row is durable, so the catch below can
577
- // never claim "Nothing was written" about a write that happened
578
- // (#155's lie).
579
- let mutated = false;
580
- // The gate's durable steps: rows GATE-2 retired before a later
581
- // failure (round-3 probe 3). Non-empty means "Nothing was written"
582
- // is no longer writable.
583
- const gateDurable: string[] = [];
584
- try {
585
- return await withStoreLock(
586
- join(memoryRoot(), "update-order"),
587
- async () => {
588
- const prior = (await loadAll()).filter(
589
- (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleTo(m, reader),
590
- );
591
- // Resolve the row BEFORE the gate: an update that cannot identify its
592
- // target must write nothing, rather than silently superseding whichever
593
- // row happened to be newest in this scope+type.
594
- let resolved = resolveMemoryTarget(prior, args.query);
595
- if (resolved.status === "not_found") {
596
- // Naming a SUPERSEDED row is not a miss (#155): the retry
597
- // after a partial update lands here, and when that row's
598
- // active successor already carries exactly this content the
599
- // honest verdict is the duplicate one, not a dead end. Two
600
- // subtleties the first cut missed: the successor's prose was
601
- // stored REDACTED while a retry re-carries the raw input
602
- // (the comparison must scrub), and "exactly this content"
603
- // must mean the metadata too — a retry that also names new
604
- // keywords still has work to do, and that work belongs on
605
- // the chain head, so the update CONTINUES against the
606
- // successor instead of collapsing here.
607
- let chainHead: Memory | undefined;
608
- if (args.query) {
609
- const rows = (await loadAll()).filter(
610
- (m) => m.scope === args.scope && m.type === args.type && isVisibleTo(m, reader),
611
- );
612
- const stale = resolveMemoryTarget(rows, args.query);
613
- if (stale.status === "ok" && stale.target && !isActive(stale.target)) {
614
- let latest = stale.target;
615
- const walked = new Set<string>([latest.ts]);
616
- while (latest.superseded_by) {
617
- const next = rows.find((m) => m.ts === latest.superseded_by);
618
- if (!next || walked.has(next.ts)) break;
619
- walked.add(next.ts);
620
- latest = next;
621
- }
622
- if (isActive(latest) && latest.content.trim() === redactSecrets(args.content).trim()) {
623
- const restated =
624
- (args.kw === undefined || sameStrList(args.kw, latest.kw)) &&
625
- (args.status === undefined || args.status === (latest.status ?? "settled"));
626
- if (restated) {
627
- // Every other verdict is auditable; this one must
628
- // be too — the message tells the model to consult
629
- // memory_evidence.
630
- await record(
631
- "dedup_collapse",
632
- { op: "update", named: stale.target.ts, match: latest.ts, action: "exact_successor", incoming_ignored: true },
633
- true,
634
- sid,
635
- );
636
- return {
637
- content:
638
- `Duplicate ignored: ${args.type}/${args.scope} — ${JSON.stringify(args.query)} was already ` +
639
- `updated to exactly this content (${latest.ts}). Nothing was written.`,
640
- };
641
- }
642
- chainHead = latest;
643
- }
644
- }
645
- }
646
- if (!chainHead) {
647
- const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
648
- return {
649
- content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
650
- };
651
- }
652
- resolved = { status: "ok", target: chainHead };
653
- }
654
- if (resolved.status === "ambiguous") {
655
- return {
656
- content:
657
- `memory_update blocked: ${JSON.stringify(args.query)} matches ${resolved.candidates.length} active ` +
658
- `${args.type} rows in ${args.scope} (${resolved.candidates.map((m) => m.ts).join(", ")}). ` +
659
- "Pass a row id or a unique content substring. Nothing was written.",
660
- };
661
- }
662
- const target = resolved.target;
663
- // A prose edit is not a metadata reset (#154): fields the
664
- // call does not name carry over from the row being
665
- // replaced, so updating an imported row can no longer
666
- // launder away its provenance or issue link. kw follows
667
- // the same rule with an override: omitted keeps the
668
- // target's, provided replaces. The carry completes to the
669
- // five fields of the #129 viewer precedent: STATUS (an
670
- // open frontier row stays open) and REPO (updating a
671
- // global row from one repository must not re-house it out
672
- // of every other repository's view — "an edit must never
673
- // widen visibility", and it must never narrow it either).
674
- // These are also the fields the collapse-completion judges
675
- // (review round 3): the fold asks whether the survivor
676
- // already carries the REQUESTED state — not the pre-edit
677
- // target's. An update naming kw:["new-alias"] is not
678
- // "already standing" on a row holding ["old-alias"].
679
- const requested = {
680
- kw: args.kw ?? target.kw,
681
- tags: target.tags,
682
- issue: target.issue,
683
- status: (args.status ?? target.status) ?? "settled",
684
- repo: target.repo ?? "global",
685
- };
686
- const outcome = await runWriteGate(
687
- {
688
- type: args.type,
689
- scope: args.scope,
690
- content: args.content,
691
- kw: requested.kw,
692
- tags: requested.tags,
693
- issue: requested.issue,
694
- status: requested.status,
695
- repo: requested.repo,
696
- repoPath: target.repo ? target.repoPath : undefined,
697
- },
698
- { ...updateGate, reader, supersedesTs: target.ts, durable: gateDurable },
699
- );
700
- if (outcome.action === "promoted" && outcome.ts && target) {
701
- mutated = true;
702
- const replacement = outcome.ts;
703
- const retired = target.ts;
704
- // The merge_review PARTIAL shape (156e887) applied to
705
- // update: the replacement IS durable, so the message says
706
- // exactly which follow-up step failed and what a retry does
707
- // (#155 — never claim "Nothing was written" from here).
708
- const partial = (why: string) => ({
709
- content:
710
- `memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
711
- `restores ${retired}), but ${why}. Re-running this update reports the duplicate.`,
712
- });
713
- let retiredNow = false;
714
- try {
715
- retiredNow = await markSuperseded(retired, {
716
- superseded_by: replacement,
717
- reason: "update",
718
- symbol: retired,
719
- from: retired,
720
- to: replacement,
721
- });
722
- } catch (err) {
723
- return partial(
724
- `retiring ${retired} failed: ${err instanceof Error && err.message ? err.message : String(err)}`,
725
- );
726
- }
727
- if (!retiredNow) {
728
- // merge_review checks exactly this boolean (156e887);
729
- // "Updated (superseded X)" cannot be printed over a
730
- // retirement a parallel supersession performed — that
731
- // pointer names a DIFFERENT successor, and the confident
732
- // line would hide a second active row.
733
- return partial(
734
- `${retired} had ALREADY been retired by another supersession while this call ran — ` +
735
- `it points at that successor, not at ${replacement}; check memory_evidence`,
736
- );
737
- }
738
- if (outcome.evidenceError !== undefined) {
739
- return partial(`its write_promoted audit line was not recorded (${outcome.evidenceError})`);
740
- }
741
- return { content: `Updated ${args.type} in ${args.scope} (superseded ${retired})` };
742
- }
743
- if (outcome.action === "promoted")
744
- return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
745
- if (outcome.action === "collapsed") {
746
- // Completion (#155 convergence): when a retry collapses
747
- // because an ACTIVE row already holds exactly this content
748
- // while the row it NAMES is still active (the supersede
749
- // step of an earlier PARTIAL attempt never landed), the
750
- // idempotent close is to retire the named row in the
751
- // survivor's favor — a bare "Duplicate ignored" would leave
752
- // two active rows forever and a retry that never converges.
753
- // first-call-wins makes this safe to attempt on any path.
754
- // But the fold must not INVERT #154 (review): retiring the
755
- // named row is loss-free only when the survivor already
756
- // carries what the named row carries — the SAME predicate
757
- // GATE-3 uses to call same-prose-different-metadata an
758
- // edit rather than a duplicate. Otherwise the survivor
759
- // would stand stripped of the named row's issue link,
760
- // keywords, tags or OPEN frontier standing, and a "clean
761
- // no-op" message would paper over a metadata destruction.
762
- // On disagreement nothing retires: both ids are named and
763
- // a human (or an update on the survivor) decides.
764
- const survivorTs = outcome.collapsedWith;
765
- if (target && survivorTs && survivorTs !== target.ts) {
766
- // #175: the gate can observe a session move after this call captured
767
- // its reader. Recheck before trusting or describing the survivor.
768
- const survivor = (await loadAll()).find(
769
- (m) => m.ts === survivorTs && !m.superseded_by && isVisibleTo(m, reader),
770
- );
771
- if (survivor) {
772
- // #175: private rows are visible by key OR path. Equal keys alone
773
- // can drop another checkout's access after an origin change.
774
- // For global rows, isVisibleTo ignores paths.
775
- // Match raw paths like isVisibleTo; filesystem aliases need not
776
- // grant the same readers access. This restricts automatic folds;
777
- // explicit merge_review authorizes both seats under #131 instead.
778
- const samePathVisibility = requested.repo === "global" ||
779
- (target.repoPath ?? "") === (survivor.repoPath ?? "");
780
- // The predicate is the REQUESTED state vs the survivor
781
- // (round 3): content equality is already proven by the
782
- // collapse, so the fold is loss-free only when the
783
- // survivor also carries the metadata THIS call asked
784
- // for — and stands where the target stands for readers
785
- // of other repositories (repo visibility: folding a
786
- // global row into a repo-private survivor would
787
- // narrow a visibility the promotion path exists to
788
- // preserve, and the reverse would leak).
789
- if (
790
- sameStrList(requested.kw, survivor.kw) &&
791
- sameStrList(requested.tags, survivor.tags) &&
792
- requested.issue === survivor.issue &&
793
- requested.status === (survivor.status ?? "settled") &&
794
- requested.repo === (survivor.repo ?? "global") &&
795
- samePathVisibility
796
- ) {
797
- const done = await markSuperseded(target.ts, {
798
- superseded_by: survivorTs,
799
- reason: "update",
800
- symbol: target.ts,
801
- from: target.ts,
802
- to: survivorTs,
803
- }, gateDurable);
804
- if (done) {
805
- return {
806
- content:
807
- `Duplicate: ${args.type}/${args.scope} already stands active as ${survivorTs}; ` +
808
- `${target.ts} was retired in its favor. Nothing new was written.`,
809
- };
810
- }
811
- } else {
812
- const differs: string[] = [];
813
- if (requested.status !== (survivor.status ?? "settled"))
814
- differs.push(`status ${requested.status} vs ${survivor.status ?? "settled"}`);
815
- if (requested.issue !== survivor.issue)
816
- differs.push(`issue ${requested.issue ?? "-"} vs ${survivor.issue ?? "-"}`);
817
- if (!sameStrList(requested.kw, survivor.kw))
818
- differs.push(`kw [${(requested.kw ?? []).join(", ") || "-"}] vs [${(survivor.kw ?? []).join(", ") || "-"}]`);
819
- if (!sameStrList(requested.tags, survivor.tags))
820
- differs.push(`tags [${(requested.tags ?? []).join(", ") || "-"}] vs [${(survivor.tags ?? []).join(", ") || "-"}]`);
821
- if (requested.repo !== (survivor.repo ?? "global"))
822
- differs.push(`visibility ${requested.repo} vs ${survivor.repo ?? "global"}`);
823
- if (!samePathVisibility) differs.push("repository path visibility differs");
824
- return {
825
- content:
826
- `Duplicate: ${args.type}/${args.scope} stands active as ${survivorTs}, but ${target.ts} ` +
827
- `was NOT retired — the survivor does not carry what this update asked for ` +
828
- `(${differs.join("; ")}), and the fold would drop it. Both stay active. To deliberately ` +
829
- `keep only the survivor, use memory_merge_review with loser="${target.ts}", ` +
830
- `survivor="${survivorTs}", and an explicit reason. This keeps the survivor's metadata and visibility.`,
831
- };
832
- }
833
- }
834
- }
835
- return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
836
- }
837
- return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
838
- },
839
- {
840
- onTimeout: "fail",
841
- onEvent: (event, waitedMs) => {
842
- void record("store_lock", { event, waited_ms: waitedMs, op: "update" });
843
- },
844
- },
845
- );
846
- } catch (err) {
847
- // Everything that still throws here was PRE-WRITE for THIS call's
848
- // replacement: the fail-closed lock timeout, the #152 choke-point
849
- // refusal, an evidence fault BEFORE the append. Post-append audit
850
- // failures no longer reach this catch — the gate reports them on
851
- // the promoted outcome (#155). mutated is the belt-and-braces
852
- // truth check: a future post-write throw must report a partial,
853
- // never a clean nothing. And gateDurable closes the last gap
854
- // (round 3): the gate may have RETIRED OTHER rows at GATE-2
855
- // before the fault that got here — those tombstones are on disk,
856
- // and naming them beats the "Nothing was written" premise.
857
- const msg = err instanceof Error && err.message ? err.message : String(err);
858
- return {
859
- content: mutated
860
- ? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
861
- "Re-running this update reports the duplicate; inspect with memory_evidence."
862
- : gateDurable.length > 0
863
- ? `memory_update PARTIAL: ${msg} No replacement was written, but this call had ALREADY retired ` +
864
- `${gateDurable.length} row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
865
- "disk and their audit lines may not all have landed. Re-running this update will not undo " +
866
- "them — reconcile with memory_evidence / memory_undo before retrying."
867
- : `memory_update blocked: ${msg} Nothing was written.`,
868
- };
869
- }
870
- },
871
- }));
872
-
873
- editor.add(validated(ForgetArgs, {
874
- name: "memory_forget",
875
- description:
876
- "Delete memories by scope and type. Snapshots first, logs the reason for audit, never touches a repo.",
877
- options: direct,
878
- async execute(args, context): Promise<{ content: string }> {
879
- const { sid } = toolIds(context);
880
- const res = await pruneMemory(args.scope, args.type, args.reason, sid);
881
- if (res.error) return { content: `memory_forget PARTIAL: deleted row(s) ${res.deleted.map((d) => d.memory.ts).join(", ")}; stopped: ${res.error}. Rejection tombstones or audit lines may be incomplete. Inspect memory_evidence / memory_undo before retrying.` };
882
- if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
883
- return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
884
- },
885
- }));
886
-
887
- editor.add(validated(EmptyArgs, {
888
- name: "memory_list",
889
- description: "List memory scopes and types for discovery.",
890
- options: direct,
891
- async execute(_args, context): Promise<{ content: string }> {
892
- const { sid } = toolIds(context);
893
- const reader = readerFromSid(sid);
894
- const mems = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
895
- if (!mems.length) return { content: "No memories found" };
896
- const scopes = new Map<string, number>();
897
- const types = new Map<string, number>();
898
- for (const m of mems) {
899
- scopes.set(m.scope, (scopes.get(m.scope) ?? 0) + 1);
900
- types.set(m.type, (types.get(m.type) ?? 0) + 1);
901
- }
902
- const fmt = (map: Map<string, number>) =>
903
- [...map.entries()]
904
- .sort((a, b) => b[1] - a[1])
905
- .map(([k, c]) => ` ${flattenMemoryText(k)}: ${c}`)
906
- .join("\n");
907
- return { content: `Total: ${mems.length}\n\nScopes:\n${fmt(scopes)}\n\nTypes:\n${fmt(types)}` };
908
- },
909
- }));
910
-
911
- editor.add(validated(UndoArgs, {
912
- name: "memory_undo",
913
- description:
914
- "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode. Rows belonging to other repositories are never restored, rewound, or dropped in any mode — their lines survive verbatim, though a restore may place them later in the shared file. Global rows are visible to every repository, so they are in every repository's rollback scope.",
915
- options: direct,
916
- async execute(args, context): Promise<{ content: string }> {
917
- if (args.snapshot) {
918
- const mode = args.force ? "force" : args.merge ? "merge" : "check";
919
- // Day files are shared across repositories (#153): the rollback
920
- // carries the CALLER's reader, so rows another repo owns survive
921
- // untouched in every mode instead of riding the snapshot wholesale.
922
- const { sid } = toolIds(context);
923
- const res = await restoreSnapshot(args.snapshot, memoryRoot(), mode, readerFromSid(sid));
924
- if (!res.restored) {
925
- const parts = [...res.concurrentAdded, ...res.concurrentChanged];
926
- return {
927
- content:
928
- `Undo refused: ${res.concurrentAdded.length} row(s) added and ` +
929
- `${res.concurrentChanged.length} changed since this snapshot — the shared file ` +
930
- `moved after it. Divergent rows (ts): ${parts.join(", ")}. ` +
931
- `If those belong to another session, re-run with merge=true (restore the file ` +
932
- `AND keep them); if they are the writes you are undoing, use force=true. ` +
933
- (res.foreignPreserved
934
- ? `${res.foreignPreserved} row(s) in this file belong to other repositories; they survive in every mode.`
935
- : "Rows belonging to other repositories survive in every mode."),
936
- };
937
- }
938
- const kept = res.mode === "merge" && (res.concurrentAdded.length || res.concurrentChanged.length)
939
- ? ` Kept ${res.concurrentAdded.length} added / ${res.concurrentChanged.length} changed row(s) written after the snapshot.`
940
- : "";
941
- const safety = res.safety ? ` Pre-restore file snapshotted -> ${res.safety}.` : "";
942
- const omitted = res.deletedOmitted.length
943
- ? ` Omitted ${res.deletedOmitted.length} deliberately deleted row(s); use force=true to recover them.`
944
- : "";
945
- const foreign = res.foreignPreserved
946
- ? ` Left ${res.foreignPreserved} row(s) belonging to other repositories untouched.`
947
- : "";
948
- return { content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}${foreign}` };
949
- }
950
- const snaps = await listSnapshots();
951
- if (!snaps.length) return { content: "No snapshots" };
952
- return { content: snaps.map((s) => `${s.name} (${s.bytes} bytes)`).join("\n") };
953
- },
954
- }));
955
-
956
- editor.add(validated(EvidenceArgs, {
957
- name: "memory_evidence",
958
- description: "Read captured evidence (data only) for a date, optionally filtered by event.",
959
- options: direct,
960
- async execute(args, context): Promise<{ content: string }> {
961
- const { sid } = toolIds(context);
962
- const reader = readerFromSid(sid);
963
- // #130: the ONE path the schema-validated date can resolve to —
964
- // a real calendar day inside the evidence dir, never a traversal
965
- // into the raw store or the filesystem beyond it.
966
- const file = evidenceFileFor(args.date);
967
- if (!file) {
968
- return {
969
- content:
970
- "memory_evidence blocked: date must be a real YYYY-MM-DD calendar date — nothing was read.",
971
- };
972
- }
973
- let lines = await readLines(file);
974
- // Data partitions too (#131's ownership rule, applied to evidence):
975
- // a line stamped to another repository is not this session's data,
976
- // and a line a NAMED session wrote while unresolved is private to
977
- // that session — the caller's sid is what the private branch
978
- // matches against (#128 re-review).
979
- if (reader.kind !== "admin") {
980
- lines = lines.filter((l) => {
981
- const fields = parseLine(l);
982
- return !fields || evidenceVisibleTo(fields, reader, sid);
983
- });
984
- }
985
- if (args.ev) lines = lines.filter((l) => l.includes(`ev=${args.ev}`));
986
- if (!lines.length) return { content: "No evidence" };
987
- const limit = args.limit || 50;
988
- return { content: lines.slice(-limit).join("\n") };
989
- },
990
- }));
991
-
992
- editor.add(validated(MergeReviewArgs, {
993
- name: "memory_merge_review",
994
- description:
995
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
996
- options: direct,
997
- async execute(args, context): Promise<{ content: string }> {
998
- const { sid } = toolIds(context);
999
- if (!args.loser || !args.survivor || !args.reason) {
1000
- return { content: "merge_review blocked: loser, survivor, and reason are all required (fail-closed)." };
1001
- }
1002
- if (args.loser === args.survivor) {
1003
- // (Same-row input would mark and then revive the same row: a
1004
- // silent no-op that reports full success.)
1005
- return { content: "merge_review blocked: loser and survivor are the same row — nothing to resolve. No evidence written." };
1006
- }
1007
- // A row id is a pointer, not authority (#131): resolving and
1008
- // authorizing BOTH seats happens against the caller's Reader —
1009
- // captured at entry, never re-read after an await (#127) — and the
1010
- // whole resolve/check/mutate runs under the same update-order lock
1011
- // memory_update serializes on (#125), so the authorization is
1012
- // revalidated under the mutation lock instead of against a snapshot
1013
- // a concurrent update could have replaced. Acquisition order is
1014
- // always update-order then store-file locks, never the reverse, so
1015
- // this cannot deadlock against a plain writer; on timeout it fails
1016
- // closed with nothing written.
1017
- const reader = readerFromSid(sid);
1018
- // A batch may publish the loser then refuse a later file. The sink
1019
- // records that publish before the overall promise settles (#197).
1020
- const mergeDurable: string[] = [];
1021
- try {
1022
- return await withStoreLock(
1023
- join(memoryRoot(), "update-order"),
1024
- async () => {
1025
- const all = await loadAll();
1026
- const survivorRow = all.find((m) => m.ts === args.survivor);
1027
- // Probed: marking with a survivor id that names no row retired
1028
- // the loser toward a pointer to nothing (the scope ended with
1029
- // zero active rows) while the response declared it canonical.
1030
- // Validate BEFORE touching the loser — a resolution must never
1031
- // retire real data for a phantom.
1032
- if (!survivorRow) {
1033
- return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
1034
- }
1035
- const loserRow = all.find((m) => m.ts === args.loser);
1036
- // Visibility is the authorization contract (#131): a session
1037
- // may merge exactly the rows it may read. Global and legacy
1038
- // unstamped rows are visible everywhere and therefore
1039
- // mergeable from anywhere — stated here, not granted
1040
- // implicitly by store-wide reach. A foreign row in EITHER
1041
- // seat — including an attempt to revive another repository's
1042
- // superseded survivor — is refused before any mutation.
1043
- if (loserRow && !isVisibleTo(loserRow, reader)) {
1044
- return { content: "merge_review blocked: the loser belongs to another repository — this session may not retire it. Nothing was done. No evidence written." };
1045
- }
1046
- if (!isVisibleTo(survivorRow, reader)) {
1047
- return { content: "merge_review blocked: the survivor belongs to another repository — this session may not promote or revive it. Nothing was done. No evidence written." };
1048
- }
1049
- const ok = await markSuperseded(args.loser, {
1050
- superseded_by: args.survivor,
1051
- reason: args.reason,
1052
- symbol: args.loser,
1053
- from: args.loser,
1054
- to: args.survivor,
1055
- }, mergeDurable);
1056
- if (!ok) {
1057
- return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
1058
- }
1059
- // The survivor may itself have been superseded earlier (e.g. by
1060
- // a row this very call just made the loser). Declaring it
1061
- // canonical has to make it recallable, so clear its own marker.
1062
- const revived = await clearSuperseded(args.survivor);
1063
- // The response has always claimed "Evidence recorded" — now it
1064
- // is true, and it names the session the merge ran FOR (#121's
1065
- // residue on this line). The host tool_result hook covers
1066
- // grep/read/edit/shell only, so a merge used to leave zero
1067
- // trace: which reviewer decision, on which reason, reviving
1068
- // what — unauditable.
1069
- await record(
1070
- "merge_resolved",
1071
- {
1072
- loser: args.loser,
1073
- survivor: args.survivor,
1074
- revived,
1075
- reason: args.reason,
1076
- },
1077
- true,
1078
- sid,
1079
- );
1080
- return {
1081
- content:
1082
- `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
1083
- (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
1084
- `Evidence recorded for reason='${args.reason}'.`,
1085
- };
1086
- },
1087
- {
1088
- onTimeout: "fail",
1089
- onEvent: (event, waitedMs) => {
1090
- void record("store_lock", { event, waited_ms: waitedMs, op: "merge" });
1091
- },
1092
- },
1093
- );
1094
- } catch (err) {
1095
- // Before mutation this is the fail-closed lock contract: nothing
1096
- // written. Once a file published, the loser IS retired —
1097
- // the honest report names the completed mutation and the failed
1098
- // follow-up (evidence/revive), not a blanket "nothing was done".
1099
- const why = err instanceof Error ? err.message : String(err);
1100
- if (mergeDurable.length === 0) {
1101
- return {
1102
- content: `merge_review blocked: ${why} — nothing was done. Retry.`,
1103
- };
1104
- }
1105
- return {
1106
- content:
1107
- `merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
1108
- `recoverable via memory_undo) but the remaining operation failed: ${why}. ` +
1109
- `The evidence line may be missing; re-running reports the loser already superseded.`,
1110
- };
1111
- }
1112
- },
1113
- }));
1114
-
1115
- editor.add(validated(ExportArgs, {
1116
- name: "memory_export",
1117
- description:
1118
- "Export active memories as a JSONL file for backup or transfer to another machine — scoped to what this session can read: its own repository plus global rows (full-store breadth belongs to a session-less call made outside the plugin, the library route; the viewer has no export route). The first line is a metadata header ({_export,version,exportedAt,count}); each later line is one JSON object {ts,type,scope,content,status,tags,issue}. The header is what lets memory_import keep repo-scoped status:\"open\" frontier rows — a hand-written file without it imports such rows as settled, as does an imported open row claiming repo:\"global\". Defaults to a unique <memory-root>/exports/<timestamp>-<unique>.jsonl (each default export gets its own file; two exports in the same second never share a path); `file` must name a path inside <memory-root>/exports (a relative path resolves against it), `scope` exports one scope. Superseded rows are not exported (history stays in the store).",
1119
- options: direct,
1120
- async execute(args, context): Promise<{ content: string }> {
1121
- try {
1122
- const { sid } = toolIds(context);
1123
- const res = await exportMemories({ scope: args.scope, file: args.file, sessionID: sid });
1124
- return { content: `Exported ${res.count} memories -> ${res.path}` };
1125
- } catch (err) {
1126
- return {
1127
- content: `memory_export failed: ${err instanceof Error ? err.message : String(err)}`,
1128
- };
1129
- }
1130
- },
1131
- }));
1132
-
1133
- editor.add(validated(ImportArgs, {
1134
- name: "memory_import",
1135
- description:
1136
- "Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. `file` must be inside the memory root — copy the export there first. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
1137
- options: direct,
1138
- async execute(args, context): Promise<{ content: string }> {
1139
- const { sid } = toolIds(context);
1140
- // Resolve before touching the file: every imported row is re-stamped
1141
- // with the IMPORTING session's repository, so an unresolved caller
1142
- // would move a whole export into whoever set up last (#152).
1143
- await bindSessionIdentity(sid);
1144
- const ownerless = ownerlessWriter(sid);
1145
- if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
1146
- const importGate = gateContext(sid);
1147
- try {
1148
- const t = await importMemories(
1149
- args.file,
1150
- (c) =>
1151
- runWriteGate(
1152
- { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
1153
- importGate,
1154
- ),
1155
- sid,
1156
- );
1157
- return {
1158
- content:
1159
- `Imported ${args.file}: ${t.promoted} promoted, ${t.collapsed} duplicates collapsed, ` +
1160
- `${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
1161
- (t.quarantined ? ` ${t.quarantined} promoted ${t.quarantined === 1 ? "row" : "rows"} quarantined: withheld from recall/injection until human release in the viewer.` : "") +
1162
- (t.downgraded
1163
- ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
1164
- : "") +
1165
- // Rows that landed without their write_promoted line are
1166
- // durable but invisible to memory_evidence (#155 review) —
1167
- // the tally owes the reader the count, not silence.
1168
- (t.unaudited
1169
- ? ` ${t.unaudited} promoted rows landed without their write_promoted audit line (${t.auditError}); memory_evidence will miss them.`
1170
- : ""),
1171
- };
1172
- } catch (err) {
1173
- return {
1174
- content: `memory_import failed: ${err instanceof Error ? err.message : String(err)}`,
1175
- };
1176
- }
1177
- },
1178
- }));
1179
-
1180
- editor.add(validated(DecayArgs, {
1181
- name: "memory_decay",
1182
- description:
1183
- "Retire stale open threads (status=open older than olderThanDays) by superseding them — never deleting; rows stay recoverable via memory_undo. DRY RUN BY DEFAULT: without an explicit dryRun=false this only LISTS what would retire and mutates nothing (fail-closed). A real run snapshots every affected file before the first mutation.",
1184
- options: direct,
1185
- async execute(args, context): Promise<{ content: string }> {
1186
- const { sid } = toolIds(context);
1187
- const days = Number(args.olderThanDays) > 0 ? Number(args.olderThanDays) : 14;
1188
- const dryRun = args.dryRun !== false; // only an explicit false mutates
1189
- const stale = await findStaleOpen(days, sid);
1190
- if (!stale.length) {
1191
- return { content: `No active open threads older than ${days} days.` };
1192
- }
1193
- const listing = stale
1194
- .map(
1195
- (m) =>
1196
- ` ${flattenMemoryText(m.ts)} ${flattenMemoryText(m.type)}/${flattenMemoryText(m.scope)}: ${flattenMemoryText(m.content).slice(0, 100)}`,
1197
- )
1198
- .join("\n");
1199
- if (dryRun) {
1200
- await record(
1201
- "decay_dry_run",
1202
- { days, stale: stale.length, mem: stale.map((m) => m.ts).join(",") },
1203
- false,
1204
- );
1205
- return {
1206
- content:
1207
- `Dry run: ${stale.length} open thread(s) older than ${days} days:\n${listing}\n` +
1208
- "Re-run with dryRun=false to supersede them (snapshot first; recoverable via memory_undo).",
1209
- };
1210
- }
1211
- // Snapshot-before-mutate: the SAME helper prune() uses in memory.ts,
1212
- // one whole-file copy per affected file, taken before the first
1213
- // mutation. The batch pass snapshots again per file it touches; this
1214
- // pass guarantees a pre-decay copy exists even if a later file fails.
1215
- const snapshot = await snapshotFiles([...new Set(stale.map((m) => m.file))]);
1216
- // One lock/read/snapshot/publish per file for the whole decay run (#61):
1217
- // N retired rows are one undo point, not N. Idempotent (a no-op on rows
1218
- // already superseded, out-of-band ones skipped under the lock).
1219
- const durable: string[] = [];
1220
- let retired: number;
1221
- try {
1222
- retired = await markManySuperseded(
1223
- stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })), durable,
1224
- );
1225
- } catch (err) {
1226
- if (durable.length === 0) throw err;
1227
- let why = err instanceof Error ? err.message : String(err);
1228
- await record("decay_applied", { days, retired: durable.length, mem: durable.join(","), snapshot: snapshot.join(","), partial: true, error: why }, false).catch((audit) => { why += `; audit failed: ${String(audit)}`; });
1229
- return { content: `memory_decay PARTIAL: retired row(s) ${durable.join(", ")}; stopped: ${why}. Recover with memory_undo; inspect memory_evidence before retrying.` };
1230
- }
1231
- await record(
1232
- "decay_applied",
1233
- {
1234
- days,
1235
- retired,
1236
- mem: durable.join(",") || "-",
1237
- snapshot: snapshot.join(",") || "-",
1238
- },
1239
- false,
1240
- );
1241
- return {
1242
- content:
1243
- `Decayed ${retired} open thread(s) older than ${days} days ` +
1244
- `(superseded, not deleted; snapshot: ${snapshot[0] ?? "-"}). ` +
1245
- "Recover with memory_undo.",
1246
- };
1247
- },
1248
- }));
1249
-
1250
- editor.add(validated(EmptyArgs, {
1251
- name: "memory_status",
1252
- description:
1253
- "Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (plain-language cache receipts: bust count, and the provider-reported share of prompt tokens served from cache — the proof that memory never mutates your prefix), the block verbatim, recent blocked writes with gate reasons, and store stats. Reads only — no model call.",
1254
- options: direct,
1255
- async execute(_args, context): Promise<{ content: string }> {
1256
- // In-process truth: the live epoch + ledger, fresher than any file.
1257
- const sid = toolIds(context).sid;
1258
- const reportReader = readerFromSid(sid);
1259
- if (sid !== "?") await sessions.refresh(sid);
1260
- const status = sid === "?" ? null : await sessions.buildPayload(sid);
1261
- const all = await loadAll();
1262
- const act = all.filter(isActive);
1263
- const store: StoreCounts = {
1264
- active: act.length,
1265
- superseded: all.length - act.length,
1266
- open: act.filter((m) => m.status === "open").length,
1267
- scopes: new Set(act.map((m) => m.scope)).size,
1268
- malformed: malformedCount(),
1269
- };
1270
- // Use ledger (#42): how much of the store has never been surfaced.
1271
- // Reported, never acted on — retirement is a decision, not a metric.
1272
- const ledger = await readLedger();
1273
- store.neverRetrieved = neverRetrieved(act, ledger).length;
1274
- store.ledgerSince = ledger.since;
1275
- // Self-metrics (#44): what the store costs, how fast it grows, and how
1276
- // stale a capture is when it fires. Same rule as above — the numbers
1277
- // are the point, not a verdict on them.
1278
- store.bytes = act.reduce((n, m) => n + new TextEncoder().encode(formatMemory(m)).length, 0);
1279
- store.bytesPerRow = act.length ? Math.round(store.bytes / act.length) : 0;
1280
- store.rowsPerDay = rowsPerDay(act) ?? undefined;
1281
- store.captureLag = captureLag(await captureLagLines());
1282
- return {
1283
- content: renderMemoryReport({ status, store, blocked: await blockedRecent(6),
1284
- quarantined: act.filter((m) => isVisibleTo(m, reportReader) && isQuarantined(m))
1285
- .map((m) => ({ ts: m.ts, patterns: quarantineReasons(m) })),
1286
- }),
1287
- };
1288
- },
1289
- }));
1290
- });
1291
-
1292
401
  // Use ledger (#42). `query` is what retrieval was asked with; what gets
1293
402
  // stored is the vocabulary the answer SHARES with the query, taken from the
1294
403
  // memory side, so the ledger can never become a copy of user prompts.
@@ -1310,6 +419,18 @@ const impl = {
1310
419
  });
1311
420
  const flushStatus = sessions.flushStatus;
1312
421
 
422
+ await ctx.tool?.transform((editor) =>
423
+ registerMemoryTools(editor, {
424
+ toolIds,
425
+ bindSessionIdentity,
426
+ ownerlessWriter,
427
+ refuseOwnerlessWrite,
428
+ gateContext,
429
+ sessions,
430
+ noteHits,
431
+ direct: { codemode: false } as const,
432
+ }),
433
+ );
1313
434
  // ---- hooks (all fail-closed) -------------------------------------------
1314
435
  // Seam set by the auto-capture wiring below ONLY when the compaction
1315
436
  // trigger is live (autoCapture on, captureOnCompact not false, valid