@jjh32456/longlive 0.0.0-stage → 2.0.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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -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 +839 -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 +48 -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 +163 -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-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,425 @@
1
+ // B3 card writer: provenance + conflict detection + `conflict` markers.
2
+ //
3
+ // Every memory card that this package writes (today `memory_procedure`, later
4
+ // A1 write-back / identityCard) should go through here or the procedure writer,
5
+ // so one place decides:
6
+ //
7
+ // * the three provenance extras (provenance.js);
8
+ // * whether the new card disagrees with a card already on disk
9
+ // (`detectConflicts`);
10
+ // * how a disagreement is recorded (`conflict` on the new card,
11
+ // `conflict_with` on the old one).
12
+ //
13
+ // An old card's prose is never replaced. Writing the marker on the old card
14
+ // only touches its frontmatter, preserves the body byte-for-byte, and keeps a
15
+ // backup first. A new card whose `rel` already exists is refused with
16
+ // `E_CARD_EXISTS` instead of silently overwriting it.
17
+ //
18
+ // Conflict taxonomy (deliberately narrow, so unrelated conclusions do not
19
+ // light up):
20
+ //
21
+ // same-slug same path as an existing card, different body
22
+ // same-title normalized title equals, normalized body differs
23
+ // same-key-opposite normalized `key` equals and the two bodies have
24
+ // opposite polarity (one negates / disables / fails,
25
+ // the other does not)
26
+ //
27
+ // A same-key pair that differs but has the same polarity is NOT a conflict:
28
+ // two positive alternatives ("蓝绿" vs "滚动") are a choice, not a
29
+ // contradiction. The marker therefore means "these two cannot both be acted
30
+ // on", which is exactly what a reader needs to resolve.
31
+
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+
35
+ import {
36
+ memoryError, memoryRootFromConfig, relativePath, resolveInside,
37
+ } from './paths.js';
38
+ import {
39
+ DEFAULT_FIELDS, FIELD_ORDER, dayString, normalizedBody, parseFrontmatter, serializeFrontmatter,
40
+ updateExtras,
41
+ } from './frontmatter.js';
42
+ import {
43
+ backupFile, listMarkdownFiles, restoreBackup, sha256Text, writeFileAtomic,
44
+ } from './state.js';
45
+ import { sourceStamp, stampExtras, MANUAL_SESSION } from './provenance.js';
46
+ import { CARD_DIRS, manifestPath, refreshManifest } from './manifest.js';
47
+
48
+ const REL_PATTERN = /^(topics|journal|procedures)\/[^\r\n]+\.md$/i;
49
+ // The conflict marker is a single-line list. A comma or bracket inside a path
50
+ // would make the list unreadable, so such a card path is refused up front.
51
+ const UNSAFE_REL_CHARS = /[,\[\]\r\n]/;
52
+
53
+ function isPlainObject(value) {
54
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
55
+ }
56
+
57
+ function singleLine(field, value) {
58
+ const text = String(value ?? '').replace(/[\r\n]+/g, ' ').trim();
59
+ if (text === '') throw memoryError('E_BAD_ARGUMENT', `${field} 不能为空`);
60
+ if (text.length > 500) throw memoryError('E_BAD_ARGUMENT', `${field} 过长(>500 字符)`);
61
+ return text;
62
+ }
63
+
64
+ function normalizeKey(value) {
65
+ if (value === undefined || value === null) return null;
66
+ const text = singleLine('key', value);
67
+ return text.toLowerCase();
68
+ }
69
+
70
+ /**
71
+ * Normalize a card path to POSIX-relative form and refuse anything that is not
72
+ * a markdown card in topics/, journal/ or procedures/.
73
+ */
74
+ export function normalizeCardRel(root, value) {
75
+ const raw = typeof value === 'string' ? value.trim() : '';
76
+ if (raw === '') {
77
+ throw memoryError('E_BAD_ARGUMENT', 'writeCard 需要 rel(如 topics/结论.md)');
78
+ }
79
+ const rel = path.isAbsolute(raw) ? relativePath(root, raw) : raw.replace(/\\/g, '/');
80
+ if (UNSAFE_REL_CHARS.test(rel)) {
81
+ throw memoryError('E_BAD_ARGUMENT', `卡片路径不能包含 , [ ] 或换行(冲突标记是行内列表):${rel}`);
82
+ }
83
+ if (!REL_PATTERN.test(rel)) {
84
+ throw memoryError(
85
+ 'E_BAD_ARGUMENT',
86
+ `卡片路径必须位于 ${CARD_DIRS.join(' / ')} 之一且以 .md 结尾:${JSON.stringify(rel)}`,
87
+ );
88
+ }
89
+ // resolveInside both validates containment and proves the real path stays in
90
+ // the store (junction/symlink guard).
91
+ resolveInside(root, rel);
92
+ return rel;
93
+ }
94
+
95
+ function firstHeading(body) {
96
+ const match = /^#\s+(.+)$/m.exec(String(body ?? ''));
97
+ return match ? match[1].trim() : null;
98
+ }
99
+
100
+ /** Compare text without case, whitespace or punctuation noise. */
101
+ function comparisonText(value) {
102
+ return String(value ?? '')
103
+ .toLowerCase()
104
+ .replace(/[\s\u3000]+/g, '')
105
+ .replace(/[。!?!?,,;;::、..\-—_()()【】\[\]「」『』“”"'’‘]/g, '');
106
+ }
107
+
108
+ const NEGATIVE_TERMS = Object.freeze([
109
+ '不支持', '不允许', '不使用', '不采用', '不选', '不推荐', '不建议',
110
+ '不要', '不能', '不可', '不需要', '不必', '不用', '不做',
111
+ '不开启', '不启用', '不保留', '不删除', '没有', '无需', '禁止', '避免', '拒绝',
112
+ '关闭', '禁用', '停用', '取消', '删除', '移除', '放弃', '失败',
113
+ '未使用', '未采用', '未启用', '未通过',
114
+ ]);
115
+ const EN_NEGATIVE = /\b(?:not|never|no|without|disable|disabled|forbid|forbidden|avoid|reject|remove|failed|failure|off)\b/i;
116
+
117
+ /** True when a conclusion negates or disables something. */
118
+ export function isNegativeConclusion(text) {
119
+ const source = String(text ?? '');
120
+ if (NEGATIVE_TERMS.some((term) => source.includes(term))) return true;
121
+ return EN_NEGATIVE.test(source);
122
+ }
123
+
124
+ function oppositePolarity(left, right) {
125
+ return isNegativeConclusion(left) !== isNegativeConclusion(right);
126
+ }
127
+
128
+ function readCardForConflict(root, abs) {
129
+ const rel = relativePath(root, abs);
130
+ const text = fs.readFileSync(abs, 'utf8');
131
+ let parsed = null;
132
+ let parseError = null;
133
+ try {
134
+ parsed = parseFrontmatter(text);
135
+ } catch (error) {
136
+ parseError = error?.code ?? 'E_CARD_PARSE';
137
+ }
138
+ const fallbackTitle = path.basename(abs, '.md');
139
+ if (parsed === null || parsed.legacy) {
140
+ return {
141
+ abs,
142
+ rel,
143
+ text,
144
+ title: firstHeading(text) ?? fallbackTitle,
145
+ body: text,
146
+ key: null,
147
+ keyNorm: null,
148
+ parseError,
149
+ };
150
+ }
151
+ const key = typeof parsed.extras.key === 'string' ? parsed.extras.key : null;
152
+ return {
153
+ abs,
154
+ rel,
155
+ text,
156
+ title: parsed.fields.title || parsed.extras.name || firstHeading(parsed.body) || fallbackTitle,
157
+ body: parsed.body,
158
+ key,
159
+ keyNorm: key === null ? null : key.trim().toLowerCase(),
160
+ parseError,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Find cards that disagree with `candidate`.
166
+ *
167
+ * `candidate` = `{rel, title, body, key}`. Returns one row per conflicting
168
+ * card: `{rel, title, reasons, key}`. Same-key alternatives with the same
169
+ * polarity are not reported (see the taxonomy at the top of the file).
170
+ */
171
+ export function detectConflicts(root, candidate = {}) {
172
+ if (!isPlainObject(candidate)) {
173
+ throw memoryError('E_BAD_ARGUMENT', 'detectConflicts 需要 candidate 对象');
174
+ }
175
+ const rel = normalizeCardRel(root, candidate.rel);
176
+ const titleNorm = comparisonText(candidate.title);
177
+ const bodyNorm = comparisonText(candidate.body);
178
+ const keyNorm = candidate.key === undefined || candidate.key === null
179
+ ? null
180
+ : normalizeKey(candidate.key);
181
+ const found = [];
182
+ for (const dir of CARD_DIRS) {
183
+ for (const abs of listMarkdownFiles(root, dir)) {
184
+ const existing = readCardForConflict(root, abs);
185
+ const reasons = [];
186
+ if (existing.rel === rel) {
187
+ if (comparisonText(existing.body) !== bodyNorm) reasons.push('same-slug');
188
+ } else {
189
+ if (titleNorm !== '' && comparisonText(existing.title) === titleNorm
190
+ && comparisonText(existing.body) !== bodyNorm) {
191
+ reasons.push('same-title');
192
+ }
193
+ if (keyNorm !== null && existing.keyNorm === keyNorm
194
+ && comparisonText(existing.body) !== bodyNorm
195
+ && oppositePolarity(candidate.body, existing.body)) {
196
+ reasons.push('same-key-opposite-conclusion');
197
+ }
198
+ }
199
+ if (reasons.length > 0) {
200
+ found.push({ rel: existing.rel, title: existing.title, reasons, key: existing.key });
201
+ }
202
+ }
203
+ }
204
+ found.sort((left, right) => (left.rel < right.rel ? -1 : left.rel > right.rel ? 1 : 0));
205
+ return found;
206
+ }
207
+
208
+ function formatCardList(rels) {
209
+ const unique = [...new Set(rels.filter((rel) => typeof rel === 'string' && rel.trim() !== ''))];
210
+ return `[${unique.join(', ')}]`;
211
+ }
212
+
213
+ /**
214
+ * Append `newRel` to an existing card's `conflict_with` list.
215
+ *
216
+ * Only the frontmatter changes; the prose body is compared before/after and
217
+ * restored from the pre-write backup if it moved. Returns
218
+ * `{rel, changed, backup?, backupRel?, sha256}`.
219
+ */
220
+ export function appendConflictWith(root, oldRel, newRel, { now = new Date() } = {}) {
221
+ const abs = resolveInside(root, oldRel);
222
+ if (!fs.existsSync(abs)) {
223
+ throw memoryError('E_CARD_NOT_FOUND', `冲突标记目标不存在:${oldRel}`);
224
+ }
225
+ const text = fs.readFileSync(abs, 'utf8');
226
+ const before = parseFrontmatter(text);
227
+ const existing = before.extras.conflict_with ?? '';
228
+ const current = /^\[(.*)\]$/.test(existing.trim())
229
+ ? existing.trim().slice(1, -1).split(',').map((part) => part.trim()).filter(Boolean)
230
+ : (existing.trim() === '' ? [] : [existing.trim()]);
231
+ if (current.includes(newRel)) {
232
+ return { rel: oldRel, changed: false, sha256: sha256Text(text) };
233
+ }
234
+ const updated = updateExtras(text, { conflict_with: formatCardList([...current, newRel]) });
235
+ const backup = backupFile(root, abs, { now });
236
+ try {
237
+ writeFileAtomic(root, abs, updated, { backup: false, now });
238
+ const readBack = fs.readFileSync(abs, 'utf8');
239
+ if (readBack !== updated) {
240
+ throw memoryError('E_CARD_VERIFY', `冲突标记写后校验失败:${oldRel}`);
241
+ }
242
+ if (normalizedBody(parseFrontmatter(readBack).body) !== normalizedBody(before.body)) {
243
+ throw memoryError('E_CARD_VERIFY', `冲突标记改动了旧卡正文:${oldRel}`);
244
+ }
245
+ return {
246
+ rel: oldRel,
247
+ changed: true,
248
+ backup: backup.path,
249
+ backupRel: backup.rel,
250
+ sha256: sha256Text(readBack),
251
+ };
252
+ } catch (error) {
253
+ try {
254
+ restoreBackup(root, backup.path, abs);
255
+ } catch (restoreError) {
256
+ throw memoryError('E_ROLLBACK_FAILED', `冲突标记失败且无法回滚:${oldRel}`, restoreError);
257
+ }
258
+ throw error instanceof Error && error.code ? error : memoryError('E_CARD_VERIFY', `冲突标记失败:${oldRel}`, error);
259
+ }
260
+ }
261
+
262
+ function normalizeFields(root, spec, title, now) {
263
+ const fields = { ...DEFAULT_FIELDS, ...(isPlainObject(spec.fields) ? spec.fields : {}) };
264
+ for (const key of Object.keys(spec.fields ?? {})) {
265
+ if (!FIELD_ORDER.includes(key)) {
266
+ throw memoryError('E_BAD_ARGUMENT', `fields 只接受标准字段 ${FIELD_ORDER.join(', ')};${key} 请放进 extras`);
267
+ }
268
+ }
269
+ fields.title = singleLine('title', title);
270
+ fields.date = singleLine('date', spec.date ?? fields.date ?? dayString(now));
271
+ fields.salience = fields.salience ?? DEFAULT_FIELDS.salience;
272
+ fields.strength = fields.strength ?? DEFAULT_FIELDS.strength;
273
+ fields.revisions = 0;
274
+ if (fields.tags == null) fields.tags = [];
275
+ if (fields.status == null) fields.status = DEFAULT_FIELDS.status;
276
+ return fields;
277
+ }
278
+
279
+ function normalizeExtras(root, spec, stamp) {
280
+ const extras = {};
281
+ if (isPlainObject(spec.extras)) {
282
+ for (const [key, value] of Object.entries(spec.extras)) {
283
+ if (FIELD_ORDER.includes(key)) {
284
+ throw memoryError('E_BAD_ARGUMENT', `extras 不能包含标准字段 ${key} — 请用 fields`);
285
+ }
286
+ if (value == null) continue;
287
+ extras[key] = singleLine(`extras.${key}`, value);
288
+ }
289
+ }
290
+ if (spec.key !== undefined && spec.key !== null) {
291
+ extras.key = singleLine('key', spec.key);
292
+ }
293
+ return stampExtras(extras, stamp);
294
+ }
295
+
296
+ function buildCardText(fields, extras, body) {
297
+ const block = serializeFrontmatter(fields, extras, '\n');
298
+ const prose = String(body).replace(/\r\n?/g, '\n').replace(/[\r\n]+$/, '');
299
+ return `${block}\n${prose === '' ? '' : `${prose}\n`}`;
300
+ }
301
+
302
+ /**
303
+ * Write one new card.
304
+ *
305
+ * Usage:
306
+ * writeCard(root, {rel, title?, body, key?, fields?, extras?}, {now?})
307
+ * writeCard({memoryRoot, rel, ...}) // config-style, for tools
308
+ *
309
+ * The card gets `source_session` / `source_turn` / `written_at`; conflicts are
310
+ * detected before the write, recorded on the new card, and mirrored onto each
311
+ * old card's `conflict_with`. The old cards' prose is never replaced.
312
+ */
313
+ export function writeCard(rootOrSpec, specOrOptions = {}, maybeOptions = {}) {
314
+ let root;
315
+ let spec;
316
+ let options;
317
+ if (typeof rootOrSpec === 'string') {
318
+ root = path.resolve(rootOrSpec);
319
+ spec = specOrOptions ?? {};
320
+ options = maybeOptions ?? {};
321
+ } else if (isPlainObject(rootOrSpec)) {
322
+ spec = rootOrSpec;
323
+ options = isPlainObject(specOrOptions) ? specOrOptions : {};
324
+ root = memoryRootFromConfig({ ...options, memoryRoot: options.memoryRoot ?? spec.memoryRoot ?? spec.root });
325
+ } else {
326
+ throw memoryError('E_BAD_ARGUMENT', 'writeCard 需要 memoryRoot 字符串或一个 spec 对象');
327
+ }
328
+ if (!isPlainObject(spec)) throw memoryError('E_BAD_ARGUMENT', 'writeCard 的 spec 必须是普通对象');
329
+ const now = options.now instanceof Date ? options.now : new Date();
330
+
331
+ const rel = normalizeCardRel(root, spec.rel ?? spec.path);
332
+ const abs = resolveInside(root, rel);
333
+ if (fs.existsSync(abs)) {
334
+ throw memoryError(
335
+ 'E_CARD_EXISTS',
336
+ `卡片已存在:${rel} — B3 拒绝覆盖旧卡(旧卡一个字节都不会动)。` +
337
+ '同一主题的新结论请用新的 rel;新旧冲突会自动写进 conflict / conflict_with 标记',
338
+ );
339
+ }
340
+
341
+ const body = typeof spec.body === 'string' ? spec.body : '';
342
+ if (body.trim() === '') throw memoryError('E_BAD_ARGUMENT', `writeCard 需要非空正文:${rel}`);
343
+ const title = spec.title ?? (isPlainObject(spec.fields) ? spec.fields.title : null)
344
+ ?? firstHeading(body) ?? path.basename(abs, '.md');
345
+ const sessionId = spec.sessionId ?? spec.source?.sessionId ?? spec.session ?? null;
346
+ const turn = spec.turn ?? spec.source?.turn ?? null;
347
+ const stampInput = { sessionId, turn, at: now };
348
+ const stamp = sourceStamp(stampInput);
349
+ const candidateKey = spec.key ?? (isPlainObject(spec.extras) ? spec.extras.key : null) ?? null;
350
+
351
+ const conflicts = detectConflicts(root, { rel, title, body, key: candidateKey });
352
+ const conflictRels = conflicts.map((row) => row.rel);
353
+
354
+ const fields = normalizeFields(root, spec, title, now);
355
+ const extras = normalizeExtras(root, spec, stampInput);
356
+ if (conflictRels.length > 0) {
357
+ const explicit = typeof extras.conflict === 'string' && extras.conflict.trim().startsWith('[')
358
+ ? extras.conflict.trim().slice(1, -1).split(',').map((part) => part.trim()).filter(Boolean)
359
+ : [];
360
+ extras.conflict = formatCardList([...explicit, ...conflictRels]);
361
+ }
362
+
363
+ const text = buildCardText(fields, extras, body);
364
+ const written = writeFileAtomic(root, abs, text, { backup: false, now });
365
+ const readBack = fs.readFileSync(abs, 'utf8');
366
+ if (readBack !== text) {
367
+ try { fs.unlinkSync(abs); } catch { /* the verify error is the one to report */ }
368
+ throw memoryError('E_CARD_VERIFY', `新卡写后校验失败,已删除:${rel}`);
369
+ }
370
+
371
+ const marked = [];
372
+ try {
373
+ for (const conflict of conflicts) {
374
+ marked.push(appendConflictWith(root, conflict.rel, rel, { now }));
375
+ }
376
+ } catch (error) {
377
+ // All-or-nothing from the caller's point of view: remove the new card and
378
+ // put back every old card whose marker was already written.
379
+ for (const row of marked.reverse()) {
380
+ if (!row.changed || !row.backup) continue;
381
+ try {
382
+ restoreBackup(root, row.backup, resolveInside(root, row.rel));
383
+ } catch {
384
+ /* best effort; the original error is the one to report */
385
+ }
386
+ }
387
+ try { fs.unlinkSync(abs); } catch { /* best effort */ }
388
+ throw error instanceof Error && error.code
389
+ ? error
390
+ : memoryError('E_CARD_VERIFY', `冲突标记失败,新卡已回滚:${rel}`, error);
391
+ }
392
+
393
+ let manifest = null;
394
+ let manifestWarning = null;
395
+ try {
396
+ const refreshed = refreshManifest(root, { now });
397
+ const cardCount = Array.isArray(refreshed.manifest?.cards) ? refreshed.manifest.cards.length : 0;
398
+ manifest = {
399
+ rel: relativePath(root, manifestPath(root)),
400
+ cards: cardCount,
401
+ sha256: refreshed.sha256,
402
+ };
403
+ } catch (error) {
404
+ manifestWarning = error?.message ?? String(error);
405
+ }
406
+
407
+ return {
408
+ ok: true,
409
+ status: 'created',
410
+ root,
411
+ path: abs,
412
+ rel,
413
+ title: fields.title,
414
+ sha256: written.sha256,
415
+ bytes: written.bytes,
416
+ source: { session: stamp.source_session, turn: stamp.source_turn, written_at: stamp.written_at },
417
+ conflicts: conflicts.map((row) => ({ rel: row.rel, title: row.title, reasons: row.reasons })),
418
+ conflictWith: marked.map((row) => row.rel),
419
+ manifest,
420
+ ...(manifestWarning === null ? {} : { manifestWarning }),
421
+ };
422
+ }
423
+
424
+ /** The session label a direct human write gets when no host session exists. */
425
+ export const DIRECT_WRITE_SESSION = MANUAL_SESSION;