@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,476 @@
1
+ // WP3 durable proposal store.
2
+ //
3
+ // DESIGN §3.1/§3.2 put everything derived under `<vault>/proposals/`; this
4
+ // module owns the file-level half of that contract:
5
+ // - strict atomic JSON write (tmp -> fsync -> rename -> read-back byte/sha)
6
+ // - proposal directory scan / read-by-id / non-terminal quota
7
+ // - append-only WAL lines used by the ticket allocator
8
+ // - queue.json read-back (the queue view is derived; the WAL wins)
9
+ //
10
+ // It never creates a directory unless a write is requested, so the default-off
11
+ // surface (routerEnabled=false, routerProposalEnabled=false) keeps zero disk
12
+ // side effects. Arithmetic lives in proposals.mjs, not here.
13
+
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+
19
+ import { ensureDir, sha256Hex } from './paths.mjs';
20
+
21
+ export const PROPOSAL_VERSION = 1;
22
+ export const PROPOSAL_FILE_MAX_BYTES = 16 * 1024; // DESIGN §3.3: 单文件 ≤16 KB(content 4,000 字 + 元数据)
23
+ export const PROPOSAL_TARGET_MAX_BYTES = 256 * 1024;
24
+ export const QUEUE_MAX_BYTES = 64 * 1024;
25
+ export const QUEUE_MAX_ENTRIES = 200;
26
+
27
+ export const PROPOSAL_ID_RE = /^p-\d{8}T\d{6}-[0-9a-f]{6}$/u;
28
+
29
+ export const PROPOSAL_STATUSES = Object.freeze([
30
+ 'pending',
31
+ // Legacy 1.1.0 alias. New proposals are written as `pending`, but a vault
32
+ // produced by 1.1.0 must stay readable after an in-place upgrade.
33
+ 'queued',
34
+ 'approved',
35
+ 'applying',
36
+ 'blocked-on-user',
37
+ 'done',
38
+ 'rejected',
39
+ 'conflict',
40
+ 'superseded',
41
+ 'rolled_back',
42
+ 'cancelled',
43
+ 'expired',
44
+ ]);
45
+
46
+ export const TERMINAL_PROPOSAL_STATUSES = Object.freeze([
47
+ 'done',
48
+ 'rejected',
49
+ 'conflict',
50
+ 'superseded',
51
+ 'rolled_back',
52
+ 'cancelled',
53
+ 'expired',
54
+ ]);
55
+
56
+ const TERMINAL = new Set(TERMINAL_PROPOSAL_STATUSES);
57
+
58
+ export function isTerminalProposalStatus(status) {
59
+ return TERMINAL.has(status);
60
+ }
61
+
62
+ export class StoreError extends Error {
63
+ constructor(code, message, extra = {}) {
64
+ super(message ?? code);
65
+ this.name = 'StoreError';
66
+ this.code = code;
67
+ Object.assign(this, extra);
68
+ }
69
+ }
70
+
71
+ function readText(file) {
72
+ try {
73
+ return { ok: true, text: fs.readFileSync(file, 'utf8') };
74
+ } catch (error) {
75
+ return { ok: false, error: error?.code ?? 'E_READ', message: error?.message ?? String(error) };
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Strict durable JSON write. Unlike paths.writeJsonAtomic this verifies the
81
+ * FINAL path after rename and throws `E_STORE_READBACK` when the bytes on disk
82
+ * no longer match what was written (DESIGN §5.3 already-write detection).
83
+ */
84
+ export function writeJsonStrict(file, value, options = {}) {
85
+ const retries = Number.isInteger(options.retries) ? options.retries : 5;
86
+ const text = `${JSON.stringify(value, null, 2)}\n`;
87
+ const bytes = Buffer.byteLength(text, 'utf8');
88
+ const digest = sha256Hex(text);
89
+ const dir = path.dirname(file);
90
+ if (!ensureDir(dir)) throw new StoreError('E_STORAGE', `cannot create ${dir}`, { file });
91
+ let lastError = null;
92
+ for (let attempt = 0; attempt < retries; attempt += 1) {
93
+ const tmp = path.join(dir, `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
94
+ try {
95
+ const fd = fs.openSync(tmp, 'w');
96
+ try {
97
+ fs.writeFileSync(fd, text, 'utf8');
98
+ try { fs.fsyncSync(fd); } catch { /* fsync is best effort on some filesystems */ }
99
+ } finally {
100
+ try { fs.closeSync(fd); } catch { /* ignore */ }
101
+ }
102
+ fs.renameSync(tmp, file);
103
+ const back = readText(file);
104
+ if (!back.ok || back.text !== text || Buffer.byteLength(back.text, 'utf8') !== bytes || sha256Hex(back.text) !== digest) {
105
+ throw new StoreError('E_STORE_READBACK', `read-back mismatch for ${file}`, { file, bytes, sha256: digest });
106
+ }
107
+ return { ok: true, file, bytes, sha256: digest };
108
+ } catch (error) {
109
+ lastError = error;
110
+ try { fs.rmSync(tmp, { force: true }); } catch { /* ignore */ }
111
+ if (error?.code === 'E_STORE_READBACK') break;
112
+ }
113
+ }
114
+ throw lastError instanceof StoreError
115
+ ? lastError
116
+ : new StoreError(lastError?.code ?? 'E_STORAGE', lastError?.message ?? String(lastError ?? 'write failed'), {
117
+ file,
118
+ bytes,
119
+ sha256: digest,
120
+ });
121
+ }
122
+
123
+ /**
124
+ * D-CR13: the 16 KB cap is on the COMPLETE serialized proposal JSON, not just
125
+ * `content`. Both the write path and the read path enforce it.
126
+ */
127
+ export function writeProposalFile(file, value, options = {}) {
128
+ const { __file, ...clean } = value ?? {};
129
+ const text = `${JSON.stringify(clean, null, 2)}\n`;
130
+ const bytes = Buffer.byteLength(text, 'utf8');
131
+ if (bytes > PROPOSAL_FILE_MAX_BYTES) {
132
+ throw new StoreError('E_CONTENT_TOO_LARGE', `proposal JSON exceeds ${PROPOSAL_FILE_MAX_BYTES} bytes`, {
133
+ file,
134
+ limit: PROPOSAL_FILE_MAX_BYTES,
135
+ actual: bytes,
136
+ });
137
+ }
138
+ return writeJsonStrict(file, clean, options);
139
+ }
140
+
141
+ // R-02: cross-process compare-and-write. `<proposalsDir>/<id>.lock` is an
142
+ // inter-process mutex created with open(wx) (never a rename), so two writers
143
+ // can never both believe they own the read-check-write window. Lock holders
144
+ // that are provably gone (same-host dead pid, or a foreign-host lock older than
145
+ // the stale threshold) are moved to an evidence file, then the CAS is repeated.
146
+ const PROPOSAL_LOCK_STALE_MS = 5_000;
147
+ const PROPOSAL_LOCK_WAIT_MS = 2_000;
148
+ const PROPOSAL_LOCK_BACKOFF_MS = 25;
149
+
150
+ function sleepMs(ms) {
151
+ if (!(ms > 0)) return;
152
+ try {
153
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
154
+ } catch {
155
+ const until = Date.now() + ms;
156
+ while (Date.now() < until) { /* bounded busy wait fallback */ }
157
+ }
158
+ }
159
+
160
+ function localPidAlive(pid) {
161
+ if (!Number.isInteger(pid) || pid <= 0) return false;
162
+ try {
163
+ process.kill(pid, 0);
164
+ return true;
165
+ } catch (error) {
166
+ return error?.code === 'EPERM';
167
+ }
168
+ }
169
+
170
+ function readLockRecord(file) {
171
+ try {
172
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
173
+ return value && typeof value === 'object' ? value : null;
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ function lockIdentity(value) {
180
+ if (!value || typeof value !== 'object') return null;
181
+ return [value.pid ?? '', value.host ?? '', value.nonce ?? '', value.startedAt ?? ''].join('|');
182
+ }
183
+
184
+ function proposalLockIsStale(file, holder, staleMs) {
185
+ let stat = null;
186
+ try { stat = fs.statSync(file); } catch { return true; }
187
+ if (!(Date.now() - stat.mtimeMs > staleMs)) return false;
188
+ if (!holder) return true; // unreadable payload that is already old
189
+ const host = typeof holder.host === 'string' && holder.host !== '' ? holder.host : os.hostname();
190
+ if (host === os.hostname()) return !localPidAlive(holder.pid);
191
+ // A foreign host cannot be probed for pid liveness; age is the only evidence.
192
+ return true;
193
+ }
194
+
195
+ /** Rename the observed stale lock out of the way, then verify the moved bytes. */
196
+ function reclaimProposalLock(file, observed) {
197
+ const evidence = `${file}.reclaimed-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`;
198
+ try {
199
+ fs.renameSync(file, evidence);
200
+ } catch {
201
+ return false;
202
+ }
203
+ const moved = readLockRecord(evidence);
204
+ if (lockIdentity(moved) !== lockIdentity(observed)) {
205
+ // A fresh holder raced in between; put its bytes back when the path is free.
206
+ try {
207
+ if (!fs.existsSync(file)) fs.renameSync(evidence, file);
208
+ } catch { /* leave the evidence file; the owner still holds its own bytes */ }
209
+ return false;
210
+ }
211
+ return true;
212
+ }
213
+
214
+ /**
215
+ * Acquire `<proposalsDir>/<id>.lock` with open(wx), write+fsync+close, then read
216
+ * back our own nonce. On contention wait in 25 ms steps for at most 2 s; stale
217
+ * holders are reclaimed with a rename-to-evidence first. Failure to win the lock
218
+ * is `E_STORAGE` with `retryable:true` (never a crash, never a silent write).
219
+ */
220
+ function acquireProposalLock(proposalsDir, id, options = {}) {
221
+ const file = proposalLockPath(proposalsDir, id);
222
+ const waitMs = Number.isInteger(options.lockWaitMs) ? options.lockWaitMs : PROPOSAL_LOCK_WAIT_MS;
223
+ const staleMs = Number.isInteger(options.lockStaleMs) ? options.lockStaleMs : PROPOSAL_LOCK_STALE_MS;
224
+ const backoffMs = Number.isInteger(options.lockBackoffMs) ? options.lockBackoffMs : PROPOSAL_LOCK_BACKOFF_MS;
225
+ const token = {
226
+ pid: process.pid,
227
+ host: os.hostname(),
228
+ nonce: crypto.randomBytes(12).toString('hex'),
229
+ startedAt: new Date().toISOString(),
230
+ };
231
+ if (!ensureDir(proposalsDir)) {
232
+ throw new StoreError('E_STORAGE', `cannot create ${proposalsDir}`, { id, retryable: true });
233
+ }
234
+ const deadline = Date.now() + Math.max(0, waitMs);
235
+
236
+ for (;;) {
237
+ let fd = null;
238
+ try {
239
+ fd = fs.openSync(file, 'wx', 0o600);
240
+ } catch (error) {
241
+ if (error?.code !== 'EEXIST') {
242
+ throw new StoreError('E_STORAGE', `cannot lock proposal ${id}`, {
243
+ id,
244
+ cause: error?.code ?? 'E_LOCK',
245
+ retryable: true,
246
+ });
247
+ }
248
+ const holder = readLockRecord(file);
249
+ if (proposalLockIsStale(file, holder, staleMs) && reclaimProposalLock(file, holder)) continue;
250
+ if (Date.now() >= deadline) {
251
+ throw new StoreError('E_STORAGE', `proposal ${id} is locked by another process`, {
252
+ id,
253
+ lock: holder ?? null,
254
+ retryable: true,
255
+ });
256
+ }
257
+ sleepMs(backoffMs);
258
+ continue;
259
+ }
260
+
261
+ try {
262
+ fs.writeFileSync(fd, `${JSON.stringify(token)}\n`, 'utf8');
263
+ try { fs.fsyncSync(fd); } catch { /* fsync is best effort on some filesystems */ }
264
+ } catch (error) {
265
+ try { fs.closeSync(fd); } catch { /* ignore */ }
266
+ try { fs.unlinkSync(file); } catch { /* wx means these are our own bytes */ }
267
+ throw new StoreError('E_STORAGE', `cannot write proposal lock ${id}`, {
268
+ id,
269
+ cause: error?.code ?? 'E_LOCK_WRITE',
270
+ retryable: true,
271
+ });
272
+ }
273
+ try { fs.closeSync(fd); } catch { /* ignore */ }
274
+
275
+ const back = readLockRecord(file);
276
+ if (!back || back.nonce !== token.nonce || lockIdentity(back) !== lockIdentity(token)) {
277
+ // Our lock was reclaimed or replaced while we were writing: never unlink
278
+ // a path we can no longer prove is ours.
279
+ throw new StoreError('E_STORAGE', `proposal lock ${id} changed hands`, { id, retryable: true });
280
+ }
281
+ return { file, token };
282
+ }
283
+ }
284
+
285
+ function releaseProposalLock(handle) {
286
+ if (!handle || !handle.file || !handle.token) return false;
287
+ const holder = readLockRecord(handle.file);
288
+ if (!holder || holder.nonce !== handle.token.nonce || holder.pid !== handle.token.pid) return false;
289
+ try {
290
+ fs.unlinkSync(handle.file);
291
+ return true;
292
+ } catch {
293
+ return false;
294
+ }
295
+ }
296
+
297
+ export function proposalLockPath(proposalsDir, id) {
298
+ return path.join(proposalsDir, `${id}.lock`);
299
+ }
300
+
301
+ /**
302
+ * D-CR7 + R-02: every proposal write point goes through one compare-then-write
303
+ * helper under an inter-process mutex. `expectedRev` is the rev the caller read;
304
+ * a mismatch is E_STATE_RACE and the file is left untouched. Callers retry with
305
+ * a fresh read (bounded). Lock acquisition failure is a retryable E_STORAGE.
306
+ */
307
+ export function updateProposalStrict(proposalsDir, id, expectedRev, mutate, options = {}) {
308
+ if (typeof proposalsDir !== 'string' || proposalsDir === ''
309
+ || typeof id !== 'string' || !PROPOSAL_ID_RE.test(id)) {
310
+ throw new StoreError('E_TICKET_UNKNOWN', `proposal not found: ${id}`, { id });
311
+ }
312
+ let dirExists = false;
313
+ try { dirExists = fs.statSync(proposalsDir).isDirectory(); } catch { dirExists = false; }
314
+ if (!dirExists) throw new StoreError('E_TICKET_UNKNOWN', `proposal not found: ${id}`, { id });
315
+
316
+ const lock = acquireProposalLock(proposalsDir, id, options);
317
+ try {
318
+ const current = readProposal(proposalsDir, id);
319
+ if (!current) throw new StoreError('E_TICKET_UNKNOWN', `proposal not found: ${id}`, { id });
320
+ const { __file, ...base } = current;
321
+ if (expectedRev !== null && expectedRev !== undefined && base.rev !== expectedRev) {
322
+ throw new StoreError('E_STATE_RACE', 'proposal changed since it was read', {
323
+ id,
324
+ rev: base.rev ?? null,
325
+ expectedRev,
326
+ });
327
+ }
328
+ const patch = typeof mutate === 'function' ? (mutate({ ...base }) ?? {}) : (mutate ?? {});
329
+ const now = options.now instanceof Date ? options.now : (typeof options.now === 'function' ? options.now() : new Date());
330
+ const next = {
331
+ ...base,
332
+ ...patch,
333
+ rev: (base.rev ?? 0) + 1,
334
+ updatedAt: now.toISOString(),
335
+ };
336
+ writeProposalFile(path.join(proposalsDir, `${id}.json`), next, options);
337
+ return next;
338
+ } finally {
339
+ releaseProposalLock(lock);
340
+ }
341
+ }
342
+
343
+ function readProposalValue(file, invalid) {
344
+ const read = readText(file);
345
+ if (!read.ok) {
346
+ invalid.push({ file, error: read.error });
347
+ return null;
348
+ }
349
+ if (Buffer.byteLength(read.text, 'utf8') > PROPOSAL_FILE_MAX_BYTES) {
350
+ invalid.push({ file, error: 'E_CONTENT_TOO_LARGE' });
351
+ return null;
352
+ }
353
+ let value = null;
354
+ try {
355
+ value = JSON.parse(read.text);
356
+ } catch (error) {
357
+ invalid.push({ file, error: 'E_PARSE', message: error?.message ?? String(error) });
358
+ return null;
359
+ }
360
+ if (!value || typeof value !== 'object' || value.v !== PROPOSAL_VERSION
361
+ || typeof value.id !== 'string' || !PROPOSAL_ID_RE.test(value.id)
362
+ || typeof value.status !== 'string' || !PROPOSAL_STATUSES.includes(value.status)
363
+ || !value.queue || typeof value.queue.ticket !== 'string') {
364
+ invalid.push({ file, error: 'E_INVALID_PROPOSAL' });
365
+ return null;
366
+ }
367
+ return value;
368
+ }
369
+
370
+ /**
371
+ * Scan `<vault>/proposals/*.json`. Missing directory = empty result, never an
372
+ * error and never a directory creation. Invalid files are counted and skipped,
373
+ * never deleted or rewritten (DESIGN F17).
374
+ */
375
+ export function scanProposalDir(dir) {
376
+ if (typeof dir !== 'string' || dir === '') return { proposals: [], invalid: [], files: [] };
377
+ let names = [];
378
+ try {
379
+ names = fs.readdirSync(dir).filter((name) => name.endsWith('.json') && !name.startsWith('.')).sort();
380
+ } catch (error) {
381
+ if (error?.code === 'ENOENT') return { proposals: [], invalid: [], files: [] };
382
+ return { proposals: [], invalid: [{ file: dir, error: error?.code ?? 'E_READ' }], files: [] };
383
+ }
384
+ const proposals = [];
385
+ const invalid = [];
386
+ const files = [];
387
+ for (const name of names) {
388
+ const file = path.join(dir, name);
389
+ files.push(file);
390
+ const value = readProposalValue(file, invalid);
391
+ if (value) proposals.push({ ...value, __file: file });
392
+ }
393
+ proposals.sort((a, b) => {
394
+ const at = Date.parse(a.createdAt ?? '');
395
+ const bt = Date.parse(b.createdAt ?? '');
396
+ if (Number.isFinite(at) && Number.isFinite(bt) && at !== bt) return at - bt;
397
+ return String(a.id).localeCompare(String(b.id));
398
+ });
399
+ return { proposals, invalid, files };
400
+ }
401
+
402
+ /** Read one proposal by id; ids are validated so `../` can never escape. */
403
+ export function readProposal(dir, id) {
404
+ if (typeof id !== 'string' || !PROPOSAL_ID_RE.test(id)) return null;
405
+ const file = path.join(dir, `${id}.json`);
406
+ const invalid = [];
407
+ const value = readProposalValue(file, invalid);
408
+ return value ? { ...value, __file: file } : null;
409
+ }
410
+
411
+ export function countNonTerminal(proposals) {
412
+ return (Array.isArray(proposals) ? proposals : []).filter((p) => !isTerminalProposalStatus(p?.status)).length;
413
+ }
414
+
415
+ /** Append one JSON line and fsync it before returning (WAL ordering contract). */
416
+ export function appendJsonLineDurable(file, value) {
417
+ const dir = path.dirname(file);
418
+ if (!ensureDir(dir)) throw new StoreError('E_STORAGE', `cannot create ${dir}`, { file });
419
+ const line = `${JSON.stringify(value)}\n`;
420
+ const fd = fs.openSync(file, 'a');
421
+ try {
422
+ fs.writeFileSync(fd, line, 'utf8');
423
+ try { fs.fsyncSync(fd); } catch { /* best effort */ }
424
+ } finally {
425
+ try { fs.closeSync(fd); } catch { /* ignore */ }
426
+ }
427
+ return { bytes: Buffer.byteLength(line, 'utf8'), sha256: sha256Hex(line) };
428
+ }
429
+
430
+ export function readWalLines(file) {
431
+ const read = readText(file);
432
+ if (!read.ok) return { lines: [], error: read.error };
433
+ const lines = [];
434
+ for (const raw of read.text.split('\n')) {
435
+ if (raw.trim() === '') continue;
436
+ try {
437
+ const value = JSON.parse(raw);
438
+ if (value && typeof value === 'object') lines.push(value);
439
+ } catch {
440
+ /* WP3 does not own WAL recovery; WP4 replays and marks wal.corrupt */
441
+ }
442
+ }
443
+ return { lines };
444
+ }
445
+
446
+ export function readQueueFile(file) {
447
+ const read = readText(file);
448
+ if (!read.ok) return null;
449
+ try {
450
+ const value = JSON.parse(read.text);
451
+ return value && typeof value === 'object' ? value : null;
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+
457
+ export function readTargetSnapshot(file) {
458
+ try {
459
+ const stat = fs.lstatSync(file);
460
+ if (stat.isSymbolicLink()) return { ok: false, code: 'E_PATH_DENIED', message: 'target is a symlink' };
461
+ if (!stat.isFile()) return { ok: false, code: 'E_PATH_DENIED', message: 'target is not a regular file' };
462
+ if (stat.size > PROPOSAL_TARGET_MAX_BYTES) {
463
+ return { ok: false, code: 'E_CONTENT_TOO_LARGE', message: 'target exceeds 256 KB' };
464
+ }
465
+ const text = fs.readFileSync(file, 'utf8');
466
+ return {
467
+ ok: true,
468
+ exists: true,
469
+ bytes: Buffer.byteLength(text, 'utf8'),
470
+ sha256: sha256Hex(text),
471
+ };
472
+ } catch (error) {
473
+ if (error?.code === 'ENOENT') return { ok: true, exists: false, bytes: 0, sha256: null };
474
+ return { ok: false, code: error?.code === 'EACCES' ? 'E_PATH_DENIED' : 'E_STORAGE', message: error?.message };
475
+ }
476
+ }