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