aegisone 1.0.34 → 1.0.35

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -575
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,979 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * profile.js — what *this holder's* memory is allowed to personalise.
10
- *
11
- * `identity.js` answers "whose memory is it"; this module answers the question
12
- * that follows immediately: given that holder's own rows, what may the avatar
13
- * say it knows about them — and what is the provenance of each claim?
14
- *
15
- * The shape is a **fold**, not an inference engine:
16
- *
17
- * fold({ holder, entries, ledger, corrections, now }) →
18
- * { holder, facets, budget, coldStart, dropped }
19
- *
20
- * Six properties, each asserted in `desktop/test/avatar-profile.test.mjs`
21
- * rather than promised in prose:
22
- *
23
- * 1. PROVENANCE-BACKED. Every facet carries `sources: [entryId…]`, and every
24
- * one of those ids is an entry id from *this holder's* input set — the
25
- * `citable()` filter below is the single place that guarantees it. A facet
26
- * that cannot cite a row it was actually built from is not emitted at all
27
- * (`sources.length === 0` drops the facet), so "the avatar can show you
28
- * why it knows this" is structurally true rather than a UI promise.
29
- * 2. CLOSED NAMESPACE. `FACET_IDS` is a frozen list of seven classes and
30
- * `checkFacetId` throws on anything else. There is deliberately no code
31
- * path for identity, health, politics, employer or location: the fold only
32
- * ever iterates `FOLDERS`, which is keyed by `FACET_IDS` and length-checked
33
- * against it at load, so an eighth class is a visible diff to the frozen
34
- * list rather than a quiet addition. The closure is the proof; §7's
35
- * "no profiling creep" is what it is for.
36
- * 3. EVIDENCE-GATED. `doNotRepeat` is honoured at a single observation —
37
- * negatives are cheap to act on and expensive to ignore. Every *positive*
38
- * facet needs its §4 gate (≥1 correction or ≥3 consistent observations,
39
- * ≥5 non-English entries, ≥2 recent entries on a path, ≥1 decision, …).
40
- * Absence of evidence produces no facet: never "probably prefers terse
41
- * answers".
42
- * 4. COLD START IS NEUTRAL. No evidence ⇒ `coldStart: true`, `facets: []`,
43
- * `budget.used: 0`. The renderer shows that as an empty fragment, i.e. an
44
- * avatar that behaves exactly like an unconfigured install. It does not
45
- * guess a personality.
46
- * 5. DETERMINISTIC. No clock (`now` is an argument), no randomness, no map
47
- * iteration order leaking into output: facets are ordered by
48
- * `(confidence desc, lastSeen desc, id asc)` and, for two facets of the
49
- * same class on the same day, `key asc` — one extra term so the order is
50
- * total and a permutation of the input cannot change the output bytes.
51
- * 6. BOUNDED. The assembled facets are capped at `BUDGET_TOKENS` (900),
52
- * dropped whole, lowest priority first — never sliced
53
- * mid-sentence, which is the failure mode a naive `slice()` produces.
54
- *
55
- * Pure: no fs, no Electron, no clock, no crypto. It reuses `persona.cleanText`
56
- * (the storage boundary's sanitizer) and `register.estimateTokens` (the same
57
- * 4-chars-per-token ceiling used elsewhere) so the two prompt fragments the renderer
58
- * concatenates are measured with one ruler.
59
- */
60
-
61
- const persona = require('./persona.js');
62
- const register = require('./register.js');
63
- const identity = require('./identity.js');
64
-
65
- /**
66
- * The closed facet namespace (§4's table). Frozen twice on purpose: freeze the
67
- * array so it cannot be extended at runtime, and length-check `FOLDERS` against
68
- * it below so the *implementation* cannot grow a class the list does not name.
69
- */
70
- const FACET_IDS = Object.freeze([
71
- 'vocabulary',
72
- 'language',
73
- 'codebase',
74
- 'decisions',
75
- 'openThreads',
76
- 'doNotRepeat',
77
- 'toneCalibration',
78
- ]);
79
-
80
- /** The profile fragment's ceiling. */
81
- const BUDGET_TOKENS = 900;
82
-
83
- /** Longest a single facet `value` may be (it is UI text and prompt text). */
84
- const MAX_VALUE_CHARS = 180;
85
- /** Longest a facet `key` may be. */
86
- const MAX_KEY_CHARS = 64;
87
- /** Distinct ids a single facet may cite; provenance stays readable. */
88
- const MAX_SOURCES = 24;
89
-
90
- /** Per-class caps — a fold is a summary, not a dump. */
91
- const MAX_VOCABULARY = 5;
92
- const MAX_LANGUAGE = 2;
93
- const MAX_CODEBASE = 5;
94
- const MAX_DECISIONS = 5;
95
- const MAX_OPEN_THREADS = 3;
96
- const MAX_DO_NOT_REPEAT = 5;
97
- const MAX_TONE = 2;
98
-
99
- /** §4 gate constants. Named so the tests can assert the gate, not a magic 5. */
100
- const MIN_LANGUAGE_ENTRIES = 5;
101
- const MIN_CODEBASE_ENTRIES = 2;
102
- const MIN_OBSERVATIONS = 3;
103
- const MIN_TONE_SAMPLES = 5;
104
- const RECENT_DAYS = 30;
105
- const DAY_MS = 24 * 60 * 60 * 1000;
106
-
107
- /** Ledger kinds this fold reads. Everything else is noise here. */
108
- const CORRECTION_KIND = 'memory.corrected';
109
- const RECALL_KINDS = Object.freeze(['memory.recalled', 'memory.saved', 'memory.reinforced']);
110
- /**
111
- * Kinds that state a negative. `xp.js` does not pay for them (they are not in
112
- * its table) — a deletion is not work — but the fold honours them, which is the
113
- * whole point of §4's "negatives are honoured even at one observation".
114
- */
115
- const NEGATIVE_KINDS = Object.freeze(['memory.deleted', 'memory.contradicted', 'memory.forgotten']);
116
- /** Entry tags that mark the entry itself as a negative. */
117
- const NEGATIVE_TAGS = Object.freeze(['do-not-repeat', 'never-repeat', 'avoid', 'never']);
118
- /** Entry tags that mark a decision. aegis1 rows carry tags, not `kind`. */
119
- const DECISION_TAGS = Object.freeze(['decision', 'decided', 'adr']);
120
-
121
- /** Confidence a facet may carry, before the clamping in `makeFacet`. */
122
- const MAX_CONFIDENCE = 0.95;
123
- const MIN_CONFIDENCE = 0.4;
124
-
125
- // ---------------------------------------------------------------------------
126
- // small pure helpers
127
- // ---------------------------------------------------------------------------
128
-
129
- /** The closed-namespace guard. Throws — this is a programming error, not data. */
130
- function checkFacetId(id) {
131
- if (!FACET_IDS.includes(id)) {
132
- throw new Error(`unknown facet id ${JSON.stringify(String(id))} — FACET_IDS is closed (identity plan §4)`);
133
- }
134
- return id;
135
- }
136
-
137
- /** Single-line, capped, control-character-free text (the same sanitizer persona uses). */
138
- function clean(value, max) {
139
- return persona.cleanText(value == null ? '' : String(value), max);
140
- }
141
-
142
- /** `Kebab Case` → `kebab-case`, for stable keys. */
143
- function keyOf(value) {
144
- return clean(value, MAX_KEY_CHARS).toLowerCase().replace(/\s+/g, ' ').trim();
145
- }
146
-
147
- function asArray(value) {
148
- if (Array.isArray(value)) return value;
149
- // A Set is what the folder builders accumulate source ids into (`ids: new
150
- // Set()` in foldVocabulary/foldLanguage/foldCodebase). Without this branch
151
- // `asArray(set)` returned [], so `citable(rec.ids)` was always empty, so
152
- // `makeFacet` returned null for want of a source: vocabulary, language and
153
- // codebase facets could never be produced at all — three of the seven classes
154
- // were dead code, and `coldStart` stayed true for a holder whose only evidence
155
- // was theirs.
156
- if (value instanceof Set) return [...value];
157
- return [];
158
- }
159
-
160
- function textOf(entry) {
161
- if (!entry) return '';
162
- if (typeof entry.content === 'string' && entry.content) return entry.content;
163
- if (typeof entry.text === 'string' && entry.text) return entry.text;
164
- return '';
165
- }
166
-
167
- /** A usable timestamp, or `null`. Nothing here ever calls `Date.now()`. */
168
- function timeOf(row) {
169
- if (!row || typeof row !== 'object') return null;
170
- const direct = row.t != null ? row.t : row.createdAt != null ? row.createdAt : row.ts;
171
- if (typeof direct === 'number' && Number.isFinite(direct)) return direct;
172
- if (typeof direct === 'string' && direct.trim()) {
173
- const parsed = Date.parse(direct);
174
- if (Number.isFinite(parsed)) return parsed;
175
- }
176
- if (typeof row.timestamp === 'string' && row.timestamp.trim()) {
177
- const parsed = Date.parse(row.timestamp);
178
- if (Number.isFinite(parsed)) return parsed;
179
- }
180
- return null;
181
- }
182
-
183
- /** Entry id, or `null`. An entry with no id can never be cited, so it is skipped. */
184
- function idOf(entry) {
185
- if (!entry || typeof entry !== 'object') return null;
186
- if (entry.id == null || entry.id === '') return null;
187
- return String(entry.id);
188
- }
189
-
190
- function tagsOf(entry) {
191
- return asArray(entry && entry.tags).map((t) => keyOf(t)).filter(Boolean);
192
- }
193
-
194
- function holderStamp(row) {
195
- if (!row || typeof row !== 'object') return null;
196
- const value = row.holder;
197
- return typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : null;
198
- }
199
-
200
- /** Clamp and round to 2dp so two runs on two machines produce identical bytes. */
201
- function clampConfidence(value) {
202
- const n = typeof value === 'number' && Number.isFinite(value) ? value : MIN_CONFIDENCE;
203
- return Math.round(Math.min(MAX_CONFIDENCE, Math.max(MIN_CONFIDENCE, n)) * 100) / 100;
204
- }
205
-
206
- /**
207
- * Levenshtein distance, iteratively and with a bounded row (only ever 2 rows of
208
- * `b.length + 1`), because tone calibration runs over a handful of strings but
209
- * a hostile input can make them long. Capped at `cap` characters per side: an
210
- * edit-distance estimate does not improve with the tail of a 10 kB paragraph,
211
- * and the cap keeps the fold linear-time by construction.
212
- */
213
- function editDistance(a, b, cap = 400) {
214
- const s = String(a == null ? '' : a).slice(0, cap);
215
- const t = String(b == null ? '' : b).slice(0, cap);
216
- if (!s) return t.length;
217
- if (!t) return s.length;
218
- let prev = new Array(t.length + 1);
219
- let curr = new Array(t.length + 1);
220
- for (let j = 0; j <= t.length; j += 1) prev[j] = j;
221
- for (let i = 1; i <= s.length; i += 1) {
222
- curr[0] = i;
223
- for (let j = 1; j <= t.length; j += 1) {
224
- const cost = s[i - 1] === t[j - 1] ? 0 : 1;
225
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
226
- }
227
- const swap = prev;
228
- prev = curr;
229
- curr = swap;
230
- }
231
- return prev[t.length];
232
- }
233
-
234
- // ---------------------------------------------------------------------------
235
- // language detection — deterministic, and blind on purpose
236
- // ---------------------------------------------------------------------------
237
-
238
- /** Script ranges we can name without a model. Order matters: first match wins. */
239
- const SCRIPT_RANGES = Object.freeze([
240
- { code: 'ja', re: /[\u3040-\u30ff]/ },
241
- { code: 'ko', re: /[\uac00-\ud7af]/ },
242
- { code: 'zh', re: /[\u4e00-\u9fff]/ },
243
- { code: 'ru', re: /[\u0400-\u04ff]/ },
244
- { code: 'ar', re: /[\u0600-\u06ff]/ },
245
- { code: 'he', re: /[\u0590-\u05ff]/ },
246
- { code: 'el', re: /[\u0370-\u03ff]/ },
247
- { code: 'th', re: /[\u0e00-\u0e7f]/ },
248
- { code: 'hi', re: /[\u0900-\u097f]/ },
249
- ]);
250
-
251
- /**
252
- * A closed stopword set for the Latin-script languages where a script check
253
- * cannot help. Small on purpose: the fold only needs to answer "is this holder
254
- * writing durably in a language that is not English", and a wrong guess here
255
- * would produce a facet about a person that is not true — the exact failure §4's
256
- * non-goal forbids. When the score is close or low, the answer is `und`.
257
- */
258
- const STOPWORDS = Object.freeze({
259
- en: Object.freeze(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'not', 'you', 'are', 'have']),
260
- de: Object.freeze(['der', 'die', 'das', 'und', 'nicht', 'mit', 'ist', 'ich', 'auch', 'dass', 'noch']),
261
- fr: Object.freeze(['le', 'la', 'les', 'des', 'est', 'pas', 'que', 'qui', 'dans', 'pour', 'avec']),
262
- es: Object.freeze(['el', 'los', 'las', 'que', 'no', 'con', 'para', 'una', 'pero', 'como', 'está']),
263
- pt: Object.freeze(['não', 'uma', 'com', 'para', 'que', 'está', 'mais', 'como', 'isso', 'você']),
264
- it: Object.freeze(['il', 'lo', 'gli', 'che', 'non', 'con', 'per', 'una', 'come', 'anche']),
265
- nl: Object.freeze(['het', 'een', 'niet', 'met', 'dat', 'zijn', 'voor', 'maar', 'ook', 'nog']),
266
- });
267
-
268
- /** Human names for the codes we can emit; anything else displays as its code. */
269
- const LANGUAGE_NAMES = Object.freeze({
270
- en: 'English', de: 'German', fr: 'French', es: 'Spanish', pt: 'Portuguese',
271
- it: 'Italian', nl: 'Dutch', ru: 'Russian', ja: 'Japanese', ko: 'Korean',
272
- zh: 'Chinese', ar: 'Arabic', he: 'Hebrew', el: 'Greek', th: 'Thai', hi: 'Hindi',
273
- });
274
-
275
- const LANGUAGE_CODE_RE = /^[a-z]{2}(?:-[a-z0-9]{2,8})?$/;
276
-
277
- /**
278
- * Detect the language of one entry. `lang`/`language` from the row wins if it is
279
- * shaped like a code (aegis1 does not send one today, but a row that does is
280
- * better evidence than a guess), then script, then stopwords. `und` means
281
- * "not enough signal", which is not a language and never becomes a facet.
282
- */
283
- function detectLanguage(entry) {
284
- const declared = entry && (entry.lang != null ? entry.lang : entry.language);
285
- if (typeof declared === 'string' && declared.trim()) {
286
- const code = declared.trim().toLowerCase();
287
- if (LANGUAGE_CODE_RE.test(code)) return code.split('-')[0];
288
- }
289
- const text = textOf(entry);
290
- if (!text) return 'und';
291
- for (const { code, re } of SCRIPT_RANGES) {
292
- if (re.test(text)) return code;
293
- }
294
- const words = text.toLowerCase().split(/[^\p{L}\p{N}'-]+/u).filter(Boolean);
295
- if (!words.length) return 'und';
296
- const seen = new Set(words);
297
- let best = 'und';
298
- let bestScore = 0;
299
- let englishScore = 0;
300
- for (const code of Object.keys(STOPWORDS)) {
301
- let score = 0;
302
- for (const word of STOPWORDS[code]) if (seen.has(word)) score += 1;
303
- if (code === 'en') { englishScore = score; continue; }
304
- // Ties resolve by code ascending, so the same text always yields one answer.
305
- if (score > bestScore || (score === bestScore && score > 0 && code < best)) {
306
- best = code;
307
- bestScore = score;
308
- }
309
- }
310
- // A non-English language must actually beat English, and clear a floor: two
311
- // shared stopwords is the smallest signal that is not a coincidence.
312
- if (bestScore >= 2 && bestScore > englishScore) return best;
313
- return englishScore > 0 ? 'en' : 'und';
314
- }
315
-
316
- // ---------------------------------------------------------------------------
317
- // facet construction
318
- // ---------------------------------------------------------------------------
319
-
320
- /**
321
- * Build one facet. `value` is the sentence the prompt will see; `key` is the
322
- * stable identity within the class (a term, a language code, a path, a topic).
323
- * Returns `null` for a facet with no citable source — see property 1 in the
324
- * header: a claim the holder cannot trace back to a row is not emitted.
325
- */
326
- function makeFacet(id, key, value, sources, confidence, firstSeen, lastSeen) {
327
- checkFacetId(id);
328
- const cleanKey = keyOf(key);
329
- const cleanValue = clean(value, MAX_VALUE_CHARS);
330
- const ids = asArray(sources).map((s) => String(s)).filter(Boolean);
331
- if (!cleanKey || !cleanValue || !ids.length) return null;
332
- const seen = ids.slice().sort().slice(0, MAX_SOURCES);
333
- const first = typeof firstSeen === 'number' && Number.isFinite(firstSeen) ? firstSeen : null;
334
- const last = typeof lastSeen === 'number' && Number.isFinite(lastSeen) ? lastSeen : null;
335
- const times = [first, last].filter((t) => t !== null);
336
- return {
337
- id,
338
- key: cleanKey,
339
- value: cleanValue,
340
- tokens: register.estimateTokens(cleanKey) + register.estimateTokens(cleanValue),
341
- sources: seen,
342
- confidence: clampConfidence(confidence),
343
- // `0` rather than a guess when the source rows carry no usable timestamp:
344
- // unknown recency sorts last, which is where an unprovable claim belongs.
345
- firstSeen: times.length ? Math.min(...times) : 0,
346
- lastSeen: times.length ? Math.max(...times) : 0,
347
- };
348
- }
349
-
350
- /**
351
- * The order the fragment is assembled in, and the order the budget drops in:
352
- * `(confidence desc, lastSeen desc, id asc)`, with `key asc` as the final term
353
- * so two facets of one class on one day still have a total order. An unknown id
354
- * here throws — this is the second of the two closure guards (the first is
355
- * `checkFacetId` on the way in), so a facet list crossing this boundary can
356
- * never carry a class the design does not name.
357
- */
358
- function orderFacets(facets) {
359
- return asArray(facets)
360
- .map((facet) => {
361
- checkFacetId(facet.id);
362
- return facet;
363
- })
364
- .sort((a, b) => {
365
- if (b.confidence !== a.confidence) return b.confidence - a.confidence;
366
- if (b.lastSeen !== a.lastSeen) return b.lastSeen - a.lastSeen;
367
- if (a.id !== b.id) return a.id < b.id ? -1 : 1;
368
- if (a.key !== b.key) return a.key < b.key ? -1 : 1;
369
- return 0;
370
- });
371
- }
372
-
373
- /**
374
- * Take facets in priority order while they fit. Whole facets only: a fragment
375
- * that ends mid-sentence reads as a truncated thought, which is worse than a
376
- * shorter one, and the test asserts exactly this.
377
- */
378
- function applyBudget(ordered, limit = BUDGET_TOKENS) {
379
- const kept = [];
380
- const dropped = [];
381
- let used = 0;
382
- for (const facet of asArray(ordered)) {
383
- if (used + facet.tokens <= limit) {
384
- kept.push(facet);
385
- used += facet.tokens;
386
- } else {
387
- dropped.push({ id: facet.id, key: facet.key, tokens: facet.tokens });
388
- }
389
- }
390
- return { facets: kept, used, dropped };
391
- }
392
-
393
- // ---------------------------------------------------------------------------
394
- // input normalisation (and the isolation filter)
395
- // ---------------------------------------------------------------------------
396
-
397
- /**
398
- * Does this row belong to the holder being folded?
399
- *
400
- * Unstamped rows belong to whoever is asking: they predate the stamping
401
- * and the alternative — dropping them — would silently empty the profile of
402
- * every existing install. A row stamped for *someone else* is never folded, and
403
- * that is the pure-seam half of §3's "isolation is the load-bearing property":
404
- * `sources` built downstream can only cite ids that survived this filter. The
405
- * real-seam half asserts it again through actual turn assembly,
406
- * because a filter applied after the wrong cache is exactly the bug a
407
- * pure-function test misses.
408
- */
409
- function belongsTo(row, holder) {
410
- if (!holder) return true;
411
- const stamp = holderStamp(row);
412
- return !stamp || stamp === holder;
413
- }
414
-
415
- function normalizeEntries(rows, holder) {
416
- const out = [];
417
- for (const raw of asArray(rows)) {
418
- if (!raw || typeof raw !== 'object') continue;
419
- if (!belongsTo(raw, holder)) continue;
420
- const id = idOf(raw);
421
- if (!id) continue;
422
- const text = textOf(raw);
423
- if (!text) continue;
424
- const t = timeOf(raw);
425
- out.push({
426
- id,
427
- text,
428
- t,
429
- tagged: tagsOf(raw),
430
- kind: clean(raw.kind, 24).toLowerCase(),
431
- lang: clean(raw.lang != null ? raw.lang : raw.language, 8).toLowerCase(),
432
- role: clean(raw.role, 16).toLowerCase(),
433
- source: clean(raw.source, 40),
434
- session: clean(raw.session, 64),
435
- holder: holderStamp(raw),
436
- });
437
- }
438
- return out;
439
- }
440
-
441
- function normalizeLedger(rows, holder) {
442
- const out = [];
443
- for (const raw of asArray(rows)) {
444
- if (!raw || typeof raw !== 'object') continue;
445
- if (!belongsTo(raw, holder)) continue;
446
- const kind = typeof raw.kind === 'string' ? raw.kind : '';
447
- if (!kind) continue;
448
- out.push({
449
- kind,
450
- ref: raw.ref == null || raw.ref === '' ? null : String(raw.ref),
451
- session: clean(raw.session, 64),
452
- t: timeOf(raw),
453
- });
454
- }
455
- return out;
456
- }
457
-
458
- /**
459
- * Correction observations. Two shapes share this input, because both are "the
460
- * holder told us it was wrong":
461
- *
462
- * { ref, term, insteadOf } a terminology correction (→ `vocabulary`)
463
- * { proposed, kept } an edit of what the avatar wrote (→ `toneCalibration`)
464
- * { ref, term, negative: true } a negative, honoured at one observation (→ `doNotRepeat`)
465
- */
466
- function normalizeCorrections(rows, holder) {
467
- const out = [];
468
- for (const raw of asArray(rows)) {
469
- if (!raw || typeof raw !== 'object') continue;
470
- if (!belongsTo(raw, holder)) continue;
471
- out.push({
472
- ref: raw.ref == null && raw.entryId == null ? null : String(raw.ref != null ? raw.ref : raw.entryId),
473
- term: clean(raw.term != null ? raw.term : raw.from, MAX_KEY_CHARS),
474
- insteadOf: clean(raw.insteadOf != null ? raw.insteadOf : raw.was, MAX_KEY_CHARS),
475
- proposed: raw.proposed == null ? '' : String(raw.proposed),
476
- kept: raw.kept == null ? '' : String(raw.kept),
477
- negative: raw.negative === true || raw.removed === true || raw.deleted === true,
478
- t: timeOf(raw),
479
- });
480
- }
481
- return out;
482
- }
483
-
484
- // ---------------------------------------------------------------------------
485
- // the seven folds
486
- // ---------------------------------------------------------------------------
487
-
488
- /** Backtick-quoted spans — the only place a "project noun" is read from prose. */
489
- function backticked(text) {
490
- const out = [];
491
- const re = /`([^`\n]{1,48})`/g;
492
- let match = re.exec(text);
493
- while (match) {
494
- const term = keyOf(match[1]);
495
- if (term) out.push(term);
496
- match = re.exec(text);
497
- }
498
- return out;
499
- }
500
-
501
- /** Paths and filenames — again, only shapes we can point at, never guesswork. */
502
- const PATH_RE = /(?:^|[\s("'`\[])((?:[\w.@-]+\/)+[\w.@-]+|[\w.@-]+\.(?:js|mjs|cjs|ts|tsx|jsx|py|json|jsonl|md|yml|yaml|sh|rs|go|java|rb|toml|css|html))/g;
503
- function pathsIn(text) {
504
- const out = [];
505
- let match = PATH_RE.exec(text);
506
- while (match) {
507
- const path = keyOf(match[1]).replace(/[.,;:]+$/, '');
508
- if (path) out.push(path);
509
- match = PATH_RE.exec(text);
510
- }
511
- PATH_RE.lastIndex = 0;
512
- return out;
513
- }
514
-
515
- /** `vocabulary` — terms the holder corrected us on, or observed consistently. */
516
- function foldVocabulary(ctx) {
517
- const perTerm = new Map();
518
- const bump = (term, { entryId, t, corrected, insteadOf }) => {
519
- const key = keyOf(term);
520
- if (!key || key.length < 2) return;
521
- const rec = perTerm.get(key) || {
522
- key, ids: new Set(), corrections: 0, observations: 0,
523
- first: null, last: null, insteadOf: null,
524
- };
525
- if (entryId) rec.ids.add(entryId);
526
- if (corrected) {
527
- rec.corrections += 1;
528
- if (insteadOf) rec.insteadOf = keyOf(insteadOf);
529
- } else {
530
- rec.observations += 1;
531
- }
532
- if (typeof t === 'number') {
533
- rec.first = rec.first === null ? t : Math.min(rec.first, t);
534
- rec.last = rec.last === null ? t : Math.max(rec.last, t);
535
- }
536
- perTerm.set(key, rec);
537
- };
538
-
539
- // Corrections: explicit rows first, then the entries the ledger marked as
540
- // corrected (`memory.corrected`). Both are the holder disagreeing with us.
541
- const correctedRefs = new Set();
542
- for (const row of ctx.ledger) {
543
- if (row.kind === CORRECTION_KIND && row.ref) correctedRefs.add(row.ref);
544
- }
545
- for (const corr of ctx.corrections) {
546
- if (corr.negative || !corr.term) continue;
547
- const entry = corr.ref ? ctx.byId.get(corr.ref) : null;
548
- bump(corr.term, {
549
- entryId: entry ? entry.id : null,
550
- t: corr.t != null ? corr.t : entry ? entry.t : null,
551
- corrected: true,
552
- insteadOf: corr.insteadOf,
553
- });
554
- }
555
- for (const id of correctedRefs) {
556
- const entry = ctx.byId.get(String(id));
557
- if (!entry) continue;
558
- for (const term of backticked(entry.text)) {
559
- bump(term, { entryId: entry.id, t: entry.t, corrected: true });
560
- }
561
- }
562
- // Consistent observations: the same backticked term in ≥3 entries.
563
- for (const entry of ctx.entries) {
564
- if (ctx.negative.has(entry.id)) continue;
565
- for (const term of backticked(entry.text)) {
566
- bump(term, { entryId: entry.id, t: entry.t, corrected: false });
567
- }
568
- }
569
-
570
- const facets = [];
571
- const keys = [...perTerm.keys()].sort();
572
- for (const key of keys) {
573
- const rec = perTerm.get(key);
574
- if (!rec.corrections && rec.observations < MIN_OBSERVATIONS) continue; // §4 gate
575
- const sources = ctx.citable(rec.ids);
576
- const confidence = rec.corrections
577
- ? 0.75 + Math.min(0.15, (rec.corrections - 1) * 0.05)
578
- : 0.6;
579
- const value = rec.insteadOf
580
- ? `calls it "${rec.key}", not "${rec.insteadOf}"`
581
- : `calls it "${rec.key}"`;
582
- const facet = makeFacet('vocabulary', rec.key, value, sources, confidence, rec.first, rec.last);
583
- if (facet) facets.push(facet);
584
- }
585
- return facets.slice(0, MAX_VOCABULARY);
586
- }
587
-
588
- /** `language` — the holder's own durable entries, ≥5 in one non-English language. */
589
- function foldLanguage(ctx) {
590
- const perLang = new Map();
591
- for (const entry of ctx.entries) {
592
- if (ctx.negative.has(entry.id)) continue;
593
- if (entry.role && entry.role !== 'user') continue; // "the holder's own" entries
594
- // Entries with a `lang` field win over the script/stopword guess.
595
- const code = detectLanguage({ content: entry.text, lang: entry.lang });
596
- if (code === 'und' || code === 'en') continue;
597
- const rec = perLang.get(code) || { key: code, ids: new Set(), first: null, last: null, count: 0 };
598
- rec.ids.add(entry.id);
599
- rec.count += 1;
600
- if (typeof entry.t === 'number') {
601
- rec.first = rec.first === null ? entry.t : Math.min(rec.first, entry.t);
602
- rec.last = rec.last === null ? entry.t : Math.max(rec.last, entry.t);
603
- }
604
- perLang.set(code, rec);
605
- }
606
- const facets = [];
607
- for (const code of [...perLang.keys()].sort()) {
608
- const rec = perLang.get(code);
609
- if (rec.count < MIN_LANGUAGE_ENTRIES) continue; // §4 gate
610
- const name = LANGUAGE_NAMES[rec.key] || rec.key;
611
- const facet = makeFacet(
612
- 'language',
613
- rec.key,
614
- `writes durably in ${name} (${rec.key}), so reply in ${name} unless asked otherwise`,
615
- ctx.citable(rec.ids),
616
- rec.count >= 10 ? 0.8 : 0.7,
617
- rec.first,
618
- rec.last,
619
- );
620
- if (facet) facets.push(facet);
621
- }
622
- // Most evidence wins the slice, ties by code asc — `orderFacets` re-sorts the
623
- // final list, so this only decides which languages survive the per-class cap.
624
- facets.sort((a, b) => (b.sources.length - a.sources.length) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
625
- return facets.slice(0, MAX_LANGUAGE);
626
- }
627
-
628
- /** `codebase` — paths in entries that were recalled and kept, ≥2 in 30 days. */
629
- function foldCodebase(ctx) {
630
- const recalled = new Set();
631
- for (const row of ctx.ledger) {
632
- if (row.ref && RECALL_KINDS.includes(row.kind)) recalled.add(row.ref);
633
- }
634
- const perPath = new Map();
635
- for (const entry of ctx.entries) {
636
- if (ctx.negative.has(entry.id)) continue;
637
- if (!recalled.has(entry.id)) continue; // "recalled and kept", not merely mentioned
638
- for (const path of pathsIn(entry.text)) {
639
- const rec = perPath.get(path) || { key: path, ids: new Set(), recent: new Set(), first: null, last: null };
640
- rec.ids.add(entry.id);
641
- if (typeof entry.t === 'number' && ctx.now - entry.t <= RECENT_DAYS * DAY_MS && entry.t <= ctx.now) {
642
- rec.recent.add(entry.id);
643
- }
644
- if (typeof entry.t === 'number') {
645
- rec.first = rec.first === null ? entry.t : Math.min(rec.first, entry.t);
646
- rec.last = rec.last === null ? entry.t : Math.max(rec.last, entry.t);
647
- }
648
- perPath.set(path, rec);
649
- }
650
- }
651
- const facets = [];
652
- for (const key of [...perPath.keys()].sort()) {
653
- const rec = perPath.get(key);
654
- if (rec.recent.size < MIN_CODEBASE_ENTRIES) continue; // §4 gate: ≥2 recent
655
- const facet = makeFacet(
656
- 'codebase',
657
- rec.key,
658
- `works in ${rec.key} (${rec.recent.size} entries touched in the last ${RECENT_DAYS} days)`,
659
- ctx.citable(rec.ids),
660
- rec.recent.size >= 4 ? 0.75 : 0.6,
661
- rec.first,
662
- rec.last,
663
- );
664
- if (facet) facets.push(facet);
665
- }
666
- facets.sort((a, b) => (b.sources.length - a.sources.length) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
667
- return facets.slice(0, MAX_CODEBASE);
668
- }
669
-
670
- /** `decisions` — newest first, superseded ones dropped, always allowed. */
671
- function foldDecisions(ctx) {
672
- const isDecision = (entry) =>
673
- entry.tagged.some((tag) => DECISION_TAGS.includes(tag)) || entry.kind === 'decision';
674
- const superseded = new Set();
675
- for (const raw of asArray(ctx.rawEntries)) {
676
- const id = idOf(raw);
677
- if (!id) continue;
678
- for (const target of asArray(raw.supersedes)) {
679
- if (target != null && target !== '') superseded.add(String(target));
680
- }
681
- }
682
-
683
- /** Two decisions on one topic: the newer one wins, so only it is folded. */
684
- const topic = (entry) => {
685
- const named = entry.tagged.find((tag) => !DECISION_TAGS.includes(tag));
686
- return named || keyOf(entry.text).slice(0, 40);
687
- };
688
-
689
- const groups = new Map();
690
- for (const entry of ctx.entries) {
691
- if (ctx.negative.has(entry.id) || superseded.has(entry.id)) continue;
692
- if (!isDecision(entry)) continue;
693
- const key = topic(entry);
694
- if (!key) continue;
695
- const rec = groups.get(key) || { key, entry: null };
696
- const current = rec.entry;
697
- const newer =
698
- !current ||
699
- (entry.t == null ? -Infinity : entry.t) > (current.t == null ? -Infinity : current.t) ||
700
- ((entry.t == null ? -Infinity : entry.t) === (current.t == null ? -Infinity : current.t) && entry.id < current.id);
701
- if (newer) rec.entry = entry;
702
- groups.set(key, rec);
703
- }
704
-
705
- const facets = [];
706
- for (const key of [...groups.keys()].sort()) {
707
- const { entry } = groups.get(key);
708
- const facet = makeFacet('decisions', key, entry.text, ctx.citable([entry.id]), 0.8, entry.t, entry.t);
709
- if (facet) facets.push(facet);
710
- }
711
- return facets.slice(0, MAX_DECISIONS);
712
- }
713
-
714
- /** `openThreads` — entries recalled in a session that is no longer the current one. */
715
- function foldOpenThreads(ctx) {
716
- const withSession = ctx.ledger.filter((row) => row.session && row.ref && RECALL_KINDS.includes(row.kind));
717
- if (!withSession.length) return []; // no silence: no sessions, no threads
718
- // "Current" is the newest session the ledger mentions. Deterministic: session
719
- // ids are compared as strings, and only their ordering matters here.
720
- let current = '';
721
- for (const row of withSession) if (row.session > current) current = row.session;
722
- if (!current) return [];
723
-
724
- const threads = new Map();
725
- for (const row of withSession) {
726
- if (row.session === current) continue; // answered/referenced since — not open
727
- const entry = ctx.byId.get(row.ref);
728
- if (!entry || ctx.negative.has(entry.id)) continue;
729
- const rec = threads.get(entry.id) || { entry, count: 0, t: null };
730
- rec.count += 1;
731
- if (typeof row.t === 'number') rec.t = rec.t === null ? row.t : Math.max(rec.t, row.t);
732
- threads.set(entry.id, rec);
733
- }
734
- const recs = [...threads.values()].sort((a, b) => {
735
- const at = a.t == null ? -Infinity : a.t;
736
- const bt = b.t == null ? -Infinity : b.t;
737
- if (bt !== at) return bt - at;
738
- return a.entry.id < b.entry.id ? -1 : 1;
739
- });
740
- const facets = [];
741
- for (const rec of recs.slice(0, MAX_OPEN_THREADS)) {
742
- const facet = makeFacet(
743
- 'openThreads',
744
- rec.entry.id,
745
- `left open: ${rec.entry.text}`,
746
- ctx.citable([rec.entry.id]),
747
- 0.5,
748
- rec.entry.t,
749
- rec.t != null ? rec.t : rec.entry.t,
750
- );
751
- if (facet) facets.push(facet);
752
- }
753
- return facets;
754
- }
755
-
756
- /** `doNotRepeat` — negatives, honoured at a single observation. */
757
- function foldDoNotRepeat(ctx) {
758
- const hits = new Map();
759
- const add = (entry, label, t) => {
760
- if (!entry) return;
761
- const rec = hits.get(entry.id) || { entry, labels: new Set(), t: null };
762
- if (label) rec.labels.add(keyOf(label));
763
- if (typeof t === 'number') rec.t = rec.t === null ? t : Math.max(rec.t, t);
764
- hits.set(entry.id, rec);
765
- };
766
-
767
- for (const row of ctx.ledger) {
768
- if (!NEGATIVE_KINDS.includes(row.kind) || !row.ref) continue;
769
- add(ctx.byId.get(row.ref), null, row.t);
770
- }
771
- for (const corr of ctx.corrections) {
772
- if (!corr.negative) continue;
773
- // A negative with no entry to cite is not folded: every claim has to be
774
- // showable and deletable (§4), and an uncitable one is neither.
775
- if (corr.ref) add(ctx.byId.get(corr.ref), corr.term || corr.insteadOf, corr.t);
776
- }
777
- for (const entry of ctx.entries) {
778
- if (entry.tagged.some((tag) => NEGATIVE_TAGS.includes(tag))) add(entry, entry.tagged.find((t) => NEGATIVE_TAGS.includes(t)));
779
- }
780
-
781
- const facets = [];
782
- for (const id of [...hits.keys()].sort()) {
783
- const rec = hits.get(id);
784
- const label = [...rec.labels].sort()[0] || null;
785
- const value = label
786
- ? `never repeat "${label}" — the holder removed or contradicted it`
787
- : `never repeat: ${rec.entry.text}`;
788
- const facet = makeFacet('doNotRepeat', rec.entry.id, value, ctx.citable([rec.entry.id]), 0.95, rec.t != null ? rec.t : rec.entry.t, rec.t != null ? rec.t : rec.entry.t);
789
- if (facet) facets.push(facet);
790
- }
791
- return facets.slice(0, MAX_DO_NOT_REPEAT);
792
- }
793
-
794
- /** `toneCalibration` — how far the holder moves what the avatar proposed. */
795
- function foldToneCalibration(ctx) {
796
- const samples = ctx.corrections.filter((corr) => corr.proposed.trim() && corr.kept.trim());
797
- if (samples.length < MIN_TONE_SAMPLES) return []; // §4 gate: register stands unchanged
798
- let distance = 0;
799
- let ratio = 0;
800
- let first = null;
801
- let last = null;
802
- for (const sample of samples) {
803
- const a = clean(sample.proposed, 400);
804
- const b = clean(sample.kept, 400);
805
- distance += a.length ? editDistance(a, b, 400) / Math.max(a.length, 1) : 0;
806
- ratio += b.length / Math.max(a.length, 1);
807
- if (typeof sample.t === 'number') {
808
- first = first === null ? sample.t : Math.min(first, sample.t);
809
- last = last === null ? sample.t : Math.max(last, sample.t);
810
- }
811
- }
812
- const meanDistance = distance / samples.length;
813
- const meanRatio = ratio / samples.length;
814
- const pct = Math.round(meanDistance * 100);
815
- const lengthPct = Math.round(Math.abs(1 - meanRatio) * 100);
816
- const direction = meanRatio < 0.9 ? 'shorter' : meanRatio > 1.1 ? 'longer' : 'about the same length as';
817
- // The correction rows ARE the sources here, so the facet cites the entries the
818
- // samples referenced; a sample citing no entry cannot be shown to the holder
819
- // and therefore cannot be folded (§4: every claim is deletable).
820
- const ids = ctx.citable(samples.map((s) => s.ref).filter(Boolean));
821
-
822
- const facets = [];
823
- const editFacet = makeFacet('toneCalibration', 'edit-distance', `the holder rewrites about ${pct}% of what the avatar drafts`, ids, 0.7, first, last);
824
- if (editFacet) facets.push(editFacet);
825
- const lengthFacet = makeFacet('toneCalibration', 'length', `the holder keeps answers about ${lengthPct}% ${direction} the draft`, ids, 0.65, first, last);
826
- if (lengthFacet) facets.push(lengthFacet);
827
- return facets.slice(0, MAX_TONE);
828
- }
829
-
830
- /**
831
- * The fold table. Keyed by `FACET_IDS`; the length check right below is what
832
- * makes "the namespace is closed" an invariant of the implementation rather
833
- * than a comment — adding an eighth class here without adding it to the frozen
834
- * list throws at require-time, on every machine, including CI.
835
- */
836
- const FOLDERS = Object.freeze({
837
- vocabulary: foldVocabulary,
838
- language: foldLanguage,
839
- codebase: foldCodebase,
840
- decisions: foldDecisions,
841
- openThreads: foldOpenThreads,
842
- doNotRepeat: foldDoNotRepeat,
843
- toneCalibration: foldToneCalibration,
844
- });
845
-
846
- if (Object.keys(FOLDERS).length !== FACET_IDS.length || FACET_IDS.some((id) => typeof FOLDERS[id] !== 'function')) {
847
- throw new Error('profile.js: FOLDERS and FACET_IDS disagree — the facet namespace is closed and must match exactly');
848
- }
849
-
850
- // ---------------------------------------------------------------------------
851
- // fold()
852
- // ---------------------------------------------------------------------------
853
-
854
- /**
855
- * Fold one holder's own rows into a bounded, provenance-backed facet list.
856
- *
857
- * @param {object} input
858
- * @param {string} [input.holder] the holder these rows belong to. Supplying
859
- * it is how a caller states *whose* memory this is: rows stamped for another
860
- * holder are dropped here and can therefore never be cited by a facet. The
861
- * caller always passes it (the registry's `active`); omitting it means "the caller
862
- * already scoped this input", which is why the test asserts the same property
863
- * again at the real turn-assembly seam.
864
- * @param {Array} [input.entries] memory entries for this holder, aegis1's
865
- * row shape: `{ id, content, role, tags: [], session, createdAt, … }`.
866
- * @param {Array} [input.ledger] `xp.js` ledger rows: `{ kind, ref, session, t }`.
867
- * @param {Array} [input.corrections] correction observations, see
868
- * `normalizeCorrections`.
869
- * @param {number} [input.now] the clock, passed in. Defaults to the
870
- * newest timestamp in the input, so a fixture folds without one and the module
871
- * still never reads a clock of its own.
872
- * @returns {{ holder: string|null, facets: Array, budget: { tokens: number, used: number },
873
- * coldStart: boolean, dropped: Array<{id: string, key: string, tokens: number}> }}
874
- */
875
- function fold(input) {
876
- const args = input && typeof input === 'object' ? input : {};
877
- const holder = identity.HOLDER_ID_SHAPE.test(String(args.holder || '').trim().toLowerCase())
878
- ? String(args.holder).trim().toLowerCase()
879
- : null;
880
-
881
- const entries = normalizeEntries(args.entries, holder);
882
- const ledger = normalizeLedger(args.ledger, holder);
883
- const corrections = normalizeCorrections(args.corrections, holder);
884
-
885
- // The citable set: exactly the ids that survived the holder filter. This is
886
- // the one place provenance is decided, and the plan names it as the negative
887
- // control for the isolation leg — remove the filter and the leg goes red.
888
- const knownIds = new Set(entries.map((entry) => entry.id));
889
-
890
- const stamps = [];
891
- for (const row of asArray(args.entries)) {
892
- const t = timeOf(row);
893
- if (typeof t === 'number') stamps.push(t);
894
- }
895
- for (const row of ledger) if (typeof row.t === 'number') stamps.push(row.t);
896
- const now = typeof args.now === 'number' && Number.isFinite(args.now) ? args.now : stamps.length ? Math.max(...stamps) : 0;
897
-
898
- // Entries the holder has negated. Nothing negative-derived is folded twice,
899
- // and a negative entry never also becomes a positive facet in the same pass.
900
- const negative = new Set();
901
- for (const row of ledger) if (NEGATIVE_KINDS.includes(row.kind) && row.ref) negative.add(row.ref);
902
- for (const corr of corrections) if (corr.negative && corr.ref) negative.add(corr.ref);
903
- for (const entry of entries) {
904
- if (entry.tagged.some((tag) => NEGATIVE_TAGS.includes(tag))) negative.add(entry.id);
905
- }
906
-
907
- const byId = new Map(entries.map((entry) => [entry.id, entry]));
908
- const citable = (ids) => {
909
- const out = [];
910
- for (const id of asArray(ids)) {
911
- const key = String(id);
912
- if (knownIds.has(key) && !out.includes(key)) out.push(key);
913
- }
914
- return out;
915
- };
916
-
917
- const ctx = {
918
- entries,
919
- rawEntries: args.entries,
920
- byId,
921
- citable,
922
- knownIds,
923
- ledger,
924
- corrections,
925
- negative,
926
- now,
927
- };
928
-
929
- let facets = [];
930
- for (const id of FACET_IDS) facets = facets.concat(FOLDERS[id](ctx));
931
-
932
- const ordered = orderFacets(facets).map((facet) =>
933
- Object.assign({}, facet, {
934
- // `id`/`lang` are normalisation-only fields; keep the record to the §4 shape.
935
- sources: facet.sources.filter((source) => knownIds.has(source)),
936
- })
937
- );
938
- const surviving = ordered.filter((facet) => facet.sources.length > 0);
939
- const { facets: kept, used, dropped } = applyBudget(surviving);
940
-
941
- return {
942
- holder,
943
- facets: kept,
944
- budget: { tokens: BUDGET_TOKENS, used },
945
- coldStart: surviving.length === 0,
946
- dropped,
947
- };
948
- }
949
-
950
- module.exports = {
951
- FACET_IDS,
952
- FOLDERS,
953
- BUDGET_TOKENS,
954
- MAX_VALUE_CHARS,
955
- MAX_KEY_CHARS,
956
- MAX_SOURCES,
957
- MIN_LANGUAGE_ENTRIES,
958
- MIN_CODEBASE_ENTRIES,
959
- MIN_OBSERVATIONS,
960
- MIN_TONE_SAMPLES,
961
- RECENT_DAYS,
962
- DAY_MS,
963
- CORRECTION_KIND,
964
- RECALL_KINDS,
965
- NEGATIVE_KINDS,
966
- NEGATIVE_TAGS,
967
- DECISION_TAGS,
968
- LANGUAGE_NAMES,
969
- checkFacetId,
970
- editDistance,
971
- detectLanguage,
972
- backticked,
973
- pathsIn,
974
- makeFacet,
975
- orderFacets,
976
- applyBudget,
977
- belongsTo,
978
- fold,
979
- };
3
+ "use strict";const persona=require("./persona.js"),register=require("./register.js"),identity=require("./identity.js"),FACET_IDS=Object.freeze(["vocabulary","language","codebase","decisions","openThreads","doNotRepeat","toneCalibration"]),BUDGET_TOKENS=900,MAX_VALUE_CHARS=180,MAX_KEY_CHARS=64,MAX_SOURCES=24,MAX_VOCABULARY=5,MAX_LANGUAGE=2,MAX_CODEBASE=5,MAX_DECISIONS=5,MAX_OPEN_THREADS=3,MAX_DO_NOT_REPEAT=5,MAX_TONE=2,MIN_LANGUAGE_ENTRIES=5,MIN_CODEBASE_ENTRIES=2,MIN_OBSERVATIONS=3,MIN_TONE_SAMPLES=5,RECENT_DAYS=30,DAY_MS=864e5,CORRECTION_KIND="memory.corrected",RECALL_KINDS=Object.freeze(["memory.recalled","memory.saved","memory.reinforced"]),NEGATIVE_KINDS=Object.freeze(["memory.deleted","memory.contradicted","memory.forgotten"]),NEGATIVE_TAGS=Object.freeze(["do-not-repeat","never-repeat","avoid","never"]),DECISION_TAGS=Object.freeze(["decision","decided","adr"]),MAX_CONFIDENCE=.95,MIN_CONFIDENCE=.4;function checkFacetId(e){if(!FACET_IDS.includes(e))throw new Error(`unknown facet id ${JSON.stringify(String(e))} — FACET_IDS is closed (identity plan §4)`);return e}function clean(e,t){return persona.cleanText(null==e?"":String(e),t)}function keyOf(e){return clean(e,MAX_KEY_CHARS).toLowerCase().replace(/\s+/g," ").trim()}function asArray(e){return Array.isArray(e)?e:e instanceof Set?[...e]:[]}function textOf(e){return e?"string"==typeof e.content&&e.content?e.content:"string"==typeof e.text&&e.text?e.text:"":""}function timeOf(e){if(!e||"object"!=typeof e)return null;const t=null!=e.t?e.t:null!=e.createdAt?e.createdAt:e.ts;if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim()){const e=Date.parse(t);if(Number.isFinite(e))return e}if("string"==typeof e.timestamp&&e.timestamp.trim()){const t=Date.parse(e.timestamp);if(Number.isFinite(t))return t}return null}function idOf(e){return e&&"object"==typeof e?null==e.id||""===e.id?null:String(e.id):null}function tagsOf(e){return asArray(e&&e.tags).map((e=>keyOf(e))).filter(Boolean)}function holderStamp(e){if(!e||"object"!=typeof e)return null;const t=e.holder;return"string"==typeof t&&t.trim()?t.trim().toLowerCase():null}function clampConfidence(e){const t="number"==typeof e&&Number.isFinite(e)?e:MIN_CONFIDENCE;return Math.round(100*Math.min(MAX_CONFIDENCE,Math.max(MIN_CONFIDENCE,t)))/100}function editDistance(e,t,n=400){const o=String(null==e?"":e).slice(0,n),r=String(null==t?"":t).slice(0,n);if(!o)return r.length;if(!r)return o.length;let s=new Array(r.length+1),i=new Array(r.length+1);for(let e=0;e<=r.length;e+=1)s[e]=e;for(let e=1;e<=o.length;e+=1){i[0]=e;for(let t=1;t<=r.length;t+=1){const n=o[e-1]===r[t-1]?0:1;i[t]=Math.min(s[t]+1,i[t-1]+1,s[t-1]+n)}const t=s;s=i,i=t}return s[r.length]}const SCRIPT_RANGES=Object.freeze([{code:"ja",re:/[\u3040-\u30ff]/},{code:"ko",re:/[\uac00-\ud7af]/},{code:"zh",re:/[\u4e00-\u9fff]/},{code:"ru",re:/[\u0400-\u04ff]/},{code:"ar",re:/[\u0600-\u06ff]/},{code:"he",re:/[\u0590-\u05ff]/},{code:"el",re:/[\u0370-\u03ff]/},{code:"th",re:/[\u0e00-\u0e7f]/},{code:"hi",re:/[\u0900-\u097f]/}]),STOPWORDS=Object.freeze({en:Object.freeze(["the","and","for","with","that","this","from","not","you","are","have"]),de:Object.freeze(["der","die","das","und","nicht","mit","ist","ich","auch","dass","noch"]),fr:Object.freeze(["le","la","les","des","est","pas","que","qui","dans","pour","avec"]),es:Object.freeze(["el","los","las","que","no","con","para","una","pero","como","está"]),pt:Object.freeze(["não","uma","com","para","que","está","mais","como","isso","você"]),it:Object.freeze(["il","lo","gli","che","non","con","per","una","come","anche"]),nl:Object.freeze(["het","een","niet","met","dat","zijn","voor","maar","ook","nog"])}),LANGUAGE_NAMES=Object.freeze({en:"English",de:"German",fr:"French",es:"Spanish",pt:"Portuguese",it:"Italian",nl:"Dutch",ru:"Russian",ja:"Japanese",ko:"Korean",zh:"Chinese",ar:"Arabic",he:"Hebrew",el:"Greek",th:"Thai",hi:"Hindi"}),LANGUAGE_CODE_RE=/^[a-z]{2}(?:-[a-z0-9]{2,8})?$/;function detectLanguage(e){const t=e&&(null!=e.lang?e.lang:e.language);if("string"==typeof t&&t.trim()){const e=t.trim().toLowerCase();if(LANGUAGE_CODE_RE.test(e))return e.split("-")[0]}const n=textOf(e);if(!n)return"und";for(const{code:e,re:t}of SCRIPT_RANGES)if(t.test(n))return e;const o=n.toLowerCase().split(/[^\p{L}\p{N}'-]+/u).filter(Boolean);if(!o.length)return"und";const r=new Set(o);let s="und",i=0,c=0;for(const e of Object.keys(STOPWORDS)){let t=0;for(const n of STOPWORDS[e])r.has(n)&&(t+=1);"en"!==e?(t>i||t===i&&t>0&&e<s)&&(s=e,i=t):c=t}return i>=2&&i>c?s:c>0?"en":"und"}function makeFacet(e,t,n,o,r,s,i){checkFacetId(e);const c=keyOf(t),a=clean(n,MAX_VALUE_CHARS),l=asArray(o).map((e=>String(e))).filter(Boolean);if(!c||!a||!l.length)return null;const f=l.slice().sort().slice(0,MAX_SOURCES),u=["number"==typeof s&&Number.isFinite(s)?s:null,"number"==typeof i&&Number.isFinite(i)?i:null].filter((e=>null!==e));return{id:e,key:c,value:a,tokens:register.estimateTokens(c)+register.estimateTokens(a),sources:f,confidence:clampConfidence(r),firstSeen:u.length?Math.min(...u):0,lastSeen:u.length?Math.max(...u):0}}function orderFacets(e){return asArray(e).map((e=>(checkFacetId(e.id),e))).sort(((e,t)=>t.confidence!==e.confidence?t.confidence-e.confidence:t.lastSeen!==e.lastSeen?t.lastSeen-e.lastSeen:e.id!==t.id?e.id<t.id?-1:1:e.key!==t.key?e.key<t.key?-1:1:0))}function applyBudget(e,t=BUDGET_TOKENS){const n=[],o=[];let r=0;for(const s of asArray(e))r+s.tokens<=t?(n.push(s),r+=s.tokens):o.push({id:s.id,key:s.key,tokens:s.tokens});return{facets:n,used:r,dropped:o}}function belongsTo(e,t){if(!t)return!0;const n=holderStamp(e);return!n||n===t}function normalizeEntries(e,t){const n=[];for(const o of asArray(e)){if(!o||"object"!=typeof o)continue;if(!belongsTo(o,t))continue;const e=idOf(o);if(!e)continue;const r=textOf(o);if(!r)continue;const s=timeOf(o);n.push({id:e,text:r,t:s,tagged:tagsOf(o),kind:clean(o.kind,24).toLowerCase(),lang:clean(null!=o.lang?o.lang:o.language,8).toLowerCase(),role:clean(o.role,16).toLowerCase(),source:clean(o.source,40),session:clean(o.session,64),holder:holderStamp(o)})}return n}function normalizeLedger(e,t){const n=[];for(const o of asArray(e)){if(!o||"object"!=typeof o)continue;if(!belongsTo(o,t))continue;const e="string"==typeof o.kind?o.kind:"";e&&n.push({kind:e,ref:null==o.ref||""===o.ref?null:String(o.ref),session:clean(o.session,64),t:timeOf(o)})}return n}function normalizeCorrections(e,t){const n=[];for(const o of asArray(e))o&&"object"==typeof o&&belongsTo(o,t)&&n.push({ref:null==o.ref&&null==o.entryId?null:String(null!=o.ref?o.ref:o.entryId),term:clean(null!=o.term?o.term:o.from,MAX_KEY_CHARS),insteadOf:clean(null!=o.insteadOf?o.insteadOf:o.was,MAX_KEY_CHARS),proposed:null==o.proposed?"":String(o.proposed),kept:null==o.kept?"":String(o.kept),negative:!0===o.negative||!0===o.removed||!0===o.deleted,t:timeOf(o)});return n}function backticked(e){const t=[],n=/`([^`\n]{1,48})`/g;let o=n.exec(e);for(;o;){const r=keyOf(o[1]);r&&t.push(r),o=n.exec(e)}return t}const PATH_RE=/(?:^|[\s("'`\[])((?:[\w.@-]+\/)+[\w.@-]+|[\w.@-]+\.(?:js|mjs|cjs|ts|tsx|jsx|py|json|jsonl|md|yml|yaml|sh|rs|go|java|rb|toml|css|html))/g;function pathsIn(e){const t=[];let n=PATH_RE.exec(e);for(;n;){const o=keyOf(n[1]).replace(/[.,;:]+$/,"");o&&t.push(o),n=PATH_RE.exec(e)}return PATH_RE.lastIndex=0,t}function foldVocabulary(e){const t=new Map,n=(e,{entryId:n,t:o,corrected:r,insteadOf:s})=>{const i=keyOf(e);if(!i||i.length<2)return;const c=t.get(i)||{key:i,ids:new Set,corrections:0,observations:0,first:null,last:null,insteadOf:null};n&&c.ids.add(n),r?(c.corrections+=1,s&&(c.insteadOf=keyOf(s))):c.observations+=1,"number"==typeof o&&(c.first=null===c.first?o:Math.min(c.first,o),c.last=null===c.last?o:Math.max(c.last,o)),t.set(i,c)},o=new Set;for(const t of e.ledger)t.kind===CORRECTION_KIND&&t.ref&&o.add(t.ref);for(const t of e.corrections){if(t.negative||!t.term)continue;const o=t.ref?e.byId.get(t.ref):null;n(t.term,{entryId:o?o.id:null,t:null!=t.t?t.t:o?o.t:null,corrected:!0,insteadOf:t.insteadOf})}for(const t of o){const o=e.byId.get(String(t));if(o)for(const e of backticked(o.text))n(e,{entryId:o.id,t:o.t,corrected:!0})}for(const t of e.entries)if(!e.negative.has(t.id))for(const e of backticked(t.text))n(e,{entryId:t.id,t:t.t,corrected:!1});const r=[],s=[...t.keys()].sort();for(const n of s){const o=t.get(n);if(!o.corrections&&o.observations<3)continue;const s=e.citable(o.ids),i=o.corrections?.75+Math.min(.15,.05*(o.corrections-1)):.6,c=o.insteadOf?`calls it "${o.key}", not "${o.insteadOf}"`:`calls it "${o.key}"`,a=makeFacet("vocabulary",o.key,c,s,i,o.first,o.last);a&&r.push(a)}return r.slice(0,5)}function foldLanguage(e){const t=new Map;for(const n of e.entries){if(e.negative.has(n.id))continue;if(n.role&&"user"!==n.role)continue;const o=detectLanguage({content:n.text,lang:n.lang});if("und"===o||"en"===o)continue;const r=t.get(o)||{key:o,ids:new Set,first:null,last:null,count:0};r.ids.add(n.id),r.count+=1,"number"==typeof n.t&&(r.first=null===r.first?n.t:Math.min(r.first,n.t),r.last=null===r.last?n.t:Math.max(r.last,n.t)),t.set(o,r)}const n=[];for(const o of[...t.keys()].sort()){const r=t.get(o);if(r.count<5)continue;const s=LANGUAGE_NAMES[r.key]||r.key,i=makeFacet("language",r.key,`writes durably in ${s} (${r.key}), so reply in ${s} unless asked otherwise`,e.citable(r.ids),r.count>=10?.8:.7,r.first,r.last);i&&n.push(i)}return n.sort(((e,t)=>t.sources.length-e.sources.length||(e.key<t.key?-1:e.key>t.key?1:0))),n.slice(0,2)}function foldCodebase(e){const t=new Set;for(const n of e.ledger)n.ref&&RECALL_KINDS.includes(n.kind)&&t.add(n.ref);const n=new Map;for(const o of e.entries)if(!e.negative.has(o.id)&&t.has(o.id))for(const t of pathsIn(o.text)){const r=n.get(t)||{key:t,ids:new Set,recent:new Set,first:null,last:null};r.ids.add(o.id),"number"==typeof o.t&&e.now-o.t<=30*DAY_MS&&o.t<=e.now&&r.recent.add(o.id),"number"==typeof o.t&&(r.first=null===r.first?o.t:Math.min(r.first,o.t),r.last=null===r.last?o.t:Math.max(r.last,o.t)),n.set(t,r)}const o=[];for(const t of[...n.keys()].sort()){const r=n.get(t);if(r.recent.size<2)continue;const s=makeFacet("codebase",r.key,`works in ${r.key} (${r.recent.size} entries touched in the last 30 days)`,e.citable(r.ids),r.recent.size>=4?.75:.6,r.first,r.last);s&&o.push(s)}return o.sort(((e,t)=>t.sources.length-e.sources.length||(e.key<t.key?-1:e.key>t.key?1:0))),o.slice(0,5)}function foldDecisions(e){const t=e=>e.tagged.some((e=>DECISION_TAGS.includes(e)))||"decision"===e.kind,n=new Set;for(const t of asArray(e.rawEntries))if(idOf(t))for(const e of asArray(t.supersedes))null!=e&&""!==e&&n.add(String(e));const o=e=>e.tagged.find((e=>!DECISION_TAGS.includes(e)))||keyOf(e.text).slice(0,40),r=new Map;for(const s of e.entries){if(e.negative.has(s.id)||n.has(s.id))continue;if(!t(s))continue;const i=o(s);if(!i)continue;const c=r.get(i)||{key:i,entry:null},a=c.entry;(!a||(null==s.t?-1/0:s.t)>(null==a.t?-1/0:a.t)||(null==s.t?-1/0:s.t)===(null==a.t?-1/0:a.t)&&s.id<a.id)&&(c.entry=s),r.set(i,c)}const s=[];for(const t of[...r.keys()].sort()){const{entry:n}=r.get(t),o=makeFacet("decisions",t,n.text,e.citable([n.id]),.8,n.t,n.t);o&&s.push(o)}return s.slice(0,5)}function foldOpenThreads(e){const t=e.ledger.filter((e=>e.session&&e.ref&&RECALL_KINDS.includes(e.kind)));if(!t.length)return[];let n="";for(const e of t)e.session>n&&(n=e.session);if(!n)return[];const o=new Map;for(const r of t){if(r.session===n)continue;const t=e.byId.get(r.ref);if(!t||e.negative.has(t.id))continue;const s=o.get(t.id)||{entry:t,count:0,t:null};s.count+=1,"number"==typeof r.t&&(s.t=null===s.t?r.t:Math.max(s.t,r.t)),o.set(t.id,s)}const r=[...o.values()].sort(((e,t)=>{const n=null==e.t?-1/0:e.t,o=null==t.t?-1/0:t.t;return o!==n?o-n:e.entry.id<t.entry.id?-1:1})),s=[];for(const t of r.slice(0,3)){const n=makeFacet("openThreads",t.entry.id,`left open: ${t.entry.text}`,e.citable([t.entry.id]),.5,t.entry.t,null!=t.t?t.t:t.entry.t);n&&s.push(n)}return s}function foldDoNotRepeat(e){const t=new Map,n=(e,n,o)=>{if(!e)return;const r=t.get(e.id)||{entry:e,labels:new Set,t:null};n&&r.labels.add(keyOf(n)),"number"==typeof o&&(r.t=null===r.t?o:Math.max(r.t,o)),t.set(e.id,r)};for(const t of e.ledger)NEGATIVE_KINDS.includes(t.kind)&&t.ref&&n(e.byId.get(t.ref),null,t.t);for(const t of e.corrections)t.negative&&t.ref&&n(e.byId.get(t.ref),t.term||t.insteadOf,t.t);for(const t of e.entries)t.tagged.some((e=>NEGATIVE_TAGS.includes(e)))&&n(t,t.tagged.find((e=>NEGATIVE_TAGS.includes(e))));const o=[];for(const n of[...t.keys()].sort()){const r=t.get(n),s=[...r.labels].sort()[0]||null,i=s?`never repeat "${s}" — the holder removed or contradicted it`:`never repeat: ${r.entry.text}`,c=makeFacet("doNotRepeat",r.entry.id,i,e.citable([r.entry.id]),.95,null!=r.t?r.t:r.entry.t,null!=r.t?r.t:r.entry.t);c&&o.push(c)}return o.slice(0,5)}function foldToneCalibration(e){const t=e.corrections.filter((e=>e.proposed.trim()&&e.kept.trim()));if(t.length<5)return[];let n=0,o=0,r=null,s=null;for(const e of t){const t=clean(e.proposed,400),i=clean(e.kept,400);n+=t.length?editDistance(t,i,400)/Math.max(t.length,1):0,o+=i.length/Math.max(t.length,1),"number"==typeof e.t&&(r=null===r?e.t:Math.min(r,e.t),s=null===s?e.t:Math.max(s,e.t))}const i=n/t.length,c=o/t.length,a=Math.round(100*i),l=Math.round(100*Math.abs(1-c)),f=c<.9?"shorter":c>1.1?"longer":"about the same length as",u=e.citable(t.map((e=>e.ref)).filter(Boolean)),d=[],g=makeFacet("toneCalibration","edit-distance",`the holder rewrites about ${a}% of what the avatar drafts`,u,.7,r,s);g&&d.push(g);const h=makeFacet("toneCalibration","length",`the holder keeps answers about ${l}% ${f} the draft`,u,.65,r,s);return h&&d.push(h),d.slice(0,2)}const FOLDERS=Object.freeze({vocabulary:foldVocabulary,language:foldLanguage,codebase:foldCodebase,decisions:foldDecisions,openThreads:foldOpenThreads,doNotRepeat:foldDoNotRepeat,toneCalibration:foldToneCalibration});if(Object.keys(FOLDERS).length!==FACET_IDS.length||FACET_IDS.some((e=>"function"!=typeof FOLDERS[e])))throw new Error("profile.js: FOLDERS and FACET_IDS disagree — the facet namespace is closed and must match exactly");function fold(e){const t=e&&"object"==typeof e?e:{},n=identity.HOLDER_ID_SHAPE.test(String(t.holder||"").trim().toLowerCase())?String(t.holder).trim().toLowerCase():null,o=normalizeEntries(t.entries,n),r=normalizeLedger(t.ledger,n),s=normalizeCorrections(t.corrections,n),i=new Set(o.map((e=>e.id))),c=[];for(const e of asArray(t.entries)){const t=timeOf(e);"number"==typeof t&&c.push(t)}for(const e of r)"number"==typeof e.t&&c.push(e.t);const a="number"==typeof t.now&&Number.isFinite(t.now)?t.now:c.length?Math.max(...c):0,l=new Set;for(const e of r)NEGATIVE_KINDS.includes(e.kind)&&e.ref&&l.add(e.ref);for(const e of s)e.negative&&e.ref&&l.add(e.ref);for(const e of o)e.tagged.some((e=>NEGATIVE_TAGS.includes(e)))&&l.add(e.id);const f=new Map(o.map((e=>[e.id,e]))),u={entries:o,rawEntries:t.entries,byId:f,citable:e=>{const t=[];for(const n of asArray(e)){const e=String(n);i.has(e)&&!t.includes(e)&&t.push(e)}return t},knownIds:i,ledger:r,corrections:s,negative:l,now:a};let d=[];for(const e of FACET_IDS)d=d.concat(FOLDERS[e](u));const g=orderFacets(d).map((e=>Object.assign({},e,{sources:e.sources.filter((e=>i.has(e)))}))).filter((e=>e.sources.length>0)),{facets:h,used:y,dropped:E}=applyBudget(g);return{holder:n,facets:h,budget:{tokens:BUDGET_TOKENS,used:y},coldStart:0===g.length,dropped:E}}module.exports={FACET_IDS:FACET_IDS,FOLDERS:FOLDERS,BUDGET_TOKENS:BUDGET_TOKENS,MAX_VALUE_CHARS:MAX_VALUE_CHARS,MAX_KEY_CHARS:MAX_KEY_CHARS,MAX_SOURCES:MAX_SOURCES,MIN_LANGUAGE_ENTRIES:5,MIN_CODEBASE_ENTRIES:2,MIN_OBSERVATIONS:3,MIN_TONE_SAMPLES:5,RECENT_DAYS:30,DAY_MS:DAY_MS,CORRECTION_KIND:CORRECTION_KIND,RECALL_KINDS:RECALL_KINDS,NEGATIVE_KINDS:NEGATIVE_KINDS,NEGATIVE_TAGS:NEGATIVE_TAGS,DECISION_TAGS:DECISION_TAGS,LANGUAGE_NAMES:LANGUAGE_NAMES,checkFacetId:checkFacetId,editDistance:editDistance,detectLanguage:detectLanguage,backticked:backticked,pathsIn:pathsIn,makeFacet:makeFacet,orderFacets:orderFacets,applyBudget:applyBudget,belongsTo:belongsTo,fold:fold};