@jjh32456/longlive 0.0.0-stage → 1.8.12

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 (309) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +363 -0
  4. package/README.en.md +55 -0
  5. package/README.md +225 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1555 -0
  8. package/cordis.patch.yml +177 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +807 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +46 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +160 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-a1-legacy.mjs +62 -0
  55. package/scripts/migrate-lifecycle.mjs +157 -0
  56. package/scripts/pack.mjs +392 -0
  57. package/scripts/recall-index-build.mjs +128 -0
  58. package/scripts/recall-links-build.mjs +420 -0
  59. package/scripts/rescore-cards.mjs +36 -0
  60. package/scripts/resident-watcher-status.ps1 +15 -0
  61. package/scripts/resident-watcher.ps1 +643 -0
  62. package/scripts/session-watch-drill.mjs +553 -0
  63. package/scripts/session-watch-status.ps1 +146 -0
  64. package/scripts/session-watch.mjs +1367 -0
  65. package/scripts/surgery-inspect.mjs +122 -0
  66. package/scripts/surgery-run.cmd +34 -0
  67. package/scripts/truncate-cli.mjs +279 -0
  68. package/scripts/unattended-surgery.ps1 +1019 -0
  69. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  70. package/scripts/uninstall-session-watch.ps1 +192 -0
  71. package/scripts/verify-card-anchors.mjs +138 -0
  72. package/scripts/watch-loop.ps1 +916 -0
  73. package/src/actions/audit.js +125 -0
  74. package/src/actions/evidence.js +122 -0
  75. package/src/actions/fs.js +162 -0
  76. package/src/activity/index.js +873 -0
  77. package/src/activity/model.js +351 -0
  78. package/src/activity/store.js +786 -0
  79. package/src/activity/summary.js +180 -0
  80. package/src/activity/thinking.js +191 -0
  81. package/src/adapters/constants.js +11 -0
  82. package/src/adapters/engram/data/aliases.json +51 -0
  83. package/src/adapters/engram/data/policy.json +8 -0
  84. package/src/adapters/engram/data/routing-rules.json +546 -0
  85. package/src/adapters/engram/index.js +278 -0
  86. package/src/adapters/registry.js +315 -0
  87. package/src/answer/audit.js +238 -0
  88. package/src/answer/evidence.js +30 -0
  89. package/src/answer/guard.js +1370 -0
  90. package/src/answer/index.js +1086 -0
  91. package/src/answer/query.js +111 -0
  92. package/src/answer/second-hop.mjs +101 -0
  93. package/src/auto-truncate-status.js +164 -0
  94. package/src/auto-truncate.js +1181 -0
  95. package/src/autoprocedure/candidate.js +342 -0
  96. package/src/autoprocedure/config.js +122 -0
  97. package/src/autoprocedure/evidence.js +345 -0
  98. package/src/autoprocedure/index.js +83 -0
  99. package/src/autoprocedure/ledger.js +329 -0
  100. package/src/autoprocedure/lint.js +232 -0
  101. package/src/autoprocedure/llm.js +409 -0
  102. package/src/autoprocedure/locks.js +102 -0
  103. package/src/autoprocedure/paths.js +39 -0
  104. package/src/autoprocedure/privacy.js +87 -0
  105. package/src/autoprocedure/rules.js +288 -0
  106. package/src/autoprocedure/runtime.js +718 -0
  107. package/src/autoprocedure/session-reader.js +328 -0
  108. package/src/backup.js +146 -0
  109. package/src/bus/bus.mjs +1446 -0
  110. package/src/codec.js +269 -0
  111. package/src/compaction/cut-engine.js +44 -0
  112. package/src/compaction/engine-core.js +1237 -0
  113. package/src/compaction/entry.js +228 -0
  114. package/src/compaction.js +230 -0
  115. package/src/conclusion.js +366 -0
  116. package/src/config.js +824 -0
  117. package/src/d6/runtime.js +517 -0
  118. package/src/d6/surface.js +181 -0
  119. package/src/deps.js +189 -0
  120. package/src/engine-status.js +141 -0
  121. package/src/features.js +912 -0
  122. package/src/handoff/index.js +944 -0
  123. package/src/handoff/model.js +1010 -0
  124. package/src/handoff/store.js +1233 -0
  125. package/src/heartbeat.js +385 -0
  126. package/src/home.js +16 -0
  127. package/src/host-version.js +280 -0
  128. package/src/hot-truncate-diag.js +98 -0
  129. package/src/identity/card-marker.js +281 -0
  130. package/src/identity/handover.js +657 -0
  131. package/src/identity/index.js +337 -0
  132. package/src/identity/inject-position.js +131 -0
  133. package/src/identity/writeback.js +344 -0
  134. package/src/identity.js +118 -0
  135. package/src/index.js +647 -0
  136. package/src/lifecycle/gap-clocks.js +364 -0
  137. package/src/lifecycle/index.js +269 -0
  138. package/src/lifecycle/proactive.js +1426 -0
  139. package/src/live-target.js +212 -0
  140. package/src/live.js +1603 -0
  141. package/src/log-rotation.js +153 -0
  142. package/src/memory/a1-migration.js +124 -0
  143. package/src/memory/activity-capture.js +229 -0
  144. package/src/memory/anchor-fallback.js +116 -0
  145. package/src/memory/anchors.js +194 -0
  146. package/src/memory/audit-records.js +222 -0
  147. package/src/memory/auto-cards.js +441 -0
  148. package/src/memory/capture-host.js +228 -0
  149. package/src/memory/capture.js +457 -0
  150. package/src/memory/card-anchors.js +203 -0
  151. package/src/memory/card-priority.js +110 -0
  152. package/src/memory/cards.js +425 -0
  153. package/src/memory/conclusion-distill.js +332 -0
  154. package/src/memory/conclusion-drafts.js +239 -0
  155. package/src/memory/conflicts.js +147 -0
  156. package/src/memory/consolidate.js +815 -0
  157. package/src/memory/decay.js +311 -0
  158. package/src/memory/distill.js +485 -0
  159. package/src/memory/event-index.js +1826 -0
  160. package/src/memory/evidence-chain.js +295 -0
  161. package/src/memory/evidence.js +213 -0
  162. package/src/memory/filter-runner.js +555 -0
  163. package/src/memory/filter.js +1035 -0
  164. package/src/memory/forget-v2.js +410 -0
  165. package/src/memory/forget.js +512 -0
  166. package/src/memory/frames-activation.js +247 -0
  167. package/src/memory/frontmatter.js +454 -0
  168. package/src/memory/fts-query.js +342 -0
  169. package/src/memory/governance.js +604 -0
  170. package/src/memory/index-freshness.js +234 -0
  171. package/src/memory/index.js +362 -0
  172. package/src/memory/l2-gate.js +169 -0
  173. package/src/memory/lifecycle.js +107 -0
  174. package/src/memory/lock.js +121 -0
  175. package/src/memory/maintenance.js +785 -0
  176. package/src/memory/manifest.js +245 -0
  177. package/src/memory/migrate-lifecycle.js +1808 -0
  178. package/src/memory/migrate.js +139 -0
  179. package/src/memory/paths.js +229 -0
  180. package/src/memory/procedure.js +963 -0
  181. package/src/memory/provenance.js +119 -0
  182. package/src/memory/recall-v2.js +206 -0
  183. package/src/memory/recall.js +256 -0
  184. package/src/memory/reconcile.js +265 -0
  185. package/src/memory/records.js +433 -0
  186. package/src/memory/reinforce.js +145 -0
  187. package/src/memory/retention.js +128 -0
  188. package/src/memory/review.js +124 -0
  189. package/src/memory/state.js +279 -0
  190. package/src/memory/tiers.js +168 -0
  191. package/src/memory/topic-phrases.js +73 -0
  192. package/src/memory/trust.js +97 -0
  193. package/src/memory/version-chain.js +264 -0
  194. package/src/memory/wal.js +137 -0
  195. package/src/memory/working-frame.js +516 -0
  196. package/src/metrics/classify.mjs +189 -0
  197. package/src/metrics/estimate.mjs +108 -0
  198. package/src/metrics/index.mjs +204 -0
  199. package/src/metrics/measure.mjs +462 -0
  200. package/src/metrics/prestep-latency.mjs +307 -0
  201. package/src/metrics/store.mjs +264 -0
  202. package/src/original.js +294 -0
  203. package/src/policy/threshold-policy.js +224 -0
  204. package/src/policy-profile.js +463 -0
  205. package/src/recall/anaphora.mjs +87 -0
  206. package/src/recall/archive-fallback.mjs +235 -0
  207. package/src/recall/archive-search.mjs +425 -0
  208. package/src/recall/cards.mjs +202 -0
  209. package/src/recall/edges.js +379 -0
  210. package/src/recall/embedding.mjs +698 -0
  211. package/src/recall/entities.mjs +112 -0
  212. package/src/recall/explain.mjs +433 -0
  213. package/src/recall/force-policy.mjs +138 -0
  214. package/src/recall/index.js +1036 -0
  215. package/src/recall/inject-order.mjs +277 -0
  216. package/src/recall/link-recall.mjs +183 -0
  217. package/src/recall/links.mjs +696 -0
  218. package/src/recall/privacy.mjs +208 -0
  219. package/src/recall/recall-core.mjs +765 -0
  220. package/src/recall/shared-visibility.js +302 -0
  221. package/src/recall/time-normalizer.mjs +196 -0
  222. package/src/retention/config.js +106 -0
  223. package/src/retention/index.js +643 -0
  224. package/src/role/activation.js +191 -0
  225. package/src/role/attention.js +318 -0
  226. package/src/role/base.js +36 -0
  227. package/src/role/channels.js +423 -0
  228. package/src/role/index.js +425 -0
  229. package/src/role/interfaces.js +115 -0
  230. package/src/role/personality.js +370 -0
  231. package/src/role/readers.js +151 -0
  232. package/src/role/relationships.js +477 -0
  233. package/src/role/store.js +202 -0
  234. package/src/role/writeprotect.js +373 -0
  235. package/src/router/aliases.json +182 -0
  236. package/src/router/background/agent-runner.mjs +239 -0
  237. package/src/router/background/anchor.mjs +323 -0
  238. package/src/router/background/audit.mjs +337 -0
  239. package/src/router/background/budget-ledger.mjs +648 -0
  240. package/src/router/background/host-sim.mjs +451 -0
  241. package/src/router/background/index.mjs +81 -0
  242. package/src/router/background/memory.mjs +63 -0
  243. package/src/router/background/mock-llm.mjs +203 -0
  244. package/src/router/background/queue.mjs +224 -0
  245. package/src/router/background/retry.mjs +255 -0
  246. package/src/router/background/router.mjs +1459 -0
  247. package/src/router/background/stream.mjs +276 -0
  248. package/src/router/background/tool-policy.mjs +255 -0
  249. package/src/router/design-headings.json +221 -0
  250. package/src/router/face/config.mjs +155 -0
  251. package/src/router/face/context.mjs +284 -0
  252. package/src/router/face/face.mjs +466 -0
  253. package/src/router/face/identity.mjs +130 -0
  254. package/src/router/face/index.mjs +65 -0
  255. package/src/router/face/journal.mjs +119 -0
  256. package/src/router/face/llm.mjs +252 -0
  257. package/src/router/face/outbox.mjs +153 -0
  258. package/src/router/face/paths.mjs +54 -0
  259. package/src/router/judge.mjs +987 -0
  260. package/src/router/policies/generic.json +131 -0
  261. package/src/router/route.js +1766 -0
  262. package/src/router/router.mjs +535 -0
  263. package/src/router/routing-rules.json +816 -0
  264. package/src/router/run-sim.mjs +530 -0
  265. package/src/router/runtime.js +569 -0
  266. package/src/router/service/apply.mjs +1218 -0
  267. package/src/router/service/board.mjs +712 -0
  268. package/src/router/service/caller.mjs +131 -0
  269. package/src/router/service/config.mjs +361 -0
  270. package/src/router/service/context.mjs +314 -0
  271. package/src/router/service/hint.mjs +668 -0
  272. package/src/router/service/lease.mjs +494 -0
  273. package/src/router/service/live.mjs +251 -0
  274. package/src/router/service/lock.mjs +550 -0
  275. package/src/router/service/merge.mjs +255 -0
  276. package/src/router/service/model-resolve.mjs +350 -0
  277. package/src/router/service/paths.mjs +168 -0
  278. package/src/router/service/proposals.mjs +1461 -0
  279. package/src/router/service/queue.mjs +477 -0
  280. package/src/router/service/reconcile.mjs +271 -0
  281. package/src/router/service/service.mjs +2998 -0
  282. package/src/router/service/sources.mjs +352 -0
  283. package/src/router/service/status.mjs +520 -0
  284. package/src/router/service/store.mjs +476 -0
  285. package/src/router/service/ticklock.mjs +239 -0
  286. package/src/router/service/tokens.mjs +95 -0
  287. package/src/router/service/tools.mjs +248 -0
  288. package/src/router/service/wake.mjs +544 -0
  289. package/src/router/service/wal.mjs +685 -0
  290. package/src/router/shadow.mjs +821 -0
  291. package/src/surgery-recovery.js +1909 -0
  292. package/src/tool-output.js +485 -0
  293. package/src/tools.js +3146 -0
  294. package/src/truncate-visible.js +2416 -0
  295. package/src/truncate.js +999 -0
  296. package/src/ui/actions.js +1312 -0
  297. package/src/ui/flags.js +259 -0
  298. package/src/ui/panel-api.js +371 -0
  299. package/src/ui/panel-auth.js +251 -0
  300. package/src/ui/panel-integrity.js +243 -0
  301. package/src/ui/routes-readonly.js +759 -0
  302. package/src/ui/routes.js +284 -0
  303. package/src/util/append-store.js +368 -0
  304. package/src/util/local-day.js +30 -0
  305. package/src/util/redact.js +227 -0
  306. package/src/util/stale-locks.js +148 -0
  307. package/src/version.js +99 -0
  308. package/test/fixtures/pre-step-container.mjs +100 -0
  309. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,234 @@
1
+ // src/memory/index-freshness.js — index freshness / lag / failure ledger.
2
+ //
3
+ // The old INDEX.md "generated at" timestamp only said when a scan ran; it did
4
+ // not say whether the scan saw the latest cards/events. This module separates:
5
+ // * generatedAt: when INDEX.md was last written
6
+ // * dataThroughAt: newest input mtime we can prove was considered
7
+ // * indexLagMs: dataThroughAt - generatedAt (index is behind data)
8
+ // * dataAgeMs: now - dataThroughAt (inputs are old but index is caught up)
9
+ // and writes the result into memory-state.json so STATUS/panel/tool callers can
10
+ // show "indexed through / lagging by" without inventing a health claim.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { memoryRootFromConfig, resolveInside } from './paths.js';
16
+ import { readState, updateState } from './state.js';
17
+ import { cardsPathOf } from './auto-cards.js';
18
+
19
+ export const INDEX_FRESHNESS_SCHEMA = 'index-freshness/v1';
20
+ export const INDEX_FRESHNESS_STALE_MS = 5 * 60 * 1000;
21
+
22
+ function parseMs(value) {
23
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
24
+ if (typeof value !== 'string' || value.trim() === '') return null;
25
+ const ms = Date.parse(value);
26
+ return Number.isFinite(ms) ? ms : null;
27
+ }
28
+
29
+ function mtimeOf(file) {
30
+ try {
31
+ return fs.statSync(file).mtimeMs;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function iso(ms) {
38
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
39
+ }
40
+
41
+ function countLines(file) {
42
+ try {
43
+ const raw = fs.readFileSync(file, 'utf8');
44
+ let count = 0;
45
+ for (const line of raw.split('\n')) if (line.trim() !== '') count += 1;
46
+ return count;
47
+ } catch {
48
+ return 0;
49
+ }
50
+ }
51
+
52
+ function indexPaths(root) {
53
+ const longlive = resolveInside(root, '.longlive');
54
+ return {
55
+ indexDir: resolveInside(root, path.join('.longlive', 'index')),
56
+ index: resolveInside(root, 'INDEX.md'),
57
+ cards: cardsPathOf(root),
58
+ events: resolveInside(root, path.join('.longlive', 'index', 'events.db')),
59
+ audit: resolveInside(root, path.join('.longlive', 'index', 'events.audit.jsonl')),
60
+ state: resolveInside(root, path.join('.longlive', 'memory-state.json')),
61
+ longlive,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Pure-ish read-only freshness view. Never writes and never creates `.longlive`.
67
+ */
68
+ export function getIndexFreshness({
69
+ memoryRoot = '',
70
+ now = new Date(),
71
+ staleAfterMs = INDEX_FRESHNESS_STALE_MS,
72
+ } = {}) {
73
+ const root = path.resolve(String(memoryRoot ?? ''));
74
+ if (root === '') {
75
+ return {
76
+ ok: false, schema: INDEX_FRESHNESS_SCHEMA, status: 'unknown',
77
+ code: 'E_NO_MEMORY_ROOT', stale: true,
78
+ };
79
+ }
80
+ const nowMs = now instanceof Date ? now.getTime() : Number(now);
81
+ const nowAt = Number.isFinite(nowMs) ? nowMs : Date.now();
82
+ const p = indexPaths(root);
83
+ let state = {};
84
+ let stateError = null;
85
+ try { state = readState(root); } catch (error) { stateError = error?.code ?? String(error); }
86
+ const generatedMs = parseMs(state.indexBuiltAt) ?? mtimeOf(p.index);
87
+ const stateDataMs = parseMs(state.indexDataAt) ?? parseMs(state.lastCaptureAt);
88
+ const dataCandidates = [
89
+ stateDataMs,
90
+ mtimeOf(p.cards),
91
+ mtimeOf(p.events),
92
+ mtimeOf(p.index),
93
+ ].filter((value) => Number.isFinite(value));
94
+ const dataMs = dataCandidates.length > 0 ? Math.max(...dataCandidates) : null;
95
+ const indexLagMs = (Number.isFinite(generatedMs) && Number.isFinite(dataMs))
96
+ ? Math.max(0, dataMs - generatedMs)
97
+ : null;
98
+ const dataAgeMs = Number.isFinite(dataMs) ? Math.max(0, nowAt - dataMs) : null;
99
+ const lastError = typeof state.indexLastError === 'string' && state.indexLastError !== ''
100
+ ? state.indexLastError
101
+ : null;
102
+ let status = 'fresh';
103
+ if (stateError) status = 'error';
104
+ else if (lastError) status = 'error';
105
+ else if (!Number.isFinite(generatedMs) || !Number.isFinite(dataMs)) status = 'unknown';
106
+ else if (indexLagMs > staleAfterMs) status = 'stale';
107
+ // Legacy cold-archive diagnostic only; not used by recall/INDEX/panel stats.
108
+ // D2 (1.8.2): cards.jsonl is no longer read or counted for freshness.
109
+ const result = {
110
+ ok: status === 'fresh' || status === 'stale',
111
+ schema: INDEX_FRESHNESS_SCHEMA,
112
+ status,
113
+ healthy: status === 'fresh',
114
+ stale: status !== 'fresh',
115
+ generatedAt: iso(generatedMs),
116
+ dataThroughAt: iso(dataMs),
117
+ indexLagMs,
118
+ dataAgeMs,
119
+ staleAfterMs,
120
+ lastError,
121
+ lastErrorAt: typeof state.indexLastErrorAt === 'string' ? state.indexLastErrorAt : null,
122
+ lastFailureCount: Number.isInteger(state.indexFailureCount) ? state.indexFailureCount : 0,
123
+ lastRefreshAt: typeof state.indexLastRefreshAt === 'string' ? state.indexLastRefreshAt : null,
124
+ paths: p,
125
+ ...(stateError ? { stateError } : {}),
126
+ };
127
+ return result;
128
+ }
129
+
130
+ /** Persist a freshness/failure patch into memory-state.json (atomic). */
131
+ export function recordIndexFreshness({
132
+ memoryRoot = '',
133
+ patch = {},
134
+ now = new Date(),
135
+ staleAfterMs = INDEX_FRESHNESS_STALE_MS,
136
+ } = {}) {
137
+ const root = path.resolve(String(memoryRoot ?? ''));
138
+ if (root === '') return { ok: false, code: 'E_NO_MEMORY_ROOT' };
139
+ const current = readState(root);
140
+ const nextPatch = {
141
+ indexFreshness: patch.indexFreshness,
142
+ indexLagMs: patch.indexLagMs,
143
+ indexDataAt: patch.indexDataAt,
144
+ indexLastRefreshAt: patch.indexLastRefreshAt,
145
+ // indexAutoCards intentionally removed in 1.8.2: no panel/INDEX stat.
146
+ ...(patch.indexBuiltAt ? { indexBuiltAt: patch.indexBuiltAt } : {}),
147
+ ...('indexLastError' in patch ? { indexLastError: patch.indexLastError } : {}),
148
+ ...(patch.indexLastErrorAt ? { indexLastErrorAt: patch.indexLastErrorAt } : {}),
149
+ ...(Number.isInteger(patch.indexFailureCount) ? { indexFailureCount: patch.indexFailureCount } : {}),
150
+ };
151
+ for (const key of Object.keys(nextPatch)) {
152
+ if (nextPatch[key] === undefined) delete nextPatch[key];
153
+ }
154
+ updateState(root, nextPatch, { now });
155
+ return { ok: true, state: readState(root), freshness: getIndexFreshness({ memoryRoot: root, now, staleAfterMs }) };
156
+ }
157
+
158
+ /**
159
+ * Record a failed refresh without throwing: capture must not lose the turn, but
160
+ * the next status read has to show the failure.
161
+ */
162
+ export function markIndexFailure({
163
+ memoryRoot = '',
164
+ error = null,
165
+ now = new Date(),
166
+ staleAfterMs = INDEX_FRESHNESS_STALE_MS,
167
+ } = {}) {
168
+ const root = path.resolve(String(memoryRoot ?? ''));
169
+ if (root === '') return { ok: false, code: 'E_NO_MEMORY_ROOT' };
170
+ let current = {};
171
+ try { current = readState(root); } catch { current = {}; }
172
+ const at = now instanceof Date ? now.toISOString() : new Date(now).toISOString();
173
+ const count = (Number.isInteger(current.indexFailureCount) ? current.indexFailureCount : 0) + 1;
174
+ const code = String(error?.code ?? error?.name ?? 'E_INDEX_REFRESH');
175
+ const message = String(error?.message ?? error ?? code);
176
+ recordIndexFreshness({
177
+ memoryRoot: root,
178
+ now,
179
+ staleAfterMs,
180
+ patch: {
181
+ indexFreshness: 'error',
182
+ indexLastError: `${code}: ${message}`.slice(0, 500),
183
+ indexLastErrorAt: at,
184
+ indexFailureCount: count,
185
+ indexLastRefreshAt: at,
186
+ },
187
+ });
188
+ return { ok: false, code, message, failureCount: count, at };
189
+ }
190
+
191
+ /**
192
+ * Called after capture has written events/cards. The caller injects the INDEX
193
+ * writer so tests can exercise failure/retry without a second dependency cycle.
194
+ */
195
+ export function refreshIndexAfterCapture({
196
+ memoryRoot = '',
197
+ now = new Date(),
198
+ indexer = null,
199
+ staleAfterMs = INDEX_FRESHNESS_STALE_MS,
200
+ } = {}) {
201
+ const root = path.resolve(String(memoryRoot ?? ''));
202
+ if (root === '') return { ok: false, code: 'E_NO_MEMORY_ROOT' };
203
+ const at = now instanceof Date ? now : new Date(now);
204
+ if (typeof indexer !== 'function') {
205
+ const failure = markIndexFailure({ memoryRoot: root, error: new Error('E_NO_INDEXER'), now: at, staleAfterMs });
206
+ return { ok: false, ...failure };
207
+ }
208
+ try {
209
+ const indexed = indexer({ apply: true, ifChanged: true }, { memoryRoot: root, now: at });
210
+ const freshness = getIndexFreshness({ memoryRoot: root, now: at, staleAfterMs });
211
+ recordIndexFreshness({
212
+ memoryRoot: root,
213
+ now: at,
214
+ staleAfterMs,
215
+ patch: {
216
+ indexFreshness: freshness.status,
217
+ indexLagMs: freshness.indexLagMs,
218
+ indexDataAt: freshness.dataThroughAt,
219
+ indexLastRefreshAt: at.toISOString(),
220
+ indexLastError: null,
221
+ ...(indexed?.indexBuiltAt ? { indexBuiltAt: indexed.indexBuiltAt } : {}),
222
+ },
223
+ });
224
+ return { ok: true, indexed, freshness };
225
+ } catch (error) {
226
+ const failure = markIndexFailure({ memoryRoot: root, error, now: at, staleAfterMs });
227
+ return { ok: false, error, failure };
228
+ }
229
+ }
230
+
231
+ /** Resolve memoryRoot exactly like every other memory_* caller. */
232
+ export function resolveFreshnessRoot(config = {}) {
233
+ return memoryRootFromConfig(config);
234
+ }
@@ -0,0 +1,362 @@
1
+ // INDEX.md regeneration.
2
+ //
3
+ // Only the region between the two generated markers is rewritten. Everything a
4
+ // human wrote outside them is copied byte-for-byte. The tool is dry-run by
5
+ // default; `apply: true` is the only path that writes. Two consecutive applies
6
+ // differ only in the generated timestamp line, so the section is idempotent.
7
+ //
8
+ // Legacy cards (no frontmatter) are real cards: they get defaults and a row,
9
+ // because the index's completeness rule is "scanned card count == generated row
10
+ // count" — dropping them would silently lose memory.
11
+ //
12
+ // Procedures get their own 「程序性」 table. They are counted in `cards` but
13
+ // never repeated in the topics/journal table, so one card still means one row.
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
19
+ import { parseFrontmatter, dayString, isoStamp } from './frontmatter.js';
20
+ import {
21
+ appendAudit, listMarkdownFiles, updateState, writeFileAtomic,
22
+ } from './state.js';
23
+ import { PROCEDURES_DIR, scanProcedures } from './procedure.js';
24
+ import { getIndexFreshness } from './index-freshness.js';
25
+
26
+ export const BEGIN_GENERATED = '<!-- BEGIN GENERATED -->';
27
+ export const END_GENERATED = '<!-- END GENERATED -->';
28
+ export const INDEX_FILE = 'INDEX.md';
29
+ export const PROCEDURES_HEADING = `### 程序性(${PROCEDURES_DIR}/)`;
30
+
31
+ const SCAN_DIRS = ['topics', 'journal'];
32
+ export const RAW_DIRS = ['raw', 'topics/raw'];
33
+ export const RAW_INDEX_POLICY = 'excluded-by-default';
34
+ export const RAW_OPT_IN_FIELD = 'index';
35
+
36
+ /**
37
+ * Raw source material is deliberately NOT part of the generated card table:
38
+ * it is evidence/archive, and indexing every transcript would make INDEX.md a
39
+ * second copy of the session log. The rule is explicit and documented in
40
+ * docs/RAW-INDEX-POLICY.md. A future opt-in can be added by frontmatter
41
+ * `index: true`; this scan reports those files instead of silently ignoring
42
+ * them.
43
+ */
44
+ export function scanRawPolicy(root) {
45
+ const files = [];
46
+ const optIn = [];
47
+ for (const dir of RAW_DIRS) {
48
+ for (const abs of listMarkdownFiles(root, dir)) {
49
+ const rel = relativePath(root, abs);
50
+ if (path.basename(rel) === 'INDEX-POLICY.md') continue;
51
+ files.push(rel);
52
+ try {
53
+ const parsed = parseFrontmatter(fs.readFileSync(abs, 'utf8'));
54
+ if (parsed.fields?.[RAW_OPT_IN_FIELD] === true || parsed.fields?.[RAW_OPT_IN_FIELD] === 'true') optIn.push(rel);
55
+ } catch { /* unreadable raw file is reported, not silently dropped */ }
56
+ }
57
+ }
58
+ return {
59
+ policy: RAW_INDEX_POLICY,
60
+ included: false,
61
+ optInSupported: true,
62
+ files,
63
+ optIn,
64
+ note: 'raw/ 与 topics/raw/ 默认不入 INDEX;仅扫描条目数并明确报告。',
65
+ };
66
+ }
67
+
68
+ function collapse(text) {
69
+ return String(text ?? '').replace(/\s+/g, ' ').trim();
70
+ }
71
+
72
+ function firstHeading(body) {
73
+ for (const raw of String(body ?? '').split(/\r?\n/)) {
74
+ const match = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(raw);
75
+ if (match) return collapse(match[1]);
76
+ }
77
+ return null;
78
+ }
79
+
80
+ function firstSummaryLine(body) {
81
+ for (const raw of String(body ?? '').split(/\r?\n/)) {
82
+ const line = raw.trim();
83
+ if (line === '') continue;
84
+ if (/^#{1,6}\s/.test(line)) continue;
85
+ if (/^<!--/.test(line) || /^-->$/.test(line)) continue;
86
+ if (/^\|/.test(line) || /^-{3,}$/.test(line)) continue;
87
+ const cleaned = line
88
+ .replace(/^[-*+]\s+/, '')
89
+ .replace(/^\d+[.)]\s+/, '')
90
+ .replace(/\*\*/g, '')
91
+ .replace(/`/g, '')
92
+ .replace(/\|/g, '/')
93
+ .trim();
94
+ if (cleaned) return cleaned.slice(0, 60);
95
+ }
96
+ return '(空)';
97
+ }
98
+
99
+ function readCard(root, abs) {
100
+ const text = fs.readFileSync(abs, 'utf8');
101
+ const parsed = parseFrontmatter(text);
102
+ const rel = relativePath(root, abs);
103
+ const title = collapse(parsed.fields.title || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
104
+ return {
105
+ abs,
106
+ rel,
107
+ title,
108
+ summary: firstSummaryLine(parsed.body),
109
+ legacy: parsed.legacy,
110
+ fields: parsed.fields,
111
+ extras: parsed.extras ?? {},
112
+ };
113
+ }
114
+
115
+ /** All cards under `topics/` and `journal/`, sorted for a stable index. */
116
+ export function scanCards(root) {
117
+ const cards = [];
118
+ for (const dir of SCAN_DIRS) {
119
+ for (const abs of listMarkdownFiles(root, dir)) {
120
+ const rel = relativePath(root, abs);
121
+ // A1 v2: auto-* staging is deliberately outside the recall surface until
122
+ // a human/dream review promotes it to a regular topic card.
123
+ if (rel.startsWith('topics/auto/')) continue;
124
+ cards.push(readCard(root, abs));
125
+ }
126
+ }
127
+ cards.sort((left, right) => {
128
+ if (right.fields.salience !== left.fields.salience) return right.fields.salience - left.fields.salience;
129
+ const leftUsed = left.fields.last_used ?? '';
130
+ const rightUsed = right.fields.last_used ?? '';
131
+ if (rightUsed !== leftUsed) return rightUsed.localeCompare(leftUsed);
132
+ return left.rel.localeCompare(right.rel);
133
+ });
134
+ return cards;
135
+ }
136
+
137
+ function cell(value) {
138
+ return collapse(value).replace(/\|/g, '\\|');
139
+ }
140
+
141
+ function withoutGeneratedStamp(text) {
142
+ return String(text ?? '').replace(/<!-- generated: [^>]* -->/gu, '<!-- generated: <stamp> -->');
143
+ }
144
+
145
+ function procedureRow(card) {
146
+ const trigger = card.trigger?.length > 0 ? card.trigger.join(', ') : '(无)';
147
+ return `| ${cell(card.name)} | ${cell(trigger)} | ${card.rel} | ${card.strength} | ${card.version} |`;
148
+ }
149
+
150
+ function statusCounts(cards) {
151
+ const counts = { active: 0, locked: 0, archived: 0 };
152
+ for (const card of cards) {
153
+ const status = card.fields?.status ?? 'active';
154
+ if (status in counts) counts[status] += 1;
155
+ else counts.active += 1;
156
+ }
157
+ return counts;
158
+ }
159
+
160
+ /**
161
+ * The generated section: one table for topics/journal cards, then a separate
162
+ * 「程序性」 table. A procedure card has `procedure: true` and is written only
163
+ * to the second table, so it never shows up twice.
164
+ */
165
+ export function buildGeneratedSection(allCards, now = new Date(), options = {}) {
166
+ const cards = allCards.filter((card) => card.procedure !== true);
167
+ const procedures = allCards.filter((card) => card.procedure === true);
168
+ const legacy = allCards.filter((card) => card.legacy).length;
169
+ const counts = statusCounts(allCards);
170
+ const rows = cards.map((card) => `| ${cell(card.title)} | ${cell(card.summary)} | ${card.rel} | ${card.fields.salience} | ${card.fields.strength} |`);
171
+ return [
172
+ BEGIN_GENERATED,
173
+ `<!-- generated: ${isoStamp(now)} -->`,
174
+ `<!-- cards: ${allCards.length} · legacy: ${legacy} · procedures: ${procedures.length} · active: ${counts.active} · locked: ${counts.locked} · archived: ${counts.archived} -->`,
175
+ '| 标题 | 一句话 | 路径 | salience | strength |',
176
+ '| --- | --- | --- | --- | --- |',
177
+ ...rows,
178
+ '',
179
+ PROCEDURES_HEADING,
180
+ '',
181
+ '| 名称 | 触发 | 路径 | strength | 版本 |',
182
+ '| --- | --- | --- | --- | --- |',
183
+ ...procedures.map(procedureRow),
184
+ END_GENERATED,
185
+ ].join('\n');
186
+ }
187
+
188
+ /**
189
+ * Count data rows in a generated section. There are two tables now, so the
190
+ * header is recognised structurally (a row followed by a `| ---` separator)
191
+ * instead of by its label; a data row is never followed by a separator row.
192
+ */
193
+ export function countGeneratedRows(section) {
194
+ const lines = String(section ?? '').split('\n');
195
+ let count = 0;
196
+ for (let index = 0; index < lines.length; index += 1) {
197
+ const line = lines[index];
198
+ if (!line.startsWith('| ')) continue;
199
+ if (/^\|\s*---/.test(line)) continue;
200
+ if (/^\|\s*---/.test(lines[index + 1] ?? '')) continue;
201
+ count += 1;
202
+ }
203
+ return count;
204
+ }
205
+
206
+ /**
207
+ * Replace the generated region in `existing`, keeping all hand-written content
208
+ * byte-for-byte. Missing markers append the section; half a pair is an error
209
+ * because guessing where it ends would let the tool rewrite hand-written text.
210
+ */
211
+ export function mergeGenerated(existing, section) {
212
+ const before = String(existing ?? '');
213
+ const begin = before.indexOf(BEGIN_GENERATED);
214
+ const end = before.indexOf(END_GENERATED, Math.max(0, begin));
215
+ if (begin >= 0 && end >= 0) {
216
+ return before.slice(0, begin) + section + before.slice(end + END_GENERATED.length);
217
+ }
218
+ if (begin >= 0 || end >= 0) {
219
+ throw memoryError(
220
+ 'E_INDEX_MARKERS',
221
+ 'INDEX.md 里只有一半生成标记 — 补成一对 BEGIN/END GENERATED,或在人工确认后删掉那一半',
222
+ );
223
+ }
224
+ if (before.trim() === '') return `${section}\n`;
225
+ const separator = before.endsWith('\n') ? '\n' : '\n\n';
226
+ return `${before}${separator}${section}\n`;
227
+ }
228
+
229
+ function incomplete(cards, section) {
230
+ const rows = countGeneratedRows(section);
231
+ if (rows !== cards.length) {
232
+ throw memoryError(
233
+ 'E_INDEX_INCOMPLETE',
234
+ `索引完整性校验失败:扫描到 ${cards.length} 张卡,却只生成 ${rows} 行 — 拒绝写入`,
235
+ );
236
+ }
237
+ }
238
+
239
+ /**
240
+ * memory_index: dry-run by default. `apply: true` rewrites only the generated
241
+ * section, after backing INDEX.md up and verifying the write.
242
+ */
243
+ export function memoryIndex(args = {}, config = {}) {
244
+ const root = memoryRootFromConfig(config);
245
+ const now = config.now instanceof Date ? config.now : new Date();
246
+ const apply = args.apply === true;
247
+ const core = scanCards(root);
248
+ const { cards: procedures, invalid: invalidCards } = scanProcedures(root);
249
+ const cards = [...core, ...procedures.map((card) => ({ ...card, procedure: true }))];
250
+ const rawPolicy = scanRawPolicy(root);
251
+ const section = buildGeneratedSection(cards, now);
252
+ const legacy = cards.filter((card) => card.legacy).length;
253
+ const counts = statusCounts(cards);
254
+ const invalid = invalidCards.length;
255
+ incomplete(cards, section);
256
+
257
+ const indexPath = resolveInside(root, INDEX_FILE);
258
+ const existed = fs.existsSync(indexPath);
259
+ const before = existed ? fs.readFileSync(indexPath, 'utf8') : '';
260
+ const after = mergeGenerated(before, section);
261
+ const changed = before !== after;
262
+ // A generated timestamp alone is not a content change; capture/ifChanged must
263
+ // not rewrite/back up INDEX.md on every turn just because time moved.
264
+ const contentChanged = withoutGeneratedStamp(before) !== withoutGeneratedStamp(after);
265
+ const base = {
266
+ root,
267
+ indexPath,
268
+ cards: cards.length,
269
+ legacy,
270
+ procedures: procedures.length,
271
+ invalid,
272
+ rawPolicy,
273
+ ...counts,
274
+ changed,
275
+ contentChanged,
276
+ generated: section,
277
+ };
278
+
279
+ if (!apply) {
280
+ return {
281
+ ...base,
282
+ ok: true,
283
+ status: 'dry-run',
284
+ dryRun: true,
285
+ applied: false,
286
+ freshness: getIndexFreshness({ memoryRoot: root, now }),
287
+ wouldWrite: after,
288
+ message:
289
+ `dry-run:扫描到 ${cards.length} 张卡(legacy ${legacy},程序性 ${procedures.length}` +
290
+ `${invalid > 0 ? `,坏卡 ${invalid}` : ''});raw 策略=${rawPolicy.policy}` +
291
+ `→ ${changed ? 'INDEX.md 会变化' : 'INDEX.md 已是最新'};加 apply:true 才落盘`,
292
+ };
293
+ }
294
+
295
+ if (args.ifChanged === true && !contentChanged) {
296
+ updateState(root, {
297
+ indexLastRefreshAt: now.toISOString(),
298
+ indexFreshness: 'fresh',
299
+ indexLastError: null,
300
+ }, { now });
301
+ const freshness = getIndexFreshness({ memoryRoot: root, now });
302
+ return {
303
+ ...base,
304
+ ok: true,
305
+ status: 'unchanged',
306
+ dryRun: false,
307
+ applied: false,
308
+ freshness,
309
+ indexBuiltAt: freshness.generatedAt,
310
+ message: `INDEX.md 已是最新(${cards.length} 行),未重写。`,
311
+ };
312
+ }
313
+
314
+ const write = writeFileAtomic(root, indexPath, after, { backup: true, now });
315
+ const readBack = fs.readFileSync(indexPath, 'utf8');
316
+ if (readBack !== after) {
317
+ throw memoryError('E_INDEX_VERIFY', `INDEX.md 写入后读回不一致:${indexPath}`);
318
+ }
319
+ updateState(root, {
320
+ indexBuiltAt: now.toISOString(),
321
+ indexDataAt: now.toISOString(),
322
+ indexFreshness: 'fresh',
323
+ indexLagMs: 0,
324
+ indexLastRefreshAt: now.toISOString(),
325
+ indexLastError: null,
326
+ }, { now });
327
+ appendAudit(root, {
328
+ action: 'memory_index',
329
+ object: INDEX_FILE,
330
+ result: `cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} raw=${rawPolicy.policy} changed=${changed}`,
331
+ now,
332
+ });
333
+ const freshness = getIndexFreshness({ memoryRoot: root, now });
334
+ return {
335
+ ...base,
336
+ ok: true,
337
+ status: 'applied',
338
+ dryRun: false,
339
+ applied: true,
340
+ freshness,
341
+ backup: write.backup,
342
+ backupRel: write.backupRel,
343
+ sha256: write.sha256,
344
+ indexBuiltAt: now.toISOString(),
345
+ message:
346
+ `已重建 INDEX.md:${cards.length} 行(legacy ${legacy},程序性 ${procedures.length}` +
347
+ `${invalid > 0 ? `,坏卡 ${invalid}` : ''}),备份 ${write.backupRel ?? '(首次创建,无旧文件)'}`,
348
+ };
349
+ }
350
+
351
+ /** Read the generated region of an INDEX.md text, or null when absent. */
352
+ export function extractGeneratedSection(text) {
353
+ const source = String(text ?? '');
354
+ const begin = source.indexOf(BEGIN_GENERATED);
355
+ if (begin < 0) return null;
356
+ const end = source.indexOf(END_GENERATED, begin);
357
+ if (end < 0) return null;
358
+ return source.slice(begin, end + END_GENERATED.length);
359
+ }
360
+
361
+ /** Local-day helper re-exported for tests and reports. */
362
+ export { dayString };