counterparts 0.1.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.
- package/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every constant `remember/` has, in one visible place (the shape `physics/` set).
|
|
3
|
+
*
|
|
4
|
+
* CAL = calibration-required (scar §2.8): it must ship with a recorded measurement
|
|
5
|
+
* against a real corpus, or ship disabled. Where a CAL number here is shipped
|
|
6
|
+
* enabled, the reason is written next to it — the honest test is "what does being
|
|
7
|
+
* wrong cost?", and for the two `updates:` thresholds the cost of being wrong is a
|
|
8
|
+
* REFUSAL, which the contract already prices at zero (§5 G10: "a miss costs nothing
|
|
9
|
+
* durable: the memory still lands").
|
|
10
|
+
*/
|
|
11
|
+
export const TUNABLES = {
|
|
12
|
+
/** Below this, a claim is not worth a run: scraps ride to the next boundary
|
|
13
|
+
* (behavioral-spec §2 G8, v1's measured 200 bytes). */
|
|
14
|
+
MIN_CLAIM_BYTES: 200,
|
|
15
|
+
/** How long a claim file must sit untouched before a later claim treats it as a
|
|
16
|
+
* crashed run's leftovers and merges it back in. Any detached worker's watchdog
|
|
17
|
+
* must fire well INSIDE this window — see `validateWatchdog()` (scars E4, E5). */
|
|
18
|
+
STALE_CLAIM_MS: 10 * 60_000,
|
|
19
|
+
/** Hashes retained in the consumed ledger (dedup layer 2's tail). Bounded on
|
|
20
|
+
* purpose: it is telemetry-grade bookkeeping, not canonical memory. */
|
|
21
|
+
CONSUMED_LEDGER_MAX: 2000,
|
|
22
|
+
/** CAL. How long a session must go SILENT — no boundary of any kind — before
|
|
23
|
+
* the fallback may call it crashed and read its transcript. It is the third
|
|
24
|
+
* clause of the crash definition (uncovered spans ∧ no `session-end`
|
|
25
|
+
* boundary ∧ this window), and it has nothing to do with `STALE_CLAIM_MS`:
|
|
26
|
+
* that one ages a CLAIM FILE against a worker's watchdog, this one ages a
|
|
27
|
+
* SESSION against its author. `validateWatchdog()` is untouched by it.
|
|
28
|
+
*
|
|
29
|
+
* TOO SHORT re-creates the bug this gate exists to kill: a live session that
|
|
30
|
+
* pauses is read as crashed, and the sweep paraphrases turns whose author is
|
|
31
|
+
* still holding the pen (measured 2026-09-04: 13 chunks, 61 sweep-minted
|
|
32
|
+
* memories beside 34 authored notes in one evening, twins that TAU_DUP 0.95
|
|
33
|
+
* can never merge). TOO LONG costs only DELAY: a genuinely crashed session's
|
|
34
|
+
* spans wait in the buffer for the next worker run past the window — nothing
|
|
35
|
+
* is lost, because nothing is dropped.
|
|
36
|
+
*
|
|
37
|
+
* CALIBRATED, not guessed (scar §2.8). This started at 60 minutes on the
|
|
38
|
+
* cost asymmetry alone, and the live store falsified that on the owner's
|
|
39
|
+
* actual pattern: conversation session `c781252f` went silent from 22:21 to
|
|
40
|
+
* 02:28 UTC — **four hours and seven minutes** — with the author still
|
|
41
|
+
* holding the pen, then resumed and authored 20 more notes. A 60-minute
|
|
42
|
+
* window would have swept that gap as a crash and produced twins for exactly
|
|
43
|
+
* the idle-then-resume shape this owner has. **12 hours** clears that
|
|
44
|
+
* measured gap with room, and still recovers a real crash the same day the
|
|
45
|
+
* next worker runs.
|
|
46
|
+
*
|
|
47
|
+
* The FALSIFIER stays the same and stays owed: sessions swept under this rule
|
|
48
|
+
* that LATER received an authored deposit. A nonzero count is the window
|
|
49
|
+
* being too short again. */
|
|
50
|
+
CRASH_STALE_MS: 12 * 60 * 60_000,
|
|
51
|
+
/** Target bytes per fallback chunk. Chunking is per-chunk failure isolation
|
|
52
|
+
* (scar E1), not a token budget — the budget belongs to whoever injects the
|
|
53
|
+
* interpret function. */
|
|
54
|
+
CHUNK_BYTES: 12_000,
|
|
55
|
+
/** How many DISTINCT LIVED DAYS a span may fail on before the sweep stops
|
|
56
|
+
* paying for it: at this count it is QUARANTINED (written to
|
|
57
|
+
* `quarantine.jsonl`, never restored) instead of retried. The P0 fix traded
|
|
58
|
+
* silent loss for indefinite retry — one model call per boundary, forever,
|
|
59
|
+
* on the owner's account (replay-review 2026-08-26, "Poison-pill retry is
|
|
60
|
+
* unbounded"). This is that bound. Days, not attempts (PR-8 review): three
|
|
61
|
+
* Stop hooks inside one API outage are ONE day's failure and quarantine
|
|
62
|
+
* nothing; a poison pill fails on every day it is tried and is set aside on
|
|
63
|
+
* the third. */
|
|
64
|
+
MAX_SPAN_FAILURES: 3,
|
|
65
|
+
/** CAL. Content-match score floor for `updates:` resolution. Shipped enabled
|
|
66
|
+
* because failure = refusal = the memory lands unlinked. */
|
|
67
|
+
UPDATES_FLOOR: 0.55,
|
|
68
|
+
/** CAL. Required margin between the best and second-best candidate. Inside this
|
|
69
|
+
* margin the author's hint is a tiebreak; below the floor it is powerless. */
|
|
70
|
+
UPDATES_MARGIN: 0.1,
|
|
71
|
+
/** Candidates scored per resolution. */
|
|
72
|
+
UPDATES_CANDIDATES: 8,
|
|
73
|
+
/**
|
|
74
|
+
* CAL. Byte cap for the SELF the fallback interpreter is woken with before it
|
|
75
|
+
* reads a transcript (owner ruling 2026-09-17: "any background writer of
|
|
76
|
+
* memories gets as much of the self as is reasonable before it reads a
|
|
77
|
+
* transcript"). It is the compose budget handed to `self/`'s own composer, so
|
|
78
|
+
* the declared trim order does the cutting — a cap is never iteration luck.
|
|
79
|
+
*
|
|
80
|
+
* `null` means THE ORDINARY WAKE BUDGET: the injection ceiling the host
|
|
81
|
+
* reported for a live session's wake, so the fallback composes against the
|
|
82
|
+
* number a live session composes against and there is one to calibrate rather
|
|
83
|
+
* than two. (Not the same BUNDLE: the sweep's carries no prospective lane and
|
|
84
|
+
* nothing protected or confidential, and a live wake subtracts its preface
|
|
85
|
+
* reserve from this figure first.) A host that reported no ceiling composed no wake for its
|
|
86
|
+
* live sessions either, and gets none here — no invented default (scar §2.18).
|
|
87
|
+
*
|
|
88
|
+
* Set a number only to hold the sweep's copy BELOW the live one, and record
|
|
89
|
+
* the measurement that justified it: the cost of being wrong is prompt bytes
|
|
90
|
+
* per chunk on the owner's account, and the cost of being too small is a
|
|
91
|
+
* fallback that writes as a stranger again, which is the whole point.
|
|
92
|
+
*/
|
|
93
|
+
SWEEP_WAKE_BYTES: null as number | null,
|
|
94
|
+
} as const;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Scar E4/E5, mechanized: a detached worker's watchdog must fire before its claim
|
|
98
|
+
* looks stale, or two runs can hold the same spans. The contract asks for the
|
|
99
|
+
* timeout to be "validated against the lock-staleness window" (§5 G1) — this is
|
|
100
|
+
* that validation, exported so the adapter that owns detachment can call it.
|
|
101
|
+
*/
|
|
102
|
+
export function validateWatchdog(
|
|
103
|
+
timeoutMs: number,
|
|
104
|
+
staleClaimMs: number = TUNABLES.STALE_CLAIM_MS,
|
|
105
|
+
): { ok: boolean; reason: "OK" | "TIMEOUT_NOT_FINITE" | "TIMEOUT_EXCEEDS_STALENESS" } {
|
|
106
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
107
|
+
return { ok: false, reason: "TIMEOUT_NOT_FINITE" };
|
|
108
|
+
}
|
|
109
|
+
if (timeoutMs >= staleClaimMs) return { ok: false, reason: "TIMEOUT_EXCEEDS_STALENESS" };
|
|
110
|
+
return { ok: true, reason: "OK" };
|
|
111
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `updates:` resolution — the one rule that decides whether an author's declared
|
|
3
|
+
* address is honored (contract §5 G10, scar §2.5).
|
|
4
|
+
*
|
|
5
|
+
* **No model-supplied identifier is trusted as an address without a fallback.** The
|
|
6
|
+
* author declares `updates: <id>`; the engine validates that the id RESOLVES, and on
|
|
7
|
+
* a miss falls back to content matching, where:
|
|
8
|
+
*
|
|
9
|
+
* - a score floor AND a margin are both required;
|
|
10
|
+
* - ambiguity REFUSES (v1's confabulation incident: 7 of 8 rejected ids existed in
|
|
11
|
+
* the schema, in a different section, in the identical `- [id]` format — a
|
|
12
|
+
* plausible-looking id is exactly the input this rule exists to survive);
|
|
13
|
+
* - the author's hint is a tiebreak INSIDE the margin and can never defeat a
|
|
14
|
+
* refusal — it cannot rescue a below-floor set;
|
|
15
|
+
* - score, margin and method are logged as provenance.
|
|
16
|
+
*
|
|
17
|
+
* A refusal costs nothing durable: the memory still lands, unlinked. That is also
|
|
18
|
+
* why the two thresholds ship enabled while still marked CAL (tunables.ts) — being
|
|
19
|
+
* wrong here produces a missing link, not a wrong write.
|
|
20
|
+
*/
|
|
21
|
+
import { tokenize, cosine } from "../store/cache.js";
|
|
22
|
+
import { TUNABLES } from "./tunables.js";
|
|
23
|
+
|
|
24
|
+
export interface Candidate {
|
|
25
|
+
id: string;
|
|
26
|
+
/** The text content matching scores against. */
|
|
27
|
+
text: string;
|
|
28
|
+
/** Optional aliases/handles; matched as a whole string, never as a substring. */
|
|
29
|
+
aliases?: readonly string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** INJECTED (INTERFACE-GAPS.md #4): who the candidates are is `store/`+`schemas/`
|
|
33
|
+
* business, and this module refuses to know about either. */
|
|
34
|
+
export type CandidateSource = (
|
|
35
|
+
query: { scope: string; content: string; limit: number },
|
|
36
|
+
) => readonly Candidate[] | Promise<readonly Candidate[]>;
|
|
37
|
+
|
|
38
|
+
/** INJECTED: does this id resolve to a live memory? Returns the resolved (possibly
|
|
39
|
+
* forwarded) id, or null. `store.resolve()` is the obvious implementation. */
|
|
40
|
+
export type IdResolver = (id: string) => string | null | Promise<string | null>;
|
|
41
|
+
|
|
42
|
+
export type UpdatesMethod = "declared" | "content" | "content+hint" | "none";
|
|
43
|
+
|
|
44
|
+
export type UpdatesReason =
|
|
45
|
+
| "NO_DECLARATION"
|
|
46
|
+
| "DECLARED_RESOLVED"
|
|
47
|
+
| "NO_CANDIDATES"
|
|
48
|
+
| "BELOW_FLOOR"
|
|
49
|
+
| "AMBIGUOUS"
|
|
50
|
+
| "MATCHED";
|
|
51
|
+
|
|
52
|
+
export interface UpdatesResolution {
|
|
53
|
+
/** The memory this proposal revises, or null. Null is not a failure (§5 G10). */
|
|
54
|
+
resolved: string | null;
|
|
55
|
+
method: UpdatesMethod;
|
|
56
|
+
reason: UpdatesReason;
|
|
57
|
+
/** Best candidate's score, when content matching ran. */
|
|
58
|
+
score: number | null;
|
|
59
|
+
/** Best minus runner-up, when content matching ran. */
|
|
60
|
+
margin: number | null;
|
|
61
|
+
declared: string | null;
|
|
62
|
+
/** True only when the hint broke a tie INSIDE the margin. */
|
|
63
|
+
hintUsed: boolean;
|
|
64
|
+
floor: number;
|
|
65
|
+
marginBar: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface UpdatesContext {
|
|
69
|
+
scope: string;
|
|
70
|
+
content: string;
|
|
71
|
+
resolveId: IdResolver;
|
|
72
|
+
candidates: CandidateSource;
|
|
73
|
+
floor?: number;
|
|
74
|
+
margin?: number;
|
|
75
|
+
limit?: number;
|
|
76
|
+
onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function resolveUpdates(
|
|
80
|
+
declared: string | null,
|
|
81
|
+
ctx: UpdatesContext,
|
|
82
|
+
): Promise<UpdatesResolution> {
|
|
83
|
+
const floor = ctx.floor ?? TUNABLES.UPDATES_FLOOR;
|
|
84
|
+
const marginBar = ctx.margin ?? TUNABLES.UPDATES_MARGIN;
|
|
85
|
+
const base = {
|
|
86
|
+
declared,
|
|
87
|
+
floor,
|
|
88
|
+
marginBar,
|
|
89
|
+
hintUsed: false,
|
|
90
|
+
score: null as number | null,
|
|
91
|
+
margin: null as number | null,
|
|
92
|
+
};
|
|
93
|
+
const done = (r: UpdatesResolution): UpdatesResolution => {
|
|
94
|
+
ctx.onEvent?.("remember.updates.resolved", {
|
|
95
|
+
method: r.method,
|
|
96
|
+
reason: r.reason,
|
|
97
|
+
resolved: r.resolved,
|
|
98
|
+
declared: r.declared,
|
|
99
|
+
score: r.score,
|
|
100
|
+
margin: r.margin,
|
|
101
|
+
hintUsed: r.hintUsed,
|
|
102
|
+
});
|
|
103
|
+
return r;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
if (declared === null || declared.trim().length === 0) {
|
|
107
|
+
return done({ ...base, resolved: null, method: "none", reason: "NO_DECLARATION" });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const hit = await ctx.resolveId(declared);
|
|
111
|
+
if (typeof hit === "string" && hit.length > 0) {
|
|
112
|
+
return done({ ...base, resolved: hit, method: "declared", reason: "DECLARED_RESOLVED" });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const limit = ctx.limit ?? TUNABLES.UPDATES_CANDIDATES;
|
|
116
|
+
const candidates = await ctx.candidates({ scope: ctx.scope, content: ctx.content, limit });
|
|
117
|
+
if (candidates.length === 0) {
|
|
118
|
+
return done({ ...base, resolved: null, method: "content", reason: "NO_CANDIDATES" });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const scored = candidates
|
|
122
|
+
.map((c) => ({ candidate: c, score: similarity(ctx.content, c.text) }))
|
|
123
|
+
.sort((a, b) => b.score - a.score || a.candidate.id.localeCompare(b.candidate.id));
|
|
124
|
+
|
|
125
|
+
const best = scored[0];
|
|
126
|
+
if (best === undefined) {
|
|
127
|
+
return done({ ...base, resolved: null, method: "content", reason: "NO_CANDIDATES" });
|
|
128
|
+
}
|
|
129
|
+
const runnerUp = scored[1]?.score ?? 0;
|
|
130
|
+
const margin = best.score - runnerUp;
|
|
131
|
+
const withScores = { ...base, score: round(best.score), margin: round(margin) };
|
|
132
|
+
|
|
133
|
+
if (best.score < floor) {
|
|
134
|
+
// The hint is powerless here, by design. A declared id that points at nothing
|
|
135
|
+
// must not be able to attach a memory to a weak match.
|
|
136
|
+
return done({ ...withScores, resolved: null, method: "content", reason: "BELOW_FLOOR" });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (margin < marginBar) {
|
|
140
|
+
// Inside the margin: the hint may break the tie, but only among candidates that
|
|
141
|
+
// ALREADY clear the floor.
|
|
142
|
+
const tied = scored.filter((s) => s.score >= floor && best.score - s.score < marginBar);
|
|
143
|
+
const hinted = tied.filter((s) => mentions(s.candidate, declared));
|
|
144
|
+
const only = hinted.length === 1 ? hinted[0] : undefined;
|
|
145
|
+
if (only !== undefined) {
|
|
146
|
+
return done({
|
|
147
|
+
...withScores,
|
|
148
|
+
resolved: only.candidate.id,
|
|
149
|
+
method: "content+hint",
|
|
150
|
+
reason: "MATCHED",
|
|
151
|
+
hintUsed: true,
|
|
152
|
+
score: round(only.score),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return done({ ...withScores, resolved: null, method: "content", reason: "AMBIGUOUS" });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return done({ ...withScores, resolved: best.candidate.id, method: "content", reason: "MATCHED" });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The hint's reach: the candidate IS the declared id, or names it in its text or
|
|
162
|
+
* aliases. Whole-value matching only — one definition, no substrings (encode §3). */
|
|
163
|
+
function mentions(candidate: Candidate, declared: string): boolean {
|
|
164
|
+
if (candidate.id === declared) return true;
|
|
165
|
+
if ((candidate.aliases ?? []).some((a) => a === declared)) return true;
|
|
166
|
+
return new RegExp(`(^|[^A-Za-z0-9_])${escapeRe(declared)}([^A-Za-z0-9_]|$)`).test(candidate.text);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Content similarity: cosine over token frequency vectors, using the store's one
|
|
171
|
+
* tokenizer so "the same cue scores the same everywhere". Deterministic, no
|
|
172
|
+
* embedder required — the semantic channel is `encode/`'s business, and this rule
|
|
173
|
+
* must work when no embedder exists at all.
|
|
174
|
+
*/
|
|
175
|
+
export function similarity(a: string, b: string): number {
|
|
176
|
+
const va = counts(a);
|
|
177
|
+
const vb = counts(b);
|
|
178
|
+
const vocab = [...new Set([...va.keys(), ...vb.keys()])];
|
|
179
|
+
if (vocab.length === 0) return 0;
|
|
180
|
+
return cosine(
|
|
181
|
+
vocab.map((t) => va.get(t) ?? 0),
|
|
182
|
+
vocab.map((t) => vb.get(t) ?? 0),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function counts(text: string): Map<string, number> {
|
|
187
|
+
const m = new Map<string, number>();
|
|
188
|
+
for (const t of tokenize(text)) m.set(t, (m.get(t) ?? 0) + 1);
|
|
189
|
+
return m;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function round(n: number): number {
|
|
193
|
+
return Math.round(n * 1000) / 1000;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function escapeRe(s: string): string {
|
|
197
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
198
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retrieval composition root — SEAMS items C, D and L close here.
|
|
3
|
+
*
|
|
4
|
+
* `recall/` owns the gate and imports none of its neighbours; `schemas/` owns the
|
|
5
|
+
* alias index; `prospective/` owns temporal arrivals; `associate/` owns the edge
|
|
6
|
+
* graph. Each of them exports what recall needs and none of them may hand it over
|
|
7
|
+
* directly. This file is the one place they meet, so a caller cannot forget one of
|
|
8
|
+
* them and silently lose the safety half that rides along with it — which is
|
|
9
|
+
* precisely what `recall/INTERFACE-GAPS.md` §2 warned about:
|
|
10
|
+
*
|
|
11
|
+
* > a caller that forgets the map silently loses the safety half — which is
|
|
12
|
+
* > exactly the scar §2.6 shape, so this gap is the one to close first.
|
|
13
|
+
*
|
|
14
|
+
* The three wirings, and the constraint each carries:
|
|
15
|
+
*
|
|
16
|
+
* C. **Aliases** — `schemas.aliasMap()` becomes `Turn.aliases`. A handle that
|
|
17
|
+
* resolves to two live entities fires at `AMBIGUOUS_WEIGHT` and sets
|
|
18
|
+
* `trains: false`, which `Recall.resolveUse` enforces as a refusal (§9 G5).
|
|
19
|
+
* D. **Temporal cues** — `prospective.arrivals()` becomes
|
|
20
|
+
* `Turn.temporal`, folded into `cueScore` alongside the token postings and
|
|
21
|
+
* COUNTED AS CUE by `cueFraction`. It is emphatically NOT recall's `arrival`
|
|
22
|
+
* (a recency multiplier): wiring it there would turn a modulator into an
|
|
23
|
+
* admission channel and break hard gate (a) for every dated memory.
|
|
24
|
+
* L. **Spreading activation** — `associate.spreadFrom()` becomes `Turn.spread`.
|
|
25
|
+
* The conservative default (SEAMS L, = option (a) of `associate/`'s gap §1):
|
|
26
|
+
* hops MODULATE candidates the conversation already reached and never mint
|
|
27
|
+
* one, which is the only reading that keeps recall's hard gate (a)
|
|
28
|
+
* structural. Excluded from `cueFraction`'s numerator, so hop weight can
|
|
29
|
+
* only push a candidate away from the loud tier.
|
|
30
|
+
*/
|
|
31
|
+
import type { RecallResult, Turn } from "./recall/index.js";
|
|
32
|
+
import type { Recall } from "./recall/index.js";
|
|
33
|
+
|
|
34
|
+
/** Structural, not nominal: this file imports no neighbour's class. */
|
|
35
|
+
export interface AliasSource {
|
|
36
|
+
aliasMap(): ReadonlyMap<string, readonly string[]>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `prospective.arrivals()`'s shape, structurally: `at` is a CALENDAR date and is
|
|
40
|
+
* required, `day` is the lived day, and the list comes back under `.arrivals`. */
|
|
41
|
+
export interface TemporalSource {
|
|
42
|
+
arrivals(input: { at: string; day?: number; sessionId?: string }): {
|
|
43
|
+
arrivals: readonly { memoryId: string; cueWeight: number }[];
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Structurally `Associate.spreadFrom`. */
|
|
48
|
+
export interface SpreadSource {
|
|
49
|
+
spreadFrom(
|
|
50
|
+
seeds: readonly { id: string; activation: number }[],
|
|
51
|
+
day?: number,
|
|
52
|
+
): { contributions: readonly { id: string; activation: number }[] };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface RetrievalSources {
|
|
56
|
+
schemas?: AliasSource;
|
|
57
|
+
prospective?: TemporalSource;
|
|
58
|
+
associate?: SpreadSource;
|
|
59
|
+
/** The CALENDAR date the temporal source asks about — an argument, never a
|
|
60
|
+
* clock read, so "was this arriving on July 5th?" is the same code path.
|
|
61
|
+
* Without it there is no temporal wiring: a lived day is not a date. */
|
|
62
|
+
at?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Compose one turn. Every source is optional and its absence is a MISSING
|
|
67
|
+
* CHANNEL, never a silently permissive one: no alias map means no handle is
|
|
68
|
+
* ambiguous (the conservative direction is to train, which is why the map's
|
|
69
|
+
* source had to stop being borrowed), no temporal source means no dated memory
|
|
70
|
+
* is cued, and no edge source means no hop contributes.
|
|
71
|
+
*/
|
|
72
|
+
export function composeTurn(turn: Turn, sources: RetrievalSources): Turn {
|
|
73
|
+
const out: Turn = { ...turn };
|
|
74
|
+
if (sources.schemas !== undefined && turn.aliases === undefined) {
|
|
75
|
+
out.aliases = sources.schemas.aliasMap();
|
|
76
|
+
}
|
|
77
|
+
if (sources.prospective !== undefined && sources.at !== undefined && turn.temporal === undefined) {
|
|
78
|
+
const result = sources.prospective.arrivals({
|
|
79
|
+
at: sources.at,
|
|
80
|
+
...(turn.day === undefined ? {} : { day: turn.day }),
|
|
81
|
+
// The once-per-session brake lives in `prospective/` and needs this.
|
|
82
|
+
sessionId: turn.sessionId,
|
|
83
|
+
});
|
|
84
|
+
out.temporal = result.arrivals.map((a) => ({ id: a.memoryId, weight: a.cueWeight }));
|
|
85
|
+
}
|
|
86
|
+
if (sources.associate !== undefined && turn.spread === undefined) {
|
|
87
|
+
const source = sources.associate;
|
|
88
|
+
out.spread = (seeds, day) => source.spreadFrom(seeds, day);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The one-line call site the gap files name, with the sources bound. */
|
|
94
|
+
export function recallTurn(recall: Recall, turn: Turn, sources: RetrievalSources): RecallResult {
|
|
95
|
+
return recall.recall(composeTurn(turn, sources));
|
|
96
|
+
}
|