@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,477 @@
1
+ // WP4a · proposal queue (DESIGN §3.4/§5.2/§5.4, K21/K25/K16).
2
+ //
3
+ // queue.json is a derived view: proposals are the row truth, the WAL is the
4
+ // assignment truth. rebuild() reconciles all three exactly as DESIGN §5.4 says:
5
+ // - queued proposal without a WAL queue.assign → keep the proposal, re-issue a
6
+ // TAIL ticket and append queue.assign.recovered (M-13, never delete);
7
+ // - orphan queue entry → drop the entry + audit queue.reconcile;
8
+ // - seqCounter = max(WAL ticket, proposal ticket, queue ticket) + 1.
9
+ //
10
+ // Aging/expiry transitions are applied to proposal files (rev CAS style) and
11
+ // then the queue file is rebuilt. This module never writes canonical memory.
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ import {
17
+ QUEUE_MAX_BYTES,
18
+ QUEUE_MAX_ENTRIES,
19
+ countNonTerminal,
20
+ readProposal,
21
+ readQueueFile,
22
+ scanProposalDir,
23
+ updateProposalStrict,
24
+ writeJsonStrict,
25
+ StoreError,
26
+ } from './store.mjs';
27
+ import { ETA_DEFAULTS_MS } from './proposals.mjs';
28
+ import { sha256Hex } from './paths.mjs';
29
+
30
+ export const QUEUE_STATE_GLOSSARY = Object.freeze({
31
+ queued: '待确认',
32
+ approved: '已准待写',
33
+ applying: '正在写',
34
+ 'blocked-on-user': '请主人判定',
35
+ expired: '已过期(不计入队列)',
36
+ });
37
+
38
+ const PRIORITY_INDEX = Object.freeze({ P0: 0, P1: 1, P2: 2, P3: 3, P4: 4 });
39
+
40
+ export function priorityIndex(priority) {
41
+ return PRIORITY_INDEX[priority] ?? 3;
42
+ }
43
+
44
+ export function priorityName(index) {
45
+ return Object.keys(PRIORITY_INDEX).find((name) => PRIORITY_INDEX[name] === index) ?? 'P3';
46
+ }
47
+
48
+ export function ticketNumber(ticket) {
49
+ const match = /^q-(\d{4,})$/u.exec(String(ticket ?? ''));
50
+ return match ? Number(match[1]) : 0;
51
+ }
52
+
53
+ export function ticketName(seq) {
54
+ return `q-${String(seq).padStart(4, '0')}`;
55
+ }
56
+
57
+ export function computeSeqCounter(...tickets) {
58
+ let max = 0;
59
+ for (const ticket of tickets.flat(Infinity)) {
60
+ max = Math.max(max, ticketNumber(ticket));
61
+ }
62
+ return max + 1;
63
+ }
64
+
65
+ function proposalValue(proposal) {
66
+ const { __file, ...value } = proposal ?? {};
67
+ return value;
68
+ }
69
+
70
+ /** Same order as DESIGN §5.2: effectivePriority → queuedAt → ticket. */
71
+ export function sortQueueEntries(entries) {
72
+ return [...entries].sort((a, b) => {
73
+ const byPriority = priorityIndex(a.effectivePriority) - priorityIndex(b.effectivePriority);
74
+ if (byPriority !== 0) return byPriority;
75
+ const at = Date.parse(a.queuedAt ?? 0);
76
+ const bt = Date.parse(b.queuedAt ?? 0);
77
+ if (at !== bt) return at - bt;
78
+ return ticketNumber(a.ticket) - ticketNumber(b.ticket);
79
+ });
80
+ }
81
+
82
+ export class QueueManager {
83
+ constructor({ paths, config = {}, wal = null, audit = null, now = () => new Date(), logger = null } = {}) {
84
+ this.paths = paths;
85
+ this.vaultDir = paths?.vaultDir;
86
+ this.proposalsDir = paths?.proposalsDir ?? path.join(this.vaultDir, 'proposals');
87
+ this.queueFile = path.join(this.proposalsDir, 'queue.json');
88
+ this.config = config;
89
+ this.wal = wal;
90
+ this.audit = audit;
91
+ this.now = typeof now === 'function' ? now : () => new Date();
92
+ this.logger = logger;
93
+ }
94
+
95
+ #auditSafe(kind, data) {
96
+ try { this.audit?.(kind, data); } catch { /* ignore */ }
97
+ }
98
+
99
+ #scan() {
100
+ return scanProposalDir(this.proposalsDir);
101
+ }
102
+
103
+ /**
104
+ * D-CR7: every queue-driven proposal write is a rev CAS. On E_STATE_RACE the
105
+ * fresh file is re-read and the mutation re-applied up to three times; a
106
+ * mutation that is no longer valid for the new status throws instead of
107
+ * overwriting a newer decision.
108
+ */
109
+ #writeProposal(proposal, mutate) {
110
+ let expectedRev = proposal.rev ?? 0;
111
+ for (let attempt = 0; attempt < 3; attempt += 1) {
112
+ try {
113
+ return updateProposalStrict(this.proposalsDir, proposal.id, expectedRev, mutate, { now: this.now() });
114
+ } catch (error) {
115
+ if (error?.code !== 'E_STATE_RACE' || error?.rev === undefined) throw error;
116
+ const fresh = readProposal(this.proposalsDir, proposal.id);
117
+ if (!fresh) throw error;
118
+ expectedRev = fresh.rev;
119
+ }
120
+ }
121
+ throw new StoreError('E_STATE_RACE', 'proposal kept changing during a queue transition', { id: proposal.id });
122
+ }
123
+
124
+ buildQueue(proposals, seqCounter, rev = 1) {
125
+ const entries = [];
126
+ for (const proposal of proposals) {
127
+ if (proposal.status !== 'pending' && proposal.status !== 'approved' && proposal.status !== 'applying') continue;
128
+ const queuedAt = proposal.queue?.queuedAt ?? proposal.createdAt;
129
+ entries.push({
130
+ ticket: proposal.queue?.ticket ?? null,
131
+ proposalId: proposal.id,
132
+ sessionId: proposal.origin?.sessionId ?? null,
133
+ target: proposal.target,
134
+ op: proposal.op,
135
+ status: proposal.status,
136
+ priority: proposal.queue?.priority ?? 'P3',
137
+ effectivePriority: proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? 'P3',
138
+ queuedAt,
139
+ waitMs: Math.max(0, this.now().getTime() - (Date.parse(queuedAt) || this.now().getTime())),
140
+ attempts: proposal.queue?.attempts ?? 0,
141
+ lease: proposal.queue?.lease ?? null,
142
+ });
143
+ }
144
+ const sorted = sortQueueEntries(entries);
145
+ const blocked = proposals
146
+ .filter((proposal) => proposal.status === 'blocked-on-user')
147
+ .map((proposal) => ({
148
+ ticket: proposal.queue?.ticket ?? null,
149
+ proposalId: proposal.id,
150
+ reason: proposal.queue?.blockedReason ?? 'BLOCKED_ON_USER',
151
+ since: proposal.queue?.deadlineAt ?? proposal.updatedAt ?? proposal.createdAt,
152
+ }));
153
+ const writer = sorted.find((entry) => entry.status === 'applying');
154
+ const body = {
155
+ v: 1,
156
+ rev,
157
+ seqCounter,
158
+ generatedAt: this.now().toISOString(),
159
+ writer: writer ? {
160
+ ticket: writer.ticket,
161
+ proposalId: writer.proposalId,
162
+ sessionId: writer.sessionId,
163
+ since: writer.queuedAt,
164
+ } : null,
165
+ entries: sorted.map((entry, index) => ({ ...entry, position: index + 1 })),
166
+ blocked,
167
+ };
168
+ body.hash = `sha256:${sha256Hex(JSON.stringify(body))}`;
169
+ return body;
170
+ }
171
+
172
+ #writeQueue(queue) {
173
+ if (queue.entries.length > QUEUE_MAX_ENTRIES) {
174
+ throw new StoreError('E_QUEUE_FULL', 'queue has too many entries', { entries: queue.entries.length });
175
+ }
176
+ const text = `${JSON.stringify(queue, null, 2)}\n`;
177
+ if (Buffer.byteLength(text) > QUEUE_MAX_BYTES) {
178
+ throw new StoreError('E_QUEUE_FULL', 'queue exceeds the size limit', { bytes: Buffer.byteLength(text) });
179
+ }
180
+ writeJsonStrict(this.queueFile, queue);
181
+ }
182
+
183
+ #readOldQueue() {
184
+ return readQueueFile(this.queueFile);
185
+ }
186
+
187
+ /**
188
+ * Reconcile proposals + WAL + queue. Safe to run every tick; only writes when
189
+ * something actually changed (no queue churn on a healthy system).
190
+ */
191
+ rebuild() {
192
+ const scan = this.#scan();
193
+ const proposals = scan.proposals;
194
+ const oldQueue = this.#readOldQueue();
195
+ const walState = this.wal?.read() ?? { lines: [], broken: false, snapshot: null };
196
+ const walLines = walState.lines;
197
+ const walSnapshot = walState.snapshot ?? null;
198
+ const summary = {
199
+ ok: true,
200
+ recovered: [],
201
+ reconciled: [],
202
+ orphans: [],
203
+ broken: walState.broken === true,
204
+ walBroken: walState.broken === true,
205
+ seqCounter: 1,
206
+ written: false,
207
+ };
208
+ let seqCounter = Math.max(
209
+ 1,
210
+ Number.isInteger(oldQueue?.seqCounter) ? oldQueue.seqCounter : 1,
211
+ Number.isInteger(walSnapshot?.seqCounter) ? walSnapshot.seqCounter : 1,
212
+ ...(walSnapshot?.assignments ?? []).map((assignment) => ticketNumber(assignment.ticket) + 1),
213
+ ...walLines.map((line) => ticketNumber(line.ticket) + 1),
214
+ ...proposals.map((proposal) => ticketNumber(proposal.queue?.ticket) + 1),
215
+ );
216
+
217
+ if (!walState.broken && this.wal) {
218
+ // Folded queue.assign events live in wal.snapshot.json (DESIGN §3.5);
219
+ // replayable segments overlay them in seq order.
220
+ const assigned = new Map();
221
+ for (const assignment of walSnapshot?.assignments ?? []) {
222
+ if (typeof assignment.proposalId !== 'string') continue;
223
+ assigned.set(assignment.proposalId, {
224
+ ticket: assignment.ticket ?? null,
225
+ seq: assignment.seq ?? ticketNumber(assignment.ticket),
226
+ source: 'snapshot',
227
+ });
228
+ }
229
+ for (const line of walLines) {
230
+ if (typeof line.proposalId !== 'string') continue;
231
+ if (line.ev === 'queue.assign' || line.ev === 'queue.assign.recovered' || line.ev === 'queue.approve') {
232
+ assigned.set(line.proposalId, { ...line, source: 'wal' });
233
+ }
234
+ }
235
+ const active = proposals.filter((proposal) => proposal.status === 'pending'
236
+ || proposal.status === 'approved' || proposal.status === 'applying');
237
+ for (const proposal of active) {
238
+ const assignment = assigned.get(proposal.id);
239
+ if (assignment && assignment.ticket === proposal.queue?.ticket) continue;
240
+ if (assignment?.ticket) {
241
+ // WAL wins over proposal stateLog (DESIGN §3.5/§5.4): restore the
242
+ // canonical ticket instead of minting a new one.
243
+ const ticket = assignment.ticket;
244
+ const previous = proposal.queue?.ticket ?? null;
245
+ const updated = this.#writeProposal(proposal, (current) => ({
246
+ queue: { ...current.queue, ticket, seq: ticketNumber(ticket) },
247
+ stateLog: [...(current.stateLog ?? []), {
248
+ at: this.now().toISOString(),
249
+ from: current.status,
250
+ to: current.status,
251
+ by: 'router',
252
+ note: 'wal.reconcile: ticket restored from WAL',
253
+ }],
254
+ }));
255
+ proposal.queue = updated.queue;
256
+ summary.reconciled.push({ proposalId: proposal.id, ticket, previous });
257
+ this.#auditSafe('wal.reconcile', {
258
+ proposalId: proposal.id,
259
+ ticket,
260
+ previous,
261
+ source: assignment.source,
262
+ });
263
+ continue;
264
+ }
265
+ const nextTicket = ticketName(seqCounter);
266
+ seqCounter += 1;
267
+ const updated = this.#writeProposal(proposal, (current) => ({
268
+ queue: { ...current.queue, ticket: nextTicket, seq: ticketNumber(nextTicket) },
269
+ stateLog: [...(current.stateLog ?? []), {
270
+ at: this.now().toISOString(),
271
+ from: current.status,
272
+ to: current.status,
273
+ by: 'router',
274
+ note: 'queue.assign.recovered: missing assign',
275
+ }],
276
+ }));
277
+ proposal.queue = updated.queue;
278
+ this.wal.append('queue.assign.recovered', {
279
+ ticket: nextTicket,
280
+ proposalId: proposal.id,
281
+ sessionId: proposal.origin?.sessionId ?? null,
282
+ op: proposal.op,
283
+ target: proposal.target,
284
+ reason: 'missing-assign',
285
+ });
286
+ summary.recovered.push({ proposalId: proposal.id, ticket: nextTicket });
287
+ this.#auditSafe('queue.assign.recovered', { proposalId: proposal.id, ticket: nextTicket });
288
+ }
289
+ }
290
+
291
+ const activeIds = new Set(proposals
292
+ .filter((proposal) => proposal.status === 'pending' || proposal.status === 'approved' || proposal.status === 'applying' || proposal.status === 'blocked-on-user')
293
+ .map((proposal) => proposal.id));
294
+ if (oldQueue) {
295
+ for (const entry of oldQueue.entries ?? []) {
296
+ const proposal = proposals.find((candidate) => candidate.id === entry.proposalId);
297
+ const orphan = !activeIds.has(entry.proposalId)
298
+ || !proposal
299
+ || (proposal.queue?.ticket ?? null) !== (entry.ticket ?? null);
300
+ if (orphan) {
301
+ summary.orphans.push({ ticket: entry.ticket, proposalId: entry.proposalId });
302
+ this.#auditSafe('queue.reconcile', { ticket: entry.ticket, proposalId: entry.proposalId, reason: 'orphan' });
303
+ }
304
+ }
305
+ }
306
+
307
+ const queue = this.buildQueue(proposals, seqCounter, (Number.isInteger(oldQueue?.rev) ? oldQueue.rev : 0) + 1);
308
+ const changed = !oldQueue
309
+ || oldQueue.seqCounter !== queue.seqCounter
310
+ || oldQueue.hash !== queue.hash
311
+ || summary.recovered.length > 0
312
+ || summary.orphans.length > 0
313
+ || JSON.stringify(oldQueue.entries ?? []) !== JSON.stringify(queue.entries)
314
+ || JSON.stringify(oldQueue.blocked ?? []) !== JSON.stringify(queue.blocked);
315
+ if (changed) {
316
+ this.#writeQueue(queue);
317
+ summary.written = true;
318
+ }
319
+ summary.seqCounter = queue.seqCounter;
320
+ summary.depth = queue.entries.length;
321
+ summary.blocked = queue.blocked.length;
322
+ summary.nonTerminal = countNonTerminal(proposals);
323
+ return summary;
324
+ }
325
+
326
+ /**
327
+ * Aging + deadline transitions. Runs after rebuild; writes each proposal once
328
+ * per transition and audits it.
329
+ */
330
+ maintain() {
331
+ const scan = this.#scan();
332
+ const nowMs = this.now().getTime();
333
+ const summary = { aged: [], expired: [], blocked: [], ok: true };
334
+ const agingMs = Math.max(10, Number(this.config.agingSeconds ?? 120)) * 1000;
335
+ const leaseWaitMs = Number(this.config.leaseWaitTimeoutMs ?? 300_000);
336
+ const blockedTtlMs = Number(this.config.blockedOnUserTtlMs ?? 86_400_000);
337
+
338
+ for (const proposal of scan.proposals) {
339
+ const nowIso = this.now().toISOString();
340
+ if (proposal.status === 'pending') {
341
+ const waitMs = nowMs - (Date.parse(proposal.queue?.queuedAt ?? proposal.createdAt) || nowMs);
342
+ const steps = Math.max(0, Math.floor(waitMs / agingMs));
343
+ const currentSteps = Number.isInteger(proposal.queue?.agingSteps) ? proposal.queue.agingSteps : 0;
344
+ const currentPriority = priorityIndex(proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? 'P3');
345
+ if (steps > currentSteps && currentPriority > 1) {
346
+ const nextIndex = Math.max(1, currentPriority - (steps - currentSteps));
347
+ const updated = this.#writeProposal(proposal, (current) => {
348
+ if (current.status !== 'pending') throw new StoreError('E_STATE_RACE', 'proposal left pending during aging');
349
+ return { queue: { ...current.queue, agingSteps: steps, effectivePriority: priorityName(nextIndex) } };
350
+ });
351
+ Object.assign(proposal, updated);
352
+ summary.aged.push({ proposalId: proposal.id, effectivePriority: priorityName(nextIndex), agingSteps: steps });
353
+ this.#auditSafe('queue.aging', { proposalId: proposal.id, ticket: proposal.queue?.ticket ?? null, from: priorityName(currentPriority), to: priorityName(nextIndex) });
354
+ }
355
+ const deadline = Date.parse(proposal.queue?.deadlineAt ?? '');
356
+ if (Number.isFinite(deadline) && nowMs > deadline) {
357
+ summary.expired.push(this.#expire(proposal, {
358
+ from: 'pending',
359
+ note: 'proposal-ttl',
360
+ reason: 'proposal-ttl',
361
+ blockedReason: 'PROPOSAL_TTL',
362
+ }, nowIso));
363
+ }
364
+ } else if (proposal.status === 'approved') {
365
+ const attempts = Number.isInteger(proposal.queue?.attempts) ? proposal.queue.attempts : 0;
366
+ if (attempts >= 3) {
367
+ this.#block(proposal, 'REPEATED_CONFLICT', blockedTtlMs, nowIso);
368
+ summary.blocked.push({ proposalId: proposal.id, reason: 'REPEATED_CONFLICT' });
369
+ continue;
370
+ }
371
+ const deadline = Date.parse(proposal.queue?.deadlineAt ?? '');
372
+ if (Number.isFinite(deadline) && nowMs > deadline) {
373
+ this.#block(proposal, 'LEASE_TIMEOUT', blockedTtlMs, nowIso);
374
+ summary.blocked.push({ proposalId: proposal.id, reason: 'LEASE_TIMEOUT', waitedMs: nowMs - deadline + leaseWaitMs });
375
+ }
376
+ } else if (proposal.status === 'blocked-on-user') {
377
+ const deadline = Date.parse(proposal.queue?.deadlineAt ?? '');
378
+ if (Number.isFinite(deadline) && nowMs > deadline) {
379
+ summary.expired.push(this.#expire(proposal, {
380
+ from: 'blocked-on-user',
381
+ note: 'blocked-on-user-ttl',
382
+ reason: 'blocked-on-user-ttl',
383
+ }, nowIso));
384
+ }
385
+ }
386
+ }
387
+ const rebuilt = this.rebuild();
388
+ return { ...summary, broken: rebuilt.broken, walBroken: rebuilt.walBroken, rebuild: rebuilt };
389
+ }
390
+
391
+ /**
392
+ * K-08 retention contract: expiry is a status transition, never a deletion.
393
+ * The proposal body stays at `proposalsDir/<id>.json` after the ticket is
394
+ * released, so an operator can still read what was proposed and why it
395
+ * lapsed. The post-write existence probe is a tripwire, not cleanup: if any
396
+ * future path removes the body, the audit trail says `proposal.retention_lost`
397
+ * instead of the outbox silently shrinking.
398
+ */
399
+ #expire(proposal, { from, note, reason, blockedReason = null }, nowIso) {
400
+ const next = this.#writeProposal(proposal, (current) => {
401
+ if (current.status !== from) throw new StoreError('E_STATE_RACE', `proposal left ${from} during expiry`);
402
+ return {
403
+ status: 'expired',
404
+ queue: {
405
+ ...current.queue,
406
+ lease: null,
407
+ ...(blockedReason === null ? {} : { blockedReason }),
408
+ },
409
+ stateLog: [...(current.stateLog ?? []), { at: nowIso, from, to: 'expired', by: 'router', note }],
410
+ };
411
+ });
412
+ Object.assign(proposal, next);
413
+ const bodyKept = fs.existsSync(path.join(this.proposalsDir, `${next.id}.json`));
414
+ if (!bodyKept) {
415
+ this.#auditSafe('proposal.retention_lost', {
416
+ proposalId: next.id,
417
+ ticket: next.queue?.ticket ?? null,
418
+ from,
419
+ reason,
420
+ });
421
+ }
422
+ this.#auditSafe('proposal.expired', {
423
+ proposalId: next.id,
424
+ ticket: next.queue?.ticket ?? null,
425
+ from,
426
+ reason,
427
+ bodyKept,
428
+ });
429
+ return { proposalId: next.id, ticket: next.queue?.ticket ?? null, reason, bodyKept };
430
+ }
431
+
432
+ #block(proposal, reason, blockedTtlMs, nowIso) {
433
+ const next = this.#writeProposal(proposal, (current) => {
434
+ if (current.status !== 'approved') throw new StoreError('E_STATE_RACE', 'proposal left approved during block');
435
+ return {
436
+ status: 'blocked-on-user',
437
+ queue: {
438
+ ...current.queue,
439
+ lease: null,
440
+ blockedReason: reason,
441
+ deadlineAt: new Date(this.now().getTime() + blockedTtlMs).toISOString(),
442
+ },
443
+ stateLog: [...(current.stateLog ?? []), { at: nowIso, from: 'approved', to: 'blocked-on-user', by: 'router', note: reason }],
444
+ };
445
+ });
446
+ Object.assign(proposal, next);
447
+ this.#auditSafe('proposal.blocked', { proposalId: proposal.id, ticket: proposal.queue?.ticket ?? null, reason });
448
+ }
449
+
450
+ /** Ordered queue view with position/etaMs (no proposal bodies). */
451
+ view() {
452
+ const scan = this.#scan();
453
+ const oldQueue = this.#readOldQueue();
454
+ const queue = this.buildQueue(scan.proposals, oldQueue?.seqCounter ?? computeSeqCounter(
455
+ scan.proposals.map((proposal) => proposal.queue?.ticket),
456
+ ), oldQueue?.rev ?? 1);
457
+ const entries = queue.entries.map((entry, index) => ({
458
+ ...entry,
459
+ position: index + 1,
460
+ etaMs: (index + 1) * (ETA_DEFAULTS_MS[entry.op] ?? 2000),
461
+ }));
462
+ return {
463
+ ok: true,
464
+ mode: 'queue',
465
+ seqCounter: queue.seqCounter,
466
+ depth: entries.length,
467
+ etaMs: entries.reduce((sum, entry) => sum + (ETA_DEFAULTS_MS[entry.op] ?? 2000), 0),
468
+ writer: queue.writer,
469
+ entries,
470
+ blocked: queue.blocked,
471
+ };
472
+ }
473
+ }
474
+
475
+ export function createQueueManager(options) {
476
+ return new QueueManager(options);
477
+ }