anno-extension 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 (199) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +30 -0
  3. package/THIRD_PARTY_NOTICES.md +8 -0
  4. package/dist/browser-fs.d.ts +14 -0
  5. package/dist/browser-fs.d.ts.map +1 -0
  6. package/dist/browser-fs.js +69 -0
  7. package/dist/browser-fs.js.map +1 -0
  8. package/dist/config.d.ts +81 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +82 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/consolidate-v2.d.ts +15 -0
  13. package/dist/consolidate-v2.d.ts.map +1 -0
  14. package/dist/consolidate-v2.js +125 -0
  15. package/dist/consolidate-v2.js.map +1 -0
  16. package/dist/consolidation.d.ts +12 -0
  17. package/dist/consolidation.d.ts.map +1 -0
  18. package/dist/consolidation.js +199 -0
  19. package/dist/consolidation.js.map +1 -0
  20. package/dist/dedup.d.ts +18 -0
  21. package/dist/dedup.d.ts.map +1 -0
  22. package/dist/dedup.js +85 -0
  23. package/dist/dedup.js.map +1 -0
  24. package/dist/diagnostics.d.ts +24 -0
  25. package/dist/diagnostics.d.ts.map +1 -0
  26. package/dist/diagnostics.js +53 -0
  27. package/dist/diagnostics.js.map +1 -0
  28. package/dist/embedding-index.d.ts +27 -0
  29. package/dist/embedding-index.d.ts.map +1 -0
  30. package/dist/embedding-index.js +111 -0
  31. package/dist/embedding-index.js.map +1 -0
  32. package/dist/engine-archive.d.ts +37 -0
  33. package/dist/engine-archive.d.ts.map +1 -0
  34. package/dist/engine-archive.js +155 -0
  35. package/dist/engine-archive.js.map +1 -0
  36. package/dist/engine-episode-sync.d.ts +19 -0
  37. package/dist/engine-episode-sync.d.ts.map +1 -0
  38. package/dist/engine-episode-sync.js +186 -0
  39. package/dist/engine-episode-sync.js.map +1 -0
  40. package/dist/engine-injection-text.d.ts +46 -0
  41. package/dist/engine-injection-text.d.ts.map +1 -0
  42. package/dist/engine-injection-text.js +271 -0
  43. package/dist/engine-injection-text.js.map +1 -0
  44. package/dist/engine-insights.d.ts +22 -0
  45. package/dist/engine-insights.d.ts.map +1 -0
  46. package/dist/engine-insights.js +127 -0
  47. package/dist/engine-insights.js.map +1 -0
  48. package/dist/engine-links.d.ts +43 -0
  49. package/dist/engine-links.d.ts.map +1 -0
  50. package/dist/engine-links.js +223 -0
  51. package/dist/engine-links.js.map +1 -0
  52. package/dist/engine-recall-select.d.ts +84 -0
  53. package/dist/engine-recall-select.d.ts.map +1 -0
  54. package/dist/engine-recall-select.js +127 -0
  55. package/dist/engine-recall-select.js.map +1 -0
  56. package/dist/engine-reinforce.d.ts +18 -0
  57. package/dist/engine-reinforce.d.ts.map +1 -0
  58. package/dist/engine-reinforce.js +116 -0
  59. package/dist/engine-reinforce.js.map +1 -0
  60. package/dist/engine-scoring-v2.d.ts +35 -0
  61. package/dist/engine-scoring-v2.d.ts.map +1 -0
  62. package/dist/engine-scoring-v2.js +178 -0
  63. package/dist/engine-scoring-v2.js.map +1 -0
  64. package/dist/engine-v2-mapping.d.ts +17 -0
  65. package/dist/engine-v2-mapping.d.ts.map +1 -0
  66. package/dist/engine-v2-mapping.js +190 -0
  67. package/dist/engine-v2-mapping.js.map +1 -0
  68. package/dist/engine.d.ts +339 -0
  69. package/dist/engine.d.ts.map +1 -0
  70. package/dist/engine.js +1964 -0
  71. package/dist/engine.js.map +1 -0
  72. package/dist/eviction.d.ts +14 -0
  73. package/dist/eviction.d.ts.map +1 -0
  74. package/dist/eviction.js +26 -0
  75. package/dist/eviction.js.map +1 -0
  76. package/dist/extraction.d.ts +11 -0
  77. package/dist/extraction.d.ts.map +1 -0
  78. package/dist/extraction.js +261 -0
  79. package/dist/extraction.js.map +1 -0
  80. package/dist/full-insights-html.d.ts +9 -0
  81. package/dist/full-insights-html.d.ts.map +1 -0
  82. package/dist/full-insights-html.js +422 -0
  83. package/dist/full-insights-html.js.map +1 -0
  84. package/dist/full-insights-sections.d.ts +48 -0
  85. package/dist/full-insights-sections.d.ts.map +1 -0
  86. package/dist/full-insights-sections.js +231 -0
  87. package/dist/full-insights-sections.js.map +1 -0
  88. package/dist/full-insights.d.ts +22 -0
  89. package/dist/full-insights.d.ts.map +1 -0
  90. package/dist/full-insights.js +370 -0
  91. package/dist/full-insights.js.map +1 -0
  92. package/dist/hash-embedding.d.ts +9 -0
  93. package/dist/hash-embedding.d.ts.map +1 -0
  94. package/dist/hash-embedding.js +44 -0
  95. package/dist/hash-embedding.js.map +1 -0
  96. package/dist/human-insights.d.ts +28 -0
  97. package/dist/human-insights.d.ts.map +1 -0
  98. package/dist/human-insights.js +260 -0
  99. package/dist/human-insights.js.map +1 -0
  100. package/dist/i18n.d.ts +64 -0
  101. package/dist/i18n.d.ts.map +1 -0
  102. package/dist/i18n.js +367 -0
  103. package/dist/i18n.js.map +1 -0
  104. package/dist/index.d.ts +27 -0
  105. package/dist/index.d.ts.map +1 -0
  106. package/dist/index.js +21 -0
  107. package/dist/index.js.map +1 -0
  108. package/dist/insights-html.d.ts +9 -0
  109. package/dist/insights-html.d.ts.map +1 -0
  110. package/dist/insights-html.js +432 -0
  111. package/dist/insights-html.js.map +1 -0
  112. package/dist/linking.d.ts +22 -0
  113. package/dist/linking.d.ts.map +1 -0
  114. package/dist/linking.js +192 -0
  115. package/dist/linking.js.map +1 -0
  116. package/dist/llm-json.d.ts +10 -0
  117. package/dist/llm-json.d.ts.map +1 -0
  118. package/dist/llm-json.js +193 -0
  119. package/dist/llm-json.js.map +1 -0
  120. package/dist/privacy.d.ts +17 -0
  121. package/dist/privacy.d.ts.map +1 -0
  122. package/dist/privacy.js +53 -0
  123. package/dist/privacy.js.map +1 -0
  124. package/dist/procedural-v2.d.ts +9 -0
  125. package/dist/procedural-v2.d.ts.map +1 -0
  126. package/dist/procedural-v2.js +123 -0
  127. package/dist/procedural-v2.js.map +1 -0
  128. package/dist/reconsolidate-v2.d.ts +19 -0
  129. package/dist/reconsolidate-v2.d.ts.map +1 -0
  130. package/dist/reconsolidate-v2.js +115 -0
  131. package/dist/reconsolidate-v2.js.map +1 -0
  132. package/dist/scoring.d.ts +32 -0
  133. package/dist/scoring.d.ts.map +1 -0
  134. package/dist/scoring.js +108 -0
  135. package/dist/scoring.js.map +1 -0
  136. package/dist/store-v2.d.ts +35 -0
  137. package/dist/store-v2.d.ts.map +1 -0
  138. package/dist/store-v2.js +98 -0
  139. package/dist/store-v2.js.map +1 -0
  140. package/dist/store.d.ts +22 -0
  141. package/dist/store.d.ts.map +1 -0
  142. package/dist/store.js +116 -0
  143. package/dist/store.js.map +1 -0
  144. package/dist/turn-context.d.ts +37 -0
  145. package/dist/turn-context.d.ts.map +1 -0
  146. package/dist/turn-context.js +31 -0
  147. package/dist/turn-context.js.map +1 -0
  148. package/dist/types-v2.d.ts +190 -0
  149. package/dist/types-v2.d.ts.map +1 -0
  150. package/dist/types-v2.js +8 -0
  151. package/dist/types-v2.js.map +1 -0
  152. package/dist/types.d.ts +330 -0
  153. package/dist/types.d.ts.map +1 -0
  154. package/dist/types.js +8 -0
  155. package/dist/types.js.map +1 -0
  156. package/dist/update.d.ts +31 -0
  157. package/dist/update.d.ts.map +1 -0
  158. package/dist/update.js +250 -0
  159. package/dist/update.js.map +1 -0
  160. package/package.json +34 -0
  161. package/src/browser-fs.ts +67 -0
  162. package/src/config.ts +138 -0
  163. package/src/consolidate-v2.ts +158 -0
  164. package/src/consolidation.ts +229 -0
  165. package/src/dedup.ts +91 -0
  166. package/src/diagnostics.ts +81 -0
  167. package/src/embedding-index.ts +138 -0
  168. package/src/engine-archive.ts +167 -0
  169. package/src/engine-episode-sync.ts +237 -0
  170. package/src/engine-injection-text.ts +334 -0
  171. package/src/engine-insights.ts +182 -0
  172. package/src/engine-links.ts +311 -0
  173. package/src/engine-recall-select.ts +298 -0
  174. package/src/engine-reinforce.ts +154 -0
  175. package/src/engine-scoring-v2.ts +188 -0
  176. package/src/engine-v2-mapping.ts +204 -0
  177. package/src/engine.ts +2499 -0
  178. package/src/eviction.ts +38 -0
  179. package/src/extraction.ts +300 -0
  180. package/src/full-insights-html.ts +474 -0
  181. package/src/full-insights-sections.ts +305 -0
  182. package/src/full-insights.ts +423 -0
  183. package/src/hash-embedding.ts +48 -0
  184. package/src/human-insights.ts +345 -0
  185. package/src/i18n.ts +455 -0
  186. package/src/index.ts +117 -0
  187. package/src/insights-html.ts +478 -0
  188. package/src/linking.ts +228 -0
  189. package/src/llm-json.ts +194 -0
  190. package/src/privacy.ts +54 -0
  191. package/src/procedural-v2.ts +142 -0
  192. package/src/reconsolidate-v2.ts +145 -0
  193. package/src/scoring.ts +156 -0
  194. package/src/store-v2.ts +138 -0
  195. package/src/store.ts +137 -0
  196. package/src/turn-context.ts +56 -0
  197. package/src/types-v2.ts +244 -0
  198. package/src/types.ts +372 -0
  199. package/src/update.ts +271 -0
@@ -0,0 +1,167 @@
1
+ /**
2
+ * [WHO]: Provides mergeArchivedEntries/Work/V2, partitionArchivedEntries/Work/Semantic/Procedural, get*ArchiveReason helpers
3
+ * [FROM]: Depends on ./scoring.js for daysSince; ./types.js, ./types-v2.js for memory types
4
+ * [TO]: Consumed by engine.ts (archiveStaleMemories, restoreArchivedEntry)
5
+ * [HERE]: packages/mem-core/src/engine-archive.ts - archive partitioning, merging, and staleness detection
6
+ */
7
+
8
+ import type { MemoryEntry, WorkEntry } from "./types.js";
9
+ import type { ProceduralMemory, SemanticMemory } from "./types-v2.js";
10
+
11
+ export interface ForgettingConfig {
12
+ ambientTtlDays: number;
13
+ workTtlDays: number;
14
+ reviveCooldownDays: number;
15
+ }
16
+
17
+ function daysBetween(iso: string, now: string): number {
18
+ return Math.max(0, (new Date(now).getTime() - new Date(iso).getTime()) / 86_400_000);
19
+ }
20
+
21
+ // ── Merge helpers ──────────────────────────────────────────
22
+
23
+ export function mergeArchivedEntries(existing: MemoryEntry[], incoming: MemoryEntry[]): MemoryEntry[] {
24
+ const merged = new Map(existing.map((entry) => [entry.id, entry]));
25
+ for (const entry of incoming) merged.set(entry.id, entry);
26
+ return [...merged.values()].sort((a, b) => (b.archivedAt ?? b.created).localeCompare(a.archivedAt ?? a.created));
27
+ }
28
+
29
+ export function mergeArchivedWork(existing: WorkEntry[], incoming: WorkEntry[]): WorkEntry[] {
30
+ const merged = new Map(existing.map((entry) => [entry.id, entry]));
31
+ for (const entry of incoming) merged.set(entry.id, entry);
32
+ return [...merged.values()].sort((a, b) => (b.archivedAt ?? b.created).localeCompare(a.archivedAt ?? a.created));
33
+ }
34
+
35
+ export function mergeArchivedV2<T extends { id: string; createdAt: string; archivedAt?: string }>(existing: T[], incoming: T[]): T[] {
36
+ const merged = new Map(existing.map((entry) => [entry.id, entry]));
37
+ for (const entry of incoming) merged.set(entry.id, entry);
38
+ return [...merged.values()].sort((a, b) => (b.archivedAt ?? b.createdAt).localeCompare(a.archivedAt ?? a.createdAt));
39
+ }
40
+
41
+ // ── Archive reason detection ───────────────────────────────
42
+
43
+ function getLegacyArchiveReason(entry: MemoryEntry, now: string, forgetting: ForgettingConfig): string | undefined {
44
+ if (entry.archivedAt) return entry.archiveReason ?? "pre-archived";
45
+ if (entry.revivedAt && daysBetween(entry.revivedAt, now) <= forgetting.reviveCooldownDays) return undefined;
46
+ const anchor = entry.lastAccessed ?? entry.eventTime ?? entry.created;
47
+ const ageDays = daysBetween(anchor, now);
48
+ const lowSignal = (entry.accessCount ?? 0) <= 1 && entry.importance <= 6 && (entry.salience ?? entry.importance) <= 6;
49
+ if (entry.retention === "ambient" && lowSignal && ageDays > forgetting.ambientTtlDays) {
50
+ return "stale-ambient-memory";
51
+ }
52
+ return undefined;
53
+ }
54
+
55
+ function getWorkArchiveReason(entry: WorkEntry, now: string, forgetting: ForgettingConfig): string | undefined {
56
+ if (entry.archivedAt) return entry.archiveReason ?? "pre-archived";
57
+ if (entry.revivedAt && daysBetween(entry.revivedAt, now) <= forgetting.reviveCooldownDays) return undefined;
58
+ const anchor = entry.lastAccessed ?? entry.eventTime ?? entry.created;
59
+ const ageDays = daysBetween(anchor, now);
60
+ if ((entry.accessCount ?? 0) <= 1 && entry.importance <= 6 && ageDays > forgetting.workTtlDays) {
61
+ return "stale-work-memory";
62
+ }
63
+ return undefined;
64
+ }
65
+
66
+ function getSemanticArchiveReason(entry: SemanticMemory, now: string, forgetting: ForgettingConfig): string | undefined {
67
+ if (entry.archivedAt) return entry.archiveReason ?? "pre-archived";
68
+ if (entry.revivedAt && daysBetween(entry.revivedAt, now) <= forgetting.reviveCooldownDays) return undefined;
69
+ const anchor = entry.lastAccessedAt ?? entry.updatedAt ?? entry.createdAt;
70
+ const ageDays = daysBetween(anchor, now);
71
+ if (entry.supersededById && ageDays > forgetting.ambientTtlDays) {
72
+ return "superseded-semantic-memory";
73
+ }
74
+ const lowSignal = (entry.accessCount ?? 0) <= 1 && entry.importance <= 6 && entry.confidence < 0.85;
75
+ if (entry.retention === "ambient" && lowSignal && ageDays > forgetting.ambientTtlDays * 2) {
76
+ return "stale-semantic-memory";
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ function getProceduralArchiveReason(entry: ProceduralMemory, now: string, forgetting: ForgettingConfig): string | undefined {
82
+ if (entry.archivedAt) return entry.archiveReason ?? "pre-archived";
83
+ if (entry.revivedAt && daysBetween(entry.revivedAt, now) <= forgetting.reviveCooldownDays) return undefined;
84
+ const anchor = entry.lastAccessedAt ?? entry.updatedAt ?? entry.createdAt;
85
+ const ageDays = daysBetween(anchor, now);
86
+ if ((entry.status === "superseded" || entry.status === "deprecated") && ageDays > forgetting.ambientTtlDays) {
87
+ return "stale-procedure-version";
88
+ }
89
+ if (entry.status === "draft" && (entry.accessCount ?? 0) <= 1 && entry.importance <= 6 && ageDays > forgetting.ambientTtlDays * 2) {
90
+ return "abandoned-draft-procedure";
91
+ }
92
+ return undefined;
93
+ }
94
+
95
+ // ── Partition helpers ──────────────────────────────────────
96
+
97
+ export function partitionArchivedEntries(entries: MemoryEntry[], now: string, forgetting: ForgettingConfig): { active: MemoryEntry[]; archived: MemoryEntry[] } {
98
+ const active: MemoryEntry[] = [];
99
+ const archived: MemoryEntry[] = [];
100
+ for (const entry of entries) {
101
+ const reason = getLegacyArchiveReason(entry, now, forgetting);
102
+ if (!reason) {
103
+ active.push(entry);
104
+ continue;
105
+ }
106
+ archived.push({
107
+ ...entry,
108
+ archivedAt: entry.archivedAt ?? now,
109
+ archiveReason: entry.archiveReason ?? reason,
110
+ });
111
+ }
112
+ return { active, archived };
113
+ }
114
+
115
+ export function partitionArchivedWork(entries: WorkEntry[], now: string, forgetting: ForgettingConfig): { active: WorkEntry[]; archived: WorkEntry[] } {
116
+ const active: WorkEntry[] = [];
117
+ const archived: WorkEntry[] = [];
118
+ for (const entry of entries) {
119
+ const reason = getWorkArchiveReason(entry, now, forgetting);
120
+ if (!reason) {
121
+ active.push(entry);
122
+ continue;
123
+ }
124
+ archived.push({
125
+ ...entry,
126
+ archivedAt: entry.archivedAt ?? now,
127
+ archiveReason: entry.archiveReason ?? reason,
128
+ });
129
+ }
130
+ return { active, archived };
131
+ }
132
+
133
+ export function partitionArchivedSemantic(entries: SemanticMemory[], now: string, forgetting: ForgettingConfig): { active: SemanticMemory[]; archived: SemanticMemory[] } {
134
+ const active: SemanticMemory[] = [];
135
+ const archived: SemanticMemory[] = [];
136
+ for (const entry of entries) {
137
+ const reason = getSemanticArchiveReason(entry, now, forgetting);
138
+ if (!reason) {
139
+ active.push(entry);
140
+ continue;
141
+ }
142
+ archived.push({
143
+ ...entry,
144
+ archivedAt: entry.archivedAt ?? now,
145
+ archiveReason: entry.archiveReason ?? reason,
146
+ });
147
+ }
148
+ return { active, archived };
149
+ }
150
+
151
+ export function partitionArchivedProcedural(entries: ProceduralMemory[], now: string, forgetting: ForgettingConfig): { active: ProceduralMemory[]; archived: ProceduralMemory[] } {
152
+ const active: ProceduralMemory[] = [];
153
+ const archived: ProceduralMemory[] = [];
154
+ for (const entry of entries) {
155
+ const reason = getProceduralArchiveReason(entry, now, forgetting);
156
+ if (!reason) {
157
+ active.push(entry);
158
+ continue;
159
+ }
160
+ archived.push({
161
+ ...entry,
162
+ archivedAt: entry.archivedAt ?? now,
163
+ archiveReason: entry.archiveReason ?? reason,
164
+ });
165
+ }
166
+ return { active, archived };
167
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * [WHO]: Provides makeEpisodeMemoryId, mapEpisodeToV2, syncEpisodeToV2
3
+ * [FROM]: Depends on ./store-v2.js for V2 I/O; ./procedural-v2.js for compileProcedureFromEpisode; ./scoring.js for extractTags; ./types.js, ./types-v2.js; ./engine-scoring-v2.js for currentStructuralAnchor
4
+ * [TO]: Consumed by engine.ts (saveEpisode, runStartupMaintenance)
5
+ * [HERE]: packages/mem-core/src/engine-episode-sync.ts - episode-to-V2 sync and mapping
6
+ */
7
+
8
+ import { currentStructuralAnchor } from "./engine-scoring-v2.js";
9
+ import { compileProcedureFromEpisode } from "./procedural-v2.js";
10
+ import { extractTags } from "./scoring.js";
11
+ import {
12
+ getV2Paths,
13
+ loadV2Episodes,
14
+ loadV2Facets,
15
+ loadV2Links,
16
+ loadV2Meta,
17
+ loadV2Procedural,
18
+ saveV2Episodes,
19
+ saveV2Facets,
20
+ saveV2Links,
21
+ saveV2Meta,
22
+ saveV2Procedural,
23
+ type NanoMemV2Paths,
24
+ } from "./store-v2.js";
25
+ import type { Episode } from "./types.js";
26
+ import type { EpisodeFacet, EpisodeMemory, FacetKind, MemoryLink } from "./types-v2.js";
27
+
28
+ export function makeEpisodeMemoryId(ep: Episode): string {
29
+ return `episode:${ep.sessionId}`;
30
+ }
31
+
32
+ export function mapEpisodeToV2(
33
+ ep: Episode,
34
+ now: string,
35
+ ): {
36
+ episode: EpisodeMemory;
37
+ facets: EpisodeFacet[];
38
+ links: MemoryLink[];
39
+ } {
40
+ const episodeId = makeEpisodeMemoryId(ep);
41
+ const baseTags = [...new Set([...(ep.tags ?? []), ...extractTags(`${ep.project} ${ep.summary} ${ep.userGoal ?? ""}`)])];
42
+ const facetDefs: Array<{
43
+ facetType: FacetKind;
44
+ searchText: string;
45
+ anchorText?: string;
46
+ summary?: string;
47
+ detail?: string;
48
+ outcomeScore?: number;
49
+ causalRole?: EpisodeFacet["causalRole"];
50
+ }> = [];
51
+
52
+ if (ep.userGoal?.trim()) {
53
+ facetDefs.push({
54
+ facetType: "goal",
55
+ searchText: ep.userGoal.trim(),
56
+ anchorText: ep.summary,
57
+ summary: `Goal: ${ep.userGoal.trim()}`,
58
+ });
59
+ }
60
+
61
+ for (const error of ep.errors.slice(0, 8)) {
62
+ if (!error.trim()) continue;
63
+ facetDefs.push({
64
+ facetType: "error",
65
+ searchText: error.trim(),
66
+ anchorText: ep.summary,
67
+ summary: `Error: ${error.trim()}`,
68
+ causalRole: "signal",
69
+ outcomeScore: Math.max(1, 6 - ep.errors.length),
70
+ });
71
+ }
72
+
73
+ for (const observation of ep.keyObservations.slice(0, 8)) {
74
+ if (!observation.trim()) continue;
75
+ facetDefs.push({
76
+ facetType: "insight",
77
+ searchText: observation.trim(),
78
+ anchorText: ep.summary,
79
+ summary: `Insight: ${observation.trim()}`,
80
+ causalRole: "resolution",
81
+ outcomeScore: Math.min(10, ep.importance),
82
+ });
83
+ }
84
+
85
+ if (ep.summary.trim()) {
86
+ facetDefs.push({
87
+ facetType: "outcome",
88
+ searchText: ep.summary.trim().slice(0, 200),
89
+ anchorText: ep.summary.trim(),
90
+ summary: ep.summary.trim(),
91
+ detail: [ep.userGoal ? `Goal: ${ep.userGoal}` : "", ep.errors.length ? `Errors: ${ep.errors.join("; ")}` : ""]
92
+ .filter(Boolean)
93
+ .join("\n"),
94
+ causalRole: ep.errors.length > 0 ? "effect" : "signal",
95
+ outcomeScore: ep.errors.length > 0 ? Math.max(3, ep.importance - 1) : ep.importance,
96
+ });
97
+ }
98
+
99
+ const facets: EpisodeFacet[] = facetDefs.map((facet, index) => {
100
+ const facetId = `${episodeId}:facet:${index + 1}`;
101
+ const facetTags = [
102
+ ...new Set([
103
+ ...baseTags,
104
+ facet.facetType,
105
+ ...extractTags(`${facet.searchText} ${facet.summary ?? ""} ${facet.anchorText ?? ""}`),
106
+ ]),
107
+ ].slice(0, 40);
108
+ return {
109
+ id: facetId,
110
+ kind: "facet" as const,
111
+ episodeId,
112
+ facetType: facet.facetType,
113
+ searchText: facet.searchText,
114
+ anchorText: facet.anchorText,
115
+ summary: facet.summary,
116
+ detail: facet.detail,
117
+ accessCount: 0,
118
+ importance: Math.max(1, Math.min(10, ep.importance)),
119
+ salience: Math.max(1, Math.min(10, facet.outcomeScore ?? ep.importance)),
120
+ confidence: 0.7,
121
+ retention: ep.importance >= 8 ? ("key-event" as const) : ("ambient" as const),
122
+ stability: ep.errors.length > 0 ? ("situational" as const) : ("stable" as const),
123
+ tags: facetTags,
124
+ sourceEpisodeIds: [episodeId],
125
+ evidence: [],
126
+ scope: { ...ep.scope, project: ep.project },
127
+ createdAt: ep.startedAt ?? `${ep.date}T00:00:00.000Z`,
128
+ updatedAt: now,
129
+ entityRefs: [],
130
+ aliases: [],
131
+ causalRole: facet.causalRole,
132
+ outcomeScore: facet.outcomeScore,
133
+ structuralAnchor: currentStructuralAnchor(),
134
+ };
135
+ });
136
+
137
+ const links = facets.map((facet) => ({
138
+ id: `${episodeId}->${facet.id}`,
139
+ fromId: episodeId,
140
+ toId: facet.id,
141
+ type: "has-facet" as const,
142
+ weight: 1,
143
+ explicit: true,
144
+ createdAt: now,
145
+ updatedAt: now,
146
+ evidence: [],
147
+ }));
148
+
149
+ const episode: EpisodeMemory = {
150
+ id: episodeId,
151
+ kind: "episode",
152
+ sessionId: ep.sessionId,
153
+ title: ep.userGoal || ep.summary.slice(0, 80),
154
+ summary: ep.summary,
155
+ startedAt: ep.startedAt,
156
+ endedAt: ep.endedAt,
157
+ timeZone: ep.timeZone,
158
+ userGoal: ep.userGoal,
159
+ outcome: ep.errors.length ? "high-friction" : "completed",
160
+ accessCount: 0,
161
+ importance: Math.max(1, Math.min(10, ep.importance)),
162
+ salience: Math.max(1, Math.min(10, ep.importance + Math.min(ep.errors.length, 2))),
163
+ confidence: 0.85,
164
+ retention: ep.importance >= 8 ? ("key-event" as const) : ("ambient" as const),
165
+ stability: ep.errors.length > 0 ? ("situational" as const) : ("stable" as const),
166
+ tags: baseTags.slice(0, 40),
167
+ sourceEpisodeIds: [episodeId],
168
+ evidence: [],
169
+ scope: { ...ep.scope, project: ep.project },
170
+ createdAt: ep.startedAt ?? `${ep.date}T00:00:00.000Z`,
171
+ updatedAt: now,
172
+ filesModified: ep.filesModified,
173
+ toolsUsed: ep.toolsUsed,
174
+ entities: [],
175
+ facetIds: facets.map((facet) => facet.id),
176
+ derivedSemanticIds: [],
177
+ derivedProcedureIds: [],
178
+ consolidatedAt: ep.consolidated ? now : undefined,
179
+ structuralAnchor: currentStructuralAnchor(),
180
+ };
181
+
182
+ return { episode, facets, links };
183
+ }
184
+
185
+ export async function syncEpisodeToV2(
186
+ ep: Episode,
187
+ v2Paths: NanoMemV2Paths,
188
+ ): Promise<{ needsEmbeddingSync: boolean }> {
189
+ const [episodes, facets, links, procedural, meta] = await Promise.all([
190
+ loadV2Episodes(v2Paths),
191
+ loadV2Facets(v2Paths),
192
+ loadV2Links(v2Paths),
193
+ loadV2Procedural(v2Paths),
194
+ loadV2Meta(v2Paths),
195
+ ]);
196
+
197
+ const now = new Date().toISOString();
198
+ const episodeId = makeEpisodeMemoryId(ep);
199
+ const mapped = mapEpisodeToV2(ep, now);
200
+ const nextEpisodes = episodes.filter((existing) => existing.id !== episodeId);
201
+ nextEpisodes.push(mapped.episode);
202
+
203
+ const nextFacets = facets.filter((facet) => facet.episodeId !== episodeId);
204
+ nextFacets.push(...mapped.facets);
205
+
206
+ const facetIds = new Set(mapped.facets.map((facet) => facet.id));
207
+ const nextLinks = links.filter(
208
+ (link) =>
209
+ link.fromId !== episodeId &&
210
+ link.toId !== episodeId &&
211
+ !facetIds.has(link.fromId) &&
212
+ !facetIds.has(link.toId),
213
+ );
214
+ nextLinks.push(...mapped.links);
215
+
216
+ const nextProcedural = procedural.filter((item) => !item.sourceEpisodeIds?.includes(episodeId));
217
+ const compiledProcedure = compileProcedureFromEpisode(mapped.episode, mapped.facets, now);
218
+ if (compiledProcedure) {
219
+ nextProcedural.push(compiledProcedure);
220
+ mapped.episode.derivedProcedureIds = [compiledProcedure.id];
221
+ nextEpisodes[nextEpisodes.length - 1] = mapped.episode;
222
+ }
223
+
224
+ await Promise.all([
225
+ saveV2Episodes(v2Paths, nextEpisodes),
226
+ saveV2Facets(v2Paths, nextFacets),
227
+ saveV2Links(v2Paths, nextLinks),
228
+ saveV2Procedural(v2Paths, nextProcedural),
229
+ saveV2Meta(v2Paths, {
230
+ ...meta,
231
+ version: 2,
232
+ lastMigrationAt: meta.lastMigrationAt ?? now,
233
+ }),
234
+ ]);
235
+
236
+ return { needsEmbeddingSync: true };
237
+ }