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,108 @@
1
+ /**
2
+ * Salience tagging at the proposal → memory seam, and novelty as prediction error.
3
+ *
4
+ * Four-dimensional salience is scored ONCE and fixed at birth [v0]. Three of the
5
+ * dimensions are the author's; the fourth — novelty — is COMPUTED, because
6
+ * prediction error is a number, not a model opinion (§3).
7
+ *
8
+ * The arithmetic is `physics/`'s and stays there: this module supplies the inputs
9
+ * and the vocabulary of "why there is no number", which is the part `physics`
10
+ * deliberately does not know about. **Vectors are supplied by the caller.**
11
+ * Nothing here fetches an embedding, calls a model, or touches the store — the
12
+ * failure modes below are all "the caller had nothing to give me".
13
+ *
14
+ * The claimed-salience FLOOR: v1's plain "remember this" note claimed a
15
+ * high-salience floor ONLY IN ITS PROMPT, with no engine backstop — the one place
16
+ * a stated guarantee had no enforcement (§5 G6). Here the claim is clamped by
17
+ * `physics.clampSalienceAtSeam`, and any lift emits `salience.lifted`. The prompt
18
+ * states nothing the engine does not enforce.
19
+ */
20
+
21
+ import { clampSalienceAtSeam, novelty as physicsNovelty } from "../physics/index.js";
22
+ import type { SeamClamp } from "../physics/index.js";
23
+ import type { Salience } from "../types.js";
24
+ import type { ClaimedDimensions } from "./types.js";
25
+
26
+ /**
27
+ * Why there is (or is not) a novelty number. `blind-no-context` is the countable
28
+ * case scar §2.9 exists for: v1's residual blind rate was ~a fifth to a quarter of
29
+ * chunks, and 7 blind chunks minted 16 real memories.
30
+ */
31
+ export type NoveltyReason =
32
+ | "computed"
33
+ | "blind-no-context"
34
+ | "no-chunk-vector"
35
+ | "vector-dimension-mismatch";
36
+
37
+ export interface NoveltyResult {
38
+ /** NULL when it could not be computed. Never defaulted to a number, in either
39
+ * direction — a defaulted 0 fakes "seen this before", a defaulted 1 fakes
40
+ * "brand new", and both are lies the rest of physics then believes. */
41
+ novelty: number | null;
42
+ reason: NoveltyReason;
43
+ blind: boolean;
44
+ /** How many context vectors were actually usable. */
45
+ contextCount: number;
46
+ }
47
+
48
+ /**
49
+ * novelty = 1 − max cos( v(chunk), v(e) ) over the supplied context.
50
+ *
51
+ * Degradable by construction: a missing vector, an empty context, or a dimension
52
+ * mismatch yields NULL and a reason — never a throw, never a guess.
53
+ */
54
+ export function computeNovelty(
55
+ chunkVector: readonly number[] | null | undefined,
56
+ contextVectors: readonly (readonly number[])[] | undefined,
57
+ ): NoveltyResult {
58
+ const context = (contextVectors ?? []).filter((v) => v.length > 0);
59
+ if (chunkVector === null || chunkVector === undefined || chunkVector.length === 0) {
60
+ return { novelty: null, reason: "no-chunk-vector", blind: true, contextCount: context.length };
61
+ }
62
+ if (context.length === 0) {
63
+ return { novelty: null, reason: "blind-no-context", blind: true, contextCount: 0 };
64
+ }
65
+ const usable = context.filter((v) => v.length === chunkVector.length);
66
+ if (usable.length === 0) {
67
+ return {
68
+ novelty: null,
69
+ reason: "vector-dimension-mismatch",
70
+ blind: true,
71
+ contextCount: context.length,
72
+ };
73
+ }
74
+ // physics' `cosine` throws on a dimension mismatch; the filter above is why it
75
+ // cannot throw here. Mismatched vectors are dropped, and the drop is countable.
76
+ const value = physicsNovelty(chunkVector, usable);
77
+ return {
78
+ novelty: value,
79
+ reason: value === null ? "blind-no-context" : "computed",
80
+ blind: value === null,
81
+ contextCount: usable.length,
82
+ };
83
+ }
84
+
85
+ export interface SalienceTag extends SeamClamp {
86
+ novelty: NoveltyResult;
87
+ }
88
+
89
+ /**
90
+ * The seam itself. Dimensions are stored EXACTLY as authored; the claim is stored
91
+ * beside them as a floor; a null novelty stays null. `physics` owns every one of
92
+ * those rules — this function's whole job is to make sure the seam is crossed
93
+ * once, in one place, with the event attached.
94
+ */
95
+ export function tagSalience(
96
+ dimensions: ClaimedDimensions | undefined,
97
+ claimedSalience: number | null | undefined,
98
+ noveltyResult: NoveltyResult,
99
+ ): SalienceTag {
100
+ const dims: Salience = {
101
+ novelty: noveltyResult.novelty,
102
+ relevance: dimensions?.relevance ?? 0,
103
+ emotional: dimensions?.emotional ?? 0,
104
+ predictive: dimensions?.predictive ?? 0,
105
+ };
106
+ const clamped = clampSalienceAtSeam(dims, claimedSalience ?? null);
107
+ return { ...clamped, novelty: noveltyResult };
108
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * The secrets gate. THE NON-ABLATABLE ONE.
3
+ *
4
+ * CONTRACT §5 G1: no off switch, no A/B arm, no bypass. *A prompt is not exempt
5
+ * from the gate.* Three things enforce that here, none of them a comment:
6
+ *
7
+ * 1. **No function in this file takes an options object.** There is no
8
+ * parameter that could carry a disable flag, so no caller can pass one.
9
+ * 2. **`SecretsGateStatus` cannot spell `stood-down`** (types.ts) — the
10
+ * disabled state is not representable in the telemetry type.
11
+ * 3. **Every text-returning export of `encode/` runs this scan on its OUTPUT**,
12
+ * regardless of call order, so a caller that reaches past the battery still
13
+ * cannot get an unredacted string out of the module.
14
+ *
15
+ * Brain analog: NONE. §2 of the contract names this the deliberate deviation —
16
+ * the brain has no interlock that refuses to encode a credential.
17
+ *
18
+ * The incident this is paid for: v1's secrets gate worked on the steady-state
19
+ * path and the MIGRATION PATH BYPASSED IT; three live Google API keys landed in
20
+ * the store across 17 traces (scar §7a). The `google-api-key` family below is
21
+ * that key's own shape.
22
+ *
23
+ * Telemetry rule: findings carry FAMILY and COUNT and nothing else. The secret is
24
+ * never logged and never HASHED — a low-entropy credential's hash is reversible
25
+ * (store §16 G9), so `hashText(secret)` would be the leak wearing a disguise.
26
+ */
27
+
28
+ import type { SecretFinding } from "./types.js";
29
+
30
+ export const REDACTION_MARK = "[REDACTED:";
31
+
32
+ /** Matches a placeholder this module wrote. Used to keep redaction idempotent. */
33
+ export const REDACTION_RE = /\[REDACTED:[a-z0-9-]+\]/g;
34
+
35
+ export interface SecretPattern {
36
+ family: string;
37
+ re: RegExp;
38
+ /** Which capture group holds the credential. 0 = the whole match. */
39
+ value: number;
40
+ /** Why this family exists — lineage where there is any. */
41
+ why: string;
42
+ }
43
+
44
+ /** Never match a placeholder we already wrote. */
45
+ const NOT_REDACTED = "(?!\\[REDACTED:)";
46
+
47
+ /**
48
+ * The URL scheme's tail, BOUNDED. `[a-z][a-z0-9+.-]*://` retried at every word
49
+ * boundary of a long hyphen- or dot-rich lowercase run is O(n²): the star eats
50
+ * to the end of the run and backtracks looking for `://` from each start —
51
+ * measured 744ms at 32KB, ~3s at 64KB, minutes at 512KB, inside the one gate
52
+ * that has no off switch (replay review 2026-08-26, PR-1 follow-up; parallel-run
53
+ * precondition §5.3). No registered URI scheme is longer than 32 characters,
54
+ * so the bound changes what the family matches for no real URL.
55
+ */
56
+ const SCHEME_TAIL = "[a-z0-9+.-]{0,32}";
57
+ // The same lever exists one class later in `url-path-token`: an unbounded
58
+ // host/path run (`[^\s"'<>]*`) retried across a comma-joined URL list was
59
+ // quadratic too (179ms at 64KB, 2.8s at 256KB — PR-8 review). Bounded to 512:
60
+ // longer than any real magic-link path, and a single oversized span can be its
61
+ // own chunk, so the input size is not otherwise capped before the gate.
62
+
63
+ /**
64
+ * The families, in application order: block forms first, then prefixed vendor
65
+ * keys (precise, no false positives), then the shape-based forms, then the
66
+ * assignment form (broadest, and the only one that keeps its key name).
67
+ *
68
+ * [A] The LIST is a preference and will grow. That a scan EXISTS and runs on
69
+ * every path is mechanized (§5 G12).
70
+ */
71
+ export const SECRET_FAMILIES: readonly SecretPattern[] = [
72
+ {
73
+ family: "private-key-block",
74
+ re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
75
+ value: 0,
76
+ why: "PEM/OpenSSH private key, whole block.",
77
+ },
78
+ {
79
+ family: "private-key-header",
80
+ re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g,
81
+ value: 0,
82
+ why: "A truncated key block is still a key block: never let the header through.",
83
+ },
84
+ {
85
+ family: "aws-access-key-id",
86
+ re: /\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA)[0-9A-Z]{16}\b/g,
87
+ value: 0,
88
+ why: "AWS key id prefixes.",
89
+ },
90
+ {
91
+ family: "google-api-key",
92
+ // A live key is AIza + exactly 35, but an exact-length pattern misses a
93
+ // truncated or typo'd paste — which is still a credential shape in the store.
94
+ re: /\bAIza[0-9A-Za-z_-]{30,}/g,
95
+ value: 0,
96
+ why: "The v1 incident's own shape (scar §7a): 3 live keys, 17 traces.",
97
+ },
98
+ {
99
+ family: "github-token",
100
+ re: /\bgh[pousr]_[A-Za-z0-9]{16,}\b/g,
101
+ value: 0,
102
+ why: "GitHub PAT / OAuth / refresh token prefixes.",
103
+ },
104
+ {
105
+ family: "gitlab-token",
106
+ re: /\bglpat-[A-Za-z0-9_-]{16,}/g,
107
+ value: 0,
108
+ why: "GitLab personal access token.",
109
+ },
110
+ {
111
+ family: "npm-token",
112
+ re: /\bnpm_[A-Za-z0-9]{30,}\b/g,
113
+ value: 0,
114
+ why: "npm automation token.",
115
+ },
116
+ {
117
+ family: "slack-token",
118
+ re: /\bxox[abprse]-[A-Za-z0-9-]{10,}/g,
119
+ value: 0,
120
+ why: "Slack bot/user/app tokens.",
121
+ },
122
+ {
123
+ family: "stripe-key",
124
+ re: /\b[rs]k_(?:live|test)_[A-Za-z0-9]{10,}\b/g,
125
+ value: 0,
126
+ why: "Stripe secret/restricted keys.",
127
+ },
128
+ {
129
+ family: "model-provider-key",
130
+ re: /\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}/g,
131
+ value: 0,
132
+ why: "Anthropic / OpenAI style `sk-` keys.",
133
+ },
134
+ {
135
+ family: "jwt",
136
+ re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}(?![A-Za-z0-9_-])/g,
137
+ value: 0,
138
+ why: "A signed JWT is a bearer credential.",
139
+ },
140
+ {
141
+ family: "bearer-token",
142
+ re: new RegExp(`\\bBearer\\s+${NOT_REDACTED}([A-Za-z0-9._~+/-]{16,}=*)`, "gi"),
143
+ value: 1,
144
+ why: "Authorization header pasted into a note.",
145
+ },
146
+ {
147
+ family: "url-credentials",
148
+ re: new RegExp(
149
+ `\\b([a-z]${SCHEME_TAIL}://[^\\s/:@]+):${NOT_REDACTED}([^\\s/@]+)@`,
150
+ "gi",
151
+ ),
152
+ value: 2,
153
+ why: "user:password@host — connection strings are the classic silent leak.",
154
+ },
155
+ {
156
+ family: "url-path-token",
157
+ re: new RegExp(
158
+ `\\b[a-z]${SCHEME_TAIL}://[^\\s"'<>]{0,512}/` +
159
+ "(?:login|logout|auth|magic|magic-?link|token|invite|reset|verify|otp|signin|sso|session)" +
160
+ // One optional lowercase segment ("auth/callback/<token>") — but the
161
+ // auth-shaped word itself is never optional. The second lookahead
162
+ // rejects a pure lowercase hyphen-slug ("getting-started-guide"): a
163
+ // token has digits or case or underscores; a slug is words. Without it
164
+ // this family redacted the last path segment of ordinary docs URLs —
165
+ // the PR-1 review's blocker 1, caught with 11 live counterexamples.
166
+ `[a-z-]*(?:/[a-z-]{1,24})?/${NOT_REDACTED}` +
167
+ "(?![a-z]+(?:-[a-z]+)*(?![A-Za-z0-9_~-]))" +
168
+ "([A-Za-z0-9_~-]{12,})(?![A-Za-z0-9_~-])",
169
+ "gi",
170
+ ),
171
+ value: 1,
172
+ why:
173
+ "A magic-login / invite / reset link carries its bearer token as a URL path " +
174
+ "segment. The 2026-08-26 replay review found a live staff login link minted " +
175
+ "whole (its Gap A: `url-credentials` only matches user:pass@host). Scoped to " +
176
+ "auth-shaped path words so a commit hash in a repo URL does not fire it.",
177
+ },
178
+ {
179
+ family: "assigned-credential",
180
+ re: new RegExp(
181
+ "\\b(password|passwd|pwd|api[_-]?key|apikey|access[_-]?key|secret[_-]?key|" +
182
+ "client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|" +
183
+ "bearer[_-]?token|secret|token|credential)\\b\\s*[:=]\\s*" +
184
+ NOT_REDACTED +
185
+ "(\"[^\"\\n]{4,}\"|'[^'\\n]{4,}'|[^\\s\"'\\n,;]{6,})",
186
+ "gi",
187
+ ),
188
+ value: 2,
189
+ why: "The catch-all assignment form. Keeps the KEY NAME, redacts only the value: a name is not a claim (§3, the ops rule).",
190
+ },
191
+ ];
192
+
193
+ export interface SecretsScan {
194
+ /** The text with every credential replaced by `[REDACTED:family]`. */
195
+ redacted: string;
196
+ /** Family + count + site. Never the secret, never its hash. */
197
+ findings: SecretFinding[];
198
+ fired: boolean;
199
+ /** True when nothing but redaction placeholders and punctuation remain. */
200
+ emptyAfterRedaction: boolean;
201
+ }
202
+
203
+ function redactOne(text: string, p: SecretPattern, hit: () => void): string {
204
+ // A fresh regex per call: a module-level /g regex carries `lastIndex` state,
205
+ // and a shared mutable cursor across callers is a bug waiting for a Tuesday.
206
+ const re = new RegExp(p.re.source, p.re.flags);
207
+ return text.replace(re, (...args: unknown[]): string => {
208
+ const match = String(args[0] ?? "");
209
+ hit();
210
+ const mark = `[REDACTED:${p.family}]`;
211
+ if (p.value === 0) return mark;
212
+ const raw = args[p.value];
213
+ const val = typeof raw === "string" ? raw : "";
214
+ if (val.length === 0) return mark;
215
+ const at = match.lastIndexOf(val);
216
+ if (at < 0) return mark;
217
+ return `${match.slice(0, at)}${mark}${match.slice(at + val.length)}`;
218
+ });
219
+ }
220
+
221
+ /** Everything this module wrote, removed — used to answer "is there anything left?". */
222
+ export function stripRedactions(text: string): string {
223
+ return text.replace(new RegExp(REDACTION_RE.source, REDACTION_RE.flags), " ");
224
+ }
225
+
226
+ /**
227
+ * THE scan. No options parameter, by design (see the header): there is nowhere
228
+ * for a caller to put a disable flag.
229
+ *
230
+ * `site` is telemetry only — body, alias, handle, feeling, context — and can
231
+ * never change the verdict.
232
+ */
233
+ export function scanSecrets(text: string, site = "body"): SecretsScan {
234
+ const counts = new Map<string, number>();
235
+ let out = text;
236
+ for (const p of SECRET_FAMILIES) {
237
+ out = redactOne(out, p, () => counts.set(p.family, (counts.get(p.family) ?? 0) + 1));
238
+ }
239
+ const findings: SecretFinding[] = [...counts.entries()].map(([family, count]) => ({
240
+ family,
241
+ count,
242
+ site,
243
+ }));
244
+ const residue = stripRedactions(out).replace(/[^\p{L}\p{N}]/gu, "");
245
+ return {
246
+ redacted: out,
247
+ findings,
248
+ fired: findings.length > 0,
249
+ emptyAfterRedaction: findings.length > 0 && residue.length === 0,
250
+ };
251
+ }
252
+
253
+ /**
254
+ * The convenience form: redacted text, nothing else. Every text-returning export
255
+ * of `encode/` funnels its output through this, so the gate is universal by
256
+ * construction rather than by everyone remembering (scar §7).
257
+ */
258
+ export function redactSecrets(text: string): string {
259
+ return scanSecrets(text).redacted;
260
+ }
261
+
262
+ /** True when a string carries any credential shape at all. */
263
+ export function containsSecret(text: string): boolean {
264
+ return scanSecrets(text).fired;
265
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The TUNABLE table — every constant in `encode/`, in one visible place, the way
3
+ * `physics/` keeps its own.
4
+ *
5
+ * CAL = calibration-required (scar §2.8, CONTRACT §5 G13): a threshold ships with
6
+ * a recorded measurement against the real corpus and a fixture-bounded window
7
+ * naming what breaks on each side, or it ships DISABLED. Every CAL entry below
8
+ * carries the v1 measurement it inherits; the ones with no measurement to inherit
9
+ * say so out loud.
10
+ *
11
+ * NOTE WHAT IS NOT HERE: there is no key that switches the secrets gate off, in
12
+ * any spelling. That is guarantee 1, and `test/encode.test.ts` source-scans for it.
13
+ */
14
+
15
+ export const TUNABLES = {
16
+ // --- the content floor (§3, earned-mechanism #3) ---
17
+ /** CAL [v1: 20 chars, set at about HALF the shortest real memory in v1's own
18
+ * fixtures]. Window: below ~12 the literal `"placeholder"` trace that minted
19
+ * this mechanism survives; above ~40 real one-line memories ("Mike uses bun,
20
+ * not npm") start dying. */
21
+ FLOOR_MIN_CHARS: 20,
22
+ /** CAL [v1: 3 words, same fixture calibration]. Window: 2 admits "no thoughts";
23
+ * 4 kills real short facts. */
24
+ FLOOR_MIN_WORDS: 3,
25
+ /**
26
+ * The stub vocabulary. Matched EXACTLY after normalization, never as a
27
+ * substring — so "keeps a TODO list in vim" survives while a bare "todo" does
28
+ * not (§3). [A] advisory: the LIST is a preference, that the floor EXISTS is
29
+ * mechanized (§5 G12).
30
+ */
31
+ STUB_TOKENS: [
32
+ "placeholder",
33
+ "todo",
34
+ "tbd",
35
+ "n/a",
36
+ "na",
37
+ "none",
38
+ "nothing",
39
+ "null",
40
+ "undefined",
41
+ "test",
42
+ "example",
43
+ "sample",
44
+ "lorem ipsum",
45
+ "xxx",
46
+ "no content",
47
+ "no memory",
48
+ "nothing to record",
49
+ "nothing of note",
50
+ ] as readonly string[],
51
+
52
+ // --- aliases (§3) ---
53
+ /** [A] TUNABLE minimum alias length. Below this an alias is a retrieval hazard,
54
+ * not a handle: one- and two-character aliases match everything. */
55
+ ALIAS_MIN_CHARS: 3,
56
+
57
+ // --- precision hedging (§3; [A] phrasings are preferences, §5 G12) ---
58
+ HEDGE_YEAR: (year: string) => `around ${year}`,
59
+ HEDGE_EARLY: (month: string) => `early ${month}`,
60
+ HEDGE_MID: (month: string) => `mid-${month}`,
61
+ HEDGE_LATE: (month: string) => `late ${month}`,
62
+
63
+ // --- encode-time preselection (§8) ---
64
+ /**
65
+ * CAL [v1: 0.60, measured — 8 schema vectors x 13,608 traces, voyage-3-large:
66
+ * all-pairs median cosine 0.576, best-per-trace median 0.635]. Window: the
67
+ * intuitive 0.35-0.45 is INERT (clears 99% of pairs); above ~0.70 the channel
68
+ * adds nothing the lexical channel did not already have.
69
+ *
70
+ * OPEN (CONTRACT open question 2, v1's own live watch): 0.60 was calibrated on
71
+ * TRACE-length text and is applied here to CHUNK-length text, where dilution
72
+ * may pull real chunks below it. Recalibrate on the text length v2 actually
73
+ * sees before trusting this number.
74
+ */
75
+ SEMANTIC_FLOOR: 0.6,
76
+ /** CAL [v1: 2]. A cap is a guard against re-inflating what a fix deflated —
77
+ * two slices is a rounding error against a 16 KB chunk; ten is the old cost
78
+ * back by another door. Zero means the channel is deliberately OFF (silence),
79
+ * which is a different record from a skip (§5 G8). */
80
+ SEMANTIC_CAP: 2,
81
+ /** [A] CHARACTER budget for the compressed identity-core render (§8 G7).
82
+ * v1's 6,144 was a BYTE budget; this counts JS characters, which is the same
83
+ * number for ASCII and smaller for anything else — the safe direction, and the
84
+ * one the elision notice can honestly report. Beliefs and current state are
85
+ * NEVER compressed: a paraphrase of a belief cannot be honestly confirmed or
86
+ * contradicted. */
87
+ IDENTITY_CORE_BUDGET: 6144,
88
+
89
+ // --- the emotion classifier channel (CONTRACT §4) ---
90
+ /**
91
+ * Ships DISABLED and stays disabled until it re-earns its fired-cue precision
92
+ * bar against a held-out reference set (§17.3: "do not enable a channel on a
93
+ * rewrite's promise"). This is a CHANNEL, not one of the five gates: the
94
+ * stated-only emotion GATE runs on every proposal regardless.
95
+ */
96
+ EMOTION_CLASSIFIER_ENABLED: false,
97
+ /** The bar the classifier must clear before the flag above may flip. */
98
+ EMOTION_CLASSIFIER_PRECISION_BAR: 0.8,
99
+ } as const;