huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.4

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,2446 @@
1
+ // Ask-mode consent ledger: one JSON event per completed ask-mode approval
2
+ // arrival, appended to the devkit state tree. Token mode records nothing —
3
+ // its evidence is the custody-HMAC grant inside approvals.json (single use,
4
+ // tombstone, five-minute TTL, all unchanged).
5
+ //
6
+ // The evidence tier is written from day one: 'elicitation' for the
7
+ // server-raised form the approval gate sends inside the run call,
8
+ // 'posture' for the T3 chat round-trip's attested retry (the model reports
9
+ // the user's chat answer; posture trust, not mechanically verified), and
10
+ // 'terminal' for approve-CLI confirmations the plan face reports. A
11
+ // channel-verified ladder arrival (PR-1.5, evidenceFinal) records the
12
+ // channel that just answered instead of inheriting. A memo-reuse event
13
+ // (PR-3a) inherits the ORIGINAL event's tier and never upgrades it, so a
14
+ // posture-grade yes can
15
+ // never be re-recorded as terminal-grade on retry — recordAskModeConsent
16
+ // ENFORCES the inheritance by resolving the tier itself from the original
17
+ // granted event on the same consent key (sessionId + tool + argsHash —
18
+ // the earliest granted event by chronology, round 8; at an exact
19
+ // same-millisecond cross-tier tie, where chronology cannot name the
20
+ // original, the WEAKEST tier present wins — round 10's never-upgrade
21
+ // direction, with the rare mis-grade DOWN as the recorded honest cost):
22
+ // the caller's evidence parameter is consulted only when no granted
23
+ // original exists.
24
+ //
25
+ // PR-3a landed contract (round 10, G2, recorded here when PR-1 carried no
26
+ // code for it): the tier-safe scoped writer is recordAskModeConsent's
27
+ // scope parameter — 'once' for ordinary arrivals and memo reuses (the tier
28
+ // resolution below applies identically), 'session' for the S3 standing
29
+ // consent grant the elicitation form's "remember for this session" tick
30
+ // writes. No writer routes through appendConsentEvent without tier
31
+ // resolution. The gate's ask result is the structured approvedVia carrier
32
+ // (approval-gate.ts, threaded through tools.ts); the S1 memo's state is
33
+ // the gate's in-memory record, armed by the dispatch recorder from the
34
+ // computed delivery outcome.
35
+ //
36
+ // Write discipline (interrogate rounds 1-7): an append ADDS, it never
37
+ // rewrites, and every committed append SURVIVES. The locked write path
38
+ // appends to the raw parsed store, so entries the filtered reader cannot
39
+ // see (a hand-edited tier, an unmodeled field) and malformed-but-array
40
+ // entries survive verbatim, and the whole read-modify-write runs inside
41
+ // the repo's per-store file lock (withDepLock, the dep receipts'
42
+ // mkdir-claim lock with takeover and exit cleanup), so concurrent locked
43
+ // writers serialize. A store that exists but does not parse is quarantined
44
+ // (renamed aside with its bytes intact, under a pid+UUID name) before a
45
+ // fresh store starts, and when even the quarantine fails the append refuses
46
+ // to write at all — evidence is preserved at the cost of the append, never
47
+ // the other way around.
48
+ //
49
+ // The DEGRADED path (round 6): past the wait cap — a wedged-but-beating
50
+ // holder, a section over the cap on a huge or slow store — the waiter
51
+ // degrades rather than stall an approved call, but the degraded append is
52
+ // NOT a second unlocked read-modify-write: that shape re-opened the exact
53
+ // erasure the lock exists to prevent (a degraded writer's snapshot loses
54
+ // the locked holder's in-flight event; measured rc=0 on both sides with
55
+ // the committed event gone). The degraded append is strictly ADDITIVE: it
56
+ // appends one JSON line per event to a spool file beside the store (the
57
+ // O_APPEND whole-file protocol — no read, no rewrite, nothing to erase),
58
+ // the reader merges spool lines into the filtered view, and the next
59
+ // LOCKED append compacts the spool into the main store under the lock.
60
+ // The degradation may cost latency; evidence survives it when the
61
+ // additive spool write lands — but the spool append is itself
62
+ // best-effort (its catch never fails the call), so on a failing state
63
+ // tree the event can be lost, the same contract as the locked write's
64
+ // internal best-effort catch.
65
+ //
66
+ // Round 7 hardened the same surface at three points the seats measured:
67
+ // the spool append inspects and terminates a torn tail before adding its
68
+ // line (a partial write must not glue — and thereby hide — the next
69
+ // committed event); the reader folds the .taken-* compaction sidecars into
70
+ // the view (an event is committed the moment its line is on disk, not the
71
+ // moment a compaction lands it in the store — a tier-inheritance lookup
72
+ // during the take-write window resolved against a store that did not
73
+ // carry the original); and a compaction never deletes a taken file it
74
+ // failed to read (the bytes survive on disk for the next compaction to
75
+ // retry).
76
+ import {
77
+ closeSync,
78
+ constants,
79
+ existsSync,
80
+ fstatSync,
81
+ mkdirSync,
82
+ openSync,
83
+ readFileSync,
84
+ readSync,
85
+ readdirSync,
86
+ renameSync,
87
+ rmSync,
88
+ statSync,
89
+ writeFileSync,
90
+ writeSync,
91
+ } from 'node:fs';
92
+ import { createHash, randomUUID } from 'node:crypto';
93
+ import { dirname, join } from 'node:path';
94
+
95
+ import { devkitStateBase } from './lib/state-dir.ts';
96
+ import { withDepLock } from './dep/receipts.ts';
97
+ import type { ConsentDeliveryOutcome, ConsentEvent, ConsentEvidence } from './approval-types.ts';
98
+
99
+ function ledgerFilePath(): string {
100
+ return join(devkitStateBase(), 'approval-consents.json');
101
+ }
102
+
103
+ // ============================================================================
104
+ // THE RESIDUAL LEDGER — every disclosed adversarial-shape residual, rounds
105
+ // 15-23, named in one place (the operator's known-boundary list; the round
106
+ // that disclosed each shape is named, and every entry below is a MEASURED,
107
+ // run-proven boundary — not a spec claim):
108
+ //
109
+ // 1. The >8MiB mid-gap in-flight memo residual (r19-r21): sidecars above
110
+ // the whole-file anchor band keep TWO 1MiB window digests; a mid-file
111
+ // insert OUTSIDE both windows, raced in-flight inside the hit path's
112
+ // validation window by a max-rate local writer, evades bounded content
113
+ // validation (measured 14-19/40 with the re-stat across rounds' runs,
114
+ // 37/40 without; the sub-8MiB whole-file band closes it
115
+ // deterministically; the complete closure is a per-append full rescan —
116
+ // the r17-F3 cost the memo exists to avoid).
117
+ // 2. The cap-degradation burst pairs (r15+): ask arrivals that cross
118
+ // LEDGER_MAX_WAIT_MS (3s) degrade together and race the unlocked
119
+ // read-derive-write window, colliding on a seq — the equal-seq pair
120
+ // then falls to grantedAt with weakest-wins at the exact tie. The
121
+ // 24x50 barrier race lane reproduces it under burst (deltas ~3s, the
122
+ // signature); the production face (8x30) stays duplicate-free. The
123
+ // keyed join that closes it lands with PR-3a.
124
+ // 3. The mid-scan out-of-band .taken-* writer (r17 O1b): a sidecar created
125
+ // between the floor scan's readdir and the take can duplicate a seq on
126
+ // the locked path — no LEGAL producer exists (takeSpool runs inside
127
+ // the same lock hold), so it is recorded, not fixed; the degraded
128
+ // readdir-vs-take interleave is a sub-shape of entry 2's unlocked race.
129
+ // 4. The compaction-crash duplicate (r7): a crash between the main write
130
+ // and the taken-file removal leaves a taken file whose lines are
131
+ // ALREADY in the store; the next compaction folds it again — the
132
+ // duplicate is additive (a repeated consent row), the documented safe
133
+ // direction.
134
+ // 5. The >V8-string taken file (r7): a sidecar past the whole-read limit
135
+ // never folds through the line path; kept with its bytes intact,
136
+ // retried every compaction, over the caps it blinds in O(1). There is
137
+ // NO in-band recovery that restores the merged view: by construction a
138
+ // spool past the read cap folds into a store past the SAME cap (a
139
+ // 568.8MB spool split into two readable chunks folds to a 568.8MB
140
+ // store — over the cap, back to quarantine). The honest operator paths
141
+ // are external: (a) archive the oversized taken file elsewhere and
142
+ // accept that its rows leave the merged view, or (b) keep the store
143
+ // under the cap by periodic maintenance before the spool accumulates
144
+ // past it. The consequences, named exactly: the bytes are ALWAYS
145
+ // preserved on disk (the taken file and the quarantine sidecar both
146
+ // keep them); the view loss is permanent for that content (no code
147
+ // path reads a .corrupt-* sidecar); and the counter reseeds from the
148
+ // surviving rows. Under the caps the file is evidence, never a floor
149
+ // source.
150
+ // 6. The fold's all-or-nothing element bound (r21-r23): a taken file
151
+ // carrying ANY over-bound line keeps the WHOLE file — clean rows defer
152
+ // with the poison (retried every compaction, never dropped) so a giant
153
+ // preserved line can never be written into the store (the kill-switch
154
+ // shape). The honest cost: a mixed file stays until the operator
155
+ // splits it.
156
+ // 7. The multibyte admitted band (r23): the element guard scores UTF-8
157
+ // BYTES — ASCII behavior is identical (bytes == units), but a
158
+ // multibyte store previously admitted by unit count now quarantines
159
+ // with its bytes (a 125Mi-unit CJK row is 375Mi of bytes, over the
160
+ // 256MiB bound — it previously ANSWERED at the edge of the measured
161
+ // 130Mi-unit abort cliff). The invariant the guard enforces: any
162
+ // store it ADMITS is writable without abort, whatever its encoding;
163
+ // the guard's byte walk adds to the admitted giant store's disclosed
164
+ // multi-second tri-copy cost.
165
+ // 8. The r3-caller cost residuals (carried): the 250MiB-admitted
166
+ // element's append keeps its multi-second tri-copy shape (unchanged
167
+ // admitted behavior); the ~2.4s floor+resolution cost at 1M rows is
168
+ // the tier resolution's inherent O(store) RMW.
169
+ // 9. The auth pack's status:'cleared' (r17 O5): classifies failed
170
+ // through the delivery recorder — unregistered in PR-1; the PR-3b
171
+ // registration round adds it to the success vocabulary.
172
+ //
173
+ // Every other adversarial surface measured across rounds 15-23 is CLOSED
174
+ // with an in-repo pin: the FIFO/device/sparse seams (r18-r20, bounded in
175
+ // ms), the O(size) reads (r20-r21, capped in O(1)), the SIGABRT shapes
176
+ // (r21-r23: the giant-value/key/exact-bound/multibyte element stores all
177
+ // quarantine with bytes preserved), the writeAll partial-count classes
178
+ // (r21-r22, byte-offset resume, byte-identity pinned), the memo key/
179
+ // anchor/tax regressions (r18-r21, each pinned with a mutation), the
180
+ // dead-span detector (r19-r20, byte-level, precise, blind memoized), the
181
+ // negation/polarity vocabulary (r16, the absence-phrase strip), the
182
+ // scanner carry (r18-r19: needle-in-carry extracts at any gap, the
183
+ // needle-lost span blinds), and the seq space (r15-r17: bounded,
184
+ // saturation a state, the file never a decision-maker).
185
+ // ============================================================================
186
+
187
+ // The spool: degraded appends land here, one JSON event per line, append
188
+ // mode only. Compacted into the main store by the next locked append.
189
+ function ledgerSpoolPath(): string {
190
+ return `${ledgerFilePath()}.spool.jsonl`;
191
+ }
192
+
193
+ // The lock directory beside the store: withDepLock claims <dir>/lock with
194
+ // mkdir (O_EXCL semantics), so every process appending to this store
195
+ // serializes on one path. The lock lives in the state tree with the store
196
+ // it guards — same ownership, same relocation via HUAWEICLOUD_HOME.
197
+ function ledgerLockDir(): string {
198
+ return join(devkitStateBase(), 'approval-consents-lock');
199
+ }
200
+
201
+ // The arrival counter's high-water file (round 13, finding 4; hardened
202
+ // rounds 14-15): the last sequence number assigned, a few bytes beside the
203
+ // store. The counter is CLOCK-INDEPENDENT by construction — grantedAt can
204
+ // step backward under an NTP correction or a VM restore, and the
205
+ // (arrivalSeq, grantedAt) chronology key must still name the true
206
+ // original.
207
+ //
208
+ // Round 15, finding 1 (both seats) bounded the space: the r14 floor fix
209
+ // validated only the TYPE of the values it consumed, so one corrupted or
210
+ // adversarial row/file value near 2^53 poisoned the counter permanently —
211
+ // a determinable row landed ON the sentinel (mis-marked chronology-UNKNOWN
212
+ // forever), following rows left the safe-integer range, LOCKED writers
213
+ // duplicated seqs (the r14 zero-duplicates invariant falsified at a
214
+ // poisoned floor), and the grantedAt fallback re-opened the r13 fabricated
215
+ // upgrade end-to-end; an Infinity row serialized arrivalSeq:null and the
216
+ // consent vanished from every reader. The assignable space is bounded
217
+ // (below the exclusive SEQ_CEILING); any row or file value outside it is
218
+ // UNREADABLE — a row normalizes to the sentinel at read (visible, sorts
219
+ // newest, never invisible, never an original: unknown chronology cannot
220
+ // name one), the counter seeds from the max of VALID seqs only, and the
221
+ // ceiling band is never assignable. Round 16, finding 1 (both seats)
222
+ // closed the top edge the r15 clamp left: the boundary value itself
223
+ // floored every later append at the top and the clamp re-issued it —
224
+ // saturation is now a STATE (nextSeqFromFloor): no room left means the
225
+ // row is marked chronology-UNKNOWN, never a duplicate of an existing
226
+ // row's seq, and the file stays at the last assignable value.
227
+ //
228
+ // Round 15, finding 4 (both seats) made the floor CHEAP: the r14 fix ran
229
+ // the full merged-view scan on EVERY append (the file "optimization"
230
+ // consulted nothing), doubling the ask-arrival stall — at 1M rows a single
231
+ // append was 4.9-10.9s (past the 3s cap, so concurrent arrivals degraded
232
+ // and their unlocked seq assignments collided). The locked path now
233
+ // derives its floor from data it ALREADY parses (lockedAppend's store read
234
+ // and takeSpool's fold) plus the streamed .taken-* scan (rounds 16-17)
235
+ // and this process's last assignment: no extra IO, no merged-view read.
236
+ // The seq FILE is no longer a floor source at all (round 17, finding 1):
237
+ // the crash-gap values it used to cover are owned by no row (the row
238
+ // either landed in the spool/store the next section parses, or was lost
239
+ // entirely), so re-using them is safe, and no file value can decide the
240
+ // counter. The merged-view scan survives as the DEGRADED path's floor
241
+ // (round 16, finding 3), which the degraded path pays unconditionally.
242
+ //
243
+ // The assignment runs INSIDE the ledger lock's hold (round 14, finding 2):
244
+ // locked writers serialize for real (24 barrier workers, zero duplicates).
245
+ // The degraded path remains the recorded duplicate residual: it cannot
246
+ // hold the lock, its file read-write races, and equal seqs fall to
247
+ // grantedAt with weakest-wins governing the exact tie.
248
+ function ledgerSeqPath(): string {
249
+ return join(devkitStateBase(), 'approval-consents.seq');
250
+ }
251
+
252
+ // The unknown-seq sentinel: sorts AFTER every real seq, so a row the
253
+ // counter could not number is never mistaken for the earliest arrival —
254
+ // and (rounds 15-16) never an original: the tier resolution skips sentinel
255
+ // rows, because unknown chronology cannot name one.
256
+ const SEQ_UNKNOWN = Number.MAX_SAFE_INTEGER;
257
+
258
+ // The EXCLUSIVE ceiling of the assignable space: integers in [0, SEQ_CEILING)
259
+ // are assignable — SEQ_CEILING itself and the one value below it
260
+ // (SEQ_UNKNOWN-1) are outside the space, never assigned, and never read as a
261
+ // row's seq. SEQ_UNKNOWN — the sentinel — IS assigned, as a STATE MARKER:
262
+ // saturation, blinded sources, and undeterminable chronology stamp rows with
263
+ // it, and every reader reads it back as exactly that (the sentinel sorts
264
+ // NEWEST, the tier resolution skips sentinel rows, and the annotate never
265
+ // binds a sentinel identity).
266
+ // Round 15 bounded the space with two values of headroom; round 16, finding 1
267
+ // (both seats) found the boundary itself was the poison: a value at the old
268
+ // ceiling floored every later append at the top, and clampNextSeq re-issued
269
+ // it — the same value an existing row owned — forever, on both paths, with
270
+ // no repair (four appends, one seq; the r14 zero-duplicate invariant
271
+ // falsified; and the grantedAt fallback re-opened the r13 fabricated
272
+ // upgrade). Saturation is now a STATE, not a value: when the floor leaves
273
+ // no assignable value above it, new rows take the SENTINEL (chronology
274
+ // unknown, sorts newest, never an original), the ceiling band reads as the
275
+ // sentinel at the raw-store guard and the filtered view alike, and the seq
276
+ // file stays at the last assignable value (the brief's "left at the
277
+ // ceiling" form: the append path checks saturation explicitly and never
278
+ // re-issues). A row or file staged INSIDE the ceiling band is unreadable —
279
+ // the counter repairs the file from the parsed floor and never floors on
280
+ // the row, so a saturated tree is sticky by construction and a corrupted
281
+ // one recovers monotonically.
282
+ const SEQ_CEILING = Number.MAX_SAFE_INTEGER - 2;
283
+
284
+ // A seq is readable iff it is an integer inside the assignable space
285
+ // (below the exclusive ceiling; safe by construction).
286
+ function isValidArrivalSeq(value: unknown): value is number {
287
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value < SEQ_CEILING;
288
+ }
289
+
290
+ // The next assignable seq from a known floor — or the sentinel when the
291
+ // space is exhausted (round 16, finding 1: "no room left" is never
292
+ // "re-issue the top"; a new arrival must never duplicate an existing
293
+ // row's seq, so an unassignable increment marks the row chronology-UNKNOWN
294
+ // instead of guessing).
295
+ function nextSeqFromFloor(floor: number): number {
296
+ return floor + 1 < SEQ_CEILING ? floor + 1 : SEQ_UNKNOWN;
297
+ }
298
+
299
+ // The highest valid seq among parsed store/spool entries — the locked
300
+ // path's floor, computed from data the caller already parsed (no IO).
301
+ // Out-of-range and absent values are invisible to the floor by design.
302
+ function maxValidSeqAmong(entries: unknown[]): number {
303
+ let max = -1;
304
+ for (const entry of entries) {
305
+ if (!entry || typeof entry !== 'object') continue;
306
+ const seq = (entry as Record<string, unknown>).arrivalSeq;
307
+ if (isValidArrivalSeq(seq) && seq > max) max = seq;
308
+ }
309
+ return max;
310
+ }
311
+
312
+ // The merged view's highest valid seq — the degraded path's repair leg
313
+ // (the file is invalid and no parsed data exists). Read-only; sentinel
314
+ // rows are skipped (they are not seqs the counter can build on).
315
+ function maxArrivalSeqInStore(): number {
316
+ let max = -1;
317
+ for (const event of readConsentEvents()) {
318
+ if (event.arrivalSeq !== SEQ_UNKNOWN && event.arrivalSeq > max) max = event.arrivalSeq;
319
+ }
320
+ return max;
321
+ }
322
+
323
+ // The seq file's value was REMOVED from every floor in round 17, finding 1
324
+ // (both seats' band work): the r16 "sticky saturation" rule trusted the
325
+ // file's value to decide that the space was exhausted, so ONE corrupted
326
+ // byte at the last valid value (MAX_SAFE-3 — in-range, indistinguishable
327
+ // from genuine saturation, which needs ~9e15 appends to reach) permanently
328
+ // marked every later consent chronology-UNKNOWN with no repair: the file
329
+ // was written back unchanged, the delivery annotation could never bind
330
+ // again (a healthy store records delivered), and the tier inheritance
331
+ // mis-graded DOWN forever (a terminal original re-recorded posture, the
332
+ // never-upgrade line broken by the counter's own state). The floor is now
333
+ // ALWAYS the parsed max — the store rows, the taken/spool entries, the
334
+ // sidecar/spool scans — plus this process's last assignment; the FILE IS
335
+ // AN OPTIMIZATION, NEVER A DECISION-MAKER (the r15 doctrine, now enforced):
336
+ // it is written with the current truth on every append and read by no code
337
+ // path (operators may inspect it). "Saturation" means exactly "the parsed
338
+ // max has no room above it": a row legitimately at the last assignable
339
+ // value still saturates (in-space seqs are trusted by design — the r15/r16
340
+ // doctrine), but no FILE value can fabricate the state, and pruning the
341
+ // store below the ceiling releases the counter naturally.
342
+ let lastAssignedSeq: number | undefined;
343
+
344
+ // Write the high-water back — the current truth (the last assignable value
345
+ // assigned, or the parsed floor when this append marked unknown), best-effort
346
+ // (a failed write never fails the append — the file decides nothing).
347
+ function writeSeqFileMonotonic(next: number): void {
348
+ if (next < 0) return; // nothing assignable has ever been seen: leave the file absent
349
+ try {
350
+ const path = ledgerSeqPath();
351
+ mkdirSync(dirname(path), { recursive: true });
352
+ const tmp = `${path}.${process.pid}.seq.tmp`;
353
+ writeFileSync(tmp, `${next}\n`, { encoding: 'utf8', mode: 0o600 });
354
+ renameSync(tmp, path);
355
+ } catch {
356
+ // best-effort: the parsed floor recovers on the next append
357
+ }
358
+ }
359
+
360
+ // The streaming seq-field scanner (round 17, findings 2 and 3): reads a
361
+ // spool/sidecar file's arrivalSeq values in chunks WITHOUT building a
362
+ // whole-file string — a file past V8's string limit (~512MB) makes every
363
+ // readFileSync(file, 'utf8') throw ERR_STRING_TOO_LONG AFTER reading all
364
+ // its bytes, the round-7 PERMANENT fold-failure class, which the r16 scan
365
+ // re-paid on every append (~1.4-1.5s per 588MB sidecar; three crossed the
366
+ // 3s wait cap and every concurrent arrival degraded). The scan finds the
367
+ // `"arrivalSeq"` key bytes and reads the numeric literal that follows —
368
+ // spoof-proof by JSON's own escaping rules: inside a string value a quote
369
+ // is ALWAYS written `\"`, so the unescaped byte sequence `"arrivalSeq"`
370
+ // can only be a real object key in valid JSON; a hand-staged invalid line
371
+ // that matches can only push the floor HIGHER (a false max creates a gap,
372
+ // never a duplicate — the safe direction), and its rows are invisible to
373
+ // every reader forever (the malformed-line tolerance), so no visible row
374
+ // can own a seq the scan missed. A file that cannot be OPENED or READ is
375
+ // a BLINDED source (the r16 doctrine): its rows are committed and own
376
+ // unknowable seqs, so the caller must mark the arrival chronology-unknown
377
+ // rather than risk a duplicate.
378
+ const SEQ_SCAN_CHUNK_BYTES = 1 << 20;
379
+ // Round 18, finding 2 (A1; A2's O1) set the carry at 320 bytes; round 19,
380
+ // finding 3 (both seats) falsified the miss claim that accompanied it.
381
+ // The extraction geometry: a needle whose number lies past the chunk end
382
+ // is carried whole into the next haystack iff its start is within the
383
+ // last CARRY bytes — so a needle at ≥ (boundary - CARRY) extracts across
384
+ // the boundary at ANY gap width (the carry+chunk concatenation makes the
385
+ // span contiguous; measured: 4000-5000-space gaps extract), and the
386
+ // boundary of the whole story is the NEEDLE's distance from the edge
387
+ // (320/321), not the gap. What the r18 comment got WRONG: it called a
388
+ // needle lost past the carry "a documented miss ... a gap, never a
389
+ // duplicate" — both directions falsified: a lost-needle row's seq is
390
+ // invisible to every floor source (the file is past the whole-read limit,
391
+ // so the fold cannot read it either), and the next append assigns the
392
+ // missed row's committed seq (A2: a 501MiB sidecar at the DEFAULT limit,
393
+ // assignments [6,7,8,9] with the missed row owning 9; after the operator
394
+ // split the equal-seq pair falls to grantedAt and the reuse inherited
395
+ // terminal — the fabricated upgrade); the truncated-prefix shape was
396
+ // worse: the prefix floors at-or-below only for the NEXT assignment, and
397
+ // the counter MARCHES INTO the row's committed seq a few appends later
398
+ // (A1: six appends walked [301..306] into the row's 305). The r19 fix
399
+ // is the dead-span detector in streamMaxValidSeq: a pass that ends
400
+ // inside an open-or-truncated needle-to-literal span whose needle falls
401
+ // outside the carry marks the source BLINDED — the chronology-unknown
402
+ // doctrine, the sentinel — never a silent miss. The extractor's reach
403
+ // stays: gaps of ANY width extract while the needle is within the
404
+ // carry; the detector governs only the needle-lost shapes.
405
+ const SEQ_SCAN_CARRY_BYTES = 320;
406
+
407
+ // The streamed scan's shape (rounds 19-20): the max plus the CONTENT
408
+ // ANCHORS the memo validates. Round 19 anchored on headSeq/tailSeq — the
409
+ // first/last seq VALUES in the end windows — and both r20 seats falsified
410
+ // that (complementary shapes): the anchors are two scalars, so a middle
411
+ // in-place insert preserving the first/last rows' seqs collides them
412
+ // (A1: a 1200-byte 3-row sidecar, only the middle row rewritten, 7/40 +
413
+ // the full harm chain; A2: a hit-path TOCTOU needing no tick race at all
414
+ // — the hit path stats ONCE, and the attacker's write lands after it —
415
+ // 15-19/40 at the production default limit). Round 20 anchors on BYTES
416
+ // and a COUNT, both derived from the SAME windows on both paths (F4's
417
+ // reader disagreement — the r19 scan's tailSeq persisted across passes
418
+ // while the anchor reader's tail window stopped at 1MiB+320, so an
419
+ // unchanged file never memoized — dissolves when both paths read the
420
+ // same windows): headDigest/tailDigest are sha256 digests of the head
421
+ // window [0, min(size,CHUNK)) and the tail window [size-CHUNK-CARRY,
422
+ // size), and seqCount is the number of seq-field matches over BOTH
423
+ // windows (deterministically double-counting their overlap for small
424
+ // files — both paths compute it identically, which is what matters).
425
+ type StreamAnchors = {
426
+ headDigest: string;
427
+ tailDigest: string;
428
+ seqCount: number;
429
+ };
430
+
431
+ // deadSpan: the blind came from the dead-span detector on a file the scan
432
+ // otherwise READ TO EOF (content-stable — memoizable, unlike an
433
+ // open/read/cap failure whose recovery must rescan); a memoized entry
434
+ // reproduces the blinded verdict on a validated hit instead of re-paying
435
+ // the per-append rescan tax (round 20, finding 3).
436
+ type StreamSeqScan = {
437
+ max: number;
438
+ blinded: boolean;
439
+ deadSpan: boolean;
440
+ anchors: StreamAnchors | undefined;
441
+ };
442
+
443
+ function streamMaxValidSeq(path: string): StreamSeqScan {
444
+ let fd: number | undefined;
445
+ try {
446
+ // Rounds 18-19, findings 3/1/4: the scan's only failure class was
447
+ // THROWN errors — a FIFO entry with the reserved .taken-* name BLOCKED
448
+ // the open, a symlink to /dev/zero never reached EOF, and a rename
449
+ // landing between the r18 stat and the open wedged the append inside
450
+ // the ledger lock's hold (the heartbeat kept the claim fresh, so
451
+ // takeover never fired). The open is atomic-by-construction now:
452
+ // O_NONBLOCK (a no-op on regular files) + the FD's own fstat — a
453
+ // non-regular entry is a BLINDED source, never read, whatever the
454
+ // path held at any instant.
455
+ fd = openRegularForRead(path);
456
+ if (fd === undefined) return { max: -1, blinded: true, deadSpan: false, anchors: undefined };
457
+ // Round 20, finding 1: the DECLARED size caps the stream — a sparse
458
+ // entry (one truncate, ~8KiB of disk, any size) would otherwise buy
459
+ // hours of CPU-bound chunk scanning inside the lock hold; over-cap
460
+ // blinds in O(1) (the over-limit posture, the store's own definition).
461
+ if (fstatSync(fd).size > streamScanLimitBytes()) {
462
+ return { max: -1, blinded: true, deadSpan: false, anchors: undefined };
463
+ }
464
+ const chunk = Buffer.alloc(SEQ_SCAN_CHUNK_BYTES);
465
+ // A number cut by a chunk boundary matches TRUNCATED in this pass and
466
+ // whole in the next when the NEEDLE is carried (the carry re-presents
467
+ // it): truncation only drops trailing digits, so the truncated value
468
+ // is never ABOVE the real one, and the full value follows — the max
469
+ // converges. A number ending at EOF is matched by its own final
470
+ // chunk's pass, terminator or not.
471
+ const seqFieldRe = /"arrivalSeq"\s*:\s*(-?[\d.eE+]+)/g;
472
+ // Round 19, finding 3 (both seats): the dead-span detector. A pass
473
+ // whose text ENDS inside a needle-to-literal span is the shape the
474
+ // r18 comment called "a gap, never a duplicate" — falsified: when the
475
+ // NEEDLE also falls outside the carry window, the span can never
476
+ // complete in a later pass (the next haystack starts mid-gap with no
477
+ // needle), the row's real seq is invisible to every floor source, and
478
+ // the next append assigned the missed row's committed seq — the
479
+ // duplicate direction (A2: a 501MiB sidecar, [6,7,8,9] with the
480
+ // missed row owning 9; A1: the truncated-prefix shape let the counter
481
+ // MARCH INTO the row's seq across six appends; both ran to the
482
+ // fabricated-upgrade chain). The detector: the text ends with an
483
+ // open-or-partial needle-to-number span (the regex allows an empty or
484
+ // truncated literal at the very end) AND the span's needle starts
485
+ // before the carry window (it will not be carried) — a DEAD span. The
486
+ // safe posture the doctrine already uses for a blinded file: mark the
487
+ // source BLINDED (chronology-unknown, the sentinel), never a silent
488
+ // miss. A needle INSIDE the carry completes next pass and never trips
489
+ // the detector (the r18 extraction pin); at true EOF an open span is
490
+ // a torn tail — an UNCOMMITTED row (the r17 doctrine, its gap
491
+ // semantics measured safe) — so the flag is cleared when the next
492
+ // read returns empty. The needle position compares in BYTES (the carry
493
+ // window is bytes; a multibyte tail would otherwise skew the boundary).
494
+ // The colon is OPTIONAL: a span whose colon lies past the chunk boundary
495
+ // ends the pass as needle+whitespace with no colon yet — the same dead
496
+ // shape (the needle outside the carry can never be re-presented).
497
+ // Round 20: the detector is BYTE-LEVEL and PRECISE. The r19 form
498
+ // computed a UTF-16 character index and re-encoded it to "bytes" —
499
+ // under the lossy utf8 decode each invalid byte became U+FFFD and
500
+ // inflated the computed offset by 2 bytes, shrinking the blind band:
501
+ // one invalid byte (or a multibyte char) before the needle turned
502
+ // the 320/321 boundary into a silent miss (seat 2's skew). The
503
+ // needle's byte offset is taken from the BUFFER directly (exact), and
504
+ // the span is open iff every byte after the needle to the buffer end
505
+ // is in the span alphabet (whitespace, ':', digits, . e E + -). The
506
+ // verdict stays PER BOUNDARY, held PENDING until the next read proves
507
+ // a following chunk exists (the EOF read discards it: a torn tail at
508
+ // true EOF is an uncommitted row, the r17 doctrine) — and round 20,
509
+ // finding 3 resolved it with a ONE-BYTE LOOKAHEAD at the next chunk's
510
+ // first byte, so a literal completing EXACTLY at the boundary (the
511
+ // r19 false positive: the value fully extracted, yet blinded — a
512
+ // permanent per-append rescan at ~1s/200MB) is recognized and NOT
513
+ // dead: digit/.eE+- continues the literal (or starts it): dead;
514
+ // whitespace completes a number whose digits were all seen (JSON
515
+ // puts no space inside a number) but keeps a digit-less span
516
+ // pre-number: dead; ':' keeps it pre-number: dead; anything else
517
+ // means the literal completed or no number is coming: not dead.
518
+ const needleBuf = Buffer.from('"arrivalSeq"', 'utf8');
519
+ const isWsByte = (b: number): boolean => b === 0x20 || b === 0x09 || b === 0x0a || b === 0x0d;
520
+ const isLiteralByte = (b: number): boolean =>
521
+ (b >= 0x30 && b <= 0x39) || b === 0x2e || b === 0x65 || b === 0x45 || b === 0x2b || b === 0x2d;
522
+ const isSpanByte = (b: number): boolean => isWsByte(b) || b === 0x3a || isLiteralByte(b);
523
+ const isDigitByte = (b: number): boolean => b >= 0x30 && b <= 0x39;
524
+ let carry = Buffer.alloc(0);
525
+ let max = -1;
526
+ let deadAccum = false;
527
+ // The PREVIOUS pass's pending open span (null = none): resolved by
528
+ // this pass's first byte per the lookahead above.
529
+ let prevOpen: { hasDigits: boolean } | null = null;
530
+ for (;;) {
531
+ const read = readSync(fd, chunk, 0, chunk.length, null);
532
+ if (read === 0) break; // the pending verdict was the EOF boundary's: discard it (torn tail)
533
+ const data = chunk.subarray(0, read);
534
+ const haystack = carry.length > 0 ? Buffer.concat([carry, data]) : data;
535
+ const text = haystack.toString('utf8');
536
+ let match: RegExpExecArray | null;
537
+ while ((match = seqFieldRe.exec(text)) !== null) {
538
+ const value = Number(match[1]!);
539
+ if (isValidArrivalSeq(value) && value > max) max = value;
540
+ }
541
+ if (prevOpen !== null) {
542
+ const b = data[0]!;
543
+ if (isLiteralByte(b) || b === 0x3a || (isWsByte(b) && !prevOpen.hasDigits)) deadAccum = true;
544
+ prevOpen = null;
545
+ }
546
+ const needleAt = haystack.lastIndexOf(needleBuf);
547
+ if (needleAt !== -1) {
548
+ let pure = true;
549
+ let hasDigits = false;
550
+ for (let j = needleAt + needleBuf.length; j < haystack.length; j += 1) {
551
+ const b = haystack[j]!;
552
+ if (isDigitByte(b)) hasDigits = true;
553
+ if (!isSpanByte(b)) {
554
+ pure = false;
555
+ break;
556
+ }
557
+ }
558
+ if (pure && needleAt < haystack.length - SEQ_SCAN_CARRY_BYTES) prevOpen = { hasDigits };
559
+ }
560
+ const keep = Math.min(SEQ_SCAN_CARRY_BYTES, haystack.length);
561
+ carry = Buffer.from(haystack.subarray(haystack.length - keep)); // copy: the chunk is reused
562
+ }
563
+ // The anchors come from the SAME windows the hit path reads (round 20,
564
+ // F4): derived after the pass via positioned reads on this fd — the
565
+ // r19 tailSeq (persisted across passes, the file's LAST seq anywhere)
566
+ // disagreed with the reader's window and an unchanged wide-tail file
567
+ // never memoized.
568
+ const anchors = anchorDataFromFd(fd, fstatSync(fd).size);
569
+ if (deadAccum) return { max: -1, blinded: true, deadSpan: true, anchors };
570
+ return { max, blinded: false, deadSpan: false, anchors };
571
+ } catch {
572
+ return { max: -1, blinded: true, deadSpan: false, anchors: undefined }; // unreadable: unknown owners
573
+ } finally {
574
+ if (fd !== undefined) {
575
+ try {
576
+ closeSync(fd);
577
+ } catch {
578
+ // best-effort: a leaked descriptor is the least harm here
579
+ }
580
+ }
581
+ }
582
+ }
583
+
584
+ // Read the anchor windows off an OPEN fd and derive the content anchors
585
+ // (round 20, findings 2 and 4): the head window [0, min(size,CHUNK)) and
586
+ // the tail window [size-CHUNK-CARRY, size), the SAME windows both the scan
587
+ // and the hit path derive their anchors from (F4: the r19 pair used
588
+ // different definitions — the scan's tailSeq persisted across passes, the
589
+ // reader's window stopped at 1MiB+320 — so an unchanged file whose last
590
+ // seq sat farther from EOF never memoized: a permanent per-append rescan).
591
+ // Two positioned reads, O(window); sha256 digests + the seq-field match
592
+ // count over the windows. The count is the brief's third gate: a middle
593
+ // INSERT inside a covered window changes the count even where a digest
594
+ // comparison alone might be argued away — and for files ≤ CHUNK+CARRY the
595
+ // windows cover the whole file, so ANY byte change anywhere (the r20 A1
596
+ // 1200-byte escape, the r20 A2 middle insert on small sidecars) changes
597
+ // a digest or the count.
598
+ const SEQ_FIELD_COUNT_RE = () => /"arrivalSeq"\s*:\s*(-?[\d.eE+]+)/g;
599
+
600
+ // Small files get WHOLE-FILE anchors (round 20, the sub-tick closure):
601
+ // windowed digests cannot see an insert between the windows, and the
602
+ // re-stat's coarse-clock granularity (~1ms kernel ticks) lets a write
603
+ // completing inside the cached-fast anchor reads pass — measured 4/40
604
+ // wins on a 5MiB file with the re-stat alone. For files ≤ 8MiB the
605
+ // anchor read covers the WHOLE file, so ANY byte change anywhere changes
606
+ // the digest deterministically, whatever the clock did. Round 21,
607
+ // finding 3 corrected the r20 cost claim ("a cached ~2ms read — inside
608
+ // the single-digit-ms cost bar" — measured ~62ms median per append at
609
+ // the 8MiB top edge, ~31ms at 4MiB, ~15ms at 2MiB, ~11x the r19 windowed
610
+ // hit at the same size) and cut the redundancy: the whole-file digest
611
+ // subsumes the seq-count gate inside the band, so the count pass (the
612
+ // full-text decode plus the regex sweep — half the measured hit cost)
613
+ // is SKIPPED for whole-file-anchored sizes and seqCount is recorded as 0
614
+ // on both paths (identically, so the memo comparison stays consistent).
615
+ // The honest measured cost of the remaining read+sha256 hit path:
616
+ // ~7-15ms at the realistic sizes (≤4MiB), ~30ms at the 8MiB top edge —
617
+ // documented in the round's record, still inside the r3 caller bar by
618
+ // two orders of magnitude. Larger files keep the two 1MiB windows; their
619
+ // residual — a same-tick insert landing in the uncovered middle of a
620
+ // >8MiB file — is the r19-disclosed class with the corrected size
621
+ // boundary.
622
+ const ANCHOR_WHOLE_FILE_BYTES = 8 * 1024 * 1024;
623
+
624
+ function anchorDataFromFd(fd: number, size: number): StreamAnchors {
625
+ if (size <= ANCHOR_WHOLE_FILE_BYTES) {
626
+ const wholeBuf = Buffer.allocUnsafe(size);
627
+ const got = readSync(fd, wholeBuf, 0, size, 0);
628
+ const digest = createHash('sha256').update(wholeBuf.subarray(0, got)).digest('base64');
629
+ return { headDigest: digest, tailDigest: digest, seqCount: 0 }; // the count gate is subsumed: skipped in the band
630
+ }
631
+ const headLen = Math.min(size, SEQ_SCAN_CHUNK_BYTES);
632
+ const headBuf = Buffer.allocUnsafe(headLen);
633
+ const headGot = readSync(fd, headBuf, 0, headLen, 0);
634
+ const headText = headBuf.toString('utf8', 0, headGot);
635
+ const tailLen = Math.min(size, SEQ_SCAN_CHUNK_BYTES + SEQ_SCAN_CARRY_BYTES);
636
+ const tailBuf = Buffer.allocUnsafe(tailLen);
637
+ const tailGot = readSync(fd, tailBuf, 0, tailLen, Math.max(0, size - tailLen));
638
+ const tailText = tailBuf.toString('utf8', 0, tailGot);
639
+ let seqCount = 0;
640
+ const countRe = SEQ_FIELD_COUNT_RE();
641
+ while (countRe.exec(headText) !== null) seqCount += 1;
642
+ const countRe2 = SEQ_FIELD_COUNT_RE();
643
+ while (countRe2.exec(tailText) !== null) seqCount += 1;
644
+ return {
645
+ headDigest: createHash('sha256').update(headBuf.subarray(0, headGot)).digest('base64'),
646
+ tailDigest: createHash('sha256').update(tailBuf.subarray(0, tailGot)).digest('base64'),
647
+ seqCount,
648
+ };
649
+ }
650
+
651
+ // The hit path's anchor read (round 20, finding 2): opens its own guarded
652
+ // fd, applies the stream cap, derives the anchors from the same windows.
653
+ // An anchor read that fails (absent, non-regular, over-cap now) returns
654
+ // undefined and forces the full rescan.
655
+ function readAnchorData(path: string): StreamAnchors | undefined {
656
+ const fd = openRegularForRead(path);
657
+ if (fd === undefined) return undefined;
658
+ try {
659
+ const size = fstatSync(fd).size;
660
+ if (size > streamScanLimitBytes()) return undefined; // over-cap: never trusted
661
+ if (size === 0) return undefined; // an empty file has no anchors: rescan (it blinded anyway)
662
+ return anchorDataFromFd(fd, size);
663
+ } catch {
664
+ return undefined;
665
+ } finally {
666
+ try {
667
+ closeSync(fd);
668
+ } catch {
669
+ // best-effort
670
+ }
671
+ }
672
+ }
673
+
674
+ // The sidecar scan memo (round 17, finding 3; key discipline rounds 18-19):
675
+ // a successful scan's result is memoized so the SECOND append pays
676
+ // nothing. The key is ENFORCED, not assumed — twice falsified now: r18
677
+ // keyed by path+mtime+size on the "append-only-immutable once taken"
678
+ // claim, and both seats falsified it with the operator-remediation class
679
+ // (a timestamp-preserving replacement collided all three fields); the r18
680
+ // fix added dev+ino+ctimeMs on the "userland cannot forge ctime" claim —
681
+ // and r19 (A1) falsified THAT against the kernel's COARSE clock (~1ms
682
+ // ticks): a touch loop holds the sidecar's ctime at the current tick
683
+ // through append1's scan, the rewrite fires in the SAME tick, all five
684
+ // fields collide, and the stale memo re-issued the replacement's
685
+ // committed seq — the full r18 harm chain, 14/100 on tmpfs (ext4 0/400,
686
+ // the filesystem-latency dependence the unconditional claim hid). The
687
+ // hit is now CONTENT-VALIDATED, not metadata-validated: the memo stores
688
+ // the CONTENT ANCHORS the scan itself extracted — headSeq/tailSeq, the
689
+ // first and last seq values in the scan's first and final haystack
690
+ // windows — and every hit re-reads those two windows (two positioned
691
+ // reads, O(1) at the 588MB scale) and compares: any mismatch rescans.
692
+ // The anchors describe the bytes the memoized max was computed FROM, so
693
+ // a replaced file shows different anchors whatever the metadata clock
694
+ // did — the same-tick forge's replacement changes the whole file, both
695
+ // windows included. The metadata fields stay as a cheap first gate (a
696
+ // post-decision replacement still rescans at the stat without paying the
697
+ // anchor reads); the read-validate (stat before and after the scan)
698
+ // stays as the in-flight guard on the WRITE side. What remains outside
699
+ // the anchors, disclosed honestly: a rewrite confined to the MIDDLE of a
700
+ // >2MB sidecar that preserves both end windows byte-for-byte — bounded
701
+ // content validation cannot see middle bytes, and the complete closure
702
+ // is a per-append full rescan (the exact r17 finding-3 cost the memo
703
+ // exists to avoid). Failures are NEVER memoized: a chmod-blocked file's
704
+ // recovery (the r16 pin) must rescan.
705
+ const takenSeqScanMemo = new Map<
706
+ string,
707
+ {
708
+ dev: number;
709
+ ino: number;
710
+ mtimeMs: number;
711
+ ctimeMs: number;
712
+ size: number;
713
+ max: number;
714
+ blinded: boolean; // round 20 F3: a memoized dead-span blind reproduces itself on a validated hit
715
+ headDigest: string;
716
+ tailDigest: string;
717
+ seqCount: number;
718
+ }
719
+ >();
720
+
721
+ // The .taken-* sidecar seq scan (round 16, finding 2, both seats; streamed
722
+ // and memoized round 17, finding 3): the reader folds every .taken-* file's
723
+ // rows, so the floor must consult them too — a committed sidecar row whose
724
+ // fold fails this cycle (round 7 finding 3's documented transient class,
725
+ // kept on disk for the mandated retry) was invisible to every r15 floor
726
+ // source, so the next append re-issued its seq and the mandated read
727
+ // recovery exposed a duplicate pair whose chronology fell back to grantedAt
728
+ // — the clock dependence the counter was built to remove, driven organically
729
+ // cross-process by both seats. The scan streams SEQ FIELDS ONLY (chunked
730
+ // bytes, no whole-file string) and is SUPERSET-honest: a sidecar that
731
+ // cannot be READ — or is not a regular file at all (round 18, finding 3:
732
+ // a FIFO or device entry with the reserved name would BLOCK the open
733
+ // inside the ledger lock's hold, cross-process, so a non-regular entry is
734
+ // a blinded source, never opened) — is a BLINDED source: its rows are
735
+ // committed and own seqs we cannot see, so the space above the known max
736
+ // is not provably free and the append takes the sentinel rather than risk
737
+ // a duplicate. When the read recovers the counter continues from the
738
+ // sidecar's real seqs.
739
+ // `skipFiles` are the files THIS section's takeSpool already folded
740
+ // successfully (their parsed events are in the floor already) — scanning
741
+ // them again would re-read bytes the section already parsed.
742
+ function scanTakenSidecarSeqs(skipFiles: string[] = []): { max: number; blinded: boolean } {
743
+ let max = -1;
744
+ let blinded = false;
745
+ for (const file of takenSpoolFiles()) {
746
+ if (skipFiles.includes(file)) continue; // folded this section: parsed events already floor us
747
+ let statBefore: ReturnType<typeof statSync> | undefined;
748
+ let memoized = false;
749
+ try {
750
+ statBefore = statSync(file);
751
+ const memo = takenSeqScanMemo.get(file);
752
+ if (
753
+ memo !== undefined &&
754
+ memo.mtimeMs === statBefore.mtimeMs &&
755
+ memo.ctimeMs === statBefore.ctimeMs &&
756
+ memo.size === statBefore.size &&
757
+ memo.dev === statBefore.dev &&
758
+ memo.ino === statBefore.ino
759
+ ) {
760
+ // Rounds 19-20, findings 2: the metadata fields can all collide
761
+ // (the same-tick in-flight rewrite — the kernel's coarse ctime
762
+ // clock; or a write landing after this stat, which the r19 hit
763
+ // path never saw because it statted ONCE), so the hit is decided
764
+ // by CONTENT, re-validated exactly like the scan path: read the
765
+ // anchor windows (the same windows the scan derives its anchors
766
+ // from — BYTES, digests, and the window seq count — not the r19
767
+ // seq VALUES a middle insert preserving the end rows collided),
768
+ // then RE-STAT: any write that moved the file between the two
769
+ // stats fails the hit and takes the full rescan. The residual
770
+ // window is the microseconds between the re-stat and the
771
+ // assignment — the scan path's own disclosed in-flight boundary,
772
+ // now symmetric.
773
+ const anchors = readAnchorData(file);
774
+ let anchorsMatch = false;
775
+ try {
776
+ const statAfterHit = statSync(file);
777
+ anchorsMatch =
778
+ anchors !== undefined &&
779
+ statAfterHit.mtimeMs === statBefore.mtimeMs &&
780
+ statAfterHit.ctimeMs === statBefore.ctimeMs &&
781
+ anchors.headDigest === memo.headDigest &&
782
+ anchors.tailDigest === memo.tailDigest &&
783
+ anchors.seqCount === memo.seqCount;
784
+ } catch {
785
+ anchorsMatch = false; // unstatable now: rescan
786
+ }
787
+ if (anchorsMatch) {
788
+ // Round 21, finding 1 (seat 1): a validated hit memoizes
789
+ // UNCONDITIONALLY — the r20 restructure made memoized conditional
790
+ // on the max improving the running floor, so in a multi-sidecar
791
+ // state a sidecar whose memoized max did not exceed an earlier
792
+ // sidecar's contribution fell through to a FULL RESCAN on every
793
+ // append forever (measured 344-593ms per 64MiB non-improving
794
+ // sidecar vs 37/28/30ms for the swapped control on identical
795
+ // content; the r19 source memoized on the same tree) — the exact
796
+ // permanent-rescan tax class r17-F3/r20-F3/F4 were each accepted
797
+ // as findings for, reintroduced by the fix that closed them.
798
+ // The improvement check stays as a max-compare only.
799
+ if (memo.blinded) {
800
+ blinded = true; // a stable dead-span blind: the verdict reproduces, no rescan (round 20 F3)
801
+ memoized = true;
802
+ } else {
803
+ if (memo.max > max) max = memo.max;
804
+ memoized = true;
805
+ }
806
+ }
807
+ }
808
+ } catch {
809
+ // the stat failed: fall through to the stream (which will blind)
810
+ }
811
+ if (memoized) continue;
812
+ const scanned = streamMaxValidSeq(file);
813
+ if (scanned.blinded && !scanned.deadSpan) {
814
+ blinded = true; // committed rows behind an unreadable/over-cap/non-regular file: unknown owners
815
+ continue; // never memoized: recovery (chmod, operator repair) must rescan (the r16 pin)
816
+ }
817
+ if (scanned.blinded) {
818
+ // deadSpan: the file read fine, the content is the cause — a stable
819
+ // blind. Memoize it (anchors validate the hit like any scan) so the
820
+ // per-append rescan tax dies (round 20, finding 3: measured ~1s per
821
+ // append at 200MB, forever, from a shape where the r19 detector
822
+ // over-fired; the precise lookahead now extracts most of those, and
823
+ // the genuinely-dead ones pay the scan ONCE).
824
+ blinded = true;
825
+ } else if (scanned.max > max) max = scanned.max;
826
+ try {
827
+ // READ-VALIDATE: the pre-scan and post-scan stats must agree, or the
828
+ // bytes scanned are not the bytes the key describes — never memoize.
829
+ const statAfter = statSync(file);
830
+ if (
831
+ statBefore !== undefined &&
832
+ statAfter.mtimeMs === statBefore.mtimeMs &&
833
+ statAfter.ctimeMs === statBefore.ctimeMs
834
+ ) {
835
+ if (scanned.anchors !== undefined) {
836
+ takenSeqScanMemo.set(file, {
837
+ dev: statAfter.dev,
838
+ ino: statAfter.ino,
839
+ mtimeMs: statAfter.mtimeMs,
840
+ ctimeMs: statAfter.ctimeMs,
841
+ size: statAfter.size,
842
+ max: scanned.max,
843
+ blinded: scanned.blinded,
844
+ headDigest: scanned.anchors.headDigest,
845
+ tailDigest: scanned.anchors.tailDigest,
846
+ seqCount: scanned.anchors.seqCount,
847
+ });
848
+ }
849
+ }
850
+ } catch {
851
+ // the memo is an optimization: an unstatable file rescans next time
852
+ }
853
+ }
854
+ return { max, blinded };
855
+ }
856
+
857
+ // The ACTIVE spool's seq scan (round 17, finding 2): the degraded path
858
+ // cannot take the spool (no lock), and the merged view's spool read throws
859
+ // for the r7 permanent class (a spool past V8's string limit) — so the
860
+ // degraded floor was one source short of superset-consistency and re-issued
861
+ // committed spool rows' seqs (the locked twin blinds correctly through the
862
+ // taken scan after takeSpool's rename). The stream covers the spool the
863
+ // same way it covers sidecars; an unreadable spool is a BLINDED source.
864
+ function scanSpoolSeqs(): { max: number; blinded: boolean } {
865
+ try {
866
+ const spool = ledgerSpoolPath();
867
+ if (!existsSync(spool)) return { max: -1, blinded: false };
868
+ return streamMaxValidSeq(spool);
869
+ } catch {
870
+ return { max: -1, blinded: false }; // absent spool: nothing to floor from
871
+ }
872
+ }
873
+
874
+ // Assign seqs to the events of a LOCKED append, floored by everything the
875
+ // section already parses (the store rows, the taken spool events) plus the
876
+ // .taken-* sidecar scan (round 16, finding 2; streamed and memoized round
877
+ // 17, findings 2-3) and this process's last assignment. Runs inside the
878
+ // ledger lock's hold — no merged-view read, no extra parse (round 15,
879
+ // finding 4). The seq FILE is not a floor source (round 17, finding 1): it
880
+ // is an optimization, never a decision-maker. Saturation and a blinded
881
+ // source both mark the row chronology-UNKNOWN (round 16, finding 1): on
882
+ // the locked path with validated sources the counter never re-issues a
883
+ // value an existing row owns; the mid-gap in-flight insert ABOVE the
884
+ // determinism band is the recorded exception (the RESIDUAL LEDGER's
885
+ // entry 1 — a racing local writer inside the memo hit's validation
886
+ // window, measured 14-19/40).
887
+ function assignSeqsLocked(
888
+ events: ConsentEvent[],
889
+ storeEntries: unknown[],
890
+ spoolEntries: unknown[],
891
+ folded: string[],
892
+ ): void {
893
+ const takenScan = scanTakenSidecarSeqs(folded);
894
+ const floor = Math.max(
895
+ maxValidSeqAmong(storeEntries),
896
+ maxValidSeqAmong(spoolEntries),
897
+ takenScan.max,
898
+ lastAssignedSeq ?? -1,
899
+ );
900
+ let next = floor;
901
+ for (const event of events) {
902
+ next = takenScan.blinded ? SEQ_UNKNOWN : nextSeqFromFloor(next);
903
+ event.arrivalSeq = next;
904
+ if (next !== SEQ_UNKNOWN) lastAssignedSeq = next;
905
+ }
906
+ // The high-water file keeps the last ASSIGNABLE value (or the known floor
907
+ // when this append marked unknown): a sentinel never reaches the file.
908
+ writeSeqFileMonotonic(lastAssignedSeq !== undefined && lastAssignedSeq > floor ? lastAssignedSeq : floor);
909
+ }
910
+
911
+ // Assign a seq on the DEGRADED path (no lock, nothing parsed): the
912
+ // merged-view scan is UNCONDITIONAL (round 16, finding 3, both seats — the
913
+ // r15 cost fix had made the repair scan conditional on an INVALID seq
914
+ // file, so a VALID-but-rewound file short-circuited the only repair leg on
915
+ // the one path that has nothing parsed; the degraded path is the rare path,
916
+ // and the cost fix's purpose was the LOCKED common case). The .taken-*
917
+ // scan (round 16, finding 2) covers what the merged view cannot read, and
918
+ // the ACTIVE-SPOOL scan (round 17, finding 2) covers the one source the
919
+ // r16 fix missed — a spool past V8's string limit whose rows the merged
920
+ // view cannot read at all: the floor must see every source the reader can,
921
+ // and a blinded sidecar, a blinded spool, or saturation marks the row
922
+ // unknown, never a duplicate. The seq file is not a floor source here
923
+ // either (round 17, finding 1). The unlocked file read-write still races
924
+ // under concurrent degraded arrivals — the recorded duplicate residual.
925
+ function assignSeqDegraded(event: ConsentEvent): void {
926
+ try {
927
+ const takenScan = scanTakenSidecarSeqs();
928
+ const spoolScan = scanSpoolSeqs();
929
+ const floor = Math.max(maxArrivalSeqInStore(), takenScan.max, spoolScan.max, lastAssignedSeq ?? -1);
930
+ const next = takenScan.blinded || spoolScan.blinded ? SEQ_UNKNOWN : nextSeqFromFloor(floor);
931
+ event.arrivalSeq = next;
932
+ if (next !== SEQ_UNKNOWN) lastAssignedSeq = next;
933
+ writeSeqFileMonotonic(lastAssignedSeq !== undefined && lastAssignedSeq > floor ? lastAssignedSeq : floor);
934
+ } catch {
935
+ event.arrivalSeq = SEQ_UNKNOWN; // the store read itself failed: unknown
936
+ }
937
+ }
938
+
939
+ // The takeover window, sized to THIS critical section (interrogate rounds
940
+ // 3-5). Round 3 set 1s on the claim that the section is a millisecond RMW;
941
+ // round 4 measured the claim false — the store is append-only forever, so
942
+ // the section is O(store) plus the home directory's latency, and a 1s
943
+ // window stole a LIVE productive writer mid-section, silently erasing a
944
+ // committed event (600k-event store: 1.9-2.9s sections; a 44KB store on a
945
+ // 1200ms-latency fs: the same). No constant can win that race; liveness
946
+ // must be the criterion. The window now covers only what cannot heartbeat:
947
+ // an empty stale lock dir (a crash between mkdir and the pid write) is
948
+ // reclaimed at 1s, a dead holder immediately, while a LIVE holder claims a
949
+ // worker-thread heartbeat (LEDGER_HEARTBEAT_MS) that refreshes the claim's
950
+ // mtime for the duration of the section — a beating holder never goes
951
+ // stale, however long its section runs, and is waited out instead of
952
+ // stolen.
953
+ //
954
+ // Round 5 closed the hole that left: a wedged MAIN thread keeps its worker
955
+ // beating, so a live-but-hung holder is indistinguishable from a healthy
956
+ // slow one and would be waited out FOREVER — the waiter is a synchronous
957
+ // poll on the caller's main thread, so the whole server's event loop
958
+ // stalls for the wedge (measured: 59.7s on a 60s wedge; still blocked at
959
+ // 20s; zero event-loop turns). The honest rule, now stated: a live-beating
960
+ // holder is PROBABLY productive, and a probably-productive holder is
961
+ // waited out — but only up to a hard total cap (LEDGER_MAX_WAIT_MS).
962
+ // Past the cap the waiter degrades to the additive-spool append: the
963
+ // ledger is best-effort by contract, and an approved call never blocks
964
+ // unboundedly ON THE LOCK — the wait is capped and the waiter degrades
965
+ // past it. The cap does NOT bound the holder's own section, which is the
966
+ // uncapped O(store) read-modify-write (the recorded cost residual: 4.1s
967
+ // at 1.4M events, 23.5s at the exact 500MB cap edge) — an approved call
968
+ // on a giant tree is slow, never wedged — and dead holders (immediate
969
+ // reclaim) and empty stale dirs (1s) keep their current behavior under
970
+ // the cap. The cap applies to
971
+ // healthy sections too by design: a healthy section longer than the cap
972
+ // makes concurrent waiters degrade — their events land additively in the
973
+ // spool instead of racing the holder's whole-file write (round 6: the
974
+ // unlocked whole-file write re-opened the round-4 erasure at 1.4M events
975
+ // and on slow homes, both writers rc=0, the committed event gone).
976
+ const LEDGER_LOCK_TAKEOVER_MS = 1_000;
977
+ const LEDGER_HEARTBEAT_MS = 200;
978
+ // The hard total-wait cap (round 5): well under the 5s bar the round-3
979
+ // stall probes set. Round 6 falsified the "above every healthy-section
980
+ // shape" sizing claim (a 1.4M-event store measures 4.1s; a slow home has
981
+ // no ceiling) — the cap no longer pretends to bound healthy sections; it
982
+ // bounds the CALLER's stall, and the additive spool carries the evidence
983
+ // for whatever runs past it.
984
+ const LEDGER_MAX_WAIT_MS = 3_000;
985
+
986
+ // Degraded-section re-entrancy (round 6, finding 1): when >0, this process
987
+ // is inside a degraded (unlocked) ledger section. Nested ledger calls
988
+ // skip acquisition entirely — a second withDepLock attempt would pay the
989
+ // wait cap AGAIN (recordAskModeConsent's section calls appendConsentEvent;
990
+ // the gate's ask path measured 6.05-6.09s on a wedged holder, 2× the cap
991
+ // the bar was sized for) — and their appends route to the additive spool,
992
+ // never to an unlocked whole-file write.
993
+ let degradedDepth = 0;
994
+
995
+ // The filtered view consumers read: every entry that parses to the
996
+ // ConsentEvent shape, from the main store, the degraded spool, AND every
997
+ // .taken-* file beside it. The taken fold (round 7, finding 2) closes the
998
+ // compaction's reader-blind window: takeSpool renames the spool away
999
+ // BEFORE the main write, and when that write fails or crashes the taken
1000
+ // file deliberately survives — without the fold, a tier-inheritance reuse
1001
+ // in that window resolved against a store that did not yet carry the
1002
+ // original and mis-recorded the tier (measured: a terminal original
1003
+ // re-recorded as posture, permanently).
1004
+ //
1005
+ // The three sources are read at three different instants, so the SAMPLING
1006
+ // order and the ARRAY order are chosen separately, and each for a distinct
1007
+ // reason. Sampling order: spool, then taken, then store. An event moves
1008
+ // spool → taken → (store + removal) as a compaction proceeds; a pass that
1009
+ // samples the slow store FIRST can read the pre-write store and then, a
1010
+ // read later, find the taken file already removed — assembling a view from
1011
+ // a state gap no single instant had (measured: one absent sample through
1012
+ // a real 400k compaction). Sampling the small spool and taken files first
1013
+ // closes every gap: by the time the slow store read opens, the event is
1014
+ // either still in the taken file or already in the store it reads. Array
1015
+ // order: store, then spool, then taken — DISPLAY order only. No ordering
1016
+ // choice here can affect an inheritance decision (round 8): the tier
1017
+ // resolution resolves the original by CHRONOLOGY and ignores array
1018
+ // position entirely, because fold order is not chronology — the taken
1019
+ // sidecars sort by a pid+UUID name, and after a stale-taken recovery even
1020
+ // the store's own row order is not chronological (a newer copy can land
1021
+ // below the older original it was folded ahead of). A taken file the
1022
+ // reader cannot read (a fold failure leaves it on disk, round 7 finding 3)
1023
+ // is skipped here the same way the fold skips it — the file survives with
1024
+ // its bytes. Malformed entries read as absent — read tolerance is fine;
1025
+ // the WRITE path never uses this view (it preserves raw entries).
1026
+ export function readConsentEvents(): ConsentEvent[] {
1027
+ const sampledSpool = spoolLines();
1028
+ const sampledTaken = takenSpoolFiles().flatMap((file) => spoolLinesOf(file));
1029
+ const foldIntoView = (lines: string[], out: ConsentEvent[]): void => {
1030
+ for (const line of lines) {
1031
+ const parsed = parseSpoolLine(line);
1032
+ if (parsed !== undefined) out.push(...filterEvents([parsed.parsed]));
1033
+ }
1034
+ };
1035
+ const out = filterEvents(readRawConsents() ?? []);
1036
+ const storeRowCount = out.length;
1037
+ foldIntoView(sampledSpool, out);
1038
+ foldIntoView(sampledTaken, out);
1039
+ // The delivery-outcome side channel (rounds 12-13): attaches the
1040
+ // annotate's lines to the STORE-resident rows they name, after every
1041
+ // source is folded — one pass, store rows only (the annotate guard's
1042
+ // own semantics: a degraded twin never receives a line).
1043
+ applyOutcomeLines(out, storeRowCount);
1044
+ return out;
1045
+ }
1046
+
1047
+ function filterEvents(entries: unknown[]): ConsentEvent[] {
1048
+ const out: ConsentEvent[] = [];
1049
+ for (const entry of entries) {
1050
+ if (!entry || typeof entry !== 'object') continue;
1051
+ const record = entry as Record<string, unknown>;
1052
+ if (
1053
+ typeof record.sessionId !== 'string' ||
1054
+ typeof record.tool !== 'string' ||
1055
+ typeof record.argsHash !== 'string' ||
1056
+ typeof record.grantedAt !== 'number' ||
1057
+ (record.outcome !== 'granted' && record.outcome !== 'denied') ||
1058
+ (record.scope !== 'once' && record.scope !== 'session') ||
1059
+ (record.evidence !== 'terminal' && record.evidence !== 'elicitation' && record.evidence !== 'posture')
1060
+ ) {
1061
+ continue;
1062
+ }
1063
+ const event: ConsentEvent = {
1064
+ sessionId: record.sessionId,
1065
+ tool: record.tool,
1066
+ argsHash: record.argsHash,
1067
+ outcome: record.outcome,
1068
+ grantedAt: record.grantedAt,
1069
+ scope: record.scope,
1070
+ evidence: record.evidence,
1071
+ // Round 15, finding 1: a seq outside the assignable space (absent,
1072
+ // null, negative, fractional, Infinity, at/above the sentinel) reads
1073
+ // as the SENTINEL — the row stays VISIBLE, sorts newest, and can
1074
+ // never be an original — never invisible (the pre-fix Infinity row
1075
+ // serialized to null and vanished from every reader, losing consent
1076
+ // events to a one-field corruption).
1077
+ arrivalSeq: isValidArrivalSeq(record.arrivalSeq) ? record.arrivalSeq : SEQ_UNKNOWN,
1078
+ };
1079
+ // The command-forward line (redacted at write time): pass it through
1080
+ // when present and well-formed; a malformed value reads as absent —
1081
+ // the same tolerance the other optional fields carry.
1082
+ if (typeof record.command === 'string' && record.command !== '') {
1083
+ event.command = record.command;
1084
+ }
1085
+ // The delivery-outcome follow-up (round 10, finding 4): pass it through
1086
+ // when present and well-formed; a malformed value reads as absent (the
1087
+ // documented read tolerance — the write path preserves the raw row).
1088
+ if (
1089
+ record.outcomeDetail === 'delivered' ||
1090
+ record.outcomeDetail === 'uncertain' ||
1091
+ record.outcomeDetail === 'failed'
1092
+ ) {
1093
+ event.outcomeDetail = record.outcomeDetail;
1094
+ }
1095
+ out.push(event);
1096
+ }
1097
+ return out;
1098
+ }
1099
+
1100
+ // The store as-is: the parsed array when the file holds one, undefined
1101
+ // when the file is absent. A file that exists but does not parse to an
1102
+ // array is the caller's corrupt case — this reader takes no position on
1103
+ // it beyond "not a usable store".
1104
+ function readRawConsents(): unknown[] | undefined {
1105
+ try {
1106
+ const path = ledgerFilePath();
1107
+ if (!existsSync(path)) return undefined;
1108
+ // Round 19, finding 1: the main store read runs through the guarded
1109
+ // open — a FIFO parked at the store path wedged every arrival (the
1110
+ // tier resolution, the append, the real callTool face, cross-process).
1111
+ // A non-regular entry reads as absent-or-unreadable, the callers'
1112
+ // existing degraded postures (lockedAppend quarantines it — the
1113
+ // rename preserves the entry's bytes and the tree unblocks).
1114
+ // Round 20, finding 1: the declared size is capped (a sparse giant
1115
+ // store blinds in O(1) instead of decoding for tens of seconds).
1116
+ const text = readWholeTextViaFd(path);
1117
+ if (text === undefined) return undefined;
1118
+ const parsed: unknown = JSON.parse(text);
1119
+ if (!Array.isArray(parsed)) return undefined;
1120
+ // Round 21, finding 1: the element-content guard — a sub-cap store
1121
+ // whose content is one giant value (the 300MiB-string shape that
1122
+ // aborted the server in the serializer) reads as UNREADABLE here, so
1123
+ // the callers take their existing degraded postures: the tier
1124
+ // resolution degrades to the caller's tier, and lockedAppend
1125
+ // QUARANTINES the file (preserve-then-write: the bytes land in the
1126
+ // .corrupt-* sidecar before the fresh store is ever written) and the
1127
+ // append proceeds. The 250MiB control stays admitted, unchanged.
1128
+ // Round 23: the skip band (above) — small files skip the walk.
1129
+ const fileBytes = statSync(path).size;
1130
+ if (fileBytes >= elementGuardSkipBandBytes() && !elementsWithinContentLimit(parsed)) return undefined;
1131
+ return parsed as unknown[];
1132
+ } catch {
1133
+ return undefined;
1134
+ }
1135
+ }
1136
+
1137
+ // V8's string limit (~512MB on 64-bit) makes readFileSync(file, 'utf8')
1138
+ // throw ERR_STRING_TOO_LONG AFTER reading every byte — the round-7
1139
+ // permanent class. Round 17, finding 3: a file KNOWN to be over the limit
1140
+ // is skipped BEFORE the read (the same no-lines outcome at O(1) — the
1141
+ // late-throw cost was ~1.4s per 588MB sidecar, paid by the tier
1142
+ // resolution's merged view and the take's fold attempt on EVERY append
1143
+ // for as long as the operator leaves the file in place).
1144
+ // HUAWEICLOUD_LEDGER_WHOLE_READ_LIMIT (bytes) tightens the guard for
1145
+ // tests — a lower limit skips MORE whole reads (fewer lines visible).
1146
+ // The env override is honored as given in EITHER direction (any
1147
+ // positive integer); the safe direction is DOWN (the tests only tighten
1148
+ // it), and the streaming seq scan still floors the counter from the
1149
+ // skipped file's bytes.
1150
+ // The default guard: just under V8's ~512MB string limit.
1151
+ const WHOLE_FILE_STRING_LIMIT_BYTES = 500 * 1024 * 1024;
1152
+
1153
+ function wholeReadLimitBytes(): number {
1154
+ const override = Number(process.env.HUAWEICLOUD_LEDGER_WHOLE_READ_LIMIT);
1155
+ return Number.isSafeInteger(override) && override > 0 ? override : WHOLE_FILE_STRING_LIMIT_BYTES;
1156
+ }
1157
+
1158
+ // The STREAMING scan's own declared-size cap (round 20, finding 1): the
1159
+ // scan streams in 1MiB chunks so V8's string limit does not bind it, but
1160
+ // an uncapped read is O(declared size) — a sparse sidecar buys hours of
1161
+ // CPU-bound scanning for ~8KiB of disk. The cap defaults to the same
1162
+ // 500MB discipline; HUAWEICLOUD_LEDGER_STREAM_LIMIT is its own seam so
1163
+ // the whole-read test seam (which stages SMALL sidecars the stream must
1164
+ // still read) does not blind them. Like the whole-read seam, the env
1165
+ // override is honored as given in either direction (any positive
1166
+ // integer; the tests only tighten it).
1167
+ const STREAM_SCAN_LIMIT_BYTES = WHOLE_FILE_STRING_LIMIT_BYTES;
1168
+
1169
+ function streamScanLimitBytes(): number {
1170
+ const override = Number(process.env.HUAWEICLOUD_LEDGER_STREAM_LIMIT);
1171
+ return Number.isSafeInteger(override) && override > 0 ? override : STREAM_SCAN_LIMIT_BYTES;
1172
+ }
1173
+
1174
+ // The ELEMENT-content bound (round 21, finding 1, seat 2 — the deepest
1175
+ // class of the round: a whole-server abort no catch can see): the r20 caps
1176
+ // bound the DECLARED size of a file, not the memory the append allocates
1177
+ // after an admitted read. A sub-cap store (300MiB, under the 500MiB cap)
1178
+ // whose content is one large JSON string parses fine alone, but the
1179
+ // append's whole-store JSON.stringify — with the tier resolution's parse
1180
+ // and lockedAppend's own parse both still live — puts three file-sized
1181
+ // strings in flight and V8 aborts from INSIDE the serializer (FATAL
1182
+ // ERROR: Zone Allocation failed), which is NOT a JS throw: lockedAppend's
1183
+ // catch never runs, the whole MCP server dies (SIGABRT over the wire,
1184
+ // reproduced against the bundled dist), and the unchanged store makes it
1185
+ // a permanent kill switch — every later ask-mode arrival aborts again.
1186
+ // The spool twin (one 300MiB line) aborts the first append the same way,
1187
+ // and the ledger's own compaction mints the poisoned store from it. The
1188
+ // realistic many-small-rows store at exactly the cap completes (23.5s,
1189
+ // 3.47GiB peak) — the aborting shape is exactly the giant-single-value
1190
+ // content a cap exists to bound, admitted because its declared size is
1191
+ // legal. The fix bounds the PARSED ARTIFACT per element: any single
1192
+ // store/fold element whose content exceeds the bound reads as
1193
+ // unreadable — the store path quarantines (bytes preserved, the
1194
+ // preserve-then-write doctrine), the fold path keeps the taken file
1195
+ // (the r7 read-failure posture, retried, never dropped), the append
1196
+ // lands in a fresh store, the call completes. The bound sits above the
1197
+ // measured-good 250MiB control (admitted, behavior unchanged) and below
1198
+ // the measured-abort 300MiB shape, with the whole-array serialization
1199
+ // ALSO replaced by a streamed per-element write (below) so the admitted
1200
+ // band's write never amplifies: per-element serialization is bounded by
1201
+ // this guard, the write buffer by construction.
1202
+ const LEDGER_ELEMENT_CONTENT_LIMIT_BYTES = 256 * 1024 * 1024; // 256MiB: 250MiB control admitted, 300MiB shape quarantined
1203
+
1204
+ // The element bound's test seam (round 23): safe-DIRECTIONAL only — an
1205
+ // override is honored only when it TIGHTENS the bound (a lower limit
1206
+ // rejects more, the same posture as the whole-read/stream seams' lower
1207
+ // direction; a higher value is ignored, because raising the bound past
1208
+ // the measured 2^28 abort cliff would be the unsafe direction). Lets the
1209
+ // pins exercise the guard's admission decision (quarantine/keep vs
1210
+ // write-into-store) at KB staging instead of 256MB.
1211
+ function elementContentLimitBytes(): number {
1212
+ const override = Number(process.env.HUAWEICLOUD_LEDGER_ELEMENT_LIMIT);
1213
+ return Number.isSafeInteger(override) && override > 0 && override < LEDGER_ELEMENT_CONTENT_LIMIT_BYTES
1214
+ ? override
1215
+ : LEDGER_ELEMENT_CONTENT_LIMIT_BYTES;
1216
+ }
1217
+
1218
+ // The guard's skip band (round 23, finding 3's cost mitigation): the
1219
+ // per-element byte walk is O(total content bytes) per append, which
1220
+ // measured ~+0.3-0.5s on an 87MB store and pushed a borderline live-writer
1221
+ // race over the 3s wait cap. For files UNDER the band the walk is
1222
+ // provably unnecessary in the SAFETY direction: an element's
1223
+ // RE-SERIALIZED bytes never exceed its share of the FILE's bytes by
1224
+ // enough to matter — escapes shrink on parse ("\u00e9" is 6 file
1225
+ // bytes, the re-serialized "é" is 4); numbers CAN grow in serialized
1226
+ // form (a file's compact "1e5" is 3 bytes, re-serialized "100000" is
1227
+ // 6) but the growth is bounded by the digit count the file itself
1228
+ // spent, and the structural slack is the ~3 bytes of quotes and the
1229
+ // newline the file already carries — so every
1230
+ // element of a file under the band has true serialized bytes under the
1231
+ // band < limit, and admission cannot reach the abort cliff. The walk
1232
+ // above the band stays the conservative padded-score check (its
1233
+ // structural padding can only over-refuse, the safe direction).
1234
+ // Realistic stores (every ledger-written tree is far under 64MiB) skip
1235
+ // the walk entirely; only genuinely giant files pay it, and those are
1236
+ // the ones the guard exists to examine.
1237
+ function elementGuardSkipBandBytes(): number {
1238
+ return elementContentLimitBytes() / 4;
1239
+ }
1240
+
1241
+ // An element's content size, computed WITHOUT serialization (round 21:
1242
+ // measuring by serializing is the very allocation the bound exists to
1243
+ // prevent): a string's UTF-16 length (the JS-string size the serializer
1244
+ // would produce), an object's summed string-property lengths plus
1245
+ // structural overhead, recursing into nested arrays/objects. O(1) per
1246
+ // string, O(properties) per row — a consent row is ~8 properties.
1247
+ // Round 23, finding 3 (seat 1's addendum): the score is in UTF-8 BYTES —
1248
+ // the domain the write actually pays. The r21/r22 form scored a string by
1249
+ // its UTF-16 unit count, which is memory-safe only in the ASCII regime
1250
+ // (units == bytes): a 130Mi-unit CJK element (390MB of file, under BOTH
1251
+ // the 256Mi-unit guard and the 500MB read cap) was ADMITTED and the write
1252
+ // aborted the process — Zone Allocation failed in the stringify, the
1253
+ // same measured 125Mi-answers/130Mi-aborts cliff the seat bisected; the
1254
+ // hole had sat inside the r21 admitted band since that round because
1255
+ // every giant-element acceptance ran ASCII. UTF-8 is at most 3 bytes per
1256
+ // BMP unit (exactly the CJK x3 regime) and 4 bytes per astral pair, so
1257
+ // byte-anchoring is the honest bound: ASCII behavior is IDENTICAL (bytes
1258
+ // == units — the 2x249MiB pair control stays admitted), and multibyte
1259
+ // content is measured at what the serializer will actually emit —
1260
+ // over-bound multibyte stores quarantine with their bytes, the r21
1261
+ // doctrine, never an abort. Buffer.byteLength measures without
1262
+ // serializing (the r21 no-serialization rule holds: it is a walk, not an
1263
+ // allocation).
1264
+ function elementContentUnits(entry: unknown): number {
1265
+ if (typeof entry === 'string') return Buffer.byteLength(entry, 'utf8');
1266
+ if (typeof entry === 'number' || typeof entry === 'boolean' || entry === null || entry === undefined) return 16;
1267
+ if (Array.isArray(entry)) {
1268
+ let total = 16;
1269
+ for (const item of entry) total += elementContentUnits(item) + 4;
1270
+ return total;
1271
+ }
1272
+ if (typeof entry === 'object') {
1273
+ let total = 256; // structural overhead: braces, quotes, commas
1274
+ const record = entry as Record<string, unknown>;
1275
+ // Round 23, finding 1: property NAMES are content too. The r21 form
1276
+ // walked Object.values only, so a row whose poison sits in a KEY
1277
+ // ({"<260MiB key>":1} scores 280 units) was ADMITTED and the write's
1278
+ // JSON.stringify aborted the process — Zone Allocation failed, not a
1279
+ // JS throw, the catch never ran, and the unchanged store made it a
1280
+ // permanent kill switch (the value control quarantined correctly at
1281
+ // the same size). Keys serialize into the piece exactly like values,
1282
+ // and in the same byte domain (round 23, finding 3).
1283
+ for (const key of Object.keys(record)) {
1284
+ total += Buffer.byteLength(key, 'utf8') + 8;
1285
+ total += elementContentUnits(record[key]) + 8;
1286
+ }
1287
+ return total;
1288
+ }
1289
+ return 16;
1290
+ }
1291
+
1292
+ // True when every element of a parsed store/fold batch is within the
1293
+ // element bound — the admission test for anything about to be serialized
1294
+ // into the store. Round 23, finding 2: the bound is EXCLUSIVE (>=) — the
1295
+ // r21 form rejected only `>`, so an element of EXACTLY the bound
1296
+ // (2^28 units) was admitted and the parse->slice->stringify path aborted
1297
+ // (the flatten at exactly 2^28; 2^28-1000 completes): the admitted band
1298
+ // must be WRITABLE, and the exact-bound element now reads as over-bound
1299
+ // with the same quarantine/keep posture as everything above it.
1300
+ function elementsWithinContentLimit(entries: unknown[]): boolean {
1301
+ for (const entry of entries) {
1302
+ if (elementContentUnits(entry) >= elementContentLimitBytes()) return false;
1303
+ }
1304
+ return true;
1305
+ }
1306
+
1307
+ // Open a ledger data file for reading WITHOUT the blocking hazard, with
1308
+ // the FD's own identity — not the path's — deciding (rounds 18-19): the
1309
+ // open carries O_NONBLOCK, so a FIFO's open returns immediately instead
1310
+ // of waiting for a writer (a regular file ignores the flag entirely), and
1311
+ // the fstatSync validates THE INODE THE OPEN LANDED ON — a FIFO, device,
1312
+ // socket, or directory renamed over the path after any stat is caught AT
1313
+ // the open, killing the stat→open TOCTOU by construction (round 19,
1314
+ // finding 4, both seats: a rename storm swapped a FIFO in between the
1315
+ // r18 stat and the open and wedged the append inside the lock's hold,
1316
+ // the heartbeat keeping the claim fresh so takeover never fired). A
1317
+ // non-regular entry is a BLINDED source, never read; an absent or
1318
+ // unopenable path reads the same (undefined) — one posture for every
1319
+ // failure, bounded by construction.
1320
+ function openRegularForRead(path: string): number | undefined {
1321
+ let fd: number | undefined;
1322
+ try {
1323
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
1324
+ if (!fstatSync(fd).isFile()) {
1325
+ closeSync(fd);
1326
+ return undefined; // FIFO/device/directory/socket: blinded, never read
1327
+ }
1328
+ return fd;
1329
+ } catch {
1330
+ if (fd !== undefined) {
1331
+ try {
1332
+ closeSync(fd);
1333
+ } catch {
1334
+ // best-effort: a leaked descriptor is the least harm here
1335
+ }
1336
+ }
1337
+ return undefined; // absent or unopenable: the same blinded posture
1338
+ }
1339
+ }
1340
+
1341
+ // Whole-file text read through the guarded open (rounds 19-20): EVERY
1342
+ // ledger read seam — the main store, the outcomes side channel, the spool
1343
+ // and its .taken-* sidecars — opens through openRegularForRead, so a
1344
+ // non-regular entry anywhere on the read path blinds in bounded time
1345
+ // instead of wedging the append (the r18 fix guarded the spool-shaped
1346
+ // seams only; a FIFO parked at the STORE or OUTCOMES path wedged the tier
1347
+ // resolution, the append, the real callTool face, and cross-process — the
1348
+ // degraded path re-entered the same blocking read past its 3s cap, S5).
1349
+ // Round 20, finding 1 closed the other unbounded axis: the r19 doctrine
1350
+ // bounded the OPEN, not the READ — a REGULAR sparse file (one truncate,
1351
+ // ~8KiB of disk, any declared size) passed the isFile guard by design and
1352
+ // the read streamed O(declared size): a sparse 8GiB store cost the
1353
+ // approved call 23s (the utf8 decode of the whole extent before the late
1354
+ // ERR_STRING_TOO_LONG), and the streaming scan measured 2.6-3.6s/GiB —
1355
+ // ~7-15 hours at the ext4 maximum, inside the lock hold, the heartbeat
1356
+ // suppressing takeover. The DECLARED size is now capped at every seam: a
1357
+ // file whose fd declares more than the whole-read limit blinds in O(1)
1358
+ // (the same posture as the unreadable class — over-limit by the store's
1359
+ // own definition). Legitimate files under the cap are unchanged; the
1360
+ // 500-512MB sliver that previously parsed now degrades honestly.
1361
+ function readWholeTextViaFd(path: string): string | undefined {
1362
+ const fd = openRegularForRead(path);
1363
+ if (fd === undefined) return undefined; // absent, unopenable, or non-regular
1364
+ try {
1365
+ if (fstatSync(fd).size > wholeReadLimitBytes()) return undefined; // over-limit: blind in O(1)
1366
+ return readFileSync(fd, 'utf8');
1367
+ } catch {
1368
+ return undefined;
1369
+ } finally {
1370
+ try {
1371
+ closeSync(fd);
1372
+ } catch {
1373
+ // best-effort: the read is complete or failed regardless
1374
+ }
1375
+ }
1376
+ }
1377
+
1378
+ // The spool-shaped whole read (the sidecars are line-oriented append-only
1379
+ // files; a past-limit one reads as no lines at O(1) while the streaming
1380
+ // scan still floors from its seq fields up to its own cap, below).
1381
+ function readSpoolTextWhole(path: string): string | undefined {
1382
+ return readWholeTextViaFd(path);
1383
+ }
1384
+
1385
+ // The spool's raw lines, best-effort: every non-empty line as text. A line
1386
+ // that does not parse degrades to skipped in the filtered view and is
1387
+ // preserved verbatim at compaction (the raw-preservation doctrine).
1388
+ function spoolLines(): string[] {
1389
+ return spoolLinesOf(ledgerSpoolPath());
1390
+ }
1391
+
1392
+ // The same best-effort line extraction over any spool-shaped file: the
1393
+ // spool itself, or a .taken-* compaction sidecar. An absent or unreadable
1394
+ // file reads as no lines (round 7, finding 3: the fold keeps unreadable
1395
+ // taken files on disk — the reader skipping them is what keeps a
1396
+ // mid-fold-failure compaction from losing the main write), and a file
1397
+ // past the whole-read limit reads as no lines BEFORE the bytes are read
1398
+ // (round 17, finding 3 — its seq fields still floor the counter through
1399
+ // the streaming scan).
1400
+ function spoolLinesOf(path: string): string[] {
1401
+ const text = readSpoolTextWhole(path);
1402
+ if (text === undefined) return [];
1403
+ return text.split('\n').filter((line) => line.trim().length > 0);
1404
+ }
1405
+
1406
+ // Every .taken-* file beside the spool, sorted for a deterministic view.
1407
+ // These are compaction sidecars: the in-flight take of the current spool,
1408
+ // or the deliberate survivors of a failed or crashed compaction (kept for
1409
+ // the next compaction's stale-taken sweep) — the same name shape the
1410
+ // sweep matches.
1411
+ function takenSpoolFiles(): string[] {
1412
+ try {
1413
+ const spool = ledgerSpoolPath();
1414
+ const dir = dirname(spool);
1415
+ return readdirSync(dir)
1416
+ .filter((entry) => entry.includes('.spool.jsonl.taken-'))
1417
+ .sort((a, b) => a.localeCompare(b))
1418
+ .map((entry) => join(dir, entry));
1419
+ } catch {
1420
+ return [];
1421
+ }
1422
+ }
1423
+
1424
+ function parseSpoolLine(line: string): { parsed: unknown } | undefined {
1425
+ try {
1426
+ return { parsed: JSON.parse(line) };
1427
+ } catch {
1428
+ return undefined;
1429
+ }
1430
+ }
1431
+
1432
+ // Quarantine sidecar naming (interrogate rounds 2-3): pid plus a random
1433
+ // UUID suffix — never a per-process counter, which resets and lets a
1434
+ // pid-reincarnated process rename onto the dead incarnation's sidecar and
1435
+ // silently replace the preserved bytes. With a UUID the name is unique per
1436
+ // quarantine by construction; the pre-existing sidecar always wins its
1437
+ // bytes.
1438
+ function quarantineSidecarName(path: string): string {
1439
+ return `${path}.corrupt-${process.pid}-${randomUUID()}`;
1440
+ }
1441
+
1442
+ // The additive line-append primitive (rounds 6-7, generalized round 12):
1443
+ // one JSON line through one O_APPEND fd the writer first inspects —
1444
+ // open, read the byte at the end, write a '\n' terminator when that byte
1445
+ // is not a newline, then write the line. Never a rewrite of existing
1446
+ // bytes; strictly additive; the whole-file O_APPEND protocol cannot
1447
+ // erase anything because it never REWRITES the file it appends to (the
1448
+ // tail inspection reads one byte; a read cannot erase). Concurrent appenders interleave lines; the kernel serializes the
1449
+ // size-update+write per open descriptor, and each line is a single small
1450
+ // write. The tail inspection is the round-7 discipline: a torn tail (a
1451
+ // disk-full clamp, a crash mid-append, a short write) must not GLUE the
1452
+ // next committed line onto the fragment — the terminator isolates it.
1453
+ function appendLineAdditively(path: string, line: string): void {
1454
+ try {
1455
+ mkdirSync(dirname(path), { recursive: true });
1456
+ const fd = openSync(path, 'a+', 0o600);
1457
+ try {
1458
+ const stat = fstatSync(fd);
1459
+ // Round 19: the additive write seams take the same non-regular
1460
+ // posture as the reads — a FIFO at the spool or outcomes path opens
1461
+ // ('a+' is O_RDWR: a FIFO is its own reader) and accepts writes
1462
+ // into its pipe buffer until the buffer fills, then BLOCKS forever
1463
+ // on the approved call's tail. The fd's own identity decides: a
1464
+ // non-regular entry is never written (the best-effort skip — the
1465
+ // same posture as a failed write).
1466
+ if (!stat.isFile()) return;
1467
+ const start = stat.size;
1468
+ if (start > 0) {
1469
+ const tail = new Uint8Array(1);
1470
+ const read = readSync(fd, tail, 0, 1, start - 1);
1471
+ if (read === 1 && tail[0] !== 0x0a) writeSync(fd, '\n');
1472
+ }
1473
+ writeSync(fd, line);
1474
+ } finally {
1475
+ closeSync(fd);
1476
+ }
1477
+ } catch {
1478
+ // same degradation contract as the locked write: never fail the call
1479
+ }
1480
+ }
1481
+
1482
+ // The degraded append (round 6, finding 2): strictly additive. One JSON
1483
+ // line per event to the spool — no read, no rewrite of the store. The
1484
+ // path resolution stays INSIDE the degradation catch (a relative
1485
+ // HUAWEICLOUD_STATE_DIR makes it throw — the round-4 posture: a
1486
+ // ledger-internal failure never fails the approved call).
1487
+ function spoolAppend(events: ConsentEvent[]): void {
1488
+ try {
1489
+ appendLineAdditively(ledgerSpoolPath(), events.map((event) => JSON.stringify(event)).join('\n') + '\n');
1490
+ } catch {
1491
+ // same degradation contract as the locked write: never fail the call
1492
+ }
1493
+ }
1494
+
1495
+ // Take the spool under the lock, atomically: rename moves every line
1496
+ // already appended into a per-compaction file; a degraded writer appending
1497
+ // after the rename lands in a FRESH spool (append mode creates it) and
1498
+ // waits for the next compaction. Returns the taken files' raw contents —
1499
+ // parseable events plus any unparseable line preserved verbatim as a
1500
+ // string element (the raw-preservation doctrine: the compaction may
1501
+ // reorder, never erase) — plus the list of files that folded SUCCESSFULLY,
1502
+ // the only ones the caller may remove. A file whose read fails (round 7,
1503
+ // finding 3: a spool past V8's max string length throws
1504
+ // ERR_STRING_TOO_LONG on readFileSync; EMFILE and EIO are the same class)
1505
+ // is kept in place with its bytes — "leave it for the next compaction" is
1506
+ // now literally true — and the next compaction's stale-taken sweep
1507
+ // retries it. The main write is not held hostage to the failure.
1508
+ function takeSpool(): { events: unknown[]; folded: string[] } {
1509
+ const spool = ledgerSpoolPath();
1510
+ const folded: string[] = [];
1511
+ const events: unknown[] = [];
1512
+ const fold = (file: string): void => {
1513
+ try {
1514
+ // Oversized-for-whole-read files are skipped BEFORE the bytes
1515
+ // (round 17, finding 3): the retry would throw late every compaction.
1516
+ const text = readSpoolTextWhole(file);
1517
+ if (text === undefined) return; // keep the file, bytes intact — the next compaction retries
1518
+ const lines = text.split('\n').filter((line) => line.trim().length > 0);
1519
+ // Round 21, finding 1: the fold is ALL-OR-NOTHING per file under the
1520
+ // element-content guard — a giant single line (the 300MiB spool twin
1521
+ // of the abort shape) would otherwise land in the store as one
1522
+ // string element and abort the append's serialization on THIS and
1523
+ // every later arrival. A file with any over-bound element is kept
1524
+ // like a read failure (the r7 posture: bytes intact, retried every
1525
+ // compaction, never dropped) and the store write proceeds without
1526
+ // it — the call completes.
1527
+ const batch: unknown[] = [];
1528
+ for (const line of lines) {
1529
+ const parsed = parseSpoolLine(line);
1530
+ batch.push(parsed === undefined ? line : parsed.parsed);
1531
+ }
1532
+ // Round 23: the skip band (above) — small spool files skip the walk.
1533
+ if (statSync(file).size >= elementGuardSkipBandBytes() && !elementsWithinContentLimit(batch)) {
1534
+ return; // keep the file: retried, evidence preserved
1535
+ }
1536
+ // Round 22, finding 2 (A2): the r21 refactor's events.push(...batch)
1537
+ // spread overflows V8's argument limit past ~125k elements — the
1538
+ // RangeError was swallowed by this catch, so a >125k-line degraded
1539
+ // spool NEVER compacted (measured: 125000 folds, 130000 silently
1540
+ // stranded, every append re-reading the 24.7MB file inside the lock;
1541
+ // the pre-r21 one-at-a-time loop folded the same spool cleanly).
1542
+ // The plain loop restores the pre-r21 shape at the r21 guard's cost.
1543
+ for (const item of batch) events.push(item);
1544
+ folded.push(file);
1545
+ } catch {
1546
+ // read failure: keep the file in place, bytes intact — evidence is
1547
+ // never deleted on a read failure; the next compaction retries
1548
+ }
1549
+ };
1550
+ try {
1551
+ if (existsSync(spool)) {
1552
+ const takenFile = `${spool}.taken-${process.pid}-${randomUUID()}`;
1553
+ renameSync(spool, takenFile);
1554
+ fold(takenFile);
1555
+ }
1556
+ } catch {
1557
+ // the rename raced a concurrent compaction or failed: the spool stays
1558
+ // for the next holder; nothing is lost
1559
+ }
1560
+ // Stale taken files from a compaction that crashed after its main write
1561
+ // (its events are already in the store): folding them again duplicates
1562
+ // those lines — the safe direction, documented residual; a crash BEFORE
1563
+ // the write is why they must be folded at all. Unreadable ones stay and
1564
+ // are retried here every compaction until they fold or an operator
1565
+ // looks at them (documented residual: a spool past V8's string limit
1566
+ // never folds through this path).
1567
+ for (const file of takenSpoolFiles()) {
1568
+ if (!folded.includes(file)) fold(file);
1569
+ }
1570
+ return { events, folded };
1571
+ }
1572
+
1573
+ // The streamed store write (round 21, finding 1): the store array is
1574
+ // serialized PER ELEMENT through a bounded buffer — '[' + row + ',' + … +
1575
+ // ']' — instead of one whole-array JSON.stringify. The r20 shape put the
1576
+ // entire future store's serialization in one zone-allocated buffer that
1577
+ // doubles its way up (256MiB->512MiB needs 768MiB contiguous), and with
1578
+ // the tier resolution's parse and lockedAppend's own parse of the same
1579
+ // file both live, three file-sized strings coexisted at the stringify:
1580
+ // V8 aborted from inside the serializer (Zone Allocation failed — not a
1581
+ // JS throw, invisible to every catch, the whole server died). Every
1582
+ // element reaching this writer is already inside the element-content
1583
+ // bound (the read and fold guards above), so each per-element
1584
+ // serialization is bounded; the write buffer is ~1MiB by construction;
1585
+ // the bytes produced are IDENTICAL to the whole-array stringify (the JSON
1586
+ // array grammar element-for-element — structure pins read the store).
1587
+ function writeStoreArrayAtomic(tmpPath: string, batches: unknown[][]): void {
1588
+ const fd = openSync(tmpPath, 'w', 0o600);
1589
+ try {
1590
+ // writeSync can return a PARTIAL count (RLIMIT_FSIZE, a full disk's
1591
+ // last block): a write loop that ignores the count accepts a
1592
+ // TRUNCATED file as complete — the tmp would be renamed over the
1593
+ // store mid-row and the folded taken files removed (evidence loss,
1594
+ // the exact r7-3 class; caught by the r8 organic probe's
1595
+ // capped-child leg, where the pre-r21 writeFileSync threw EFBIG on
1596
+ // the second attempt and left the taken files in place). Round 22,
1597
+ // finding 1 (BOTH seats): the r21 loop was byte-safe ONLY for ASCII —
1598
+ // writeSync's return counts BYTES while the loop sliced and bounded
1599
+ // by UTF-16 code units, so for non-ASCII content a short count either
1600
+ // exited "successfully" with the piece's tail never written (units <=
1601
+ // W < bytes: the truncated tmp landed as the store, taken file
1602
+ // removed, exit 0 — the natural RLIMIT_FSIZE shape: storeParses=false
1603
+ // at 61440 bytes, taken gone) or resumed misaligned mid-multibyte
1604
+ // (W < units: a span silently dropped, the store still parsing —
1605
+ // 14852 vs 18430 bytes — the "never rewrites" doctrine broken without
1606
+ // any detectable marker). The piece is now encoded ONCE and the loop
1607
+ // runs over BYTE offsets — the read side's own discipline — so the
1608
+ // byte-identity of the landed store holds by construction for ANY
1609
+ // content; a zero-progress write still throws so the caller's catch
1610
+ // keeps the taken files.
1611
+ const writeAll = (text: string): void => {
1612
+ const buf = Buffer.from(text, 'utf8'); // encode once: byte offsets from here on
1613
+ let at = 0;
1614
+ for (;;) {
1615
+ const wrote = writeSync(fd, buf.subarray(at));
1616
+ if (wrote <= 0) throw new Error('the store write made no progress');
1617
+ at += wrote;
1618
+ if (at >= buf.byteLength) return;
1619
+ }
1620
+ };
1621
+ let buffer = '';
1622
+ const flush = (): void => {
1623
+ if (buffer.length > 0) {
1624
+ writeAll(buffer);
1625
+ buffer = '';
1626
+ }
1627
+ };
1628
+ buffer += '[';
1629
+ let first = true;
1630
+ for (const batch of batches) {
1631
+ for (const element of batch) {
1632
+ buffer += first ? '' : ',';
1633
+ first = false;
1634
+ const piece = JSON.stringify(element);
1635
+ // A single element's serialization can exceed the flush buffer
1636
+ // (an admitted up-to-256MiB string element): write it directly,
1637
+ // never holding two oversized pieces at once.
1638
+ if (piece.length > 1024 * 1024) {
1639
+ const head = buffer;
1640
+ buffer = '';
1641
+ if (head.length > 0) writeAll(head);
1642
+ writeAll(piece);
1643
+ } else {
1644
+ buffer += piece;
1645
+ if (buffer.length >= 1024 * 1024) flush();
1646
+ }
1647
+ }
1648
+ }
1649
+ buffer += ']';
1650
+ flush();
1651
+ } finally {
1652
+ closeSync(fd);
1653
+ }
1654
+ }
1655
+
1656
+ // The locked append core: read the raw store, quarantine an unreadable
1657
+ // one, compact the spool, write existing-plus-spoolevents-plus-events.
1658
+ // Runs ONLY inside a withDepLock hold — the public functions acquire it
1659
+ // (and re-entrancy makes a nested call from inside another hold safe, so
1660
+ // the tier resolution in recordAskModeConsent and the append share ONE
1661
+ // serialized section). The WHOLE body is best-effort (interrogate round 4):
1662
+ // every internal failure — the store-path resolution included (a relative
1663
+ // HUAWEICLOUD_STATE_DIR makes devkitStateBase throw INSIDE the lock), any
1664
+ // fs error, the quarantine rename — degrades internally, so lockedAppend
1665
+ // CANNOT throw. That invariant, now true, is what lets withLedgerLock
1666
+ // treat any exception from withDepLock as an acquisition failure, and lets
1667
+ // the ledger honor its contract: an internal failure degrades the audit
1668
+ // trail, never the approved call (trunk recorded no consent at all).
1669
+ function lockedAppend(events: ConsentEvent[]): void {
1670
+ try {
1671
+ const path = ledgerFilePath();
1672
+ // The spool is taken FIRST, inside the lock: its lines plus the new
1673
+ // events land in the main store in one write, and a degraded writer
1674
+ // racing this compaction appends to the fresh spool the rename left
1675
+ // behind — no window, no loss.
1676
+ const spool = takeSpool();
1677
+ let existing: unknown[];
1678
+ const raw = readRawConsents();
1679
+ if (raw !== undefined) {
1680
+ existing = raw;
1681
+ } else if (existsSync(path)) {
1682
+ // Present but unreadable (or not an array): preserve-then-write. The
1683
+ // rename is atomic on POSIX, so the bytes land in the quarantine file
1684
+ // before the new store is ever written.
1685
+ try {
1686
+ renameSync(path, quarantineSidecarName(path));
1687
+ } catch {
1688
+ return; // cannot preserve → refuse to overwrite
1689
+ }
1690
+ existing = [];
1691
+ } else {
1692
+ existing = [];
1693
+ }
1694
+ // The seq assignment runs HERE, inside the lock's hold, floored by the
1695
+ // data this section already parsed (round 15, findings 1 and 4) plus the
1696
+ // streamed .taken-* scan (rounds 16-17): the store rows, the taken spool
1697
+ // events, the sidecar seq fields, and this process's last assignment.
1698
+ // No merged-view read, no seq-file trust (round 17, finding 1: the file
1699
+ // is an optimization, never a decision-maker) — the parsed and streamed
1700
+ // floor keeps the r14 durability guarantee (no source the reader can
1701
+ // see is invisible to the floor) at zero whole-file string reads.
1702
+ assignSeqsLocked(events, existing, spool.events, spool.folded);
1703
+ try {
1704
+ mkdirSync(dirname(path), { recursive: true });
1705
+ const tmp = `${path}.${process.pid}.tmp`;
1706
+ // Round 21, finding 1: the streamed per-element write (bounded
1707
+ // memory by construction) — see writeStoreArrayAtomic above.
1708
+ writeStoreArrayAtomic(tmp, [existing, spool.events, events]);
1709
+ renameSync(tmp, path);
1710
+ } catch {
1711
+ // same degradation contract as writeApprovals in approval-tokens.ts
1712
+ return; // the main write failed: keep the taken files for the next compaction
1713
+ }
1714
+ // The taken spool files are removed only after the main write landed,
1715
+ // and only the ones that folded successfully (round 7, finding 3) — an
1716
+ // unfolded file is evidence the store does not carry, so removing it
1717
+ // would silently drop every consent line it holds. A crash between
1718
+ // write and removal duplicates the folded lines at the next
1719
+ // compaction — the safe direction (additive), documented residual.
1720
+ for (const file of spool.folded) {
1721
+ try {
1722
+ rmSync(file, { force: true });
1723
+ } catch {
1724
+ // the stale-taken sweep at the next compaction reclaims it
1725
+ }
1726
+ }
1727
+ } catch {
1728
+ // never fail the approved call the user just approved
1729
+ }
1730
+ }
1731
+
1732
+ // Acquire the ledger lock for one append body. The degradation covers the
1733
+ // WHOLE acquisition attempt, not just the lock root's creation (interrogate
1734
+ // round 3, finding 4): once the root exists — the first append creates it
1735
+ // and it is never removed — a read-only tree makes the CLAIM mkdir's
1736
+ // EACCES the caller's problem, and an approved call failed. A tree that
1737
+ // cannot host the lock cannot host racing writers, warm or fresh, so ANY
1738
+ // acquisition failure (root mkdir, stale-stash sweep, claim mkdir, poll
1739
+ // error — and the lock-dir path resolution itself, which a relative
1740
+ // HUAWEICLOUD_STATE_DIR makes throw) proceeds DEGRADED instead of
1741
+ // surfacing. A body failure is a different fact: the bodyRan flag makes
1742
+ // the catch a no-op once the body started, so the append body never runs
1743
+ // twice and a body-internal throw (impossible by lockedAppend's hardening,
1744
+ // but held defensively) degrades to a no-op rather than a second attempt.
1745
+ // The heartbeat rides on the same acquisition, keeping a live section
1746
+ // claim-fresh for its whole duration (interrogate round 4).
1747
+ function withLedgerLock(fn: () => void): void {
1748
+ // Degraded-section re-entrancy (round 6, finding 1): inside a degraded
1749
+ // section there is no lock to contend for — acquiring again would pay
1750
+ // the wait cap a second time (2× the bound on the gate's ask path).
1751
+ if (degradedDepth > 0) {
1752
+ fn();
1753
+ return;
1754
+ }
1755
+ let bodyRan = false;
1756
+ try {
1757
+ withDepLock(
1758
+ () => {
1759
+ bodyRan = true;
1760
+ fn();
1761
+ },
1762
+ ledgerLockDir(),
1763
+ LEDGER_LOCK_TAKEOVER_MS,
1764
+ LEDGER_HEARTBEAT_MS,
1765
+ LEDGER_MAX_WAIT_MS,
1766
+ );
1767
+ } catch {
1768
+ // Acquisition failures (unhostable tree, read-only claim path) and the
1769
+ // round-5 wait-budget throw share this posture: the body has not run,
1770
+ // so it runs DEGRADED — the ledger is best-effort, an approved call
1771
+ // never blocks unboundedly on a lock, and a body-internal throw (made
1772
+ // impossible by the hardened bodies) is held defensively. The
1773
+ // degradedDepth marker makes the section re-entrant (no second cap)
1774
+ // and routes every append inside it to the additive spool.
1775
+ if (!bodyRan) {
1776
+ degradedDepth += 1;
1777
+ try {
1778
+ fn();
1779
+ } finally {
1780
+ degradedDepth -= 1;
1781
+ }
1782
+ }
1783
+ }
1784
+ }
1785
+
1786
+ // Best-effort append, same failure posture as the approvals store: an
1787
+ // in-file failure degrades the audit trail but never fails the call the
1788
+ // user just approved — with one carve-out: a store that exists but cannot
1789
+ // be read is never overwritten (it is quarantined with its bytes intact
1790
+ // first, and the append is dropped when even that fails). With a lock in
1791
+ // hand the whole read-modify-write runs under the per-store file lock, so
1792
+ // concurrent appenders — separate MCP server processes on one machine —
1793
+ // serialize. Without a lock (wedged holder, over-cap section, unhostable
1794
+ // tree) the append goes to the ADDITIVE SPOOL — a degraded whole-file
1795
+ // write would race the locked holder's own write and erase whatever
1796
+ // commits between the degraded read and the degraded rename (round 6,
1797
+ // finding 2: rc=0 on both sides, the committed event gone). The spool
1798
+ // appends one line and never reads the store, so nothing committed can be
1799
+ // erased; the next locked append compacts it.
1800
+ export function appendConsentEvent(event: ConsentEvent): void {
1801
+ // The seq starts UNKNOWN and is assigned by the ledger inside the write
1802
+ // path (rounds 13-15) — the caller cannot game or clock-order it, and an
1803
+ // append that dies before assignment leaves the sentinel (the annotate
1804
+ // then finds no row with that identity and skips — absence never proves
1805
+ // ownership, the round-12 doctrine).
1806
+ event.arrivalSeq = SEQ_UNKNOWN;
1807
+ // Inside a degraded section already: additive, no acquisition attempt.
1808
+ // The assignment rides inside the write bodies: the locked body assigns
1809
+ // under the ledger lock's hold (locked writers serialize for real), the
1810
+ // degraded body assigns inside its own degraded section.
1811
+ if (degradedDepth > 0) {
1812
+ assignSeqDegraded(event);
1813
+ spoolAppend([event]);
1814
+ return;
1815
+ }
1816
+ try {
1817
+ withDepLock(
1818
+ // lockedAppend assigns the seq from its parsed+streamed floor
1819
+ // (rounds 15-17): store rows + taken spool events + the sidecar
1820
+ // scan + this process's last assignment — no merged-view read, no
1821
+ // seq-file trust.
1822
+ () => lockedAppend([event]),
1823
+ ledgerLockDir(),
1824
+ LEDGER_LOCK_TAKEOVER_MS,
1825
+ LEDGER_HEARTBEAT_MS,
1826
+ LEDGER_MAX_WAIT_MS,
1827
+ );
1828
+ } catch {
1829
+ // Acquisition failed (budget, unhostable tree, read-only claim): the
1830
+ // spool is the degraded append — lockedAppend never runs unlocked.
1831
+ // The assignment is the degraded one (file + last assignment, or the
1832
+ // merged-view repair when the file is invalid) and remains the
1833
+ // recorded duplicate residual: it cannot hold the lock.
1834
+ assignSeqDegraded(event);
1835
+ spoolAppend([event]);
1836
+ }
1837
+ }
1838
+
1839
+ // The ORIGINAL granted event on this consent key: the one a memo-reuse
1840
+ // inherits its evidence tier from. A denied arrival is not a consent — a
1841
+ // retry after one is a fresh ask, not a reuse.
1842
+ //
1843
+ // Round 8, finding 1 (both seats): the original is resolved by
1844
+ // CHRONOLOGY — the earliest arrival on the key, keyed (arrivalSeq,
1845
+ // grantedAt) since round 13 — never by array position. The merged view's order is fold order (store, spool, then
1846
+ // .taken-* sidecars in name order — a pid+UUID artifact with no relation
1847
+ // to chronology, and after a stale-taken recovery even the store's own
1848
+ // row order is not chronological), and a recovery state can hold the
1849
+ // same key in several sources at once: the terminal original in one
1850
+ // sidecar, a mis-recorded posture copy — born when a transient read
1851
+ // failure hid the original — in another. Taking the last array element
1852
+ // handed the inheritance to whichever random UUID name-sorted last
1853
+ // (measured: a controlled pair flipped terminal/posture on the name
1854
+ // order alone; the organic chain mis-inherited deterministically; the
1855
+ // real API downgraded on half the runs). Chronology is the rule the plan
1856
+ // states — a reuse inherits the ORIGINAL event's tier — and it is also
1857
+ // the self-consistent one: every reuse row re-records the inherited
1858
+ // tier, so in a healthy chain every granted row on the key carries the
1859
+ // original's tier and the scan direction is invisible; only the
1860
+ // failure-born copy differs, and it is always the NEWER row — except at
1861
+ // an exact millisecond collision (round 9, finding 1: the same-ms
1862
+ // boundary reopened the round-8 defect — the strict-< incumbent kept
1863
+ // the FIRST row in array order, which is fold order, so the copy won
1864
+ // whenever its host name-sorted or folded first; measured 10/20 wrong on
1865
+ // the taken pair, three of six host cells wrong 20/20, the first
1866
+ // compaction baking the pick into the store permanently). At such a tie
1867
+ // chronology cannot distinguish the rows, so the tiebreak is CONTENT —
1868
+ // but round 10, finding 1 (both seats) fixed its direction: the WEAKEST
1869
+ // tier present wins (posture < elicitation < terminal), a function of
1870
+ // the rows' own content and never of the fold order, and the only
1871
+ // direction the plan's never-upgrade line survives — see
1872
+ // TIER_PRECEDENCE below for the honest cost.
1873
+
1874
+ // Tier precedence for the equal-chronology tiebreak (rounds 9-10): the
1875
+ // strength of the HUMAN evidence behind the consent — a terminal
1876
+ // confirmation outranks an elicitation response, which outranks a
1877
+ // posture-grade arrival. Pure data, keyed by the evidence model, with no
1878
+ // undefined case (the filtered view only yields these three tiers). The
1879
+ // table NAMES the strength order; round 10, finding 1 (both seats) fixed
1880
+ // the DIRECTION it is consulted in: at an exact cross-tier tie the WEAKEST
1881
+ // tier present wins, never the strongest. The round-9 strongest-wins rule
1882
+ // was an UPGRADE path — a posture-grade original with a stronger-tier
1883
+ // same-millisecond copy re-recorded elicitation/terminal over it (10/10
1884
+ // in both stagings, all six host cells, the locked path baking it
1885
+ // permanently), violating the plan line ("inherits the evidence tier of
1886
+ // the original event it reuses and never upgrades it, so a posture-grade
1887
+ // yes can never be re-recorded as terminal-grade on retry"). At an exact
1888
+ // tie chronology cannot name the original, so no tiebreak can recover
1889
+ // originality — the only plan-conforming direction is the SAFE one: the
1890
+ // weakest tier present. The honest cost, recorded: the r9 cell (a
1891
+ // terminal original beside a posture copy at the same stamp) now records
1892
+ // posture — a rare mis-grade DOWN. That is the correct trade: a mis-grade
1893
+ // down never fabricates stronger evidence, while a mis-grade up does.
1894
+ const TIER_PRECEDENCE: Record<ConsentEvidence, number> = { posture: 0, elicitation: 1, terminal: 2 };
1895
+
1896
+ function originalGrantedFor(sessionId: string, tool: string, argsHash: string): ConsentEvent | undefined {
1897
+ const events = readConsentEvents();
1898
+ let original: ConsentEvent | undefined;
1899
+ for (const event of events) {
1900
+ if (
1901
+ event.sessionId !== sessionId ||
1902
+ event.tool !== tool ||
1903
+ event.argsHash !== argsHash ||
1904
+ event.outcome !== 'granted'
1905
+ ) {
1906
+ continue;
1907
+ }
1908
+ // Round 15, finding 1: a sentinel row's chronology is UNKNOWN — it can
1909
+ // never name the original (a corrupted or pre-field row must not
1910
+ // fabricate an upgrade when the wall clock, or a hand-staged stall,
1911
+ // would hand it the win). Keys whose only granted rows are sentinel
1912
+ // rows resolve as fresh keys: the caller's tier.
1913
+ if (event.arrivalSeq === SEQ_UNKNOWN) continue;
1914
+ if (original === undefined || event.arrivalSeq < original.arrivalSeq) {
1915
+ original = event;
1916
+ continue;
1917
+ }
1918
+ if (event.arrivalSeq === original.arrivalSeq && event.grantedAt < original.grantedAt) {
1919
+ original = event;
1920
+ continue;
1921
+ }
1922
+ // Round 9, finding 1 (both seats) + round 10, finding 1 (both seats):
1923
+ // an EXACT grantedAt collision between rows with DIFFERENT tiers was
1924
+ // first resolved by array position — fold order — so a
1925
+ // same-millisecond failure-born posture copy could win the
1926
+ // inheritance whenever its host name-sorted or folded first. Round 9
1927
+ // replaced position with content: tier precedence, strongest wins.
1928
+ // Round 10 falsified the DIRECTION: strongest-wins is an UPGRADE path
1929
+ // — a posture-grade original with a stronger-tier same-ms copy
1930
+ // re-recorded the stronger tier over it (10/10 in three stagings, all
1931
+ // six host cells, the locked path permanent), the exact sentence the
1932
+ // plan forbids. At a tie chronology cannot distinguish the rows, and
1933
+ // it cannot name the original either — so the tiebreak resolves to
1934
+ // the WEAKEST tier present: downgrade-safe, upgrade-impossible. The
1935
+ // honest cost: a terminal original beside a weaker same-ms copy
1936
+ // records the weaker tier — a rare mis-grade DOWN, never a fabricated
1937
+ // upgrade. At a tie with EQUAL tiers the choice is immaterial (both
1938
+ // rows carry the same tier; the incumbent stays).
1939
+ //
1940
+ // Round 13, finding 4: the primary key is the ARRIVAL SEQUENCE, not
1941
+ // grantedAt — grantedAt steps backward under an NTP/VM-restore clock
1942
+ // correction, and a later-written failure-born copy with a smaller
1943
+ // stamp then won strict chronology (measured: a posture original
1944
+ // re-recorded as terminal, no tiebreak firing because the stamps
1945
+ // differ). The counter is assigned per append from the high-water
1946
+ // file, so it tracks real arrival order whatever the wall clock did;
1947
+ // grantedAt stays the key within an equal-seq collision (concurrent
1948
+ // degraded arrivals can race the unlocked counter read-write and take
1949
+ // the same number) and the weakest-wins rule governs the exact
1950
+ // (seq, grantedAt) tie.
1951
+ if (
1952
+ event.arrivalSeq === original.arrivalSeq &&
1953
+ event.grantedAt === original.grantedAt &&
1954
+ TIER_PRECEDENCE[event.evidence] < TIER_PRECEDENCE[original.evidence]
1955
+ ) {
1956
+ original = event;
1957
+ }
1958
+ }
1959
+ return original;
1960
+ }
1961
+
1962
+ // Returns the arrival's grantedAt stamp — the identity the dispatch layer
1963
+ // hands to annotateDispatchOutcome so the delivery outcome can be keyed to
1964
+ // EXACTLY the row this arrival wrote (round 12, finding 2: ownership is
1965
+ // proven by the stamp, never by absence — an append the best-effort catch
1966
+ // drops leaves a stamp no row matches, and the annotate then no-ops
1967
+ // instead of stamping an earlier call's row).
1968
+ // Returns the arrival's IDENTITY — the stamp AND the seq the ledger
1969
+ // assigned (round 15, finding 2). See the return statement below.
1970
+ export function recordAskModeConsent(params: {
1971
+ sessionId: string;
1972
+ tool: string;
1973
+ argsHash: string;
1974
+ outcome: 'granted' | 'denied';
1975
+ evidence?: ConsentEvidence;
1976
+ arrivalSeq?: number;
1977
+ // The command-forward line the summarize view rendered (already redacted
1978
+ // by the spec's contract); written on the row so the consent record names
1979
+ // what the user allowed, not only its hash.
1980
+ command?: string;
1981
+ // The consent's scope. 'once' (the default) is every ordinary arrival
1982
+ // and every PR-3a memo reuse. 'session' is the S3 session standing
1983
+ // consent grant (PR-3a): the elicitation form's "remember for this
1984
+ // session" tick — the grant row the doctor lists and the gate's
1985
+ // in-memory standing map keys rides. Tier resolution below applies
1986
+ // identically to both scopes: a reuse inherits the original's tier and
1987
+ // never upgrades (the PR-1 ledger rule; the round-10 G2 note's
1988
+ // tier-safe-writer contract).
1989
+ scope?: 'once' | 'session';
1990
+ // The caller knows WHICH channel answered this arrival and wants that
1991
+ // channel recorded (PR-1.5's ladder: an elicitation form answer is
1992
+ // `elicitation`, a chat-round-trip retry is `posture`). Without this the
1993
+ // ledger inherits the earliest granted row's tier on the consent key —
1994
+ // PR-1's reuse rule, which would label a chat retry `elicitation` whenever
1995
+ // a form had answered the same key earlier (a fabricated upgrade: the row
1996
+ // would claim a form nobody answered for this arrival). Memo reuse keeps
1997
+ // the inheriting path; a channel-verified arrival opts out.
1998
+ evidenceFinal?: boolean;
1999
+ }): { grantedAt: number; arrivalSeq: number } {
2000
+ // Tier resolution is the ledger's rule, not the caller's: a reuse
2001
+ // inherits the original event's tier verbatim — never upgraded (posture
2002
+ // stays posture when the caller asks for terminal); the one sanctioned
2003
+ // downgrade is the exact same-millisecond cross-tier tie, where
2004
+ // chronology cannot name the original and the WEAKEST tier present wins
2005
+ // (round 10, finding 1 — a rare mis-grade DOWN, never a fabricated
2006
+ // upgrade). Only a FRESH key takes the caller's evidence (posture for
2007
+ // ask arrivals, terminal for approve-CLI confirmations in the later
2008
+ // PRs). The ORIGINAL is resolved by chronology (round 8): the earliest
2009
+ // granted event on the key, wherever it lives — a recovery state can
2010
+ // hold the same key in the store, the spool, and several .taken-*
2011
+ // sidecars at once, and the failure-born mis-tiered copy is always the
2012
+ // NEWER row, so the earliest granted row is the original by
2013
+ // construction — except at the exact-tie boundary, where the
2014
+ // weakest-wins rule above is the only plan-conforming answer. The
2015
+ // resolution and the append share ONE section (locked: one hold;
2016
+ // degraded: one synchronous block with the spool routing), so two
2017
+ // racing arrivals on the same key both resolve against the store the
2018
+ // other left, not a stale snapshot. A resolution failure (an unreadable
2019
+ // store the hardened read already degrades to empty, a state-dir
2020
+ // validation throw) degrades to the caller's tier so the append still
2021
+ // lands — the same best-effort posture as the append itself
2022
+ // (interrogate round 4).
2023
+ const grantedAt = Date.now();
2024
+ const event: ConsentEvent = {
2025
+ sessionId: params.sessionId,
2026
+ tool: params.tool,
2027
+ argsHash: params.argsHash,
2028
+ outcome: params.outcome,
2029
+ grantedAt,
2030
+ scope: params.scope ?? 'once',
2031
+ evidence: 'posture', // resolved below, before the append
2032
+ arrivalSeq: 0, // appendConsentEvent assigns the real counter
2033
+ };
2034
+ if (params.command !== undefined && params.command !== '') event.command = params.command;
2035
+ withLedgerLock(() => {
2036
+ let evidence = params.evidence ?? 'posture';
2037
+ if (!params.evidenceFinal) {
2038
+ try {
2039
+ const original = originalGrantedFor(params.sessionId, params.tool, params.argsHash);
2040
+ if (original) evidence = original.evidence;
2041
+ } catch {
2042
+ // degrade to the caller's tier: the append is the fact that matters
2043
+ }
2044
+ }
2045
+ event.evidence = evidence;
2046
+ appendConsentEvent(event);
2047
+ });
2048
+ // Round 15, finding 2: the arrival's IDENTITY — the stamp AND the seq the
2049
+ // ledger assigned. The dispatch layer threads both to the delivery
2050
+ // recorder, whose annotate binds the outcome line to EXACTLY the row this
2051
+ // arrival wrote (ownership by identity, never by position: the positional
2052
+ // capture let a same-ms degraded twin compacted in behind the dispatch's
2053
+ // own row steal the delivery outcome). A dropped append returns the
2054
+ // sentinel seq — no row matches it, and the annotate skips.
2055
+ return { grantedAt, arrivalSeq: event.arrivalSeq };
2056
+ }
2057
+
2058
+ // The delivery-outcome follow-up (round 10, finding 4, both seats' shape):
2059
+ // annotate the most recent granted consent row on a key with what became of
2060
+ // the call the consent authorized. The gate records the ARRIVAL
2061
+ // (recordAskModeConsent, above); the dispatch layer — which is the only
2062
+ // place that ever sees the handler's return or throw — calls this
2063
+ // best-effort follow-up after the handler ran. The ledger's subject widens
2064
+ // accordingly: the CONSENT's lifecycle (arrival + what became of the call
2065
+ // it authorized), never the handler's internal execution. The annotation
2066
+ // is the AUDIT record of the delivery class; PR-3a's retry memo (the
2067
+ // gate's in-memory state, approval-gate.ts) keys on the dispatch layer's
2068
+ // COMPUTED outcome at dispatch time and never reads this annotation back.
2069
+ //
2070
+ // Best-effort in every direction, by design: the annotation is
2071
+ // LOCKLESS — it never takes the ledger lock (a wedged holder must not
2072
+ // tax the approved call's tail a second time after the arrival already
2073
+ // paid the 3s cap) and never writes the main store; it appends ONE line
2074
+ // to the additive outcomes side channel (.outcomes.jsonl). It SKIPS on
2075
+ // any failure — no store, an unreadable store, or the row not found.
2076
+ // "Not found" is the common healthy skip: token mode records no arrival
2077
+ // (nothing to annotate), a classified pass-through records none either,
2078
+ // and a consent whose arrival degraded to the spool or a taken sidecar
2079
+ // is left alone — enforced (round 11, finding 1, both seats), not just
2080
+ // promised: pre-fix, the store-only target scan stamped this call's
2081
+ // outcome over an EARLIER arrival's committed row in exactly that
2082
+ // state (sequential, deterministic, the ~3s healthy-section band), so
2083
+ // the annotate now resolves the newest granted row on the key through
2084
+ // the MERGED reader (store + spool + taken) first and skips entirely
2085
+ // unless that row is the store row this dispatch's own arrival wrote —
2086
+ // rewriting a spool line stays forbidden (the unlocked read-rewrite
2087
+ // this ledger forbids, round 6), and so does rewriting another
2088
+ // arrival's store row. A skipped annotation leaves the row as the
2089
+ // arrival wrote it; the AUDIT VIEW of an absent outcomeDetail reads as
2090
+ // delivery-unknown. The recorded residual narrows to the RACING shape alone: concurrent
2091
+ // same-key arrivals can interleave between this call's arrival and its
2092
+ // annotate so the newest store row is not provably this dispatch's own
2093
+ // — PR-3a's precise keyed join lands with the approvedVia carrier (the
2094
+ // recorded G2 note).
2095
+ // The newest granted stamp on a consent key among the rows OUTSIDE the
2096
+ // main store (the spool and every .taken-* sidecar) — the merged-world
2097
+ // leg of the annotate's targeting guard (round 11, finding 1). A spool
2098
+ // or taken line is a committed event (round 7), so the annotate must
2099
+ // treat its stamp as authoritative when deciding which row is the
2100
+ // newest consent on the key. Read tolerance matches the filtered view:
2101
+ // a line that does not parse, or a row that does not match the key or
2102
+ // is not granted, contributes nothing.
2103
+ function newestGrantedStampOutsideStore(params: { sessionId: string; tool: string; argsHash: string }): number {
2104
+ let newest = Number.NEGATIVE_INFINITY;
2105
+ const consider = (lines: string[]): void => {
2106
+ for (const line of lines) {
2107
+ const parsed = parseSpoolLine(line);
2108
+ if (parsed === undefined) continue;
2109
+ const record = parsed.parsed;
2110
+ if (!record || typeof record !== 'object') continue;
2111
+ const row = record as Record<string, unknown>;
2112
+ if (
2113
+ row.sessionId === params.sessionId &&
2114
+ row.tool === params.tool &&
2115
+ row.argsHash === params.argsHash &&
2116
+ row.outcome === 'granted' &&
2117
+ typeof row.grantedAt === 'number' &&
2118
+ row.grantedAt > newest
2119
+ ) {
2120
+ newest = row.grantedAt;
2121
+ }
2122
+ }
2123
+ };
2124
+ consider(spoolLines());
2125
+ for (const file of takenSpoolFiles()) {
2126
+ consider(spoolLinesOf(file));
2127
+ }
2128
+ return newest;
2129
+ }
2130
+
2131
+ // The delivery-outcome side channel (round 12, finding 4): one JSON line
2132
+ // per annotate, keyed by the arrival's stamp —
2133
+ // {sessionId, tool, argsHash, grantedAt, outcomeDetail}. Additive in both
2134
+ // directions: the append can erase nothing (the same O_APPEND discipline
2135
+ // as the spool), and the reader attaches a line only to the consent row
2136
+ // whose stamp it names. The annotate that writes here never touches the
2137
+ // main store at all, which is the whole point: rounds 10-11's annotate
2138
+ // was a third whole-file writer, and a heartbeat-less holder legitimately
2139
+ // deposed past the 1s takeover window could commit its lockedAppend
2140
+ // INSIDE the annotate's read→rename window — the annotate's stale-snapshot
2141
+ // rename then erased the holder's committed event (measured: gone from
2142
+ // every source, both writers rc=0), the round-6 erasure class reopened
2143
+ // through the writer that landed after the round-6 fix. The annotate is
2144
+ // now LOCKLESS as well as additive: it neither writes the store nor
2145
+ // needs serialization, so it can neither race a store commit nor depose
2146
+ // a live holder. Growth is append-only (one small line per annotated
2147
+ // dispatch — slower than the spool, which carries a full row per
2148
+ // arrival); a compaction that folds lines into store rows is honest
2149
+ // future work, not PR-1.
2150
+ function ledgerOutcomePath(): string {
2151
+ return `${ledgerFilePath()}.outcomes.jsonl`;
2152
+ }
2153
+
2154
+ interface OutcomeLine {
2155
+ sessionId: string;
2156
+ tool: string;
2157
+ argsHash: string;
2158
+ grantedAt: number;
2159
+ outcomeDetail: ConsentDeliveryOutcome;
2160
+ // The arrival's seq (round 14, finding 4): captured by the annotate
2161
+ // from the row its guard verified, so the fold binds to the exact row
2162
+ // whatever any compaction did to the store order. Absent on lines
2163
+ // written before the field or when the row's seq was the unknown
2164
+ // sentinel — those fall back to the key+stamp rule.
2165
+ arrivalSeq?: number;
2166
+ }
2167
+
2168
+ // Attach the outcome lines to the merged view (rounds 12-14): each line
2169
+ // names the consent row it annotates by the arrival's stamp AND — since
2170
+ // round 14, finding 4 — the arrival's SEQ, captured by the annotate from
2171
+ // the very row its guard verified. The compaction always folds spool rows
2172
+ // AFTER existing store rows, so a same-ms degraded twin compacted by the
2173
+ // next ordinary append lands BEHIND the annotated row and the key+stamp
2174
+ // fold handed the line to the twin (the row that annotated lost it). The
2175
+ // seq exists precisely to disambiguate: a line carrying a seq binds to the
2176
+ // store row matching (key, stamp, seq) — the exact row, whatever any
2177
+ // compaction did to the order; a legacy line with no seq falls back to
2178
+ // the key+stamp last-store-row rule (the r13 same-ms store rule). A
2179
+ // degraded twin never receives a line either way: the annotate's guard
2180
+ // never wrote one for it, and its own seq differs from the line's.
2181
+ // Round 13, finding 2's doctrine and finding 1's one-pass shape both
2182
+ // hold: store rows only, Map-indexed, O(store + lines).
2183
+ function applyOutcomeLines(out: ConsentEvent[], storeRowCount: number): void {
2184
+ let lines: string[];
2185
+ try {
2186
+ const path = ledgerOutcomePath();
2187
+ if (!existsSync(path)) return;
2188
+ // Round 19, finding 1: the outcomes channel's read runs through the
2189
+ // guarded open (a FIFO at this path wedged every readConsentEvents —
2190
+ // the tier resolution reaches it on the way IN of every arrival);
2191
+ // unreadable-or-non-regular reads as no lines: the rows keep their
2192
+ // arrival shape, the documented side-channel tolerance. Round 20,
2193
+ // finding 1: the declared size is capped (a sparse giant channel
2194
+ // blinds in O(1)).
2195
+ const text = readWholeTextViaFd(path);
2196
+ if (text === undefined) return;
2197
+ lines = text.split('\n').filter((line) => line.trim().length > 0);
2198
+ } catch {
2199
+ return; // unreadable side channel: the rows keep their arrival shape
2200
+ }
2201
+ if (lines.length === 0) return;
2202
+ const rowIndexOf = new Map<string, number>();
2203
+ // Round 17, finding 4 (both seats — the reader side of the r16
2204
+ // finding-6 guard): the seq-keyed index takes only VALID seqs — a row
2205
+ // whose seq is out of space (the ceiling band, the sentinel, Infinity,
2206
+ // absent) has no provable identity and is never a bind target, the
2207
+ // reader's mirror of the writer's "a sentinel identity binds nothing".
2208
+ // A DUPLICATED (key, stamp, seq) identity — two rows, one identity, the
2209
+ // r15-era racing residual — is marked AMBIGUOUS (-1) and binds nothing:
2210
+ // the reader's mirror of the writer's count-and-skip, never array-last.
2211
+ // The r15-era writer emitted exactly these lines (no range check on the
2212
+ // threaded identity) and the channel is append-only, so a mixed-version
2213
+ // fleet carries them; the reader must consume them safely.
2214
+ const rowSeqIndexOf = new Map<string, number>();
2215
+ const bound = Math.min(storeRowCount, out.length);
2216
+ for (let i = 0; i < bound; i += 1) {
2217
+ const event = out[i]!;
2218
+ const triple = `${event.sessionId}\0${event.tool}\0${event.argsHash}\0${event.grantedAt}`;
2219
+ rowIndexOf.set(triple, i);
2220
+ if (!isValidArrivalSeq(event.arrivalSeq)) continue; // unknown chronology: no identity
2221
+ const seqKey = `${triple}\0${event.arrivalSeq}`;
2222
+ rowSeqIndexOf.set(seqKey, rowSeqIndexOf.has(seqKey) ? -1 : i);
2223
+ }
2224
+ // Round 15 (A2's cell 3): LEGACY lines apply first, then SEQ — the
2225
+ // seq-bearing line is the precise identity (the dispatch's own row), so
2226
+ // it wins over any legacy line at the same row regardless of file order
2227
+ // (a mixed-version fleet writing both shapes cannot have a pre-seq line
2228
+ // overwrite a seq-bound datum). Each line parses ONCE here (the
2229
+ // pre-r15 shape re-parsed in the apply pass); the apply pass is one
2230
+ // parameterized loop — the seq keying adds the row's identity to the
2231
+ // legacy triple. Round 17, finding 4: a line whose arrivalSeq is outside
2232
+ // the assignable space is DROPPED entirely — it names an unprovable
2233
+ // identity (the writer's r16 rule), and treating it as legacy would let
2234
+ // it bind a row at the stamp positionally.
2235
+ const legacyRows: Partial<OutcomeLine>[] = [];
2236
+ const seqRows: Partial<OutcomeLine>[] = [];
2237
+ for (const line of lines) {
2238
+ const parsed = parseSpoolLine(line);
2239
+ if (parsed === undefined) continue;
2240
+ const record = parsed.parsed;
2241
+ if (!record || typeof record !== 'object') continue;
2242
+ const row = record as Partial<OutcomeLine>;
2243
+ if (
2244
+ typeof row.sessionId !== 'string' ||
2245
+ typeof row.tool !== 'string' ||
2246
+ typeof row.argsHash !== 'string' ||
2247
+ typeof row.grantedAt !== 'number' ||
2248
+ (row.outcomeDetail !== 'delivered' && row.outcomeDetail !== 'uncertain' && row.outcomeDetail !== 'failed')
2249
+ ) {
2250
+ continue;
2251
+ }
2252
+ if (isValidArrivalSeq(row.arrivalSeq)) seqRows.push(row);
2253
+ else if (row.arrivalSeq === undefined) legacyRows.push(row);
2254
+ // else: an out-of-space seq — no identity, never legacy: dropped
2255
+ }
2256
+ // One apply pass, parameterized by keying: legacy lines by the
2257
+ // (key, stamp) triple, seq lines by the full (key, stamp, seq) identity.
2258
+ // LEGACY runs first so the seq-bearing line — the precise identity —
2259
+ // wins over any legacy line at the same row regardless of file order.
2260
+ const applyOutcomeRows = (rows: Partial<OutcomeLine>[], seqKeyed: boolean): void => {
2261
+ for (const row of rows) {
2262
+ const triple = `${row.sessionId}\0${row.tool}\0${row.argsHash}\0${row.grantedAt}`;
2263
+ const index = seqKeyed ? rowSeqIndexOf.get(`${triple}\0${row.arrivalSeq}`) : rowIndexOf.get(triple);
2264
+ if (index !== undefined && index >= 0) out[index]!.outcomeDetail = row.outcomeDetail as ConsentDeliveryOutcome;
2265
+ }
2266
+ };
2267
+ applyOutcomeRows(legacyRows, false);
2268
+ applyOutcomeRows(seqRows, true);
2269
+ }
2270
+
2271
+ // The delivery-outcome follow-up (round 10, finding 4, both seats' shape):
2272
+ // record what became of the call a consent authorized, on the consent row
2273
+ // that arrival created — the AUDIT record of the delivery class (the
2274
+ // retry memo's state is the gate's in-memory record, never this
2275
+ // annotation). The gate records the ARRIVAL (recordAskModeConsent, which
2276
+ // returns the identity it wrote — the stamp and the seq); the dispatch
2277
+ // layer — the only place that ever sees the handler's return or throw —
2278
+ // hands that identity here with the delivery class. The ledger's subject
2279
+ // is the CONSENT's lifecycle (arrival + what became of the call it
2280
+ // authorized), never the handler's internal execution.
2281
+ //
2282
+ // Ownership is proven by IDENTITY, never by position or absence (rounds
2283
+ // 12, 15, and 16): the annotate proceeds only when the store holds
2284
+ // EXACTLY ONE granted row with the arrival's (stamp, seq). Round 15,
2285
+ // finding 2 (both seats) closed the positional hole: the capture used to
2286
+ // scan for the last store row at key+stamp, so a same-ms degraded twin
2287
+ // compacted in behind the dispatch's own row before its annotate ran
2288
+ // received the line — the degraded row carrying a delivery outcome the
2289
+ // annotate's own guard refuses to write, and the dispatch's row losing
2290
+ // it. Round 16, finding 6 hardened the guard both ways: the threaded seq
2291
+ // must be INSIDE the assignable space (a dropped or saturated arrival's
2292
+ // identity IS the sentinel, and a sentinel identity binds nothing —
2293
+ // ownership is not provable at an unknown chronology), each candidate
2294
+ // row's seq is range-normalized before the comparison (a corrupted
2295
+ // ceiling-band or sentinel-valued row never matches), and a full
2296
+ // (key, stamp, seq) identity collision — two rows, one identity — is
2297
+ // COUNTED and skipped, never bound by array position. The direct call
2298
+ // with no threaded identity binds only a UNIQUE key+stamp match (round
2299
+ // 16, finding 5: a unique match on a row without a valid seq binds too —
2300
+ // the line carries no arrivalSeq and the legacy fold rule applies; the
2301
+ // r15 conjunct had silently narrowed the stated contract and left the
2302
+ // legacy fold unreachable by any writer); ambiguity skips — never
2303
+ // positional. An arrival whose append was silently dropped
2304
+ // (lockedAppend's best-effort catch — ENOSPC/EIO/EACCES, the clamp
2305
+ // shapes) leaves no row anywhere, so the identity matches nothing and
2306
+ // the annotate is a no-op: the earlier call's row on the same key keeps
2307
+ // its own datum. An arrival that degraded to the spool or a taken sidecar
2308
+ // fails the same test (its row is not store-resident), which also
2309
+ // enforces the r10/r11 posture — degraded arrivals carry no delivery
2310
+ // outcome — and the outside-store guard (round 11, finding 1) still skips
2311
+ // when any granted row on the key outside the store carries a stamp at
2312
+ // or beyond this arrival's (this call's arrival degraded, a newer arrival
2313
+ // lives outside the store, or an equal-stamp ambiguity).
2314
+ //
2315
+ // Best-effort in every direction: lockless (it writes only the additive
2316
+ // side channel, so there is nothing to serialize and no holder to
2317
+ // depose), skip on any failure, never throw, and never write the main
2318
+ // store — the annotate may skip, never erase. A skipped or dropped
2319
+ // annotation leaves the row as the arrival wrote it; the memo treats an
2320
+ // absent outcomeDetail as unknown. The recorded residual is the RACING
2321
+ // same-key shape alone (concurrent arrivals interleaving between arrival
2322
+ // and annotate — PR-3a's keyed join lands with the approvedVia carrier,
2323
+ // the recorded G2 note), plus the same-millisecond equal-stamp pairs a
2324
+ // direct (no-seq) call cannot disambiguate — skipped, never positional.
2325
+ export function annotateDispatchOutcome(params: {
2326
+ sessionId: string;
2327
+ tool: string;
2328
+ argsHash: string;
2329
+ arrivalStamp?: number;
2330
+ // The arrival's seq, threaded from recordAskModeConsent's return through
2331
+ // the gate and the dispatch layer (round 15, finding 2) — the dispatch's
2332
+ // own identity. Optional for direct callers (probes, legacy): see the
2333
+ // unique-match fallback below.
2334
+ arrivalSeq?: number;
2335
+ outcomeDetail: ConsentDeliveryOutcome;
2336
+ }): void {
2337
+ try {
2338
+ if (typeof params.arrivalStamp !== 'number') return; // no stamp: never annotate
2339
+ const raw = readRawConsents();
2340
+ if (raw === undefined) return; // absent or unreadable store: nothing to annotate
2341
+ // Round 15, finding 2 (both seats): the capture used to take the LAST
2342
+ // raw-store row matching key+stamp — a positional ownership rule, so a
2343
+ // same-ms degraded twin compacted in BEHIND the dispatch's own row
2344
+ // before its annotate ran received the line (the twin carried a
2345
+ // delivery outcome the annotate's own guard refuses to write; the
2346
+ // dispatch's row lost it). The identity is now THREADED, never
2347
+ // captured: the dispatch's own (stamp, seq) names the exact row, and
2348
+ // the guard verifies that exact row exists in the store.
2349
+ let arrivalSeq: number | undefined;
2350
+ let arrivalPresent = false;
2351
+ // The guard prefix both captures share: the row must be this key's
2352
+ // granted arrival at the arrival's stamp. The threaded capture adds
2353
+ // the seq conjunct; the fallback counts matches instead.
2354
+ const rowAtKeyAndStamp = (entry: unknown): Record<string, unknown> | undefined => {
2355
+ if (!entry || typeof entry !== 'object') return undefined;
2356
+ const record = entry as Record<string, unknown>;
2357
+ return record.sessionId === params.sessionId &&
2358
+ record.tool === params.tool &&
2359
+ record.argsHash === params.argsHash &&
2360
+ record.outcome === 'granted' &&
2361
+ record.grantedAt === params.arrivalStamp
2362
+ ? record
2363
+ : undefined;
2364
+ };
2365
+ if (params.arrivalSeq !== undefined) {
2366
+ // The threaded face (rounds 15-16). Round 16, finding 6 (both legs):
2367
+ // (a) the raw guard used to compare arrivalSeq by === with no range
2368
+ // normalization — a sentinel-valued row (the exact shape-only class
2369
+ // round 15 named) bound a sentinel identity, and a row staged in the
2370
+ // ceiling band matched a threaded ceiling value. The comparison now
2371
+ // requires the threaded identity to be INSIDE the assignable space
2372
+ // and normalizes each candidate row the same way — an unknown or
2373
+ // unreadable seq never matches, so a dropped/saturated arrival
2374
+ // (whose identity IS the sentinel) binds NOTHING: ownership is not
2375
+ // provable at an unknown chronology, and an invalid threaded
2376
+ // identity never falls through to the positional fallback.
2377
+ // (b) At a full (key, stamp, seq) identity collision — two rows,
2378
+ // one identity, the intersection of finding 2's duplicate with the
2379
+ // same-ms racing residual — the guard used to bind array-last,
2380
+ // positional; indistinguishable pairs are COUNTED and skipped
2381
+ // instead, never bound by position.
2382
+ if (isValidArrivalSeq(params.arrivalSeq)) {
2383
+ let matches = 0;
2384
+ for (const entry of raw) {
2385
+ const record = rowAtKeyAndStamp(entry);
2386
+ if (record !== undefined && isValidArrivalSeq(record.arrivalSeq) && record.arrivalSeq === params.arrivalSeq) {
2387
+ matches += 1;
2388
+ }
2389
+ }
2390
+ if (matches === 1) {
2391
+ arrivalSeq = params.arrivalSeq;
2392
+ arrivalPresent = true;
2393
+ }
2394
+ // matches === 0: no row with the identity; > 1: an indistinguishable
2395
+ // pair — skip, never positional.
2396
+ }
2397
+ // An invalid threaded identity (the sentinel a dropped, saturated, or
2398
+ // blinded append returned): binds nothing — the annotate skips.
2399
+ } else {
2400
+ // The direct-call fallback (no threaded identity): the store row at
2401
+ // key+stamp is bound ONLY when it is UNIQUE — ambiguity (the twin
2402
+ // shape) skips, so a legacy/probe call can never bind the wrong row.
2403
+ // Round 16, finding 5: a unique match on a row WITHOUT a seq field
2404
+ // binds too (the r15 conjunct silently narrowed the stated contract
2405
+ // and left the legacy-line fold unreachable by any writer) — the
2406
+ // line then carries no arrivalSeq and the legacy fold rule applies.
2407
+ // Round 16, finding 6(a) applies here as well: a row whose seq is
2408
+ // PRESENT but out of space is UNREADABLE — not a legacy row, never
2409
+ // a candidate; only an ABSENT seq (the pre-field legacy shape) or a
2410
+ // VALID seq counts.
2411
+ let matches = 0;
2412
+ let uniqueSeq: number | undefined;
2413
+ for (const entry of raw) {
2414
+ const record = rowAtKeyAndStamp(entry);
2415
+ if (record === undefined) continue;
2416
+ if (record.arrivalSeq === undefined || record.arrivalSeq === null) {
2417
+ matches += 1; // the legacy shape: no seq field at all
2418
+ continue;
2419
+ }
2420
+ if (!isValidArrivalSeq(record.arrivalSeq)) continue; // unreadable: never a candidate
2421
+ matches += 1;
2422
+ uniqueSeq = record.arrivalSeq;
2423
+ }
2424
+ if (matches === 1) {
2425
+ arrivalSeq = uniqueSeq;
2426
+ arrivalPresent = true;
2427
+ }
2428
+ // matches !== 1: ambiguous or absent — never positional.
2429
+ }
2430
+ if (!arrivalPresent) return; // dropped append or degraded arrival: no row is provably this dispatch's
2431
+ if (newestGrantedStampOutsideStore(params) >= params.arrivalStamp) return; // the r11 guard
2432
+ appendLineAdditively(
2433
+ ledgerOutcomePath(),
2434
+ JSON.stringify({
2435
+ sessionId: params.sessionId,
2436
+ tool: params.tool,
2437
+ argsHash: params.argsHash,
2438
+ grantedAt: params.arrivalStamp,
2439
+ ...(arrivalSeq !== undefined ? { arrivalSeq } : {}), // SEQ_UNKNOWN lines stay legacy-keyed
2440
+ outcomeDetail: params.outcomeDetail,
2441
+ }) + '\n',
2442
+ );
2443
+ } catch {
2444
+ // best-effort by contract: a recording failure never fails the call
2445
+ }
2446
+ }