@sema-agent/core 7.64.0 → 7.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +571 -0
  2. package/dist/agents/delegation-registry-seat.d.ts +15 -0
  3. package/dist/agents/delegation-registry-seat.js +13 -0
  4. package/dist/agents/org-delivery-gate.d.ts +8 -1
  5. package/dist/agents/org-delivery-gate.js +9 -3
  6. package/dist/agents/peer-held-queue.js +1 -1
  7. package/dist/agents/peer-idle.js +1 -1
  8. package/dist/agents/peer-session-drain.d.ts +51 -12
  9. package/dist/agents/peer-session-drain.js +47 -34
  10. package/dist/agents/read-inbox-tool.d.ts +6 -2
  11. package/dist/agents/read-inbox-tool.js +18 -5
  12. package/dist/agents/subagent.d.ts +3 -1
  13. package/dist/agents/subagent.js +84 -77
  14. package/dist/brain/reasoning.d.ts +2 -0
  15. package/dist/brain/reasoning.js +1 -0
  16. package/dist/core/allow-entry.d.ts +9 -0
  17. package/dist/core/allow-entry.js +7 -1
  18. package/dist/core/ask-origin.d.ts +23 -3
  19. package/dist/core/ask-origin.js +11 -1
  20. package/dist/core/auto-promote.d.ts +3 -2
  21. package/dist/core/background-agent-store.d.ts +7 -0
  22. package/dist/core/checkpoint-store.d.ts +2 -3
  23. package/dist/core/context-settings.d.ts +1 -2
  24. package/dist/core/context-settings.js +1 -1
  25. package/dist/core/engine-attestation.d.ts +2 -2
  26. package/dist/core/engine-notice.d.ts +13 -1
  27. package/dist/core/engine-notice.js +3 -1
  28. package/dist/core/file-history-store.d.ts +2 -2
  29. package/dist/core/file-history-store.js +0 -4
  30. package/dist/core/gate-fold.js +3 -1
  31. package/dist/core/governance-codes.d.ts +6 -4
  32. package/dist/core/governance-codes.js +5 -3
  33. package/dist/core/human-input-projection.d.ts +9 -0
  34. package/dist/core/human-input-projection.js +13 -0
  35. package/dist/core/input-author.d.ts +66 -6
  36. package/dist/core/input-author.js +21 -3
  37. package/dist/core/leg-identity.d.ts +18 -2
  38. package/dist/core/leg-identity.js +5 -7
  39. package/dist/core/mailbox-store.d.ts +1 -1
  40. package/dist/core/memory-engine/consolidation.d.ts +30 -10
  41. package/dist/core/memory-engine/consolidation.js +41 -6
  42. package/dist/core/memory-engine/control-objects.d.ts +36 -3
  43. package/dist/core/memory-engine/control-objects.js +134 -12
  44. package/dist/core/memory-engine/control-plane-adoption.d.ts +13 -9
  45. package/dist/core/memory-engine/control-plane-adoption.js +58 -31
  46. package/dist/core/memory-engine/delegation-settlement.d.ts +75 -52
  47. package/dist/core/memory-engine/delegation-settlement.js +211 -228
  48. package/dist/core/memory-engine/dual-root.d.ts +3 -2
  49. package/dist/core/memory-engine/dual-root.js +5 -1
  50. package/dist/core/memory-engine/engine.d.ts +33 -16
  51. package/dist/core/memory-engine/engine.js +213 -177
  52. package/dist/core/memory-engine/file-backend.d.ts +21 -12
  53. package/dist/core/memory-engine/file-backend.js +58 -104
  54. package/dist/core/memory-engine/index.d.ts +2 -2
  55. package/dist/core/memory-engine/index.js +2 -2
  56. package/dist/core/memory-engine/layout.d.ts +184 -83
  57. package/dist/core/memory-engine/layout.js +267 -172
  58. package/dist/core/memory-engine/memory-age.d.ts +12 -0
  59. package/dist/core/memory-engine/memory-age.js +17 -0
  60. package/dist/core/memory-engine/memory-backend-contract.js +12 -11
  61. package/dist/core/memory-engine/memory-deployment.d.ts +4 -3
  62. package/dist/core/memory-engine/memory-deployment.js +6 -3
  63. package/dist/core/memory-engine/origin-clearance.d.ts +43 -15
  64. package/dist/core/memory-engine/origin-clearance.js +142 -58
  65. package/dist/core/memory-engine/tools.d.ts +2 -2
  66. package/dist/core/memory-engine/tools.js +7 -7
  67. package/dist/core/memory-engine/types.d.ts +16 -10
  68. package/dist/core/memory-vector.d.ts +6 -14
  69. package/dist/core/memory.d.ts +0 -462
  70. package/dist/core/memory.js +0 -333
  71. package/dist/core/model-receipt.d.ts +2 -1
  72. package/dist/core/model-receipt.js +5 -0
  73. package/dist/core/mods/dollar.d.ts +12 -0
  74. package/dist/core/mods/kernel/dispatch.d.ts +3 -1
  75. package/dist/core/mods/kernel/dispatch.js +5 -2
  76. package/dist/core/mods/kernel/events.d.ts +3 -1
  77. package/dist/core/mods/kernel/events.js +2 -2
  78. package/dist/core/mods/prompt-submit.d.ts +4 -0
  79. package/dist/core/mods/prompt-submit.js +24 -0
  80. package/dist/core/mods/stations.d.ts +23 -4
  81. package/dist/core/mods/stations.js +14 -7
  82. package/dist/core/permission-rule-consent.d.ts +49 -18
  83. package/dist/core/permission-rule-consent.js +59 -38
  84. package/dist/core/permission-rule-store.d.ts +24 -14
  85. package/dist/core/retention.d.ts +2 -7
  86. package/dist/core/retention.js +0 -1
  87. package/dist/core/retired-host-table-account.d.ts +19 -0
  88. package/dist/core/retired-host-table-account.js +28 -0
  89. package/dist/core/retired-tool-name-account.d.ts +60 -0
  90. package/dist/core/retired-tool-name-account.js +32 -0
  91. package/dist/core/roles.d.ts +3 -1
  92. package/dist/core/roles.js +5 -2
  93. package/dist/core/runner/classifier-ladder.d.ts +3 -1
  94. package/dist/core/runner/classifier-ladder.js +2 -2
  95. package/dist/core/runner/compact-session.js +2 -1
  96. package/dist/core/runner/contracts.d.ts +9 -9
  97. package/dist/core/runner/delegation-owner.d.ts +0 -8
  98. package/dist/core/runner/delegation-owner.js +1 -3
  99. package/dist/core/runner/gate-exit.js +9 -2
  100. package/dist/core/runner/memory-consolidation-driver.js +2 -2
  101. package/dist/core/runner/prepare-config-doors.js +1 -1
  102. package/dist/core/runner/prepare-delegation-surface.d.ts +1 -1
  103. package/dist/core/runner/prepare-delegation-surface.js +5 -3
  104. package/dist/core/runner/prepare-gate-stations.d.ts +8 -5
  105. package/dist/core/runner/prepare-gate-stations.js +13 -5
  106. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  107. package/dist/core/runner/prepare-memory-engine-session.js +1 -1
  108. package/dist/core/runner/prepare-memory.js +35 -14
  109. package/dist/core/runner/prepare-policy-chain.js +12 -3
  110. package/dist/core/runner/prepare-project-context.js +2 -2
  111. package/dist/core/runner/prepare-task.d.ts +9 -1
  112. package/dist/core/runner/prepare-task.js +6 -5
  113. package/dist/core/runner/prepare-wiring-manifest.js +5 -4
  114. package/dist/core/runner/prompt-suggestions.js +1 -1
  115. package/dist/core/runner/run-identity-wiring.js +2 -2
  116. package/dist/core/runner/run-leg.js +3 -3
  117. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  118. package/dist/core/runner/run-notification-lane.js +2 -2
  119. package/dist/core/runner/runtask.js +6 -3
  120. package/dist/core/runner/steer-admission.d.ts +11 -2
  121. package/dist/core/runner/stream-steer-verb.d.ts +5 -2
  122. package/dist/core/runner/stream-steer-verb.js +67 -14
  123. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -8
  124. package/dist/core/runner/sub-agent-deny-lists.js +22 -8
  125. package/dist/core/runner-deps.d.ts +4 -4
  126. package/dist/core/secret-env.d.ts +2 -2
  127. package/dist/core/secret-env.js +6 -20
  128. package/dist/core/session-store.d.ts +6 -6
  129. package/dist/core/session-store.js +3 -3
  130. package/dist/core/shell-run-candidates.js +3 -3
  131. package/dist/core/side-query.js +1 -1
  132. package/dist/core/skill-grant.d.ts +7 -0
  133. package/dist/core/skill-grant.js +14 -5
  134. package/dist/core/store-contracts/background-agent-store-contract.js +13 -0
  135. package/dist/core/task-event.d.ts +14 -0
  136. package/dist/core/task-notification.d.ts +35 -8
  137. package/dist/core/task-notification.js +31 -13
  138. package/dist/core/task-registry-agent.js +1 -0
  139. package/dist/core/task-registry-shared.d.ts +4 -0
  140. package/dist/core/tool-errors.d.ts +3 -3
  141. package/dist/core/tool-policy.js +2 -3
  142. package/dist/core/tool-spec.d.ts +20 -10
  143. package/dist/core/user-attachment.d.ts +5 -1
  144. package/dist/core/user-attachment.js +11 -5
  145. package/dist/core/write-protect.d.ts +16 -0
  146. package/dist/core/write-protect.js +10 -0
  147. package/dist/engine/harness/agent-harness.d.ts +19 -11
  148. package/dist/engine/harness/agent-harness.js +7 -4
  149. package/dist/engine/llm/types.d.ts +22 -10
  150. package/dist/engine/session/repo-utils.d.ts +14 -4
  151. package/dist/engine/session/repo-utils.js +5 -4
  152. package/dist/index.d.ts +10 -8
  153. package/dist/index.js +9 -7
  154. package/dist/prompts/default.d.ts +1 -2
  155. package/dist/scenarios/full-body.d.ts +1 -1
  156. package/dist/shell/lex.d.ts +50 -15
  157. package/dist/shell/lex.js +43 -9
  158. package/dist/stores/file/adoption/adopt.d.ts +1 -1
  159. package/dist/stores/file/index.d.ts +1 -15
  160. package/dist/stores/file/index.js +1 -15
  161. package/dist/stores/file/permission-rule-store.d.ts +12 -1
  162. package/dist/stores/file/permission-rule-store.js +31 -4
  163. package/dist/stores/file/session-store.js +1 -1
  164. package/dist/tools/fs/fs-bash.js +3 -3
  165. package/dist/tools/fs/removal-targets.d.ts +8 -2
  166. package/dist/tools/fs/removal-targets.js +31 -4
  167. package/dist/tools/fs/shell-read-argv.js +7 -1
  168. package/dist/tools/fs/shell-read-bindings.d.ts +21 -5
  169. package/dist/tools/fs/shell-read-bindings.js +130 -44
  170. package/dist/tools/fs/shell-read-plan.js +95 -29
  171. package/dist/tools/fs/shell-read-sourced.d.ts +25 -0
  172. package/dist/tools/fs/shell-read-sourced.js +119 -0
  173. package/dist/tools/fs/shell-read-word.d.ts +2 -2
  174. package/dist/tools/fs/shell-read-word.js +4 -5
  175. package/dist/tools/fs/shell-read-workdir.d.ts +19 -3
  176. package/dist/tools/fs/shell-read-workdir.js +60 -15
  177. package/dist/tools/fs/shell-reentry-text.d.ts +10 -2
  178. package/dist/tools/fs/shell-reentry-text.js +11 -4
  179. package/package.json +2 -2
  180. package/test/export-surface.snapshot.json +21 -79
  181. package/wire-changes/core-stores-sql@7.65.0.json +30 -0
  182. package/wire-changes/core-stores-sql@7.66.0.json +30 -0
  183. package/wire-changes/core@7.65.0.json +1650 -0
  184. package/wire-changes/core@7.66.0.json +1218 -0
  185. package/wire-changes/mods-kernel@7.65.0.json +30 -0
  186. package/wire-changes/mods-kernel@7.66.0.json +65 -0
  187. package/wire-changes/primitives@7.65.0.json +337 -0
  188. package/wire-changes/primitives@7.66.0.json +30 -0
  189. package/dist/core/memory-recall.d.ts +0 -208
  190. package/dist/core/memory-recall.js +0 -136
  191. package/dist/stores/file/memory-store.d.ts +0 -124
  192. package/dist/stores/file/memory-store.js +0 -353
@@ -220,7 +220,7 @@ export interface MemoryEntryHeader {
220
220
  }
221
221
  /** A scored search hit (FileBackend = lexical floor; PgBackend = design/81 vector rungs, S3). */
222
222
  export interface ScoredMemoryEntry extends MemoryEntryHeader {
223
- /** Cosine-DISTANCE ∈ [0,2], 0 = identical (same contract as {@link import("../memory.js").ScoredMemory}). */
223
+ /** Cosine-DISTANCE ∈ [0,2], 0 = identical (the scale of {@link import("../memory-vector.js").cosineDistance}). */
224
224
  score: number;
225
225
  }
226
226
  /**
@@ -283,8 +283,7 @@ export interface PatchReport {
283
283
  }>;
284
284
  }
285
285
  /**
286
- * design/138 §2.1 — the storage seam under the MemoryEngine. NOT a MemoryStore replacement shim: this
287
- * is the S1 new-architecture surface (the legacy `MemoryStore` path is untouched and switched off it).
286
+ * design/138 §2.1 — the storage seam under the MemoryEngine: the one memory contract a host implements.
288
287
  */
289
288
  export interface MemoryBackend {
290
289
  /** Headers for every entry in the given scopes (manifest surface — bodies excluded). */
@@ -367,8 +366,10 @@ export interface MemoryBackend {
367
366
  * /malformed patch refused/, never the ordinary rev-mismatch conflict (a whitewash is illegal
368
367
  * at ANY rev, and the weaker conflict would tell the caller's ladder to rebase and retry it);
369
368
  * design/339 c37: the same precedence covers the `distilled` law;
370
- * - design/336 §4 hold protocol: the backend is hold-UNAWARE — instruction holds live on the
371
- * ENGINE's control plane, so a held id keeps serving reads and ordinary add/update patches for
369
+ * - design/336 §4 hold protocol: the backend is hold-UNAWARE — instruction holds live in the
370
+ * ENGINE's governance records (the `holds` document and its `hold` / `quarantine` objects, in
371
+ * the store `governance` names when the backend carries one), never in the backend's entries,
372
+ * so a held id keeps serving reads and ordinary add/update patches for
372
373
  * it apply plainly (no queueing, no refusal). The settlement-period write interaction resolves
373
374
  * at release time through the clauses above: the release replays the capture-time anchor
374
375
  * (update+`baseRev` / `guard: "absent"` add), a mid-hold winner surfaces as the REPORTED
@@ -494,14 +495,16 @@ export interface MemoryGovernanceStore {
494
495
  result: T;
495
496
  }): Promise<T>;
496
497
  /** Write a control object ({@link MEMORY_CONTROL_OBJECT_KINDS}) once: `"created"` ⇔ this call wrote `bytes` under
497
- * `(kind, name)`, `"existed"` ⇔ that name already stood — whatever it holds, it is never overwritten. A reader never
498
+ * `(kind, name)`, `"existed"` ⇔ that name already stood holding exactly `bytes` — it is never overwritten, and a name
499
+ * that stands holding other bytes (or as an entry that cannot be read to tell) throws `ControlPlaneCorruptError`, the way
500
+ * a move over a target holding other bytes does: a put never answers as written for bytes it did not store. A reader never
498
501
  * meets half an object. `meta.scope` names the memory scope the object concerns when the writer knows one (a store
499
502
  * with a scope column keeps it; the File store has none and ignores it). A kind outside the closed set, or a name that
500
- * is not one opaque segment (empty, `.` / `..`, a `/`, a `\` or a NUL), is refused `memory.control_object_unknown`.
503
+ * is not one opaque segment (empty, `.` / `..`, a `/`, a `\` or a NUL, or longer than 255 UTF-8 bytes), is refused `memory.control_object_unknown`.
501
504
  *
502
505
  * @contract memory.governance.object_written_once — once a name of a kind stands, no store call replaces its bytes:
503
- * a second put answers `"existed"`, a move refuses a target holding other bytes, and only `deleteObject` takes it
504
- * away; core keeps the records whose silent replacement would launder what they recorded (a pollution marker, a
506
+ * a second put of the same bytes answers `"existed"`, a second put of other bytes (or over an entry that cannot be read to
507
+ * tell) is refused, a move refuses a target holding other bytes, and only `deleteObject` takes it away; core keeps the records whose silent replacement would launder what they recorded (a pollution marker, a
505
508
  * capture opt-out, a hold's captured bytes) on this promise. */
506
509
  putObject(kind: MemoryControlObjectKind, name: string, bytes: Uint8Array, meta?: {
507
510
  readonly scope?: string;
@@ -514,7 +517,8 @@ export interface MemoryGovernanceStore {
514
517
  listObjects(kind: MemoryControlObjectKind): Promise<string[]>;
515
518
  /** Move one object to a new `(kind, name)` in one step, never overwriting: `"moved"` ⇔ the object now stands only at
516
519
  * `to`; `"already-moved"` ⇔ the source was gone and `to` stands (a resumed move). A source and target that both stand
517
- * with different bytes, or a source and target both gone, throw. */
520
+ * with the same bytes finish by dropping the source; the File store drops it only onto a target that is a file of its
521
+ * own (a link there throws and keeps the source). Both standing with different bytes, or both gone, throw. */
518
522
  moveObject(from: {
519
523
  readonly kind: MemoryControlObjectKind;
520
524
  readonly name: string;
@@ -543,6 +547,8 @@ export declare const MEMORY_CONTROL_OBJECT_KINDS: readonly ["pollution", "import
543
547
  export type MemoryControlObjectKind = (typeof MEMORY_CONTROL_OBJECT_KINDS)[number];
544
548
  /** The part of a {@link MemoryGovernanceStore} the governance documents are kept through. */
545
549
  export type MemoryGovernanceDocs = Pick<MemoryGovernanceStore, "readDoc" | "updateDoc">;
550
+ /** The part of a {@link MemoryGovernanceStore} the control objects are kept through. */
551
+ export type MemoryGovernanceObjects = Pick<MemoryGovernanceStore, "putObject" | "getObject" | "listObjects" | "moveObject" | "deleteObject">;
546
552
  /** One file the engine materialized into the session memory directory. */
547
553
  export interface MaterializedFile {
548
554
  /** Absolute canonical path of the projected file. */
@@ -1,17 +1,9 @@
1
1
  /**
2
- * design/81 Slice 5 — the shared distance primitives for the consolidation `searchScored` retrieval, extracted
3
- * BYTE-IDENTICAL from the original PgMemoryStore implementation so the File (portable/TOC) and Pg (native/TOB)
4
- * backends rank on ONE source of truth and can't drift. The consolidation
5
- * band `{0.05, 0.3}` is defined on this cosine-distance scale; the lexical `1 - Jaccard ∈ [0,1] ⊂ [0,2]` is the
6
- * same-zero-point stand-in used when no embedding vector is present (fail-open per row).
7
- *
8
- * The capability LADDER a store reports via {@link import("./memory.js").MemoryStore.vectorMode}:
9
- * - `lexical` — no embedder: `1 - Jaccard(terms)` everywhere.
10
- * - `portable` — embedder + IN-PROCESS cosine over stored vectors (File jsonl / Pg jsonb / MySQL JSON — ANY
11
- * backend that can store a float array; O(n) over the scope, no index).
12
- * - `native` — embedder + a backend index/operator (pgvector `<=>` / TiDB `VEC_COSINE_DISTANCE`).
13
- * MySQL is NOT "can't support vectors" — it is `portable`-capable (JSON column + in-process cosine), just not
14
- * `native`. A deployment injects an embedder (config-driven); the store then reports the achieved rung.
2
+ * design/81 Slice 5 — the shared distance primitives memory search ranks on: one source of truth, so every
3
+ * backend scores on the same scale. A score is a cosine distance ∈ [0,2] (0 = identical); the lexical
4
+ * `1 - Jaccard ∈ [0,1] ⊂ [0,2]` is the same-zero-point stand-in used when no embedding vector is present
5
+ * (fail-open per row). The engine's File backend ranks on the lexical rung (`memory-engine/file-backend.ts`);
6
+ * a host backend with vectors scores with {@link cosineDistance} on dimension-matched vectors.
15
7
  */
16
8
  /** Lower-cased lexical term set: alphanumeric runs PLUS CJK character bigrams (a single-character
17
9
  * run contributes its unigram). CJK scripts have no `a-z0-9` runs at all, so an alphanumeric-only
@@ -22,7 +14,7 @@
22
14
  export declare function termSet(s: string): Set<string>;
23
15
  /** Lexical stand-in distance: `1 - Jaccard(terms)` ∈ [0,1] ⊂ [0,2]; `null` = no overlap (not a candidate). */
24
16
  export declare function jaccardDistance(query: Set<string>, text: string): number | null;
25
- /** Cosine distance ∈ [0,2] (0 = identical), the {@link import("./memory.js").ScoredMemory} contract. Uses
17
+ /** Cosine distance ∈ [0,2] (0 = identical), the scale every memory search score is on. Uses
26
18
  * `Math.min(a.length,b.length)` — a store MUST only call this on dimension-matched vectors (the row-level
27
19
  * dimension guard lives at the caller; a mismatch falls open to {@link jaccardDistance}). */
28
20
  export declare function cosineDistance(a: number[], b: number[]): number;
@@ -1,300 +1,4 @@
1
1
  import type { EngineNotice } from "./engine-notice.js";
2
- /**
3
- * A scored memory candidate returned by {@link MemoryStore.searchScored} (design/41). Carries a
4
- * **stable id** (for {@link MemoryStore.update}/{@link MemoryStore.delete}) and a similarity `score`.
5
- *
6
- * `score` is a **cosine distance ∈ [0, 2]** where **0 = identical** and larger = less similar — pinned
7
- * by contract so the consolidation band (`{lo, hi}`) is calibrated the same way across stores (a store
8
- * that returned a *similarity* instead of a *distance* would invert the band). The reference
9
- * {@link InMemoryMemoryStore} has no embeddings, so it returns a lexical distance in [0, 1] (a subset
10
- * of the range) as a stand-in for tests/dev; a production store returns a real cosine distance.
11
- */
12
- export interface ScoredMemory {
13
- id: string;
14
- text: string;
15
- score: number;
16
- /** design/84 Seam B (前置 BLOCKER): true when this note was CREATED by a consolidation ADD (not the
17
- * `remember` tool / a caller). Periodic/incremental consolidation EXCLUDES these from its candidate set so
18
- * it never re-consolidates its own output (infinite re-merge). Stores that don't track it leave it absent
19
- * (treated as not-generated — back-compat, RL-1654-store-family: the inline task-end path already excludes this-task notes by id). */
20
- consolidationGenerated?: boolean;
21
- }
22
- /**
23
- * The vector-ranking capability RUNG a {@link MemoryStore} actually achieves (design/81 Slice 5). It is a
24
- * runtime OBSERVABLE (it depends on whether an embedder was injected AND whether the backend has native vector
25
- * ops), NOT a static class trait — a deployment reads `store.vectorMode` to decide whether to build a native
26
- * index / for metrics, and to answer "does this backend do neural recall?".
27
- * - `lexical` — no embedder: `1 - Jaccard` everywhere (the default; byte-identical to the pre-Slice-5 floor).
28
- * - `portable` — embedder + IN-PROCESS cosine over stored vectors (File jsonl / Pg jsonb / **MySQL JSON** —
29
- * any backend that can store a float array; O(n), no index). MySQL sits HERE, not "unsupported".
30
- * - `native` — embedder + a backend index/operator (pgvector `<=>` / TiDB `VEC_COSINE_DISTANCE`).
31
- */
32
- export type MemoryVectorMode = "lexical" | "portable" | "native";
33
- /**
34
- * Produces an embedding for one note/query (design/81 Slice 3 — the OPTIONAL vector seam). **Byte-identical
35
- * to the repo example `PgEmbedder` (src/examples/adapters/pg-adapter.ts — repo example only, not part of the
36
- * npm surface since 1.424.0)** so the same caller-injected embedder satisfies both the Pg and File backends. It is an OPTIONAL injection: a store WITHOUT one falls back to the lexical
37
- * cosine-distance (the TOC default — no model file, no native binary in core's default path). When one IS
38
- * injected the File backend uses it for vector ranking (Slice 5) via a rebuildable sidecar index; injecting
39
- * none keeps the lexical floor unchanged. Core bundles NO embedder; a cloud/TOB consumer injects its own.
40
- */
41
- export interface Embedder {
42
- embed(text: string): Promise<number[]>;
43
- dimensions: number;
44
- }
45
- /**
46
- * Long-term (L2) memory backend — pluggable, scoped, durable across sessions.
47
- *
48
- * Design adapted (MIT) from CodeWhale's `memory.rs` (a persistent note file injected into the
49
- * system prompt) and Anthropic's memory tool (the model manages its own memory via a tool; the
50
- * backend lives in your infrastructure). The default is in-memory; a deployment provides a durable
51
- * backend (e.g. TiDB) implementing this interface.
52
- *
53
- * `scope` partitions memory by tenant — e.g. `user:42`, `org:7`, `agent:main`, or `global`.
54
- */
55
- export interface MemoryStore {
56
- /** Full memory content for a scope (timestamped bullets), or null when empty. */
57
- read(scope: string): Promise<string | null> | string | null;
58
- /**
59
- * Append one durable note to a scope. Implementations timestamp it. A store that supports
60
- * consolidation (implements {@link searchScored}/{@link update}/{@link delete}) **MUST** return the new
61
- * note's **stable id**: memory consolidation (design/41) uses it to exclude a just-appended note from
62
- * its own reconcile candidates, so an id-addressable store that returns `void` would let a note
63
- * self-match and trigger a wasteful no-op every cycle. Returning `void` is fine only for stores that
64
- * do NOT support consolidation.
65
- */
66
- append(scope: string, note: string): Promise<string | void> | string | void;
67
- /** Clear a scope's memory. */
68
- clear(scope: string): Promise<void> | void;
69
- /**
70
- * Optional just-in-time (L3) retrieval: return notes in `scope` relevant to `query`.
71
- * When implemented, the Runner exposes a `recall` tool so the model can query memory on demand
72
- * instead of relying only on the injected block (useful when a scope's memory is large).
73
- */
74
- search?(scope: string, query: string, limit?: number): Promise<string[]> | string[];
75
- /**
76
- * Optional id-addressable similarity retrieval (design/41): return up to `limit` notes in `scope`
77
- * most similar to `query`, each with a **stable id** and a cosine-distance `score` (see
78
- * {@link ScoredMemory}). Required (together with {@link update}/{@link delete}) for memory
79
- * consolidation; when any of the three is absent, consolidation is a safe no-op.
80
- *
81
- * **Concurrency contract:** memory consolidation keys on the task's memory `scope`, NOT its session,
82
- * and the Runner's per-session lock does not serialize across sessions. So `searchScored`/`update`/
83
- * `delete` MAY be called concurrently for the SAME scope from different sessions. A durable async store
84
- * must therefore either linearize per-scope writes (e.g. optimistic lock by id) or accept eventual
85
- * consistency — at worst a near-duplicate survives one extra consolidation pass (fail-open, no loss).
86
- */
87
- searchScored?(scope: string, query: string, limit?: number): Promise<ScoredMemory[]> | ScoredMemory[];
88
- /** The vector-ranking rung this store achieves (design/81 Slice 5). Absent ⇒ treated as `"lexical"`
89
- * (back-compat, RL-1654-store-family). A runtime observable — a deployment reads it to decide index/metrics, NOT to decide
90
- * whether to inject an embedder (injection is config-driven; this is the RESULT). See {@link MemoryVectorMode}. */
91
- readonly vectorMode?: MemoryVectorMode;
92
- /** Optional: replace a note's text by id (consolidation UPDATE). The id stays stable. Must be safe
93
- * under concurrent same-scope calls — see {@link searchScored}'s concurrency contract. */
94
- update?(scope: string, id: string, text: string): Promise<void> | void;
95
- /** Optional: remove a note by id (consolidation DELETE). The id is never reused afterwards. Must be
96
- * safe under concurrent same-scope calls — see {@link searchScored}'s concurrency contract. */
97
- delete?(scope: string, id: string): Promise<void> | void;
98
- /**
99
- * Optional **manifest** for selective recall (design/65 §2.2/§8#6): a per-note HEADER (id + a short
100
- * description + mtime [+ name/type when structured]) — **NOT the body** (mirrors CC reading only the
101
- * frontmatter, `memoryScan.ts FRONTMATTER_MAX_LINES=30`). The Runner injects this index for a large
102
- * scope and side-queries which ids are relevant, then fetches only those via {@link getByIds}.
103
- */
104
- listStructuredNotes?(scope: string): Promise<MemoryNoteHeader[]> | MemoryNoteHeader[];
105
- /** Optional: fetch the FULL records (with body) for the selected ids (design/65 §2.2). Unknown ids are
106
- * silently skipped. Order is not guaranteed. Pairs with {@link listStructuredNotes}. */
107
- getByIds?(scope: string, ids: string[]): Promise<MemoryNoteRecord[]> | MemoryNoteRecord[];
108
- /**
109
- * Optional: append a **structured/typed** note (design/65 §2.1, P2). `type` defaults to `"project"` and
110
- * `description` to the body's first sentence (derived at write time — store responsibility, §8#6). Returns
111
- * the new note's stable id (like {@link append}). A store that supports this surfaces `name`/`type` in
112
- * {@link listStructuredNotes} so the selective-recall side-query gets a `[type]` relevance signal.
113
- */
114
- appendStructured?(scope: string, note: StructuredNoteInput): Promise<string> | string;
115
- /**
116
- * Optional **legitimate door** for a *promotable* artifact write (design/77 §2 Gate-2). A promotable
117
- * note (a self-evolution artifact — skill/playbook/outcome-stats; classified by NOTE STRUCTURE, not a
118
- * caller flag, via {@link classifyPromotable}) may ONLY reach the backend through this method, which
119
- * carries the required `utilityVerdict`. The store-boundary gate ({@link guardedMemoryStore}) routes a
120
- * present+positive promotable write here; a promotable note WITHOUT a present+positive verdict is
121
- * fail-closed REJECTED at the boundary (never reaches any store method). `utilityVerdict` is opaque
122
- * `unknown` in core — the *definition* of "positive" stays in the profile (taxonomy never enters core).
123
- * Stores that do not implement this can still serve caller-authored writes; promotable writes simply
124
- * have nowhere legitimate to land and are rejected (fail-closed).
125
- */
126
- appendPromotable?(scope: string, note: StructuredNoteInput, utilityVerdict: unknown): Promise<string> | string;
127
- /**
128
- * **INTERNAL consolidation-only door** for the design/84 Seam B marker. A consolidation pass (and ONLY
129
- * it; none ships in the package any more) calls this to materialize a merged "add" decision tagged
130
- * `consolidationGenerated:true`, so a later periodic/incremental pass EXCLUDES its own output from the
131
- * candidate set (no infinite re-merge). It is the COUNTERPART to the {@link guardedMemoryStore} boundary
132
- * defense: the public {@link appendStructured} STRIPS a caller-supplied `consolidationGenerated` (an
133
- * external caller must never be able to mark a note "consolidation-generated" and silently exile it from
134
- * consolidation forever), while THIS method is the single legitimate inlet that may set it. The guarded
135
- * store wires it to set the marker then forward to the inner `appendStructured`; a raw (un-wrapped) store
136
- * need not implement it — consolidation then falls back to `appendStructured` (which on an un-wrapped
137
- * store still honors the marker, preserving the old behavior for direct-store tests). NOT a public caller
138
- * surface: it carries no extra capability beyond `appendStructured` + the one internal flag.
139
- */
140
- appendConsolidationGenerated?(scope: string, note: StructuredNoteInput): Promise<string> | string;
141
- /**
142
- * design/84 Seam B — read the periodic/incremental consolidation cursor for `scope` (decision 3). The
143
- * cursor is an **opaque ordering marker** the STORE defines (this core never inspects it): a value such
144
- * that every note whose ordering marker is `<= cursor` has ALREADY been folded into a prior consolidation
145
- * pass and MUST NOT be re-fed (no infinite re-merge), while every note `> cursor` is still pending. In the
146
- * reference stores it is a note **id** (uuidv7 — lexicographically time-sortable), so "after the cursor"
147
- * is a simple string `>` comparison. Returns `undefined` when no pass has run yet (⇒ the WHOLE scope is
148
- * pending — the first pass sweeps it all). PAIR with {@link setConsolidationCursor}: a store implements
149
- * BOTH or NEITHER ({@link supportsPeriodicConsolidation}); the package no longer ships the pass that read it
150
- * (the store family that keeps it is on RL-1654-store-family).
151
- */
152
- getConsolidationCursor?(scope: string): Promise<string | undefined> | string | undefined;
153
- /**
154
- * design/84 Seam B — persist the periodic/incremental consolidation cursor for `scope` (decision 3). Called
155
- * by a consolidation pass ONLY after it succeeds in full, advancing the cursor to the max ordering
156
- * marker the pass observed (seen note ids ∪ added ids). Must be durable (a later pass reads it back). PAIR
157
- * with {@link getConsolidationCursor}.
158
- */
159
- setConsolidationCursor?(scope: string, cursor: string): Promise<void> | void;
160
- }
161
- /** Standard structured-note types (design/65 §2.1, CC `memoryTypes.ts`). Any other string is accepted and
162
- * degrades gracefully (stored + shown as-is) — `type` is widened to `string` everywhere for that reason. */
163
- export type MemoryNoteType = "user" | "feedback" | "project" | "reference";
164
- /** Input to {@link MemoryStore.appendStructured}. Only `body` is required. */
165
- export interface StructuredNoteInput {
166
- body: string;
167
- /** A short slug for `[[name]]` cross-references (design/65 §2.1). Optional. */
168
- name?: string;
169
- /** One of {@link MemoryNoteType}, or any string (unknown types degrade). Default `"project"`. */
170
- type?: string;
171
- /** One-line summary for the manifest. Default = first sentence of `body`. */
172
- description?: string;
173
- /** `[[name]]` cross-reference slugs (design/65 §2.1; v1 stores/displays, no link-following). */
174
- links?: string[];
175
- /**
176
- * design/77 §2 Gate-2 structural marker. An opaque (`unknown`) outcome-statistics blob attached to a
177
- * self-evolution artifact (held-out pass-rate, usage count, …). Its PRESENCE makes a note *promotable*
178
- * even when `type` is in the caller-authored closed set — the structural marker WINS over the type
179
- * (see {@link classifyPromotable}). Core never inspects its shape; the taxonomy/threshold stays in the
180
- * profile (the `utilityGate` a deployment threads into {@link guardedMemoryStore}, e.g. via
181
- * `FileStorageBackendOptions.utilityGate`).
182
- */
183
- outcomeStats?: unknown;
184
- /**
185
- * design/84 Seam B (前置 BLOCKER): mark a note as CREATED BY A CONSOLIDATION ADD. Set ONLY by
186
- * a consolidation pass (none ships in the package any more) when it materializes a merged
187
- * "add" decision — never by the `remember` tool or a normal caller. A store persists it (and surfaces it on
188
- * {@link ScoredMemory}/{@link MemoryNoteHeader}) so periodic/incremental consolidation can EXCLUDE these
189
- * notes from its candidate set and not re-consolidate its own output forever. It does NOT affect the
190
- * promotable/secret gates (a consolidation ADD is `caller_authored` by construction).
191
- */
192
- consolidationGenerated?: boolean;
193
- }
194
- /** A manifest entry: enough to judge relevance, never the body (design/65 §2.2). */
195
- export interface MemoryNoteHeader {
196
- /** Store contract: ids must be SINGLE-LINE whitespace-free tokens (uuid-like). The manifest renders
197
- * `- {id}: …` lines and the side-query matches selected ids by string equality — an id containing
198
- * a newline could self-declare manifest lines, and a renderer-side rewrite would break the equality match,
199
- * so the contract sits on the store (search 1.95.1 review #2). */
200
- id: string;
201
- /** A one-line summary used as the relevance signal (derived from the note's first sentence when untyped). */
202
- description: string;
203
- /** Append/update time as ms since epoch — drives the freshness caveat (design/65 §8#8).
204
- * ⚠️ Always read together with {@link timestampMissing}: when that flag is set this slot is a `0`
205
- * SHELL, not a measurement. Never infer "unknown" from the value — `0` is a legal real timestamp. */
206
- mtimeMs: number;
207
- /**
208
- * Set when the note carries NO usable write time, so {@link mtimeMs} above is an unknown-shell rather
209
- * than a measurement (the same "unknown ≠ zero" shape as the brain layer's `usageMissing`).
210
- *
211
- * Minted only by {@link parseNoteTimestamp}, which produces the pair together — see its note for why a
212
- * bare `0` was a silent recall loss. A consumer that ORDERS or AGES notes must branch on this flag:
213
- * an unknown time is INCOMPARABLE (neither the oldest nor the newest note in the scope), and it must
214
- * never be rendered as an age. It does NOT remove the note from recall — the note stays in the
215
- * manifest, stays searchable, and stays selectable; only the recency axis abstains.
216
- */
217
- timestampMissing?: true;
218
- /** Present once notes are structured (design/65 §2.1, P2); absent for legacy flat notes. */
219
- name?: string;
220
- /** One of {@link MemoryNoteType} or any other string (unknown degrades gracefully). */
221
- type?: string;
222
- /** design/84 Seam B: true when this note was created by a consolidation ADD (excluded from periodic
223
- * consolidation candidates). Absent for `remember`/caller notes. */
224
- consolidationGenerated?: boolean;
225
- }
226
- /** A full note record (header + body) returned by {@link MemoryStore.getByIds}. */
227
- export interface MemoryNoteRecord extends MemoryNoteHeader {
228
- text: string;
229
- }
230
- /** A store that has passed {@link supportsConsolidation} — the id-addressable trio is present. */
231
- export type ConsolidationCapableStore = MemoryStore & Required<Pick<MemoryStore, "searchScored" | "update" | "delete">>;
232
- /**
233
- * True when a store implements the full id-addressable trio required for memory consolidation
234
- * (design/41): {@link MemoryStore.searchScored}/{@link MemoryStore.update}/{@link MemoryStore.delete}.
235
- * When false, the Runner skips consolidation entirely (graceful no-op).
236
- *
237
- * A TYPE PREDICATE, so the guard's conclusion travels to the call sites. A bare boolean left
238
- * every post-guard call site writing `store.update!(…)`, and a guard that later forgot one of the three
239
- * would have been invisible — the `!`s keep compiling. Now dropping a method from the check turns the
240
- * call sites red.
241
- */
242
- export declare function supportsConsolidation(store: MemoryStore): store is ConsolidationCapableStore;
243
- /** A store that has passed {@link supportsPeriodicConsolidation} — the Seam B cursor pair is present. */
244
- export type PeriodicConsolidationCapableStore = MemoryStore & Required<Pick<MemoryStore, "getConsolidationCursor" | "setConsolidationCursor">>;
245
- /**
246
- * True when a store implements the design/84 Seam B cursor PAIR
247
- * ({@link MemoryStore.getConsolidationCursor}/{@link MemoryStore.setConsolidationCursor}). Periodic/incremental
248
- * consolidation (a pass the package no longer ships) GATES on this: a store missing
249
- * either method makes a periodic pass a safe **NO-OP** (never a silent full re-consolidation of the whole
250
- * scope, which would re-merge already-consolidated notes forever). Both-or-neither — a store implementing
251
- * only one is treated as unsupported. Independent of {@link supportsConsolidation} (the id-addressable trio),
252
- * which a periodic pass ALSO needs to actually mutate.
253
- */
254
- export declare function supportsPeriodicConsolidation(store: MemoryStore): store is PeriodicConsolidationCapableStore;
255
- /** The closed set of caller-authored note types (design/65 {@link MemoryNoteType}, memory.ts). A note
256
- * whose `type` is in this set is caller-authored; a `type` *outside* it (e.g. `"skill"`) is promotable.
257
- * Exported so a caller-authored inlet (e.g. consolidation ADD) can NORMALIZE a model-suggested type to
258
- * the closed set before the store boundary — a legitimate caller_authored write must never trip the
259
- * promotable gate just because the model invented a non-standard `type` slug (MINOR-3). */
260
- export declare const CALLER_AUTHORED_TYPES: ReadonlySet<string>;
261
- /** The default caller-authored note type (matches {@link StructuredNoteInput.type}'s documented default). */
262
- export declare const DEFAULT_CALLER_AUTHORED_TYPE: MemoryNoteType;
263
- /**
264
- * Profile-injected predicate that judges whether a promotable note's `outcomeStats` clear the promotion bar
265
- * (design/77 §2). Core only guarantees a verdict is PRESENT for a promotable write; this predicate — wired
266
- * by the deployment — receives the note's (opaque) `outcomeStats` blob and returns whether it clears the
267
- * bar. (It is NOT handed the `utilityVerdict` token; the verdict's PRESENCE is checked separately by
268
- * {@link enforcePromotableWriteGate}, then the gate judges the outcome statistics.) When UNWIRED, a
269
- * promotable write fails closed.
270
- */
271
- export type UtilityGate = (stats: unknown) => boolean;
272
- /** Typed, fail-closed error thrown when a promotable artifact write reaches the store boundary without a
273
- * present-and-positive `utilityVerdict` (design/77 §2). The `code` is stable for callers to switch on;
274
- * the write NEVER reaches the backend. */
275
- export declare class MemoryGateError extends Error {
276
- readonly code: string;
277
- constructor(code: string, detail?: string);
278
- }
279
- /**
280
- * The same SHAPE as {@link MemoryGateError} — a stable `code` a caller switches on — for the opposite
281
- * PHASE of a memory write, and deliberately NOT that class: a gate error means the write was REFUSED
282
- * and never reached the backend, so a host branching on it would take exactly the wrong action here.
283
- *
284
- * @contract memory.projection_failure_is_post_durable — a store throws this ONLY after the note's own
285
- * event is durably appended and fsync'd, so `committed` is always true and the note survives a restart:
286
- * a caller that retries the write on this error stores the note a second time. Only the derived
287
- * projection is missing, and the next mutation of the same scope rewrites it whole.
288
- */
289
- export declare class MemoryProjectionError extends Error {
290
- /** Stable, switchable — the phase this failure belongs to. */
291
- readonly code = "memory.projection_failed";
292
- /** Always true: this error only exists AFTER the durable append was fsync'd. Never retry the write. */
293
- readonly committed = true;
294
- /** The projection file that could not be rewritten. */
295
- readonly path: string;
296
- constructor(path: string, cause: unknown);
297
- }
298
2
  /**
299
3
  * Scan `text` for a high-confidence credential (CC-parity P0-2). Returns the matched pattern's stable
300
4
  * `label` (NEVER the matched secret value — labels are safe to log/surface), or `null` when clean.
@@ -311,174 +15,8 @@ export declare class MemoryProjectionError extends Error {
311
15
  * front of the store; widening candidates are evaluated per-format in the review backlog (RB-445).
312
16
  */
313
17
  export declare function detectSecret(text: string): string | null;
314
- /**
315
- * Store-boundary secret-scan invariant (CC-parity P0-2). Fail-closed: if `body` carries a high-confidence
316
- * credential, throw {@link MemoryGateError}`("memory.secret_detected")` — the write NEVER reaches the
317
- * backend. The error detail names the pattern LABEL (e.g. `aws_access_key_id`), never the matched value,
318
- * so the secret is not re-leaked into a log/error sink. A clean body is a no-op. Applied by
319
- * {@link guardedMemoryStore} on EVERY durable write inlet (`append`, `appendStructured`, the
320
- * `appendPromotable` door) so both the `remember` tool and consolidation ADD are covered at one chokepoint.
321
- */
322
- export declare function enforceSecretWriteGate(body: string): void;
323
- /**
324
- * Structured-note secret-scan invariant (CC-parity P0-2). Scans EVERY text field of a {@link StructuredNoteInput}
325
- * that becomes DURABLE and/or enters the manifest — not just `body`. The body alone is insufficient: `name`
326
- * (rendered as `[[name]]` cross-references) and `description` (rendered into the recall manifest + injected
327
- * into the side-query sub-prompt) are ALSO persisted and surfaced, so a secret hidden there
328
- * (`appendStructured({ body: "safe", description: "sk_live_…" })`) would otherwise be durably stored and
329
- * leaked into every later same-scope manifest — a real circumvention of the body-only scan. `links` slugs are NOT
330
- * scanned: they are short `[[name]]`-style reference tokens (no credential body shape clears the
331
- * conservative detector), and scanning them adds FP surface for no realistic gain. Fail-closed: the first
332
- * field that carries a high-confidence credential throws {@link MemoryGateError}`("memory.secret_detected")`.
333
- */
334
- export declare function enforceStructuredNoteSecretGate(note: StructuredNoteInput): void;
335
- /**
336
- * Classify a structured-note write as `caller_authored` (normal memory — ungated) or `promotable` (a
337
- * self-evolution artifact — gated) — design/77 §2. PURE, taxonomy-free CORE logic.
338
- *
339
- * `promotable` iff the note's `type` is defined AND outside the caller-authored closed set, OR the note
340
- * carries a structural promotable marker. **The structural marker WINS over the closed-set type** — a
341
- * `type:"reference"` note WITH an `outcomeStats` marker classifies `promotable`.
342
- */
343
- export declare function classifyPromotable(note: StructuredNoteInput): "caller_authored" | "promotable";
344
- /**
345
- * The store-boundary Gate-2 check (design/77 §2). For a `promotable` note, require a present-and-positive
346
- * `utilityVerdict`; otherwise throw {@link MemoryGateError}`("memory.promotable_ungated")` fail-closed —
347
- * the write NEVER reaches the backend. A `caller_authored` note is unchanged (no verdict needed).
348
- *
349
- * **Gate-presence invariant (CRITICAL):** "positive" is decided by the profile `utilityGate`. When the
350
- * gate is UNWIRED, a promotable note STILL fails closed (an absent gate never auto-passes). When wired,
351
- * the verdict must be present (`!== undefined`) and the gate must accept its `outcomeStats`.
352
- */
353
- export declare function enforcePromotableWriteGate(note: StructuredNoteInput, utilityVerdict: unknown, utilityGate?: UtilityGate): void;
354
- /**
355
- * Wrap a {@link MemoryStore} so EVERY durable write path runs the Gate-2 chokepoint (design/77 §2). One
356
- * wrapper at the store boundary covers BOTH inlets (the `remember` tool and consolidation ADD) — no
357
- * per-inlet edits. It intercepts BOTH write methods (§2 polish):
358
- * - `appendStructured` — classify the structured note; a `promotable` one needs a present+positive verdict.
359
- * Since `appendStructured` carries NO verdict, a promotable structured write is ALWAYS rejected here;
360
- * the legitimate way to land one is {@link MemoryStore.appendPromotable} (which carries the verdict).
361
- * - `append` — the legacy/typeless fallback CANNOT carry structure, so any append-path write is
362
- * classified `caller_authored` and passes through unchanged (documents the chokepoint's exhaustiveness
363
- * across store methods — a promotable artifact structurally cannot flow out of this path).
364
- *
365
- * `appendPromotable` is the gated legitimate door: it runs the gate WITH the supplied verdict, then (on
366
- * pass) writes via the inner store's `appendStructured` (or `append` fallback). The id-addressed `update`
367
- * (consolidation's UPDATE op) replaces a note's text with new model-generated content, so it is ALSO
368
- * secret-scanned (a promotable artifact structurally cannot flow out of it — only existing-note text is
369
- * rewritten). `delete` and the read/search/manifest surface are straight pass-throughs (they carry no new
370
- * content and never WRITE a promotable artifact).
371
- */
372
- export declare function guardedMemoryStore(inner: MemoryStore, utilityGate?: UtilityGate): MemoryStore;
373
- /**
374
- * Default in-memory MemoryStore (lost on restart). Use a durable backend in production.
375
- *
376
- * Id-addressable (design/41): each note gets a UUID stable across `update` and never reused after
377
- * `delete`, so {@link searchScored}/{@link update}/{@link delete} work and memory consolidation can run.
378
- * It has no embeddings, so `searchScored` returns a **lexical** (Jaccard) distance as a stand-in for a
379
- * real cosine distance — fine for dev/tests, but a production store should back this with vectors.
380
- */
381
- export declare class InMemoryMemoryStore implements MemoryStore {
382
- private byScope;
383
- /** design/84 Seam B: per-scope periodic-consolidation cursor (lost on restart, like the rest of this store). */
384
- private cursorByScope;
385
- /** design/81 Slice 5: the in-memory store has no embedder — always the lexical floor. */
386
- readonly vectorMode: "lexical";
387
- read(scope: string): string | null;
388
- append(scope: string, note: string): string | void;
389
- appendStructured(scope: string, note: StructuredNoteInput): string;
390
- clear(scope: string): void;
391
- /**
392
- * Keyword search backing the `recall` tool. design/81 Slice 2b — uses the SHARED synonym/stem-aware
393
- * {@link lexicalSearchMatch} (the SAME matcher as {@link import("../stores/file/memory-store.js").FileMemoryStore.search}),
394
- * so the `recall` tool returns IDENTICAL results across the InMemory and File backends. With no synonym/stem
395
- * hit it degrades to the plain substring filter (byte-identical to the pre-Slice-2b behavior).
396
- */
397
- search(scope: string, query: string, limit?: number): string[];
398
- /**
399
- * Lexical-distance retrieval (consolidation candidate source). Distance = `1 - Jaccard(terms)` so it
400
- * lives in [0, 1] ⊂ the [0, 2] cosine-distance contract (0 = identical term set). Returns the top
401
- * `limit` nearest entries (excludes zero-overlap ones). Deterministic — handy for tests.
402
- */
403
- searchScored(scope: string, query: string, limit?: number): ScoredMemory[];
404
- update(scope: string, id: string, text: string): void;
405
- delete(scope: string, id: string): void;
406
- /** Manifest (design/65 §2.2): a header per note, body excluded. description = the note's first sentence
407
- * (legacy flat notes have no frontmatter; this is the council #10 P1 fallback). */
408
- listStructuredNotes(scope: string): MemoryNoteHeader[];
409
- /** design/84 Seam B: read the periodic-consolidation cursor (opaque note-id high-water mark). */
410
- getConsolidationCursor(scope: string): string | undefined;
411
- /** design/84 Seam B: persist the periodic-consolidation cursor. */
412
- setConsolidationCursor(scope: string, cursor: string): void;
413
- getByIds(scope: string, ids: string[]): MemoryNoteRecord[];
414
- }
415
- /**
416
- * design/81 Slice 2b — a ZERO-MODEL lexical term expander closing the only real lexical recall weakness the
417
- * defect-hunt raised (the `recall`-tool `search` misses paraphrases like "auth token" vs "credentials/bearer").
418
- * Pure TS, NO embedder/native/model dep — same posture as the Jaccard stand-in. For a lower-cased query
419
- * term it returns that term PLUS:
420
- * - its members of a small bidirectional **synonym set** (auth↔credentials↔bearer, token↔key↔secret, …),
421
- * looked up for BOTH the original term AND its plural stem (so an inflected query like "tokens" — whose
422
- * singular "token" is the synonym-group member — still expands to {bearer, apikey, secret, key}), and
423
- * - a light **plural** stem (`-ies→-y`, `-es`, `-s`, with a ≥3-char guard) so "tokens" reaches "token".
424
- * (The `-ing`/`-ed` rules were removed — they over-truncated and produced wrong stems.)
425
- * Always includes the original term, so a non-expandable term degrades to the existing substring match
426
- * (byte-identical to the prior behavior when no synonym/stem applies). The caller (`lexicalSearchMatch`)
427
- * treats the returned variants as an OR within one query term (still AND across terms).
428
- */
429
- export declare function expandLexicalTerms(term: string): string[];
430
- /**
431
- * Shared SYNONYM/STEM-aware lexical match (design/81 Slice 2b) — the ONE matcher used by BOTH
432
- * {@link InMemoryMemoryStore.search} and {@link import("../stores/file/memory-store.js").FileMemoryStore.search},
433
- * so the `recall` tool returns IDENTICAL results across backends (the "byte-identical to InMemory" contract).
434
- * It is a recall-QUALITY behavior, correct to apply everywhere. (Pg's `search` is a separate SQL path —
435
- * a known follow-on, unchanged in this pass.)
436
- *
437
- * Matching rule: tokenize `text` on word boundaries, then for each whitespace-separated `query` term the
438
- * text must match AT LEAST ONE of that term's {@link expandLexicalTerms} variants (OR within a term), and
439
- * EVERY query term must match (AND across terms). The ORIGINAL query term keeps its pre-Slice-2b SUBSTRING
440
- * semantics (back-compat, RL-1654-store-family); the EXPANDED synonym/stem variants are matched on WORD BOUNDARIES (set membership
441
- * over the text's token set) so a short injected synonym like "key"/"db" cannot substring-match an unrelated
442
- * word ("keyboard"/"double"). An empty/whitespace-only query never matches.
443
- */
444
- export declare function lexicalSearchMatch(query: string, text: string): boolean;
445
18
  /** First sentence (or ~120-char head) of a note — the manifest description fallback for untyped notes. */
446
19
  export declare function firstSentence(text: string): string;
447
- /**
448
- * Parse a note's `"YYYY-MM-DD HH:MM"` (UTC) stamp into the {@link MemoryNoteHeader} timestamp PAIR —
449
- * the ONE mint point for `mtimeMs`/`timestampMissing`, shared by the in-memory and file stores.
450
- *
451
- * **Unknown is not 1970.** This used to return a bare `0` for anything unparseable, and every consumer
452
- * then read that `0` as a real epoch timestamp. A note whose stamp was absent, blank, or written in a
453
- * foreign format (a full ISO-8601 `2026-08-04T12:30:00Z` from a third-party producer survives JSON
454
- * replay intact, but the `" " → "T"` rewrite below turns it into an unparseable `…T12:30:00Z:00Z`)
455
- * therefore became the OLDEST note in its scope forever: it lost every `[[name]]` collision to every
456
- * stamped note, and the recall renderer told the model it was "written 678 months ago — verify it's
457
- * still current". Both are silent recall losses caused by the sentinel, not by the note.
458
- *
459
- * The unknown case is now an EXPLICIT axis (same shape as the brain layer's `usageMissing`): the numeric
460
- * slot stays a `0` shell and `timestampMissing: true` states that the shell is not a measurement. The two
461
- * fields are minted TOGETHER here and callers spread the result, so it is not constructible to publish
462
- * the shell without its flag. Consumers branch on the flag and never on the value — `mtimeMs === 0` is a
463
- * legal timestamp (a note genuinely stamped `1970-01-01 00:00` parses fine and is NOT flagged).
464
- *
465
- * **No persisted format ripple.** What the stores durably hold is the `ts` STRING, never this parsed
466
- * number, so there is no stored `0` whose meaning has to be re-decided: unknown-ness is re-derived on
467
- * every read from whether the string parses. The one genuinely ambiguous stored value is the literal
468
- * string `"1970-01-01 00:00"`. It is treated as a real time, and that is the honest call rather than a
469
- * convenient one — neither store has ever WRITTEN that string (both stamp `new Date()` at append/update),
470
- * so it can only come from a foreign producer, and a foreign producer that meant "unknown" has always
471
- * had the unambiguous spelling available: omit `ts`, or leave it blank.
472
- *
473
- * Takes `unknown` because the stamp arrives from a PERSISTED WIRE record (the file store's `append`
474
- * event, whose forward-compat promise covers logs this build did not write). A line carrying no `ts` at
475
- * all reached the old signature as `undefined` and threw a `TypeError` out of the manifest build — the
476
- * whole scope's recall died on one malformed line.
477
- */
478
- export declare function parseNoteTimestamp(ts: unknown): {
479
- mtimeMs: number;
480
- timestampMissing?: true;
481
- };
482
20
  /** The canonical, normalized shape of {@link import("./types.js").TaskSpec.memory} — the ONE form every
483
21
  * consumer reads (prepare-task, recall, consolidation, the remember tool), so the union never narrows
484
22
  * downstream. `scopes` is the ordered read-side layering (first = stable prefix, last = volatile tail =