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.
Files changed (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The content floor — the named earned mechanism (§3, earned-mechanism #3).
3
+ *
4
+ * v1's model bake-off minted a literal `"placeholder"` trace that passed every
5
+ * other gate. A degenerate-but-well-formed proposal is not a memory (scar §2.14),
6
+ * and the four checks above this one all pass it happily, because none of them
7
+ * asks whether there is anything there.
8
+ *
9
+ * The floor evaluates the FINAL content — after redaction and after hedging — so
10
+ * that a proposal which is nothing but a redacted credential fails here as well
11
+ * as at the secrets gate, and both reasons are reported. Redaction placeholders
12
+ * are stripped before measuring: `[REDACTED:google-api-key]` is 26 characters of
13
+ * nothing.
14
+ *
15
+ * The stub list is matched EXACTLY after normalization, never as a substring, so
16
+ * "keeps a TODO list in vim" survives while a bare "TODO" does not.
17
+ *
18
+ * §5 G12: the exact minimums and the stub vocabulary are preferences (TUNABLES).
19
+ * That the floor EXISTS is mechanized.
20
+ */
21
+
22
+ import { stripRedactions } from "./secrets.js";
23
+ import { TUNABLES } from "./tunables.js";
24
+ import { normalizeForFloor } from "./words.js";
25
+ import type { RefusalReason } from "./types.js";
26
+
27
+ export type FloorReason =
28
+ | "above-floor"
29
+ | "content-empty"
30
+ | "content-stub"
31
+ | "content-too-short"
32
+ | "content-too-few-words";
33
+
34
+ export interface FloorResult {
35
+ ok: boolean;
36
+ /** The first blocking reason, or "above-floor". */
37
+ reason: FloorReason;
38
+ /** Every blocking reason — the same shape physics' verdicts use. */
39
+ blockedBy: Exclude<FloorReason, "above-floor">[];
40
+ chars: number;
41
+ words: number;
42
+ minChars: number;
43
+ minWords: number;
44
+ }
45
+
46
+ const STUBS = new Set(TUNABLES.STUB_TOKENS.map((s) => normalizeForFloor(s)));
47
+
48
+ export function contentFloor(content: string): FloorResult {
49
+ const real = stripRedactions(content).trim();
50
+ const normalized = normalizeForFloor(real);
51
+ const chars = normalized.length;
52
+ const words = chars === 0 ? 0 : normalized.split(" ").length;
53
+ const blockedBy: Exclude<FloorReason, "above-floor">[] = [];
54
+
55
+ if (chars === 0) blockedBy.push("content-empty");
56
+ else {
57
+ if (STUBS.has(normalized)) blockedBy.push("content-stub");
58
+ if (chars < TUNABLES.FLOOR_MIN_CHARS) blockedBy.push("content-too-short");
59
+ if (words < TUNABLES.FLOOR_MIN_WORDS) blockedBy.push("content-too-few-words");
60
+ }
61
+
62
+ return {
63
+ ok: blockedBy.length === 0,
64
+ reason: blockedBy[0] ?? "above-floor",
65
+ blockedBy,
66
+ chars,
67
+ words,
68
+ minChars: TUNABLES.FLOOR_MIN_CHARS,
69
+ minWords: TUNABLES.FLOOR_MIN_WORDS,
70
+ };
71
+ }
72
+
73
+ /** The floor's reasons are refusal reasons verbatim; this keeps that checkable. */
74
+ export function floorRefusals(f: FloorResult): RefusalReason[] {
75
+ return f.blockedBy;
76
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * `encode/` — attention plus amygdala tagging. The bouncer.
3
+ *
4
+ * What gets in: the gate battery every proposal passes, the salience tags it
5
+ * carries, and the computed novelty that makes prediction error a number.
6
+ * Implements CONTRACT.md; ambiguities and the places the contract was silent are
7
+ * recorded in NOTES.md.
8
+ *
9
+ * THREE PROPERTIES HOLD ACROSS THE WHOLE MODULE, and each is enforced rather than
10
+ * asserted:
11
+ *
12
+ * 1. **The secrets gate is not ablatable.** No parameter anywhere disables it,
13
+ * `SecretsGateStatus` cannot spell `stood-down`, `assertNoBypassOption`
14
+ * refuses an invented option key at runtime, and EVERY export below that can
15
+ * return author-supplied text leaves through `redactSecrets` — whatever order
16
+ * a caller invoked things in.
17
+ * 2. **Encode writes nothing.** It computes verdicts and returns `DurableEffect`
18
+ * intents for `remember/` to apply. It imports `hashText` from the store's
19
+ * prose module and nothing at all from the store's write surface — so "a
20
+ * fully-gated proposal moves zero durable state" is structural, and the test
21
+ * asserts it both behaviorally and by source-scan.
22
+ * 3. **No model calls, no fetching.** Vectors are inputs. A missing vector
23
+ * degrades a channel loudly; it never triggers a lookup.
24
+ *
25
+ * THE PUBLIC SURFACE IS ENUMERATED, NOT SPILLED. Every re-export below is named
26
+ * one at a time, because `test/encode.test.ts` asserts a total classification of
27
+ * this surface: every export is either a text path that must redact, a verdict
28
+ * function, a shared definition, or a constant. A new export with no
29
+ * classification fails the suite rather than slipping in ungated (scar §7: one
30
+ * un-gated entrance defeats the gate).
31
+ *
32
+ * `normalizeForFloor` and `stripRedactions` are deliberately NOT exported: both
33
+ * return author text with the redaction marks taken back off, which is exactly
34
+ * the shape a leak has. They stay internal to the floor.
35
+ */
36
+
37
+ // ── the vocabulary ──────────────────────────────────────────────────────────
38
+ export { GATES, CHANNELS, SELF_SUBJECT, EncodeError } from "./types.js";
39
+ export type {
40
+ AcceptedProposal,
41
+ AliasGateRecord,
42
+ ChannelName,
43
+ ChannelRecord,
44
+ ChannelState,
45
+ ClaimedDimensions,
46
+ DurableEffect,
47
+ DurableFeeling,
48
+ EmotionGateRecord,
49
+ EncodeEvent,
50
+ Feeling,
51
+ FloorGateRecord,
52
+ GateName,
53
+ GateRecord,
54
+ GateRecordBase,
55
+ GateStatus,
56
+ GatedProposal,
57
+ PrecisionGateRecord,
58
+ PredictionCheck,
59
+ Proposal,
60
+ RefusalReason,
61
+ RefusedProposal,
62
+ SecretFinding,
63
+ SecretsGateRecord,
64
+ SecretsGateStatus,
65
+ } from "./types.js";
66
+
67
+ export { TUNABLES } from "./tunables.js";
68
+
69
+ // ── the ONE whole-word definition (§8 G3 — shared with schema birth) ────────
70
+ export { escapeRegExp, wholeWordRegex, occursAsWholeWord, countWholeWord } from "./words.js";
71
+
72
+ // ── the non-ablatable gate ─────────────────────────────────────────────────
73
+ export { REDACTION_MARK, SECRET_FAMILIES, scanSecrets, redactSecrets, containsSecret } from "./secrets.js";
74
+ export type { SecretPattern, SecretsScan } from "./secrets.js";
75
+
76
+ // ── the other four checks ──────────────────────────────────────────────────
77
+ export { hedgePrecision } from "./precision.js";
78
+ export type { PrecisionResult } from "./precision.js";
79
+ export { gateAliases } from "./aliases.js";
80
+ export type { AliasDropReason, AliasGateResult } from "./aliases.js";
81
+ export { gateEmotion, emotionClassifierRecord } from "./emotion.js";
82
+ export type { EmotionGateResult, EmotionVerdict } from "./emotion.js";
83
+ export { contentFloor, floorRefusals } from "./floor.js";
84
+ export type { FloorReason, FloorResult } from "./floor.js";
85
+
86
+ // ── tagging + prediction error ─────────────────────────────────────────────
87
+ export { computeNovelty, tagSalience } from "./salience.js";
88
+ export type { NoveltyReason, NoveltyResult, SalienceTag } from "./salience.js";
89
+
90
+ // ── what the author may see ────────────────────────────────────────────────
91
+ export { preselectSchemas, renderSchemaContext } from "./preselect.js";
92
+ export type { Channel, Preselection, PreselectInput, SchemaSlice, SelectedSchema } from "./preselect.js";
93
+
94
+ // ── the battery and the one chokepoint ─────────────────────────────────────
95
+ export { assertNoBypassOption, gateProposal } from "./battery.js";
96
+ export type { BatteryOptions, BatteryOutcome, GateInput } from "./battery.js";
97
+ export { encodeChunk, mentionsSchema } from "./chunk.js";
98
+ export type { ChunkInput, EncodeOptions, EncodeResult } from "./chunk.js";
99
+
100
+ export type { Kind, Salience } from "../types.js";
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The precision gate — a confabulation brake, not a truth test.
3
+ *
4
+ * Dates, years, and quoted strings that do not occur in the source span are
5
+ * AUTO-HEDGED: softened, never dropped (§3). A specific date the author did not
6
+ * get from anywhere becomes "mid-July"; a quotation the span never contained
7
+ * keeps its words and loses its quote marks, because the words may well be a
8
+ * fair paraphrase and only the *claim of exactness* was invented.
9
+ *
10
+ * Everything runs in ONE pass over the original content, and a hedge's own output
11
+ * is never re-examined: a second pass is how "mid-July 2026" becomes
12
+ * "mid-July around 2026".
13
+ *
14
+ * Ops rule (§3): "a matching key that never persists is exempt from hedging — a
15
+ * name is not a claim." Hedging therefore applies to CONTENT only; handles and
16
+ * aliases are matched, not asserted, so they are exempt here. They are NOT exempt
17
+ * from the secrets gate.
18
+ *
19
+ * CONTRACT §5 G12: the hedge PHRASINGS are preferences (TUNABLES). That hedging
20
+ * happens at all is not.
21
+ */
22
+
23
+ import { redactSecrets } from "./secrets.js";
24
+ import { TUNABLES } from "./tunables.js";
25
+
26
+ const MONTHS = [
27
+ "January",
28
+ "February",
29
+ "March",
30
+ "April",
31
+ "May",
32
+ "June",
33
+ "July",
34
+ "August",
35
+ "September",
36
+ "October",
37
+ "November",
38
+ "December",
39
+ ] as const;
40
+
41
+ const MONTH_ALT = MONTHS.flatMap((m) => [m, m.slice(0, 3)]).join("|");
42
+
43
+ /**
44
+ * Alternation order is load-bearing: a quoted region is consumed WHOLE before
45
+ * anything inside it is considered, and a month+year is consumed before the bare
46
+ * year inside it can be hedged separately.
47
+ */
48
+ const SCAN = new RegExp(
49
+ [
50
+ `(?<dq>"[^"\\n]{1,300}")`,
51
+ `(?<cq>“[^”\\n]{1,300}”)`,
52
+ `(?<sq>(?<![\\p{L}\\p{N}])'[^'\\n]{1,300}'(?![\\p{L}\\p{N}]))`,
53
+ `(?<iso>\\b\\d{4}-\\d{2}-\\d{2}\\b)`,
54
+ `(?<md>\\b(?:${MONTH_ALT})\\.?\\s+\\d{1,2}(?:st|nd|rd|th)?(?:,\\s*\\d{4})?(?![\\p{L}\\p{N}]))`,
55
+ `(?<my>\\b(?:${MONTH_ALT})\\.?\\s+(?:19|20)\\d{2}\\b)`,
56
+ `(?<yr>\\b(?:19|20)\\d{2}\\b)`,
57
+ ].join("|"),
58
+ "gu",
59
+ );
60
+
61
+ export interface PrecisionResult {
62
+ text: string;
63
+ /** By kind and count. The hedged text itself is never logged (§5 G10). */
64
+ hedges: { kind: string; count: number }[];
65
+ fired: boolean;
66
+ }
67
+
68
+ function monthName(index: number): string {
69
+ return MONTHS[index] ?? "";
70
+ }
71
+
72
+ function bandFor(day: number): (m: string) => string {
73
+ if (day <= 10) return TUNABLES.HEDGE_EARLY;
74
+ if (day <= 20) return TUNABLES.HEDGE_MID;
75
+ return TUNABLES.HEDGE_LATE;
76
+ }
77
+
78
+ function hedgeIso(iso: string): string {
79
+ const parts = iso.split("-");
80
+ const year = parts[0] ?? "";
81
+ const month = Number(parts[1] ?? "0");
82
+ const day = Number(parts[2] ?? "0");
83
+ const name = monthName(month - 1);
84
+ if (name === "" || !Number.isFinite(day)) return TUNABLES.HEDGE_YEAR(year);
85
+ return `${bandFor(day)(name)} ${year}`;
86
+ }
87
+
88
+ function hedgeMonthDay(text: string): string {
89
+ const m = /^([A-Za-z]+)\.?\s+(\d{1,2})/.exec(text);
90
+ const rawMonth = m?.[1] ?? "";
91
+ const day = Number(m?.[2] ?? "0");
92
+ const full = MONTHS.find((x) => x.toLowerCase().startsWith(rawMonth.toLowerCase()));
93
+ if (full === undefined) return text;
94
+ const year = /,\s*(\d{4})/.exec(text)?.[1];
95
+ const hedged = bandFor(day)(full);
96
+ return year === undefined ? hedged : `${hedged} ${year}`;
97
+ }
98
+
99
+ /**
100
+ * The gate. `source` is the span the proposal was written from; anything present
101
+ * there VERBATIM is left exactly as the author wrote it.
102
+ */
103
+ export function hedgePrecision(content: string, source: string): PrecisionResult {
104
+ const counts = new Map<string, number>();
105
+ const bump = (kind: string) => counts.set(kind, (counts.get(kind) ?? 0) + 1);
106
+
107
+ const re = new RegExp(SCAN.source, SCAN.flags);
108
+ let out = "";
109
+ let last = 0;
110
+ let m: RegExpExecArray | null;
111
+ while ((m = re.exec(content)) !== null) {
112
+ const whole = m[0];
113
+ const g = m.groups ?? {};
114
+ out += content.slice(last, m.index);
115
+ last = m.index + whole.length;
116
+
117
+ const quoted = g["dq"] ?? g["cq"] ?? g["sq"];
118
+ if (quoted !== undefined) {
119
+ const inner = quoted.slice(1, -1);
120
+ if (source.includes(inner)) {
121
+ out += quoted;
122
+ } else {
123
+ // Keeps its words, loses its quote marks: softening, never dropping.
124
+ bump("quote");
125
+ out += inner;
126
+ }
127
+ continue;
128
+ }
129
+
130
+ if (source.includes(whole)) {
131
+ out += whole;
132
+ continue;
133
+ }
134
+
135
+ if (g["iso"] !== undefined) {
136
+ bump("date");
137
+ out += hedgeIso(whole);
138
+ } else if (g["md"] !== undefined) {
139
+ bump("date");
140
+ out += hedgeMonthDay(whole);
141
+ } else if (g["my"] !== undefined) {
142
+ // Month+year IS the hedge granularity ("mid-July"). Consumed so the bare
143
+ // year inside it cannot be hedged a second time; left unchanged.
144
+ out += whole;
145
+ } else if (g["yr"] !== undefined) {
146
+ bump("year");
147
+ out += TUNABLES.HEDGE_YEAR(whole);
148
+ } else {
149
+ out += whole;
150
+ }
151
+ }
152
+ out += content.slice(last);
153
+
154
+ const hedges = [...counts.entries()].map(([kind, count]) => ({ kind, count }));
155
+ return {
156
+ // Universality (scar §7): every text-returning export leaves through the gate,
157
+ // whatever order a caller invoked things in.
158
+ text: redactSecrets(out),
159
+ hedges,
160
+ fired: hedges.length > 0,
161
+ };
162
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Encode-time preselection — what the author may see (behavioral-spec §8).
3
+ *
4
+ * Brain analog: schema activation at encoding. Without it there is no prediction
5
+ * error, and therefore no revision.
6
+ *
7
+ * TWO CHANNELS, UNIONED — never one replacing the other (§8 G1):
8
+ * - a precise LEXICAL channel (name or alias in the span, AS A WHOLE WORD, by
9
+ * the one definition schema birth also uses) that never gives ground;
10
+ * - a SEMANTIC channel (nearest schemas above a floor, capped) that only ever
11
+ * *adds*.
12
+ *
13
+ * The semantic channel is degradable by construction (§5 G8, scar E1): no
14
+ * vectors, or a vector that does not line up, yields an empty semantic set and a
15
+ * LOUD SKIP — never a thrown chunk. Worst case is exactly lexical-only.
16
+ * **Deliberately off (cap 0) is silence; a failure is a skip**, and the two are
17
+ * different records.
18
+ *
19
+ * Preselection happens ONCE PER CHUNK (§5 G7): `preselectSchemas` returns the one
20
+ * object, and `renderSchemaContext` takes that object rather than the raw inputs,
21
+ * so the prompt builder and the blind-rate counter cannot disagree about what the
22
+ * author saw.
23
+ */
24
+
25
+ import { cosine } from "../physics/index.js";
26
+ import { redactSecrets } from "./secrets.js";
27
+ import { TUNABLES } from "./tunables.js";
28
+ import { occursAsWholeWord } from "./words.js";
29
+ import type { ChannelRecord, ChannelState, EncodeEvent } from "./types.js";
30
+
31
+ export type Channel = "lexical" | "semantic";
32
+
33
+ /** One element on a slice: a verbatim statement, optionally with its ADDRESS —
34
+ * the id an `updates:` declaration names, which is what lets a shown
35
+ * contradiction become a DECLARED revision instead of a loose restatement.
36
+ * Bare strings stay accepted for address-less context (an id renders only
37
+ * when real — never invented). */
38
+ export type SliceStatement = string | { readonly id: string; readonly statement: string };
39
+
40
+ export interface SchemaSlice {
41
+ id: string;
42
+ name: string;
43
+ aliases?: readonly string[];
44
+ /** Supplied by the caller. Encode never fetches or computes one. */
45
+ vector?: readonly number[] | null;
46
+ /** Rendered VERBATIM (§8 G7): the surface contradiction detection runs on. */
47
+ beliefs?: readonly SliceStatement[];
48
+ /** Rendered VERBATIM, same reason. */
49
+ currentState?: readonly SliceStatement[];
50
+ /** Rendered COMPRESSED, under a byte budget, with the elision announced. */
51
+ identityCore?: string;
52
+ }
53
+
54
+ export function sliceStatementOf(s: SliceStatement): string {
55
+ return typeof s === "string" ? s : s.statement;
56
+ }
57
+
58
+ export function sliceAddressOf(s: SliceStatement): string | null {
59
+ return typeof s === "string" ? null : s.id;
60
+ }
61
+
62
+ export interface SelectedSchema {
63
+ id: string;
64
+ /** Every channel that selected it — the OVERLAP is reported, not hidden (§8 G4). */
65
+ channels: Channel[];
66
+ /** cos(chunk, schema) when the semantic channel ranked it; null otherwise. */
67
+ score: number | null;
68
+ }
69
+
70
+ export interface Preselection {
71
+ chunkRef: string;
72
+ shown: SelectedSchema[];
73
+ lexicalIds: string[];
74
+ semanticIds: string[];
75
+ /** Ids BOTH channels reached — the answer to "did the new channel add anything?" */
76
+ overlapIds: string[];
77
+ /** Ids ONLY the semantic channel reached. Framed honestly at render (§8 G6). */
78
+ semanticOnlyIds: string[];
79
+ /** Counted, not assumed (§5 G9, scar §2.9). */
80
+ blind: boolean;
81
+ semantic: ChannelRecord;
82
+ candidates: number;
83
+ floor: number;
84
+ cap: number;
85
+ events: EncodeEvent[];
86
+ }
87
+
88
+ export interface PreselectInput {
89
+ chunkRef: string;
90
+ span: string;
91
+ schemas: readonly SchemaSlice[];
92
+ /** The chunk's vector, supplied by the caller. Absent ⇒ the channel SKIPS. */
93
+ chunkVector?: readonly number[] | null;
94
+ /** 0 means deliberately off (silence). Absent uses the TUNABLE. */
95
+ semanticCap?: number;
96
+ semanticFloor?: number;
97
+ }
98
+
99
+ function channelRecord(state: ChannelState, reason: string): ChannelRecord {
100
+ return { channel: "semantic-preselection", state, reason };
101
+ }
102
+
103
+ export function preselectSchemas(input: PreselectInput): Preselection {
104
+ const cap = input.semanticCap ?? TUNABLES.SEMANTIC_CAP;
105
+ const floor = input.semanticFloor ?? TUNABLES.SEMANTIC_FLOOR;
106
+ const schemas = input.schemas;
107
+
108
+ // ── the lexical channel: never gives ground ───────────────────────────────
109
+ const lexicalIds: string[] = [];
110
+ for (const s of schemas) {
111
+ const terms = [s.name, ...(s.aliases ?? [])];
112
+ if (terms.some((t) => occursAsWholeWord(input.span, t))) lexicalIds.push(s.id);
113
+ }
114
+
115
+ // ── the semantic channel: only ever adds, and degrades to empty ───────────
116
+ const scores = new Map<string, number>();
117
+ const semanticSelected = new Set<string>();
118
+ let semantic: ChannelRecord;
119
+ if (cap <= 0) {
120
+ semantic = channelRecord("off", "cap-zero-deliberately-off");
121
+ } else if (
122
+ input.chunkVector === null ||
123
+ input.chunkVector === undefined ||
124
+ input.chunkVector.length === 0
125
+ ) {
126
+ semantic = channelRecord("skipped", "no-chunk-vector");
127
+ } else {
128
+ const v = input.chunkVector;
129
+ // Ranks over EVERY schema, alias hits included (§8 G4), so the overlap is a
130
+ // measurement rather than an argument.
131
+ const ranked: { id: string; score: number }[] = [];
132
+ let mismatched = 0;
133
+ for (const s of schemas) {
134
+ const sv = s.vector;
135
+ if (sv === null || sv === undefined || sv.length === 0) continue;
136
+ if (sv.length !== v.length) {
137
+ mismatched += 1;
138
+ continue;
139
+ }
140
+ ranked.push({ id: s.id, score: cosine(v, sv) });
141
+ }
142
+ if (ranked.length === 0) {
143
+ semantic = channelRecord(
144
+ "skipped",
145
+ mismatched > 0 ? "vector-dimension-mismatch" : "no-schema-vectors",
146
+ );
147
+ } else {
148
+ ranked.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
149
+ for (const r of ranked) scores.set(r.id, r.score);
150
+ // The floor first, THEN the cap: a cap is a guard against re-inflating what
151
+ // a fix deflated, not a way to smuggle sub-floor schemas in.
152
+ for (const r of ranked.filter((x) => x.score >= floor).slice(0, cap)) {
153
+ semanticSelected.add(r.id);
154
+ }
155
+ semantic = channelRecord("ran", mismatched > 0 ? "ran-with-dropped-vectors" : "ran");
156
+ }
157
+ }
158
+
159
+ const semanticIds = [...semanticSelected];
160
+
161
+ const shownIds = [...new Set([...lexicalIds, ...semanticIds])];
162
+ const overlapIds = shownIds.filter(
163
+ (id) => lexicalIds.includes(id) && semanticIds.includes(id),
164
+ );
165
+ const semanticOnlyIds = semanticIds.filter((id) => !lexicalIds.includes(id));
166
+
167
+ const shown: SelectedSchema[] = shownIds.map((id) => {
168
+ const channels: Channel[] = [];
169
+ if (lexicalIds.includes(id)) channels.push("lexical");
170
+ if (semanticIds.includes(id)) channels.push("semantic");
171
+ return { id, channels, score: scores.get(id) ?? null };
172
+ });
173
+
174
+ const blind = shown.length === 0;
175
+ const events: EncodeEvent[] = [
176
+ {
177
+ event: "preselect.shown",
178
+ ref: input.chunkRef,
179
+ data: {
180
+ lexical: lexicalIds.length,
181
+ semantic: semanticIds.length,
182
+ overlap: overlapIds.length,
183
+ shown: shown.length,
184
+ candidates: schemas.length,
185
+ semanticState: semantic.state,
186
+ semanticReason: semantic.reason,
187
+ },
188
+ },
189
+ ];
190
+ if (blind) {
191
+ // Counted, by id-less event: a blind chunk is a FACT about coverage.
192
+ events.push({
193
+ event: "preselect.blind",
194
+ ref: input.chunkRef,
195
+ data: { candidates: schemas.length, semanticState: semantic.state },
196
+ });
197
+ }
198
+
199
+ return {
200
+ chunkRef: input.chunkRef,
201
+ shown,
202
+ lexicalIds,
203
+ semanticIds,
204
+ overlapIds,
205
+ semanticOnlyIds,
206
+ blind,
207
+ semantic,
208
+ candidates: schemas.length,
209
+ floor,
210
+ cap,
211
+ events,
212
+ };
213
+ }
214
+
215
+ /**
216
+ * What the author is shown, rendered (§8 G6, G7).
217
+ *
218
+ * - Beliefs and current state render VERBATIM, for every shown schema: a
219
+ * paraphrase of a belief cannot be honestly confirmed or contradicted.
220
+ * - Identity core renders COMPRESSED, under a byte budget, and the elision is
221
+ * announced as a count rather than hidden.
222
+ * - A semantic-only slice is framed as "named in — or closely related to — this
223
+ * span", never as "mentioned": the author is never told something false about
224
+ * why a slice is present.
225
+ * - **The whole render leaves through the secrets gate.** This is a prompt, and a
226
+ * prompt is not exempt (§5 G1). A belief carrying a credential is redacted on
227
+ * its way to the author's eyes, not just on its way to disk.
228
+ */
229
+ export function renderSchemaContext(
230
+ pre: Preselection,
231
+ schemas: readonly SchemaSlice[],
232
+ budget: number = TUNABLES.IDENTITY_CORE_BUDGET,
233
+ ): string {
234
+ const byId = new Map(schemas.map((s) => [s.id, s]));
235
+ const lines: string[] = [];
236
+ for (const sel of pre.shown) {
237
+ const s = byId.get(sel.id);
238
+ if (s === undefined) continue;
239
+ const framing = sel.channels.includes("lexical")
240
+ ? "named in this span"
241
+ : "named in — or closely related to — this span";
242
+ lines.push(`## ${s.name} (${framing})`);
243
+ // The id is the belief's ADDRESS: shown so a contradiction can be DECLARED
244
+ // (`updates: <id>`) rather than loosely restated — declared revisions are
245
+ // what the accommodation path resolves first.
246
+ for (const b of s.beliefs ?? []) {
247
+ const addr = sliceAddressOf(b);
248
+ lines.push(
249
+ addr === null ? `- belief: ${sliceStatementOf(b)}` : `- belief [${addr}]: ${sliceStatementOf(b)}`,
250
+ );
251
+ }
252
+ for (const c of s.currentState ?? []) {
253
+ const addr = sliceAddressOf(c);
254
+ lines.push(
255
+ addr === null ? `- now: ${sliceStatementOf(c)}` : `- now [${addr}]: ${sliceStatementOf(c)}`,
256
+ );
257
+ }
258
+ const core = s.identityCore ?? "";
259
+ if (core.length > 0) {
260
+ if (core.length <= budget) lines.push(core);
261
+ else {
262
+ lines.push(core.slice(0, budget));
263
+ lines.push(`[… ${core.length - budget} further characters elided]`);
264
+ }
265
+ }
266
+ }
267
+ if (lines.length === 0) lines.push("(no schemas matched this span)");
268
+ return redactSecrets(lines.join("\n"));
269
+ }