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
@@ -0,0 +1,83 @@
1
+ // The memory_decay tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { record } from "../evidence/record.ts";
6
+ import { snapshotFiles } from "../store/files/snapshots.ts"
7
+ import { markManySuperseded } from "../store/files/supersede.ts";
8
+ import { findStaleOpen } from "../portable/decay.ts";
9
+ import { flattenMemoryText } from "../store/sanitize.ts";
10
+ import { DecayArgs, validated } from "./schema.ts";
11
+
12
+ export const register: ToolRegister = (editor, deps) => {
13
+ const { toolIds, direct } = deps;
14
+ editor.add(validated(DecayArgs, {
15
+ name: "memory_decay",
16
+ description:
17
+ "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.",
18
+ options: direct,
19
+ async execute(args, context): Promise<{ content: string }> {
20
+ const { sid } = toolIds(context);
21
+ const days = Number(args.olderThanDays) > 0 ? Number(args.olderThanDays) : 14;
22
+ const dryRun = args.dryRun !== false; // only an explicit false mutates
23
+ const stale = await findStaleOpen(days, sid);
24
+ if (!stale.length) {
25
+ return { content: `No active open threads older than ${days} days.` };
26
+ }
27
+ const listing = stale
28
+ .map(
29
+ (m) =>
30
+ ` ${flattenMemoryText(m.ts)} ${flattenMemoryText(m.type)}/${flattenMemoryText(m.scope)}: ${flattenMemoryText(m.content).slice(0, 100)}`,
31
+ )
32
+ .join("\n");
33
+ if (dryRun) {
34
+ await record(
35
+ "decay_dry_run",
36
+ { days, stale: stale.length, mem: stale.map((m) => m.ts).join(",") },
37
+ false,
38
+ );
39
+ return {
40
+ content:
41
+ `Dry run: ${stale.length} open thread(s) older than ${days} days:\n${listing}\n` +
42
+ "Re-run with dryRun=false to supersede them (snapshot first; recoverable via memory_undo).",
43
+ };
44
+ }
45
+ // Snapshot-before-mutate: the SAME helper prune() uses in memory.ts,
46
+ // one whole-file copy per affected file, taken before the first
47
+ // mutation. The batch pass snapshots again per file it touches; this
48
+ // pass guarantees a pre-decay copy exists even if a later file fails.
49
+ const snapshot = await snapshotFiles([...new Set(stale.map((m) => m.file))]);
50
+ // One lock/read/snapshot/publish per file for the whole decay run (#61):
51
+ // N retired rows are one undo point, not N. Idempotent (a no-op on rows
52
+ // already superseded, out-of-band ones skipped under the lock).
53
+ const durable: string[] = [];
54
+ let retired: number;
55
+ try {
56
+ retired = await markManySuperseded(
57
+ stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })), durable,
58
+ );
59
+ } catch (err) {
60
+ if (durable.length === 0) throw err;
61
+ let why = err instanceof Error ? err.message : String(err);
62
+ 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)}`; });
63
+ return { content: `memory_decay PARTIAL: retired row(s) ${durable.join(", ")}; stopped: ${why}. Recover with memory_undo; inspect memory_evidence before retrying.` };
64
+ }
65
+ await record(
66
+ "decay_applied",
67
+ {
68
+ days,
69
+ retired,
70
+ mem: durable.join(",") || "-",
71
+ snapshot: snapshot.join(",") || "-",
72
+ },
73
+ false,
74
+ );
75
+ return {
76
+ content:
77
+ `Decayed ${retired} open thread(s) older than ${days} days ` +
78
+ `(superseded, not deleted; snapshot: ${snapshot[0] ?? "-"}). ` +
79
+ "Recover with memory_undo.",
80
+ };
81
+ },
82
+ }));
83
+ };
@@ -0,0 +1,27 @@
1
+ // Shared dependency surface for the memory tools (#168). The tools module is
2
+ // a leaf: host wiring stays in index.ts and arrives through this interface,
3
+ // so a tool file never reaches into the plugin setup closure.
4
+ import type { GateContext } from "../gate/gate.ts";
5
+ import type { createInjectionEpochs } from "../inject/epochs.ts";
6
+ import type { HitSource } from "../hits/ledger.ts";
7
+ import type { Memory } from "../store/model/memory.ts";
8
+
9
+ export interface ToolDeps {
10
+ toolIds: (context?: unknown) => { sid: string; call: string };
11
+ bindSessionIdentity: (sid: string | undefined) => Promise<void>;
12
+ ownerlessWriter: (sid: string | undefined) => string | null;
13
+ refuseOwnerlessWrite: (sid: string, op: string) => Promise<{ content: string }>;
14
+ gateContext: (sid?: string) => GateContext;
15
+ sessions: ReturnType<typeof createInjectionEpochs>;
16
+ noteHits: (src: HitSource, sid: string, rows: Memory[], query: string) => Promise<void>;
17
+ direct: { readonly codemode: false };
18
+ }
19
+
20
+ // Structural twin of the host's tool editor; `any` mirrors the loose host
21
+ // interop types index.ts already uses for the plugin surface.
22
+ export interface ToolEditorLike {
23
+ // biome-ignore lint/suspicious/noExplicitAny: host interop boundary
24
+ add: (tool: any) => void;
25
+ }
26
+
27
+ export type ToolRegister = (editor: ToolEditorLike, deps: ToolDeps) => void;
@@ -0,0 +1,48 @@
1
+ // The memory_evidence tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { evidenceFileFor } from "../evidence/record.ts";
6
+ import { parseLine } from "../core/logfmt/format.ts"
7
+ import { readLines } from "../core/logfmt/read.ts";
8
+ import { evidenceVisibleTo, readerFromSid } from "../store/model/visibility.ts";
9
+ import { EvidenceArgs, validated } from "./schema.ts";
10
+
11
+ export const register: ToolRegister = (editor, deps) => {
12
+ const { toolIds, direct } = deps;
13
+ editor.add(validated(EvidenceArgs, {
14
+ name: "memory_evidence",
15
+ description: "Read captured evidence (data only) for a date, optionally filtered by event.",
16
+ options: direct,
17
+ async execute(args, context): Promise<{ content: string }> {
18
+ const { sid } = toolIds(context);
19
+ const reader = readerFromSid(sid);
20
+ // #130: the ONE path the schema-validated date can resolve to —
21
+ // a real calendar day inside the evidence dir, never a traversal
22
+ // into the raw store or the filesystem beyond it.
23
+ const file = evidenceFileFor(args.date);
24
+ if (!file) {
25
+ return {
26
+ content:
27
+ "memory_evidence blocked: date must be a real YYYY-MM-DD calendar date — nothing was read.",
28
+ };
29
+ }
30
+ let lines = await readLines(file);
31
+ // Data partitions too (#131's ownership rule, applied to evidence):
32
+ // a line stamped to another repository is not this session's data,
33
+ // and a line a NAMED session wrote while unresolved is private to
34
+ // that session — the caller's sid is what the private branch
35
+ // matches against (#128 re-review).
36
+ if (reader.kind !== "admin") {
37
+ lines = lines.filter((l) => {
38
+ const fields = parseLine(l);
39
+ return !fields || evidenceVisibleTo(fields, reader, sid);
40
+ });
41
+ }
42
+ if (args.ev) lines = lines.filter((l) => l.includes(`ev=${args.ev}`));
43
+ if (!lines.length) return { content: "No evidence" };
44
+ const limit = args.limit || 50;
45
+ return { content: lines.slice(-limit).join("\n") };
46
+ },
47
+ }));
48
+ };
@@ -0,0 +1,27 @@
1
+ // The memory_export tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { exportMemories } from "../portable/export.ts";
6
+ import { ExportArgs, validated } from "./schema.ts";
7
+
8
+ export const register: ToolRegister = (editor, deps) => {
9
+ const { toolIds, direct } = deps;
10
+ editor.add(validated(ExportArgs, {
11
+ name: "memory_export",
12
+ description:
13
+ "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).",
14
+ options: direct,
15
+ async execute(args, context): Promise<{ content: string }> {
16
+ try {
17
+ const { sid } = toolIds(context);
18
+ const res = await exportMemories({ scope: args.scope, file: args.file, sessionID: sid });
19
+ return { content: `Exported ${res.count} memories -> ${res.path}` };
20
+ } catch (err) {
21
+ return {
22
+ content: `memory_export failed: ${err instanceof Error ? err.message : String(err)}`,
23
+ };
24
+ }
25
+ },
26
+ }));
27
+ };
@@ -0,0 +1,23 @@
1
+ // The memory_forget tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { pruneMemory } from "../store/prune.ts";
6
+ import { ForgetArgs, validated } from "./schema.ts";
7
+
8
+ export const register: ToolRegister = (editor, deps) => {
9
+ const { toolIds, direct } = deps;
10
+ editor.add(validated(ForgetArgs, {
11
+ name: "memory_forget",
12
+ description:
13
+ "Delete memories by scope and type. Snapshots first, logs the reason for audit, never touches a repo.",
14
+ options: direct,
15
+ async execute(args, context): Promise<{ content: string }> {
16
+ const { sid } = toolIds(context);
17
+ const res = await pruneMemory(args.scope, args.type, args.reason, sid);
18
+ 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.` };
19
+ if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
20
+ return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
21
+ },
22
+ }));
23
+ };
@@ -0,0 +1,57 @@
1
+ // The memory_import tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { runWriteGate } from "../gate/gate.ts";
6
+ import { importMemories } from "../portable/import.ts";
7
+ import { ImportArgs, validated } from "./schema.ts";
8
+
9
+ export const register: ToolRegister = (editor, deps) => {
10
+ const { toolIds, bindSessionIdentity, ownerlessWriter, refuseOwnerlessWrite, gateContext, direct } = deps;
11
+ editor.add(validated(ImportArgs, {
12
+ name: "memory_import",
13
+ description:
14
+ "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.",
15
+ options: direct,
16
+ async execute(args, context): Promise<{ content: string }> {
17
+ const { sid } = toolIds(context);
18
+ // Resolve before touching the file: every imported row is re-stamped
19
+ // with the IMPORTING session's repository, so an unresolved caller
20
+ // would move a whole export into whoever set up last (#152).
21
+ await bindSessionIdentity(sid);
22
+ const ownerless = ownerlessWriter(sid);
23
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
24
+ const importGate = gateContext(sid);
25
+ try {
26
+ const t = await importMemories(
27
+ args.file,
28
+ (c) =>
29
+ runWriteGate(
30
+ { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
31
+ importGate,
32
+ ),
33
+ sid,
34
+ );
35
+ return {
36
+ content:
37
+ `Imported ${args.file}: ${t.promoted} promoted, ${t.collapsed} duplicates collapsed, ` +
38
+ `${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
39
+ (t.quarantined ? ` ${t.quarantined} promoted ${t.quarantined === 1 ? "row" : "rows"} quarantined: withheld from recall/injection until human release in the viewer.` : "") +
40
+ (t.downgraded
41
+ ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
42
+ : "") +
43
+ // Rows that landed without their write_promoted line are
44
+ // durable but invisible to memory_evidence (#155 review) —
45
+ // the tally owes the reader the count, not silence.
46
+ (t.unaudited
47
+ ? ` ${t.unaudited} promoted rows landed without their write_promoted audit line (${t.auditError}); memory_evidence will miss them.`
48
+ : ""),
49
+ };
50
+ } catch (err) {
51
+ return {
52
+ content: `memory_import failed: ${err instanceof Error ? err.message : String(err)}`,
53
+ };
54
+ }
55
+ },
56
+ }));
57
+ };
@@ -0,0 +1,30 @@
1
+ // The memory_init tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { formatInit } from "../init/format.ts"
6
+ import { runInit } from "../init/run.ts";
7
+ import { InitArgs, validated } from "./schema.ts";
8
+
9
+ export const register: ToolRegister = (editor, deps) => {
10
+ const { toolIds, bindSessionIdentity, ownerlessWriter, refuseOwnerlessWrite, gateContext, direct } = deps;
11
+ editor.add(validated(InitArgs, {
12
+ name: "memory_init",
13
+ description:
14
+ "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).",
15
+ options: direct,
16
+ async execute(args, context): Promise<{ content: string }> {
17
+ const { sid } = toolIds(context);
18
+ await bindSessionIdentity(sid);
19
+ const ownerless = ownerlessWriter(sid);
20
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "init");
21
+ const summary = await runInit({
22
+ liveRoot: gateContext(sid).liveRoot,
23
+ force: args.force,
24
+ mode: args.mode,
25
+ sessionID: sid,
26
+ });
27
+ return { content: formatInit(summary) };
28
+ },
29
+ }));
30
+ };
@@ -0,0 +1,36 @@
1
+ // The memory_list tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { loadAll } from "../store/files/load.ts"
6
+ import { isInjectable } from "../store/model/predicates.ts"
7
+ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
8
+ import { flattenMemoryText } from "../store/sanitize.ts";
9
+ import { EmptyArgs, validated } from "./schema.ts";
10
+
11
+ export const register: ToolRegister = (editor, deps) => {
12
+ const { toolIds, direct } = deps;
13
+ editor.add(validated(EmptyArgs, {
14
+ name: "memory_list",
15
+ description: "List memory scopes and types for discovery.",
16
+ options: direct,
17
+ async execute(_args, context): Promise<{ content: string }> {
18
+ const { sid } = toolIds(context);
19
+ const reader = readerFromSid(sid);
20
+ const mems = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
21
+ if (!mems.length) return { content: "No memories found" };
22
+ const scopes = new Map<string, number>();
23
+ const types = new Map<string, number>();
24
+ for (const m of mems) {
25
+ scopes.set(m.scope, (scopes.get(m.scope) ?? 0) + 1);
26
+ types.set(m.type, (types.get(m.type) ?? 0) + 1);
27
+ }
28
+ const fmt = (map: Map<string, number>) =>
29
+ [...map.entries()]
30
+ .sort((a, b) => b[1] - a[1])
31
+ .map(([k, c]) => ` ${flattenMemoryText(k)}: ${c}`)
32
+ .join("\n");
33
+ return { content: `Total: ${mems.length}\n\nScopes:\n${fmt(scopes)}\n\nTypes:\n${fmt(types)}` };
34
+ },
35
+ }));
36
+ };
@@ -0,0 +1,138 @@
1
+ // The memory_merge_review tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { memoryRoot } from "../core/config/paths.ts";
6
+ import { record } from "../evidence/record.ts";
7
+ import { withStoreLock } from "../store/lock.ts";
8
+ import { loadAll } from "../store/files/load.ts"
9
+ import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts"
10
+ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
11
+ import { MergeReviewArgs, validated } from "./schema.ts";
12
+ import { join } from "node:path";
13
+
14
+ export const register: ToolRegister = (editor, deps) => {
15
+ const { toolIds, direct } = deps;
16
+ editor.add(validated(MergeReviewArgs, {
17
+ name: "memory_merge_review",
18
+ description:
19
+ "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.",
20
+ options: direct,
21
+ async execute(args, context): Promise<{ content: string }> {
22
+ const { sid } = toolIds(context);
23
+ if (!args.loser || !args.survivor || !args.reason) {
24
+ return { content: "merge_review blocked: loser, survivor, and reason are all required (fail-closed)." };
25
+ }
26
+ if (args.loser === args.survivor) {
27
+ // (Same-row input would mark and then revive the same row: a
28
+ // silent no-op that reports full success.)
29
+ return { content: "merge_review blocked: loser and survivor are the same row — nothing to resolve. No evidence written." };
30
+ }
31
+ // A row id is a pointer, not authority (#131): resolving and
32
+ // authorizing BOTH seats happens against the caller's Reader —
33
+ // captured at entry, never re-read after an await (#127) — and the
34
+ // whole resolve/check/mutate runs under the same update-order lock
35
+ // memory_update serializes on (#125), so the authorization is
36
+ // revalidated under the mutation lock instead of against a snapshot
37
+ // a concurrent update could have replaced. Acquisition order is
38
+ // always update-order then store-file locks, never the reverse, so
39
+ // this cannot deadlock against a plain writer; on timeout it fails
40
+ // closed with nothing written.
41
+ const reader = readerFromSid(sid);
42
+ // A batch may publish the loser then refuse a later file. The sink
43
+ // records that publish before the overall promise settles (#197).
44
+ const mergeDurable: string[] = [];
45
+ try {
46
+ return await withStoreLock(
47
+ join(memoryRoot(), "update-order"),
48
+ async () => {
49
+ const all = await loadAll();
50
+ const survivorRow = all.find((m) => m.ts === args.survivor);
51
+ // Probed: marking with a survivor id that names no row retired
52
+ // the loser toward a pointer to nothing (the scope ended with
53
+ // zero active rows) while the response declared it canonical.
54
+ // Validate BEFORE touching the loser — a resolution must never
55
+ // retire real data for a phantom.
56
+ if (!survivorRow) {
57
+ return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
58
+ }
59
+ const loserRow = all.find((m) => m.ts === args.loser);
60
+ // Visibility is the authorization contract (#131): a session
61
+ // may merge exactly the rows it may read. Global and legacy
62
+ // unstamped rows are visible everywhere and therefore
63
+ // mergeable from anywhere — stated here, not granted
64
+ // implicitly by store-wide reach. A foreign row in EITHER
65
+ // seat — including an attempt to revive another repository's
66
+ // superseded survivor — is refused before any mutation.
67
+ if (loserRow && !isVisibleTo(loserRow, reader)) {
68
+ return { content: "merge_review blocked: the loser belongs to another repository — this session may not retire it. Nothing was done. No evidence written." };
69
+ }
70
+ if (!isVisibleTo(survivorRow, reader)) {
71
+ 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." };
72
+ }
73
+ const ok = await markSuperseded(args.loser, {
74
+ superseded_by: args.survivor,
75
+ reason: args.reason,
76
+ symbol: args.loser,
77
+ from: args.loser,
78
+ to: args.survivor,
79
+ }, mergeDurable);
80
+ if (!ok) {
81
+ return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
82
+ }
83
+ // The survivor may itself have been superseded earlier (e.g. by
84
+ // a row this very call just made the loser). Declaring it
85
+ // canonical has to make it recallable, so clear its own marker.
86
+ const revived = await clearSuperseded(args.survivor);
87
+ // The response has always claimed "Evidence recorded" — now it
88
+ // is true, and it names the session the merge ran FOR (#121's
89
+ // residue on this line). The host tool_result hook covers
90
+ // grep/read/edit/shell only, so a merge used to leave zero
91
+ // trace: which reviewer decision, on which reason, reviving
92
+ // what — unauditable.
93
+ await record(
94
+ "merge_resolved",
95
+ {
96
+ loser: args.loser,
97
+ survivor: args.survivor,
98
+ revived,
99
+ reason: args.reason,
100
+ },
101
+ true,
102
+ sid,
103
+ );
104
+ return {
105
+ content:
106
+ `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
107
+ (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
108
+ `Evidence recorded for reason='${args.reason}'.`,
109
+ };
110
+ },
111
+ {
112
+ onTimeout: "fail",
113
+ onEvent: (event, waitedMs) => {
114
+ void record("store_lock", { event, waited_ms: waitedMs, op: "merge" });
115
+ },
116
+ },
117
+ );
118
+ } catch (err) {
119
+ // Before mutation this is the fail-closed lock contract: nothing
120
+ // written. Once a file published, the loser IS retired —
121
+ // the honest report names the completed mutation and the failed
122
+ // follow-up (evidence/revive), not a blanket "nothing was done".
123
+ const why = err instanceof Error ? err.message : String(err);
124
+ if (mergeDurable.length === 0) {
125
+ return {
126
+ content: `merge_review blocked: ${why} — nothing was done. Retry.`,
127
+ };
128
+ }
129
+ return {
130
+ content:
131
+ `merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
132
+ `recoverable via memory_undo) but the remaining operation failed: ${why}. ` +
133
+ `The evidence line may be missing; re-running reports the loser already superseded.`,
134
+ };
135
+ }
136
+ },
137
+ }));
138
+ };
@@ -0,0 +1,72 @@
1
+ // The memory_recall tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { record } from "../evidence/record.ts";
6
+ import { formatMemory } from "../inject/format.ts";
7
+ import { loadAll } from "../store/files/load.ts"
8
+ import { isInjectable } from "../store/model/predicates.ts"
9
+ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
10
+ import type { Memory } from "../store/model/memory.ts";
11
+ import { RecallArgs, validated } from "./schema.ts";
12
+ import { firstFrontierTap, markFrontierTap } from "../capture/triggers.ts";
13
+
14
+ function scoreMemory(m: Memory, q: string): number {
15
+ // Same indexed fields as the injection scorer (#40): a row recalled by one of
16
+ // its keywords is the same row recalled by the prose that keyword stands for.
17
+ const kw = m.kw?.length ? ` ${m.kw.join(" ")}` : "";
18
+ const hay = `${m.type} ${m.scope} ${m.content}${kw}`.toLowerCase();
19
+ let score = 0;
20
+ for (const w of q.toLowerCase().split(/\s+/).filter(Boolean)) {
21
+ if (hay.includes(w)) score++;
22
+ if (m.scope.toLowerCase() === w) score += 2;
23
+ if (m.type.toLowerCase() === w) score += 2;
24
+ }
25
+ return score;
26
+ }
27
+
28
+
29
+ export const register: ToolRegister = (editor, deps) => {
30
+ const { toolIds, noteHits, direct } = deps;
31
+ editor.add(validated(RecallArgs, {
32
+ name: "memory_recall",
33
+ description:
34
+ "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.",
35
+ options: direct,
36
+ async execute(args, context): Promise<{ content: string }> {
37
+ const { sid, call } = toolIds(context);
38
+ const reader = readerFromSid(sid);
39
+ let results = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
40
+ if (!results.length) return { content: "No memories found" };
41
+ const total = results.length;
42
+ if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
43
+ if (args.type) results = results.filter((m) => m.type === args.type);
44
+ if (args.query) {
45
+ results = results
46
+ .map((m) => ({ m, score: scoreMemory(m, args.query!) }))
47
+ .filter((x) => x.score > 0)
48
+ .sort((a, b) => b.score - a.score)
49
+ .map((x) => x.m);
50
+ }
51
+ const limit = args.limit || 20;
52
+ const limited = args.query ? results.slice(0, limit) : results.slice(-limit);
53
+ if (!limited.length) return { content: "No matching memories" };
54
+ const openIn = limited.filter((m) => m.status === "open").length;
55
+ if (openIn > 0) {
56
+ markFrontierTap(sid, call);
57
+ await record(
58
+ "frontier_tapped",
59
+ {
60
+ n_open: openIn,
61
+ in_results: limited.length,
62
+ turn: firstFrontierTap(sid)?.turn,
63
+ },
64
+ true,
65
+ sid,
66
+ );
67
+ }
68
+ if (args.query) await noteHits("recall", sid, limited, args.query);
69
+ return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
70
+ },
71
+ }));
72
+ };
@@ -0,0 +1,40 @@
1
+ // Memory tool registration (#168): one module per tool, registered here in
2
+ // the same order index.ts used before the split. Behavior, schemas and result
3
+ // shapes are pinned by the e2e characterization suite (#241) and the
4
+ // registration coverage gate (e2e/coverage.test.ts).
5
+ import { register as registerRemember } from "./remember.ts";
6
+ import { register as registerConsolidate } from "./consolidate.ts";
7
+ import { register as registerInit } from "./init.ts";
8
+ import { register as registerRecall } from "./recall.ts";
9
+ import { register as registerUpdate } from "./update.ts";
10
+ import { register as registerForget } from "./forget.ts";
11
+ import { register as registerList } from "./list.ts";
12
+ import { register as registerUndo } from "./undo.ts";
13
+ import { register as registerEvidence } from "./evidence.ts";
14
+ import { register as registerMergeReview } from "./merge-review.ts";
15
+ import { register as registerExport } from "./export.ts";
16
+ import { register as registerImport } from "./import.ts";
17
+ import { register as registerDecay } from "./decay.ts";
18
+ import { register as registerStatus } from "./status-tool.ts";
19
+ import type { ToolDeps, ToolEditorLike } from "./deps.ts";
20
+
21
+ export function registerMemoryTools(editor: ToolEditorLike, deps: ToolDeps): void {
22
+ for (const register of [
23
+ registerRemember,
24
+ registerConsolidate,
25
+ registerInit,
26
+ registerRecall,
27
+ registerUpdate,
28
+ registerForget,
29
+ registerList,
30
+ registerUndo,
31
+ registerEvidence,
32
+ registerMergeReview,
33
+ registerExport,
34
+ registerImport,
35
+ registerDecay,
36
+ registerStatus,
37
+ ]) {
38
+ register(editor, deps);
39
+ }
40
+ }
@@ -0,0 +1,49 @@
1
+ // The memory_remember tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { auditCaveat, runWriteGate } from "../gate/gate.ts";
6
+ import type { WriteCandidate } from "../gate/gate.ts";
7
+ import { RememberArgs, validated } from "./schema.ts";
8
+
9
+ export const register: ToolRegister = (editor, deps) => {
10
+ const { toolIds, bindSessionIdentity, ownerlessWriter, refuseOwnerlessWrite, gateContext, direct } = deps;
11
+ editor.add(validated(RememberArgs, {
12
+ name: "memory_remember",
13
+ description:
14
+ "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.",
15
+ options: direct,
16
+ async execute(args, context): Promise<{ content: string }> {
17
+ const { sid } = toolIds(context);
18
+ const candidate: WriteCandidate = {
19
+ type: args.type,
20
+ scope: args.scope,
21
+ content: args.content,
22
+ issue: args.issue,
23
+ tags: args.tags,
24
+ kw: args.kw,
25
+ status: args.status,
26
+ repo: args.global ? "global" : undefined,
27
+ };
28
+ await bindSessionIdentity(sid);
29
+ // An explicit global write needs no repository owner; anything else
30
+ // does (#152).
31
+ if (!args.global) {
32
+ const ownerless = ownerlessWriter(sid);
33
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
34
+ }
35
+ const outcome = await runWriteGate(candidate, gateContext(sid));
36
+ // A durable row whose audit line fell is NOT a clean success
37
+ // (#155 review): the reply says what is missing where it is
38
+ // missing, and the row itself stands.
39
+ if (outcome.action === "promoted")
40
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
41
+ if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
42
+ return {
43
+ content: `Write blocked at GATE (${outcome.reason}). ${
44
+ outcome.hint ?? "Evidence recorded; inspect with memory_evidence."
45
+ }`,
46
+ };
47
+ },
48
+ }));
49
+ };