@oscharko-dev/keiko 1.1.10 → 1.1.11

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 (600) hide show
  1. package/dist/ui/csp-hashes.json +7 -7
  2. package/dist/ui/static/404.html +1 -1
  3. package/dist/ui/static/__next.__PAGE__.txt +11 -11
  4. package/dist/ui/static/__next._full.txt +13 -13
  5. package/dist/ui/static/__next._tree.txt +2 -2
  6. package/dist/ui/static/_next/static/chunks/00dd_gyzi9unw.js +1 -0
  7. package/dist/ui/static/_next/static/chunks/{2r-wzbygkv3rm.js → 00n029ow-5_tt.js} +2 -2
  8. package/dist/ui/static/_next/static/chunks/0_7ry-vzqryfq.js +1 -0
  9. package/dist/ui/static/_next/static/chunks/{42y02tbxkub8f.js → 0_p1naz51ki9i.js} +1 -1
  10. package/dist/ui/static/_next/static/chunks/0cksy9u2ysiuy.js +1 -0
  11. package/dist/ui/static/_next/static/chunks/{0rd6-ijqn28cg.js → 0xhrzm-zp_lsx.js} +1 -1
  12. package/dist/ui/static/_next/static/chunks/159szpr5ffygs.js +1 -0
  13. package/dist/ui/static/_next/static/chunks/1x5aw_ayly-sh.js +1 -0
  14. package/dist/ui/static/_next/static/chunks/2-h3ow6f6ywtk.js +1 -0
  15. package/dist/ui/static/_next/static/chunks/233j_pai87f3k.js +2 -0
  16. package/dist/ui/static/_next/static/chunks/27490erridyaz.js +1 -0
  17. package/dist/ui/static/_next/static/chunks/2tcon4aj5dc5t.js +1 -0
  18. package/dist/ui/static/_next/static/chunks/{1ql6xdhcq4th6.js → 2uewj5n3jrohk.js} +1 -1
  19. package/dist/ui/static/_next/static/chunks/365nk-5mmf_8c.js +1 -0
  20. package/dist/ui/static/_next/static/chunks/{0no8igw4lg7c2.js → 36t-jmpwnypy0.js} +1 -1
  21. package/dist/ui/static/_next/static/chunks/37f_o8ne61ty2.js +1 -0
  22. package/dist/ui/static/_next/static/chunks/3_u5w33et675r.js +1 -0
  23. package/dist/ui/static/_next/static/chunks/{01jy5ldd_0r_5.css → 3jb5u4g15g__m.css} +1 -1
  24. package/dist/ui/static/_next/static/chunks/434km55nqikg-.js +7 -0
  25. package/dist/ui/static/_not-found/__next._full.txt +9 -9
  26. package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +8 -8
  27. package/dist/ui/static/_not-found/__next._tree.txt +1 -1
  28. package/dist/ui/static/_not-found.html +1 -1
  29. package/dist/ui/static/_not-found.txt +9 -9
  30. package/dist/ui/static/atlassian-connectors/__next._full.txt +11 -11
  31. package/dist/ui/static/atlassian-connectors/__next._tree.txt +1 -1
  32. package/dist/ui/static/atlassian-connectors/__next.atlassian-connectors.__PAGE__.txt +10 -10
  33. package/dist/ui/static/atlassian-connectors.html +1 -1
  34. package/dist/ui/static/atlassian-connectors.txt +11 -11
  35. package/dist/ui/static/index.html +1 -1
  36. package/dist/ui/static/index.txt +13 -13
  37. package/dist/ui/static/launch/__next._full.txt +13 -13
  38. package/dist/ui/static/launch/__next._tree.txt +2 -2
  39. package/dist/ui/static/launch/__next.launch.__PAGE__.txt +11 -11
  40. package/dist/ui/static/launch.html +1 -1
  41. package/dist/ui/static/launch.txt +13 -13
  42. package/dist/ui/static/local-knowledge/__next._full.txt +13 -13
  43. package/dist/ui/static/local-knowledge/__next._tree.txt +2 -2
  44. package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +11 -11
  45. package/dist/ui/static/local-knowledge/capsule/__next._full.txt +12 -12
  46. package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +1 -1
  47. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +10 -10
  48. package/dist/ui/static/local-knowledge/capsule.html +1 -1
  49. package/dist/ui/static/local-knowledge/capsule.txt +12 -12
  50. package/dist/ui/static/local-knowledge.html +1 -1
  51. package/dist/ui/static/local-knowledge.txt +13 -13
  52. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-loss-summary.d.ts +2 -2
  53. package/node_modules/@oscharko-dev/keiko-activity-log/dist/activity-log-loss-summary.d.ts.map +1 -0
  54. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-loss-summary.js +2 -2
  55. package/node_modules/@oscharko-dev/keiko-activity-log/dist/activity-log-persistence.d.ts.map +1 -0
  56. package/node_modules/@oscharko-dev/keiko-activity-log/dist/activity-log-readiness.d.ts.map +1 -0
  57. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-readiness.js +2 -2
  58. package/node_modules/@oscharko-dev/keiko-activity-log/dist/activity-log-store.d.ts.map +1 -0
  59. package/node_modules/@oscharko-dev/keiko-activity-log/dist/error-classification.d.ts.map +1 -0
  60. package/node_modules/@oscharko-dev/keiko-activity-log/dist/index.d.ts +11 -0
  61. package/node_modules/@oscharko-dev/keiko-activity-log/dist/index.d.ts.map +1 -0
  62. package/node_modules/@oscharko-dev/keiko-activity-log/dist/index.js +14 -0
  63. package/node_modules/@oscharko-dev/keiko-activity-log/dist/log-level.d.ts.map +1 -0
  64. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/log-redaction.d.ts +17 -0
  65. package/node_modules/@oscharko-dev/keiko-activity-log/dist/log-redaction.d.ts.map +1 -0
  66. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/log-redaction.js +35 -3
  67. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/activity-log-line-reader.d.ts +2 -0
  68. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/activity-log-line-reader.d.ts.map +1 -0
  69. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/activity-log-line-reader.js +258 -0
  70. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/error-kind.d.ts +3 -0
  71. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/error-kind.d.ts.map +1 -0
  72. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/error-kind.js +11 -0
  73. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/index.d.ts +11 -0
  74. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/index.d.ts.map +1 -0
  75. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/index.js +10 -0
  76. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/sequence-number-set.d.ts +12 -0
  77. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/sequence-number-set.d.ts.map +1 -0
  78. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/sequence-number-set.js +46 -0
  79. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-analyze-sufficiency.d.ts.map +1 -0
  80. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-analyze.d.ts +3 -1
  81. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-analyze.d.ts.map +1 -0
  82. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-analyze.js +44 -19
  83. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-query.d.ts.map +1 -0
  84. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-segment-manifest-names.d.ts.map +1 -0
  85. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-segment-manifest.d.ts.map +1 -0
  86. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-manifest.js +6 -4
  87. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-scan.d.ts +5 -0
  88. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-segment-scan.d.ts.map +1 -0
  89. package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-scan.js +45 -15
  90. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-selective-export.d.ts +29 -0
  91. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-selective-export.d.ts.map +1 -0
  92. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-selective-export.js +30 -0
  93. package/node_modules/@oscharko-dev/keiko-activity-log/dist/reader/support-tool-catalog.d.ts.map +1 -0
  94. package/node_modules/@oscharko-dev/keiko-activity-log/dist/runtime-state-dir.d.ts.map +1 -0
  95. package/node_modules/@oscharko-dev/keiko-activity-log/dist/server-log.d.ts +186 -0
  96. package/node_modules/@oscharko-dev/keiko-activity-log/dist/server-log.d.ts.map +1 -0
  97. package/node_modules/@oscharko-dev/keiko-activity-log/dist/server-log.js +3107 -0
  98. package/node_modules/@oscharko-dev/keiko-activity-log/dist/server-logger.d.ts.map +1 -0
  99. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/server-logger.js +5 -2
  100. package/node_modules/@oscharko-dev/keiko-activity-log/dist/stack-frames.d.ts.map +1 -0
  101. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/stack-frames.js +1 -0
  102. package/node_modules/@oscharko-dev/keiko-activity-log/dist/support-incident-store.d.ts.map +1 -0
  103. package/node_modules/@oscharko-dev/keiko-activity-log/dist/support-incident.d.ts.map +1 -0
  104. package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/support-incident.js +13 -11
  105. package/node_modules/@oscharko-dev/keiko-activity-log/package.json +31 -0
  106. package/node_modules/@oscharko-dev/keiko-cli/dist/investigate.d.ts +1 -1
  107. package/node_modules/@oscharko-dev/keiko-cli/dist/investigate.d.ts.map +1 -1
  108. package/node_modules/@oscharko-dev/keiko-cli/dist/lazy-modules.d.ts +1 -0
  109. package/node_modules/@oscharko-dev/keiko-cli/dist/lazy-modules.d.ts.map +1 -1
  110. package/node_modules/@oscharko-dev/keiko-cli/dist/lazy-modules.js +1 -0
  111. package/node_modules/@oscharko-dev/keiko-cli/dist/repair.d.ts +1 -1
  112. package/node_modules/@oscharko-dev/keiko-cli/dist/repair.d.ts.map +1 -1
  113. package/node_modules/@oscharko-dev/keiko-cli/dist/repair.js +16 -16
  114. package/node_modules/@oscharko-dev/keiko-cli/dist/runner.js +3 -3
  115. package/node_modules/@oscharko-dev/keiko-cli/dist/state-paths.js +3 -3
  116. package/node_modules/@oscharko-dev/keiko-cli/dist/support-export.d.ts +1 -1
  117. package/node_modules/@oscharko-dev/keiko-cli/dist/support-export.d.ts.map +1 -1
  118. package/node_modules/@oscharko-dev/keiko-cli/dist/support-export.js +4 -17
  119. package/node_modules/@oscharko-dev/keiko-cli/dist/support-incident.d.ts +2 -2
  120. package/node_modules/@oscharko-dev/keiko-cli/dist/support-incident.d.ts.map +1 -1
  121. package/node_modules/@oscharko-dev/keiko-cli/dist/support-incident.js +11 -13
  122. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query-cli.d.ts +7 -8
  123. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query-cli.d.ts.map +1 -1
  124. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query-cli.js +22 -24
  125. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query-evidence.d.ts +1 -2
  126. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query-evidence.d.ts.map +1 -1
  127. package/node_modules/@oscharko-dev/keiko-cli/dist/support-selective-export.d.ts +6 -27
  128. package/node_modules/@oscharko-dev/keiko-cli/dist/support-selective-export.d.ts.map +1 -1
  129. package/node_modules/@oscharko-dev/keiko-cli/dist/support-selective-export.js +5 -33
  130. package/node_modules/@oscharko-dev/keiko-cli/dist/support.d.ts.map +1 -1
  131. package/node_modules/@oscharko-dev/keiko-cli/dist/support.js +7 -8
  132. package/node_modules/@oscharko-dev/keiko-cli/package.json +15 -14
  133. package/node_modules/@oscharko-dev/keiko-connectors/dist/version.d.ts +1 -1
  134. package/node_modules/@oscharko-dev/keiko-connectors/dist/version.js +1 -1
  135. package/node_modules/@oscharko-dev/keiko-connectors/package.json +3 -3
  136. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-failure-class-contracts.d.ts +71 -31
  137. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-failure-class-contracts.d.ts.map +1 -1
  138. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-failure-class-contracts.js +100 -26
  139. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-files.js +1 -1
  140. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-registry.generated.d.ts +924 -96
  141. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-registry.generated.d.ts.map +1 -1
  142. package/node_modules/@oscharko-dev/keiko-contracts/dist/activity-log-registry.generated.js +1074 -90
  143. package/node_modules/@oscharko-dev/keiko-contracts/dist/diagnostics.d.ts +4 -4
  144. package/node_modules/@oscharko-dev/keiko-contracts/dist/diagnostics.d.ts.map +1 -1
  145. package/node_modules/@oscharko-dev/keiko-contracts/dist/diagnostics.js +40 -11
  146. package/node_modules/@oscharko-dev/keiko-contracts/dist/observability.d.ts.map +1 -1
  147. package/node_modules/@oscharko-dev/keiko-contracts/dist/observability.js +17 -5
  148. package/node_modules/@oscharko-dev/keiko-contracts/dist/task-workspace.d.ts +2 -0
  149. package/node_modules/@oscharko-dev/keiko-contracts/dist/task-workspace.d.ts.map +1 -1
  150. package/node_modules/@oscharko-dev/keiko-contracts/dist/task-workspace.js +7 -0
  151. package/node_modules/@oscharko-dev/keiko-contracts/dist/version.d.ts +2 -2
  152. package/node_modules/@oscharko-dev/keiko-contracts/dist/version.js +2 -2
  153. package/node_modules/@oscharko-dev/keiko-contracts/package.json +1 -1
  154. package/node_modules/@oscharko-dev/keiko-evaluations/package.json +9 -9
  155. package/node_modules/@oscharko-dev/keiko-evidence/dist/version.d.ts +1 -1
  156. package/node_modules/@oscharko-dev/keiko-evidence/dist/version.js +1 -1
  157. package/node_modules/@oscharko-dev/keiko-evidence/package.json +4 -4
  158. package/node_modules/@oscharko-dev/keiko-git/dist/env.d.ts.map +1 -1
  159. package/node_modules/@oscharko-dev/keiko-git/dist/env.js +4 -0
  160. package/node_modules/@oscharko-dev/keiko-git/dist/index.d.ts +1 -0
  161. package/node_modules/@oscharko-dev/keiko-git/dist/index.d.ts.map +1 -1
  162. package/node_modules/@oscharko-dev/keiko-git/dist/index.js +1 -0
  163. package/node_modules/@oscharko-dev/keiko-git/dist/version.d.ts +1 -1
  164. package/node_modules/@oscharko-dev/keiko-git/dist/version.js +1 -1
  165. package/node_modules/@oscharko-dev/keiko-git/package.json +1 -1
  166. package/node_modules/@oscharko-dev/keiko-harness/dist/version.d.ts +1 -1
  167. package/node_modules/@oscharko-dev/keiko-harness/dist/version.js +1 -1
  168. package/node_modules/@oscharko-dev/keiko-harness/package.json +7 -7
  169. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/knowledge-log.js +1 -1
  170. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/version.d.ts +1 -1
  171. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/version.js +1 -1
  172. package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +5 -5
  173. package/node_modules/@oscharko-dev/keiko-memory-capture/dist/version.d.ts +1 -1
  174. package/node_modules/@oscharko-dev/keiko-memory-capture/dist/version.js +1 -1
  175. package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +3 -3
  176. package/node_modules/@oscharko-dev/keiko-memory-consolidation/dist/log-port.js +1 -1
  177. package/node_modules/@oscharko-dev/keiko-memory-consolidation/dist/version.d.ts +1 -1
  178. package/node_modules/@oscharko-dev/keiko-memory-consolidation/dist/version.js +1 -1
  179. package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +3 -3
  180. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/version.d.ts +1 -1
  181. package/node_modules/@oscharko-dev/keiko-memory-governance/dist/version.js +1 -1
  182. package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +3 -3
  183. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/version.d.ts +1 -1
  184. package/node_modules/@oscharko-dev/keiko-memory-retrieval/dist/version.js +1 -1
  185. package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +3 -3
  186. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/vault-log.js +1 -1
  187. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/version.d.ts +1 -1
  188. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/version.js +1 -1
  189. package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +3 -3
  190. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/gateway.d.ts +3 -0
  191. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/gateway.d.ts.map +1 -1
  192. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/gateway.js +118 -38
  193. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/resilience.d.ts +11 -4
  194. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/resilience.d.ts.map +1 -1
  195. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/resilience.js +29 -2
  196. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/version.d.ts +1 -1
  197. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/version.js +1 -1
  198. package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +4 -4
  199. package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +3 -3
  200. package/node_modules/@oscharko-dev/keiko-sandbox/dist/index.d.ts +3 -0
  201. package/node_modules/@oscharko-dev/keiko-sandbox/dist/index.d.ts.map +1 -1
  202. package/node_modules/@oscharko-dev/keiko-sandbox/dist/index.js +1 -0
  203. package/node_modules/@oscharko-dev/keiko-sandbox/dist/runtime-egress.d.ts +63 -0
  204. package/node_modules/@oscharko-dev/keiko-sandbox/dist/runtime-egress.d.ts.map +1 -0
  205. package/node_modules/@oscharko-dev/keiko-sandbox/dist/runtime-egress.js +182 -0
  206. package/node_modules/@oscharko-dev/keiko-sandbox/package.json +2 -2
  207. package/node_modules/@oscharko-dev/keiko-sdk/package.json +9 -9
  208. package/node_modules/@oscharko-dev/keiko-security/dist/log-port.js +1 -1
  209. package/node_modules/@oscharko-dev/keiko-security/dist/version.d.ts +1 -1
  210. package/node_modules/@oscharko-dev/keiko-security/dist/version.js +1 -1
  211. package/node_modules/@oscharko-dev/keiko-security/dist/windows-system-directory.d.ts.map +1 -1
  212. package/node_modules/@oscharko-dev/keiko-security/dist/windows-system-directory.js +6 -4
  213. package/node_modules/@oscharko-dev/keiko-security/package.json +2 -2
  214. package/node_modules/@oscharko-dev/keiko-server/dist/atlassian/credentialRoutes.d.ts +1 -1
  215. package/node_modules/@oscharko-dev/keiko-server/dist/atlassian/credentialRoutes.d.ts.map +1 -1
  216. package/node_modules/@oscharko-dev/keiko-server/dist/atlassian/wiring.d.ts +1 -1
  217. package/node_modules/@oscharko-dev/keiko-server/dist/atlassian/wiring.d.ts.map +1 -1
  218. package/node_modules/@oscharko-dev/keiko-server/dist/bounded-request-body.js +1 -1
  219. package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts +1 -1
  220. package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.d.ts.map +1 -1
  221. package/node_modules/@oscharko-dev/keiko-server/dist/chat-handlers.js +2 -2
  222. package/node_modules/@oscharko-dev/keiko-server/dist/client-diagnostics-routes.d.ts.map +1 -1
  223. package/node_modules/@oscharko-dev/keiko-server/dist/client-diagnostics-routes.js +67 -24
  224. package/node_modules/@oscharko-dev/keiko-server/dist/coding-app-session/codingAppSessionRoutes.d.ts +1 -1
  225. package/node_modules/@oscharko-dev/keiko-server/dist/coding-app-session/codingAppSessionRoutes.d.ts.map +1 -1
  226. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/activity-log.d.ts +1 -1
  227. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/activity-log.d.ts.map +1 -1
  228. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/codeContextConnector.d.ts +1 -1
  229. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/codeContextConnector.d.ts.map +1 -1
  230. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/githubCodeContextPort.d.ts +1 -1
  231. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/githubCodeContextPort.d.ts.map +1 -1
  232. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/githubCodeContextPort.js +1 -2
  233. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/githubIssueResolution.d.ts.map +1 -1
  234. package/node_modules/@oscharko-dev/keiko-server/dist/coding-context/githubIssueResolution.js +1 -2
  235. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRepositorySearchHandler.d.ts +1 -1
  236. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRepositorySearchHandler.d.ts.map +1 -1
  237. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRepositorySearchHandler.js +1 -1
  238. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeCiRepairBudgetStore.d.ts +1 -1
  239. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeCiRepairBudgetStore.d.ts.map +1 -1
  240. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeCiRepairBudgetStore.js +1 -1
  241. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeControlPlane.d.ts +1 -1
  242. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeControlPlane.d.ts.map +1 -1
  243. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeEvidenceAggregator.d.ts +3 -1
  244. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeEvidenceAggregator.d.ts.map +1 -1
  245. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeEvidenceAggregator.js +50 -0
  246. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeHistory.d.ts +1 -1
  247. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeHistory.d.ts.map +1 -1
  248. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeHistory.js +1 -1
  249. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeIssueIntake.d.ts +1 -1
  250. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeIssueIntake.d.ts.map +1 -1
  251. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeIssueIntake.js +1 -1
  252. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeManager.d.ts +5 -1
  253. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeManager.d.ts.map +1 -1
  254. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeManager.js +96 -11
  255. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOperationCoordinator.d.ts +1 -1
  256. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOperationCoordinator.d.ts.map +1 -1
  257. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOperationCoordinator.js +1 -2
  258. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOrchestrator.d.ts.map +1 -1
  259. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOrchestrator.js +31 -0
  260. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOrchestratorTypes.d.ts +1 -1
  261. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeOrchestratorTypes.d.ts.map +1 -1
  262. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeRoutes.d.ts.map +1 -1
  263. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeRoutes.js +8 -1
  264. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingRuntimeVerifiedCommitAuthorityStore.js +1 -1
  265. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingSafeActivityProjection.d.ts +1 -1
  266. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingSafeActivityProjection.d.ts.map +1 -1
  267. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingSafeActivityProjection.js +9 -9
  268. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolAuthorityPort.d.ts +1 -1
  269. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolAuthorityPort.d.ts.map +1 -1
  270. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolGovernedDelegate.d.ts +1 -1
  271. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolGovernedDelegate.d.ts.map +1 -1
  272. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolReadEditPorts.d.ts +1 -1
  273. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolReadEditPorts.d.ts.map +1 -1
  274. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/codingToolReadEditPorts.js +1 -1
  275. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/devLaneRuntimeProcessBackend.d.ts +1 -1
  276. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/devLaneRuntimeProcessBackend.d.ts.map +1 -1
  277. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/devLaneRuntimeProcessBackend.js +28 -5
  278. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/nativeRuntimeProcessBackend.d.ts +1 -1
  279. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/nativeRuntimeProcessBackend.d.ts.map +1 -1
  280. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/nativeRuntimeProcessBackend.js +14 -10
  281. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeAdapter.d.ts +1 -1
  282. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeAdapter.d.ts.map +1 -1
  283. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeAdapter.js +1 -1
  284. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeComposition.d.ts +2 -1
  285. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeComposition.d.ts.map +1 -1
  286. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeRuntimeComposition.js +43 -1
  287. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeV2History.d.ts +1 -1
  288. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeV2History.d.ts.map +1 -1
  289. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeV2HttpClient.d.ts.map +1 -1
  290. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/opencodeV2HttpClient.js +3 -1
  291. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionAuxiliaryPorts.d.ts +1 -1
  292. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionAuxiliaryPorts.d.ts.map +1 -1
  293. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionAuxiliaryPorts.js +1 -2
  294. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionCiRepairRuntime.js +1 -1
  295. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionCodingRuntimePorts.js +1 -1
  296. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionCodingRuntimeResolver.d.ts +1 -1
  297. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionCodingRuntimeResolver.d.ts.map +1 -1
  298. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionCodingRuntimeResolver.js +9 -1
  299. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionDraftDeliveryDependencies.js +1 -1
  300. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionManagedWorktreeTools.d.ts +2 -2
  301. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionManagedWorktreeTools.d.ts.map +1 -1
  302. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionManagedWorktreeTools.js +41 -3
  303. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionOpenCodeBackend.d.ts +1 -1
  304. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionOpenCodeBackend.d.ts.map +1 -1
  305. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionOpenCodeBackend.js +15 -1
  306. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionRuntimeGitPreparation.js +1 -1
  307. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionRuntimeWorkspaceAuthority.js +7 -4
  308. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionWorkspaceHeadReader.d.ts +7 -0
  309. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionWorkspaceHeadReader.d.ts.map +1 -1
  310. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/productionWorkspaceHeadReader.js +52 -17
  311. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/readOnlyChildOrchestrator.d.ts +1 -1
  312. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/readOnlyChildOrchestrator.d.ts.map +1 -1
  313. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/readOnlyChildOrchestrator.js +1 -1
  314. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeAuthorityService.d.ts +1 -1
  315. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeAuthorityService.d.ts.map +1 -1
  316. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeAuthorityService.js +1 -1
  317. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeProcessSupervisor.d.ts +17 -4
  318. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeProcessSupervisor.d.ts.map +1 -1
  319. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/runtimeProcessSupervisor.js +47 -9
  320. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/secureWorkspaceTextReadProcess.d.ts +1 -1
  321. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/secureWorkspaceTextReadProcess.d.ts.map +1 -1
  322. package/node_modules/@oscharko-dev/keiko-server/dist/coding-runtime/secureWorkspaceTextReadProcess.js +3 -1
  323. package/node_modules/@oscharko-dev/keiko-server/dist/command-runner.d.ts +1 -1
  324. package/node_modules/@oscharko-dev/keiko-server/dist/command-runner.d.ts.map +1 -1
  325. package/node_modules/@oscharko-dev/keiko-server/dist/credentialPersistence.js +1 -1
  326. package/node_modules/@oscharko-dev/keiko-server/dist/deps-activity.d.ts +1 -0
  327. package/node_modules/@oscharko-dev/keiko-server/dist/deps-activity.d.ts.map +1 -1
  328. package/node_modules/@oscharko-dev/keiko-server/dist/deps-activity.js +23 -0
  329. package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts +1 -0
  330. package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts.map +1 -1
  331. package/node_modules/@oscharko-dev/keiko-server/dist/deps.js +76 -19
  332. package/node_modules/@oscharko-dev/keiko-server/dist/diagnostics-log.d.ts +1 -1
  333. package/node_modules/@oscharko-dev/keiko-server/dist/diagnostics-log.d.ts.map +1 -1
  334. package/node_modules/@oscharko-dev/keiko-server/dist/diagnostics-log.js +2 -6
  335. package/node_modules/@oscharko-dev/keiko-server/dist/editor/agentRoutes.d.ts +1 -1
  336. package/node_modules/@oscharko-dev/keiko-server/dist/editor/agentRoutes.d.ts.map +1 -1
  337. package/node_modules/@oscharko-dev/keiko-server/dist/editor/agentRoutes.js +13 -5
  338. package/node_modules/@oscharko-dev/keiko-server/dist/editor/dap/debugLaunchPlan.d.ts +1 -1
  339. package/node_modules/@oscharko-dev/keiko-server/dist/editor/dap/debugLaunchPlan.d.ts.map +1 -1
  340. package/node_modules/@oscharko-dev/keiko-server/dist/editor/lsp/lspNodeAdapter.d.ts.map +1 -1
  341. package/node_modules/@oscharko-dev/keiko-server/dist/editor/lsp/lspNodeAdapter.js +1 -2
  342. package/node_modules/@oscharko-dev/keiko-server/dist/editor/verificationExecution.d.ts +1 -1
  343. package/node_modules/@oscharko-dev/keiko-server/dist/editor/verificationExecution.d.ts.map +1 -1
  344. package/node_modules/@oscharko-dev/keiko-server/dist/evidence-retention-log.d.ts +1 -1
  345. package/node_modules/@oscharko-dev/keiko-server/dist/evidence-retention-log.d.ts.map +1 -1
  346. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-spend-budget.d.ts +1 -1
  347. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-spend-budget.d.ts.map +1 -1
  348. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-spend-budget.js +1 -2
  349. package/node_modules/@oscharko-dev/keiko-server/dist/gateway-tool-calling-probe.js +1 -1
  350. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeChatTestSupport.d.ts.map +1 -1
  351. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeChatTestSupport.js +6 -2
  352. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeSnapshotRegistry.d.ts +1 -1
  353. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeSnapshotRegistry.d.ts.map +1 -1
  354. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeSnapshotService.d.ts +1 -1
  355. package/node_modules/@oscharko-dev/keiko-server/dist/gitChangeSnapshotService.d.ts.map +1 -1
  356. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/actionSheetRoutes.d.ts +1 -1
  357. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/actionSheetRoutes.d.ts.map +1 -1
  358. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/approvalEvents.d.ts +1 -1
  359. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/approvalEvents.d.ts.map +1 -1
  360. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitDraftQuality.d.ts +25 -0
  361. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitDraftQuality.d.ts.map +1 -0
  362. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitDraftQuality.js +167 -0
  363. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitRoutes.d.ts +2 -2
  364. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitRoutes.d.ts.map +1 -1
  365. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/commitRoutes.js +252 -79
  366. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryChecks.d.ts +1 -1
  367. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryChecks.d.ts.map +1 -1
  368. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryService.js +1 -1
  369. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryServiceTestSupport.d.ts +2 -1
  370. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryServiceTestSupport.d.ts.map +1 -1
  371. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryServiceTestSupport.js +53 -22
  372. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryTemplate.d.ts +1 -1
  373. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftDeliveryTemplate.d.ts.map +1 -1
  374. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftRelatedIssuesActivity.d.ts +1 -1
  375. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/draftRelatedIssuesActivity.d.ts.map +1 -1
  376. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/execution.d.ts +1 -1
  377. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/execution.d.ts.map +1 -1
  378. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/execution.js +1 -2
  379. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/journeyObservationService.d.ts +1 -1
  380. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/journeyObservationService.d.ts.map +1 -1
  381. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/mergeExecution.d.ts +1 -1
  382. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/mergeExecution.d.ts.map +1 -1
  383. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionGeneration.js +1 -1
  384. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionProjection.js +1 -1
  385. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionReceiptStore.d.ts +1 -1
  386. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionReceiptStore.d.ts.map +1 -1
  387. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionRoutes.d.ts +1 -1
  388. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionRoutes.d.ts.map +1 -1
  389. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionTestSupport.d.ts +1 -1
  390. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionTestSupport.d.ts.map +1 -1
  391. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prDescriptionTestSupport.js +5 -1
  392. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prExecution.d.ts +1 -1
  393. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prExecution.d.ts.map +1 -1
  394. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prMarkReadyExecution.d.ts +1 -1
  395. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/prMarkReadyExecution.d.ts.map +1 -1
  396. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/pushExecution.d.ts +1 -1
  397. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/pushExecution.d.ts.map +1 -1
  398. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/requestPreparation.d.ts.map +1 -1
  399. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/requestPreparation.js +1 -2
  400. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/runtimeGitService.js +1 -1
  401. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/verifiedCommitFacts.d.ts.map +1 -1
  402. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/verifiedCommitFacts.js +1 -0
  403. package/node_modules/@oscharko-dev/keiko-server/dist/gitDelivery/verifiedCommitService.js +1 -1
  404. package/node_modules/@oscharko-dev/keiko-server/dist/grounded-orchestrator.js +1 -1
  405. package/node_modules/@oscharko-dev/keiko-server/dist/harness-context-compactor.d.ts +1 -1
  406. package/node_modules/@oscharko-dev/keiko-server/dist/harness-context-compactor.d.ts.map +1 -1
  407. package/node_modules/@oscharko-dev/keiko-server/dist/index.d.ts +7 -7
  408. package/node_modules/@oscharko-dev/keiko-server/dist/index.d.ts.map +1 -1
  409. package/node_modules/@oscharko-dev/keiko-server/dist/index.js +7 -7
  410. package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-handlers.js +1 -1
  411. package/node_modules/@oscharko-dev/keiko-server/dist/memory-autonomy-policy-handlers.d.ts.map +1 -1
  412. package/node_modules/@oscharko-dev/keiko-server/dist/memory-autonomy-policy-handlers.js +2 -2
  413. package/node_modules/@oscharko-dev/keiko-server/dist/memory-capture-policy.d.ts +4 -3
  414. package/node_modules/@oscharko-dev/keiko-server/dist/memory-capture-policy.d.ts.map +1 -1
  415. package/node_modules/@oscharko-dev/keiko-server/dist/memory-capture-policy.js +10 -2
  416. package/node_modules/@oscharko-dev/keiko-server/dist/observability/index.d.ts +2 -6
  417. package/node_modules/@oscharko-dev/keiko-server/dist/observability/index.d.ts.map +1 -1
  418. package/node_modules/@oscharko-dev/keiko-server/dist/observability/index.js +11 -13
  419. package/node_modules/@oscharko-dev/keiko-server/dist/observability/route-template.d.ts +1 -0
  420. package/node_modules/@oscharko-dev/keiko-server/dist/observability/route-template.d.ts.map +1 -1
  421. package/node_modules/@oscharko-dev/keiko-server/dist/observability/route-template.js +5 -0
  422. package/node_modules/@oscharko-dev/keiko-server/dist/observability/server-log.d.ts +1 -180
  423. package/node_modules/@oscharko-dev/keiko-server/dist/observability/server-log.d.ts.map +1 -1
  424. package/node_modules/@oscharko-dev/keiko-server/dist/observability/server-log.js +3 -2950
  425. package/node_modules/@oscharko-dev/keiko-server/dist/routes.d.ts.map +1 -1
  426. package/node_modules/@oscharko-dev/keiko-server/dist/routes.js +3 -2
  427. package/node_modules/@oscharko-dev/keiko-server/dist/runtime/containerEngineDetector.d.ts +1 -1
  428. package/node_modules/@oscharko-dev/keiko-server/dist/runtime/containerEngineDetector.d.ts.map +1 -1
  429. package/node_modules/@oscharko-dev/keiko-server/dist/runtime/containerRunner.d.ts +1 -1
  430. package/node_modules/@oscharko-dev/keiko-server/dist/runtime/containerRunner.d.ts.map +1 -1
  431. package/node_modules/@oscharko-dev/keiko-server/dist/server.d.ts +1 -1
  432. package/node_modules/@oscharko-dev/keiko-server/dist/server.d.ts.map +1 -1
  433. package/node_modules/@oscharko-dev/keiko-server/dist/server.js +3 -1
  434. package/node_modules/@oscharko-dev/keiko-server/dist/sink.js +1 -1
  435. package/node_modules/@oscharko-dev/keiko-server/dist/store/legacySchemaTestFixture.d.ts.map +1 -1
  436. package/node_modules/@oscharko-dev/keiko-server/dist/store/legacySchemaTestFixture.js +5 -1
  437. package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.d.ts +1 -1
  438. package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.d.ts.map +1 -1
  439. package/node_modules/@oscharko-dev/keiko-server/dist/store/schema.js +7 -1
  440. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/activity-log.d.ts +1 -1
  441. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/activity-log.d.ts.map +1 -1
  442. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/activity-log.js +3 -2
  443. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/binding.js +2 -2
  444. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/cleanup.d.ts.map +1 -1
  445. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/cleanup.js +2 -1
  446. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/health.d.ts.map +1 -1
  447. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/health.js +4 -3
  448. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/lifecycle.d.ts.map +1 -1
  449. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/lifecycle.js +9 -3
  450. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/local-checkout.d.ts +21 -0
  451. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/local-checkout.d.ts.map +1 -0
  452. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/local-checkout.js +392 -0
  453. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/managed-root.d.ts +4 -0
  454. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/managed-root.d.ts.map +1 -1
  455. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/managed-root.js +6 -0
  456. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/provisioning.d.ts.map +1 -1
  457. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/provisioning.js +2 -1
  458. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/reconciliation.d.ts.map +1 -1
  459. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/reconciliation.js +6 -3
  460. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/repair.d.ts.map +1 -1
  461. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/repair.js +2 -0
  462. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/routes.d.ts +1 -0
  463. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/routes.d.ts.map +1 -1
  464. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/routes.js +47 -0
  465. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/store.d.ts.map +1 -1
  466. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/store.js +12 -8
  467. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/types.d.ts +6 -0
  468. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/types.d.ts.map +1 -1
  469. package/node_modules/@oscharko-dev/keiko-server/dist/task-workspace/workspace-root-access.js +1 -1
  470. package/node_modules/@oscharko-dev/keiko-server/dist/terminal.d.ts +1 -1
  471. package/node_modules/@oscharko-dev/keiko-server/dist/terminal.d.ts.map +1 -1
  472. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolFacadeBridge.d.ts.map +1 -1
  473. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolFacadeBridge.js +8 -2
  474. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolLifecycle.d.ts +2 -2
  475. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolLifecycle.d.ts.map +1 -1
  476. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolLifecycle.js +2 -2
  477. package/node_modules/@oscharko-dev/keiko-server/dist/tool-catalog/catalogToolSettlement.js +1 -1
  478. package/node_modules/@oscharko-dev/keiko-server/dist/update-legacy-audit-import.d.ts +1 -1
  479. package/node_modules/@oscharko-dev/keiko-server/dist/update-legacy-audit-import.d.ts.map +1 -1
  480. package/node_modules/@oscharko-dev/keiko-server/dist/update-legacy-audit-import.js +1 -1
  481. package/node_modules/@oscharko-dev/keiko-server/dist/update-runtime-activity.js +1 -1
  482. package/node_modules/@oscharko-dev/keiko-server/dist/workspace-root-denial-log.js +1 -1
  483. package/node_modules/@oscharko-dev/keiko-server/dist/workspace-script-trust.d.ts +1 -1
  484. package/node_modules/@oscharko-dev/keiko-server/dist/workspace-script-trust.d.ts.map +1 -1
  485. package/node_modules/@oscharko-dev/keiko-server/package.json +23 -22
  486. package/node_modules/@oscharko-dev/keiko-tool-catalog/package.json +3 -3
  487. package/node_modules/@oscharko-dev/keiko-tools/dist/git-worktree-snapshot-node.d.ts.map +1 -1
  488. package/node_modules/@oscharko-dev/keiko-tools/dist/git-worktree-snapshot-node.js +8 -1
  489. package/node_modules/@oscharko-dev/keiko-tools/dist/version.d.ts +1 -1
  490. package/node_modules/@oscharko-dev/keiko-tools/dist/version.js +1 -1
  491. package/node_modules/@oscharko-dev/keiko-tools/package.json +7 -7
  492. package/node_modules/@oscharko-dev/keiko-verification/package.json +5 -5
  493. package/node_modules/@oscharko-dev/keiko-workflows/package.json +10 -10
  494. package/node_modules/@oscharko-dev/keiko-workspace/dist/fs.d.ts.map +1 -1
  495. package/node_modules/@oscharko-dev/keiko-workspace/dist/fs.js +4 -1
  496. package/node_modules/@oscharko-dev/keiko-workspace/dist/version.d.ts +1 -1
  497. package/node_modules/@oscharko-dev/keiko-workspace/dist/version.js +1 -1
  498. package/node_modules/@oscharko-dev/keiko-workspace/package.json +3 -3
  499. package/package.json +28 -26
  500. package/release-impact.catalog.json +71 -0
  501. package/scripts/lib/local-state-audit.mjs +3 -2
  502. package/vendor/oscharko-dev-keiko-activity-log-1.1.11.tgz +0 -0
  503. package/vendor/oscharko-dev-keiko-cli-1.1.11.tgz +0 -0
  504. package/vendor/{oscharko-dev-keiko-connectors-1.1.10.tgz → oscharko-dev-keiko-connectors-1.1.11.tgz} +0 -0
  505. package/vendor/oscharko-dev-keiko-contracts-1.1.11.tgz +0 -0
  506. package/vendor/{oscharko-dev-keiko-evaluations-1.1.10.tgz → oscharko-dev-keiko-evaluations-1.1.11.tgz} +0 -0
  507. package/vendor/{oscharko-dev-keiko-evidence-1.1.10.tgz → oscharko-dev-keiko-evidence-1.1.11.tgz} +0 -0
  508. package/vendor/oscharko-dev-keiko-git-1.1.11.tgz +0 -0
  509. package/vendor/{oscharko-dev-keiko-harness-1.1.10.tgz → oscharko-dev-keiko-harness-1.1.11.tgz} +0 -0
  510. package/vendor/oscharko-dev-keiko-local-knowledge-1.1.11.tgz +0 -0
  511. package/vendor/{oscharko-dev-keiko-memory-capture-1.1.10.tgz → oscharko-dev-keiko-memory-capture-1.1.11.tgz} +0 -0
  512. package/vendor/oscharko-dev-keiko-memory-consolidation-1.1.11.tgz +0 -0
  513. package/vendor/{oscharko-dev-keiko-memory-governance-1.1.10.tgz → oscharko-dev-keiko-memory-governance-1.1.11.tgz} +0 -0
  514. package/vendor/oscharko-dev-keiko-memory-retrieval-1.1.11.tgz +0 -0
  515. package/vendor/{oscharko-dev-keiko-memory-vault-1.1.10.tgz → oscharko-dev-keiko-memory-vault-1.1.11.tgz} +0 -0
  516. package/vendor/oscharko-dev-keiko-model-gateway-1.1.11.tgz +0 -0
  517. package/vendor/{oscharko-dev-keiko-quality-intelligence-1.1.10.tgz → oscharko-dev-keiko-quality-intelligence-1.1.11.tgz} +0 -0
  518. package/vendor/oscharko-dev-keiko-sandbox-1.1.11.tgz +0 -0
  519. package/vendor/{oscharko-dev-keiko-sdk-1.1.10.tgz → oscharko-dev-keiko-sdk-1.1.11.tgz} +0 -0
  520. package/vendor/oscharko-dev-keiko-security-1.1.11.tgz +0 -0
  521. package/vendor/oscharko-dev-keiko-server-1.1.11.tgz +0 -0
  522. package/vendor/{oscharko-dev-keiko-tool-catalog-1.1.10.tgz → oscharko-dev-keiko-tool-catalog-1.1.11.tgz} +0 -0
  523. package/vendor/oscharko-dev-keiko-tools-1.1.11.tgz +0 -0
  524. package/vendor/{oscharko-dev-keiko-verification-1.1.10.tgz → oscharko-dev-keiko-verification-1.1.11.tgz} +0 -0
  525. package/vendor/{oscharko-dev-keiko-workflows-1.1.10.tgz → oscharko-dev-keiko-workflows-1.1.11.tgz} +0 -0
  526. package/vendor/oscharko-dev-keiko-workspace-1.1.11.tgz +0 -0
  527. package/dist/ui/static/_next/static/chunks/04c8gos36pwl8.js +0 -1
  528. package/dist/ui/static/_next/static/chunks/0erql9ej2t_r7.js +0 -1
  529. package/dist/ui/static/_next/static/chunks/0w48lw1wvc7ig.js +0 -1
  530. package/dist/ui/static/_next/static/chunks/18qf6y7a99idv.js +0 -1
  531. package/dist/ui/static/_next/static/chunks/1mi566lu15tc0.js +0 -1
  532. package/dist/ui/static/_next/static/chunks/1tq9npejhlwm0.js +0 -1
  533. package/dist/ui/static/_next/static/chunks/2p6x_6c78vqic.js +0 -1
  534. package/dist/ui/static/_next/static/chunks/35q-v--ikwjcq.js +0 -1
  535. package/dist/ui/static/_next/static/chunks/36m_1433yesno.js +0 -1
  536. package/dist/ui/static/_next/static/chunks/3gb3syh5vkuxt.js +0 -1
  537. package/dist/ui/static/_next/static/chunks/3gtstv3k7jsm2.js +0 -1
  538. package/dist/ui/static/_next/static/chunks/3hs8v_qv53sil.js +0 -7
  539. package/dist/ui/static/_next/static/chunks/3u8vvvcl8_psd.js +0 -2
  540. package/node_modules/@oscharko-dev/keiko-cli/dist/activity-log-line-reader.d.ts.map +0 -1
  541. package/node_modules/@oscharko-dev/keiko-cli/dist/activity-log-line-reader.js +0 -114
  542. package/node_modules/@oscharko-dev/keiko-cli/dist/support-analyze-sufficiency.d.ts.map +0 -1
  543. package/node_modules/@oscharko-dev/keiko-cli/dist/support-analyze.d.ts.map +0 -1
  544. package/node_modules/@oscharko-dev/keiko-cli/dist/support-query.d.ts.map +0 -1
  545. package/node_modules/@oscharko-dev/keiko-cli/dist/support-segment-manifest-names.d.ts.map +0 -1
  546. package/node_modules/@oscharko-dev/keiko-cli/dist/support-segment-manifest.d.ts.map +0 -1
  547. package/node_modules/@oscharko-dev/keiko-cli/dist/support-segment-scan.d.ts.map +0 -1
  548. package/node_modules/@oscharko-dev/keiko-cli/dist/support-tool-catalog.d.ts.map +0 -1
  549. package/node_modules/@oscharko-dev/keiko-server/dist/observability/activity-log-loss-summary.d.ts.map +0 -1
  550. package/node_modules/@oscharko-dev/keiko-server/dist/observability/activity-log-persistence.d.ts.map +0 -1
  551. package/node_modules/@oscharko-dev/keiko-server/dist/observability/activity-log-readiness.d.ts.map +0 -1
  552. package/node_modules/@oscharko-dev/keiko-server/dist/observability/activity-log-store.d.ts.map +0 -1
  553. package/node_modules/@oscharko-dev/keiko-server/dist/observability/error-classification.d.ts.map +0 -1
  554. package/node_modules/@oscharko-dev/keiko-server/dist/observability/log-level.d.ts.map +0 -1
  555. package/node_modules/@oscharko-dev/keiko-server/dist/observability/log-redaction.d.ts.map +0 -1
  556. package/node_modules/@oscharko-dev/keiko-server/dist/observability/runtime-state-dir.d.ts.map +0 -1
  557. package/node_modules/@oscharko-dev/keiko-server/dist/observability/server-logger.d.ts.map +0 -1
  558. package/node_modules/@oscharko-dev/keiko-server/dist/observability/stack-frames.d.ts.map +0 -1
  559. package/node_modules/@oscharko-dev/keiko-server/dist/observability/support-incident-store.d.ts.map +0 -1
  560. package/node_modules/@oscharko-dev/keiko-server/dist/observability/support-incident.d.ts.map +0 -1
  561. package/vendor/oscharko-dev-keiko-cli-1.1.10.tgz +0 -0
  562. package/vendor/oscharko-dev-keiko-contracts-1.1.10.tgz +0 -0
  563. package/vendor/oscharko-dev-keiko-git-1.1.10.tgz +0 -0
  564. package/vendor/oscharko-dev-keiko-local-knowledge-1.1.10.tgz +0 -0
  565. package/vendor/oscharko-dev-keiko-memory-consolidation-1.1.10.tgz +0 -0
  566. package/vendor/oscharko-dev-keiko-memory-retrieval-1.1.10.tgz +0 -0
  567. package/vendor/oscharko-dev-keiko-model-gateway-1.1.10.tgz +0 -0
  568. package/vendor/oscharko-dev-keiko-sandbox-1.1.10.tgz +0 -0
  569. package/vendor/oscharko-dev-keiko-security-1.1.10.tgz +0 -0
  570. package/vendor/oscharko-dev-keiko-server-1.1.10.tgz +0 -0
  571. package/vendor/oscharko-dev-keiko-tools-1.1.10.tgz +0 -0
  572. package/vendor/oscharko-dev-keiko-workspace-1.1.10.tgz +0 -0
  573. /package/dist/ui/static/_next/static/{lA0N8Tc8KZpJTM4YAywwM → GX41Kg0XC2e1CF4PEQCfA}/_buildManifest.js +0 -0
  574. /package/dist/ui/static/_next/static/{lA0N8Tc8KZpJTM4YAywwM → GX41Kg0XC2e1CF4PEQCfA}/_clientMiddlewareManifest.js +0 -0
  575. /package/dist/ui/static/_next/static/{lA0N8Tc8KZpJTM4YAywwM → GX41Kg0XC2e1CF4PEQCfA}/_ssgManifest.js +0 -0
  576. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-persistence.d.ts +0 -0
  577. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-persistence.js +0 -0
  578. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-readiness.d.ts +0 -0
  579. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-store.d.ts +0 -0
  580. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/activity-log-store.js +0 -0
  581. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/error-classification.d.ts +0 -0
  582. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/error-classification.js +0 -0
  583. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/log-level.d.ts +0 -0
  584. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/log-level.js +0 -0
  585. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-analyze-sufficiency.d.ts +0 -0
  586. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-analyze-sufficiency.js +0 -0
  587. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-query.d.ts +0 -0
  588. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-query.js +0 -0
  589. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-manifest-names.d.ts +0 -0
  590. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-manifest-names.js +0 -0
  591. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-segment-manifest.d.ts +0 -0
  592. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-tool-catalog.d.ts +0 -0
  593. /package/node_modules/@oscharko-dev/{keiko-cli/dist → keiko-activity-log/dist/reader}/support-tool-catalog.js +0 -0
  594. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/runtime-state-dir.d.ts +0 -0
  595. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/runtime-state-dir.js +0 -0
  596. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/server-logger.d.ts +0 -0
  597. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/stack-frames.d.ts +0 -0
  598. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/support-incident-store.d.ts +0 -0
  599. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/support-incident-store.js +0 -0
  600. /package/node_modules/@oscharko-dev/{keiko-server/dist/observability → keiko-activity-log/dist}/support-incident.d.ts +0 -0
@@ -1,2951 +1,4 @@
1
- // Server activity log — one JSON line per operation into the one logical Activity Log under
2
- // `<stateDir>/logs/`. Written unconditionally, no env-var opt-in: operators facing a stuck run must
3
- // not have to know a magic switch to see what the process is doing. Redaction stays strict —
4
- // endpoints, sizes, HTTP statuses, error kinds and correlation ids only; request bodies, response
5
- // bodies, tokens, api-keys and user text never appear, and that is enforced structurally by
6
- // `log-redaction.ts` rather than by caller discipline.
7
- //
8
- // BOUNDED IMMUTABLE SEGMENTS (#3530, ADR-0173 D14)
9
- //
10
- // The logical log is physically a sequence of small segments (`activity-log-files.ts` in the
11
- // contracts leaf owns the closed name grammar). Every process instance appends only to its own
12
- // active segment, created exclusively, so no process ever appends to or renames another process's
13
- // open file. A segment is sealed — a final `activity-log.segment.sealed` line, fsync, a guarded
14
- // same-directory rename that drops `.active`, and mode 0400 — when the next line would pass the
15
- // configured byte bound, when it is older than the configured time bound, on close, and on a pin
16
- // request. A sealed segment is never written again. Crash recovery seals an orphaned segment as it is
17
- // and reports a partial final line; valid lines are never rewritten. Retention (byte budget and age,
18
- // with a reserved pin quota) runs whenever a segment is opened, which is at startup and immediately
19
- // after every rollover seal, and every outcome is registered, body-free evidence.
20
- // `activity-log-store.ts` owns the arithmetic; this module owns the one writer and its evidence.
21
- //
22
- // WHY THE WRITE IS SYNCHRONOUS (and stays that way)
23
- //
24
- // The failure this log exists to diagnose is a process that stops making progress: a six-minute
25
- // wall inside an embedding batch, a wedged proxy CONNECT, a migration holding a transaction. A
26
- // write-behind queue is exactly wrong for that shape — the lines an operator needs are the last
27
- // ones before the wedge, and those are the ones a queue still holds when the event loop stops
28
- // turning or the process is killed. Synchronous append is the only mode where "the line is in the
29
- // file" and "the operation happened" cannot come apart.
30
- //
31
- // The cost is bounded and pinned by COUNTING, not by timing. The sink holds ONE append-mode
32
- // descriptor open for the life of a segment, so a line costs a single `write(2)` rather than the
33
- // open/write/close triple `appendFileSync` pays per call. `server-log.test.ts` asserts that the
34
- // fixed setup count does not grow over a burst — never one open per line — plus one `writeSync` per
35
- // line and a segment whose size is the SUM of each line's own byte length (lines are no longer
36
- // byte-identical once `seq` is in the envelope: its digit width grows at each power-of-ten boundary
37
- // the burst crosses). A regression to per-write open/close, or to a quadratic format path,
38
- // therefore fails deterministically instead of showing up as latency in production.
39
- //
40
- // Levels are the volume control instead: an event below the configured threshold returns before
41
- // any string or JSON work happens at all (`KEIKO_LOG_LEVEL`, default `info`).
42
- import { randomBytes, randomUUID } from "node:crypto";
43
- import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, realpathSync, writeSync, } from "node:fs";
44
- import { join, resolve as resolvePath } from "node:path";
45
- import { performance } from "node:perf_hooks";
46
- import { SAFE_ARTIFACT_FILE_FAILURE_KINDS, SafeArtifactFileError, archiveSafeArtifactFile, openSafeArtifactFile, safeArtifactContainmentAssurance, safeArtifactPermissionAssurance, } from "@oscharko-dev/keiko-security/fs-hardening";
47
- import { ACTIVITY_LOG_CATALOG_DIGEST, ACTIVITY_LOG_REGISTRY_VERSION, ACTIVITY_LOG_SCHEMA_DIGEST, ActivityLogEventValidationError, activityLogErrorKindOr, activityLogEvent, activityLogSegmentFileName, classifyErrorKind, defineActivityLogOperation, formatActivityLogSegmentId, isActivityLogIdentityDigest, isActivityLogInstanceId, isActivityLogPlatformClass, isActivityLogProcessId, isActivityLogProductVersion, isActivityLogSequence, readableActivityLogFileNames, recordActivityLogLoss, validateRegisteredActivityLogEvent, } from "@oscharko-dev/keiko-contracts/runtime/observability";
48
- import { KEIKO_PRODUCT_VERSION } from "@oscharko-dev/keiko-contracts/runtime/version";
49
- import { correlationIdOrUnknown, isValidCorrelationId } from "../correlation.js";
50
- import { MAX_ACTIVITY_LOG_PIN_DURATION_MS, MAX_ACTIVITY_LOG_PINS, MAX_LOG_LINE_BYTES, activeActivityLogPins, activityLogFreeBytes, activityLogLowDiskThresholdBytes, activityLogOrphanOwner, activityLogPinCovers, activityLogSegmentSeqSpan, applyActivityLogRetention, clampActivityLogSegmentBytes, inspectActivityLogSegmentTail, isActivityLogPinId, isActivityLogPinScope, isActivityLogSegmentEntry, listActivityLogDirectory, planActivityLogPinProtection, processIsAlive, readActivityLogPins, readActivityLogPolicyRecord, removeActivityLogFile, ACTIVITY_LOG_POLICY_SETTINGS, resolveActivityLogStorageConfig, resolveActivityLogStorePolicy, writeActivityLogPinRecord, } from "./activity-log-store.js";
51
- import { contentFreeErrorClass, machineToken, safeProperty } from "./error-classification.js";
52
- import { DEFAULT_SERVER_LOG_LEVEL, resolveServerLogThreshold, serverLogLevelEnabled, } from "./log-level.js";
53
- import { redactLogFields, redactLogLabel } from "./log-redaction.js";
54
- import { observeSupportIncidentTrigger } from "./support-incident.js";
55
- export { ACTIVITY_LOG_PIN_QUOTA_BYTES_ENV, ACTIVITY_LOG_RETENTION_BYTES_ENV, ACTIVITY_LOG_RETENTION_DAYS_ENV, ACTIVITY_LOG_SEGMENT_BYTES_ENV, ACTIVITY_LOG_SEGMENT_SECONDS_ENV, DEFAULT_ACTIVITY_LOG_PIN_QUOTA_BYTES, DEFAULT_ACTIVITY_LOG_RETENTION_BYTES, DEFAULT_ACTIVITY_LOG_RETENTION_DAYS, DEFAULT_ACTIVITY_LOG_SEGMENT_BYTES, DEFAULT_ACTIVITY_LOG_SEGMENT_SECONDS, MAX_ACTIVITY_LOG_PIN_DURATION_MS, MAX_ACTIVITY_LOG_PIN_SEGMENTS, MAX_ACTIVITY_LOG_PIN_WINDOW_MS, MAX_ACTIVITY_LOG_PINS, MAX_LOG_LINE_BYTES, MIN_ACTIVITY_LOG_RETENTION_BYTES, MIN_ACTIVITY_LOG_SEGMENT_BYTES, resolveActivityLogStorageConfig, } from "./activity-log-store.js";
56
- export { DEFAULT_SERVER_LOG_LEVEL, SERVER_LOG_LEVELS, SERVER_LOG_LEVEL_ENV, isServerLogLevel, isServerLogThreshold, parseServerLogThreshold, resolveServerLogThreshold, serverLogLevelEnabled, serverLogLevelRank, } from "./log-level.js";
57
- export { MAX_LOG_ARRAY_LENGTH, MAX_LOG_FIELD_COUNT, MAX_LOG_FIELD_DEPTH, MAX_LOG_STRING_LENGTH, REDACTED_KEY, REDACTED_LENGTH, REDACTED_PATH, REDACTED_PERSONAL, REDACTED_SECRET, REDACTED_SHAPE, DROPPED_DEPTH, DROPPED_LENGTH, closeReasonVocabulary, isDeniedLogFieldName, normalizeLogFieldName, redactLogFields, redactLogLabel, redactLogString, } from "./log-redaction.js";
1
+ // Compatibility surface for the long-standing server subpath. The implementation moved to the
2
+ // Activity Log package; keep this module as re-exports only so there is still one writer/store.
3
+ export { activityLogStorageHealth, appendDurableServerLogBatch, closeFileServerLogSinks, closeReasonVocabulary, createFileServerLogSink, errorKindOf, formatRegisteredServerLogLine, formatServerLogLine, isDeniedLogFieldName, isServerLogLevel, isServerLogThreshold, listActivityLogFiles, normalizeLogFieldName, nullServerLogSink, parseServerLogThreshold, pinActivityLogWindow, redactLogFields, redactLogLabel, redactLogString, releaseActivityLogPin, reportServerLogFailure, resolveActivityLogStorageConfig, resolveServerLogThreshold, serverLogInstanceId, serverLogLevelEnabled, serverLogLevelRank, serverLogLineBytes, serverLogLineWithinCap, serverLogProcessIdentity, ACTIVITY_LOG_PIN_QUOTA_BYTES_ENV, ACTIVITY_LOG_RETENTION_BYTES_ENV, ACTIVITY_LOG_RETENTION_DAYS_ENV, ACTIVITY_LOG_SEGMENT_BYTES_ENV, ACTIVITY_LOG_SEGMENT_SECONDS_ENV, ACTIVITY_LOG_STORAGE_OPERATIONS, DEFAULT_ACTIVITY_LOG_PIN_QUOTA_BYTES, DEFAULT_ACTIVITY_LOG_RETENTION_BYTES, DEFAULT_ACTIVITY_LOG_RETENTION_DAYS, DEFAULT_ACTIVITY_LOG_SEGMENT_BYTES, DEFAULT_ACTIVITY_LOG_SEGMENT_SECONDS, DEFAULT_SERVER_LOG_LEVEL, DROPPED_DEPTH, DROPPED_LENGTH, LOG_FAILURE_NOTICE_WINDOW_MS, MAX_ACTIVITY_LOG_PINS, MAX_ACTIVITY_LOG_PIN_DURATION_MS, MAX_ACTIVITY_LOG_PIN_SEGMENTS, MAX_ACTIVITY_LOG_PIN_WINDOW_MS, MAX_LOG_ARRAY_LENGTH, MAX_LOG_FIELD_COUNT, MAX_LOG_FIELD_DEPTH, MAX_LOG_LINE_BYTES, MAX_LOG_STRING_LENGTH, MIN_ACTIVITY_LOG_RETENTION_BYTES, MIN_ACTIVITY_LOG_SEGMENT_BYTES, REDACTED_KEY, REDACTED_LENGTH, REDACTED_PATH, REDACTED_PERSONAL, REDACTED_SECRET, REDACTED_SHAPE, SERVER_LOG_LEVELS, SERVER_LOG_LEVEL_ENV, SERVER_LOG_SCHEMA_VERSION, ActivityLogWriterOwnershipError, } from "./index.js";
58
4
  export { redactRoutePath } from "./route-template.js";
59
- // Bumped only on a breaking change to the line FORMAT (a reserved field renamed, removed, or
60
- // retyped) — never on an additive change, which is what every wave of this schema so far has been.
61
- export const SERVER_LOG_SCHEMA_VERSION = 2;
62
- // One instance id per process, computed once from a single `randomUUID()` call so every line this
63
- // process ever writes carries the SAME value. A pid alone is not a process-identity key: the OS
64
- // reuses pids across restarts, so two different process lifetimes can share one multi-day file.
65
- // `pid` + `instanceId` together, never `pid` alone, is what an agent joins on.
66
- const INSTANCE_ID = randomUUID().replaceAll("-", "").slice(0, 8);
67
- // Exposed so a future consumer (the CLI's support-bundle manifest) can name the same instance the
68
- // running process is stamping onto its own lines, without recomputing or guessing at the value.
69
- export function serverLogInstanceId() {
70
- return INSTANCE_ID;
71
- }
72
- const ACTIVITY_LOG_RELEASE_CLASSES = new Set(["stable", "prerelease"]);
73
- const PERSISTED_WRITER_CAPABILITIES = new Set(["active", "degraded"]);
74
- const SUPPORTED_PLATFORMS = new Set(["darwin", "linux", "win32"]);
75
- const SUPPORTED_ARCHITECTURES = new Set(["arm64", "x64"]);
76
- function validRegistryIdentity(identity) {
77
- return (identity.schemaVersion === SERVER_LOG_SCHEMA_VERSION &&
78
- identity.registryVersion === ACTIVITY_LOG_REGISTRY_VERSION);
79
- }
80
- function validDigestIdentity(identity) {
81
- return (isActivityLogIdentityDigest(identity.schemaDigest) &&
82
- identity.schemaDigest === ACTIVITY_LOG_SCHEMA_DIGEST &&
83
- isActivityLogIdentityDigest(identity.catalogDigest) &&
84
- identity.catalogDigest === ACTIVITY_LOG_CATALOG_DIGEST);
85
- }
86
- function validBuildIdentity(identity) {
87
- const buildClass = Reflect.get(identity, "buildClass");
88
- const releaseClass = Reflect.get(identity, "releaseClass");
89
- const platformClass = Reflect.get(identity, "platformClass");
90
- return (buildClass === "node-esm" &&
91
- ACTIVITY_LOG_RELEASE_CLASSES.has(releaseClass) &&
92
- isActivityLogPlatformClass(platformClass));
93
- }
94
- function validProductIdentity(identity) {
95
- return (isActivityLogProductVersion(identity.productVersion) &&
96
- identity.productVersion === KEIKO_PRODUCT_VERSION);
97
- }
98
- function validWriterIdentity(identity) {
99
- const compatibilityState = Reflect.get(identity, "compatibilityState");
100
- const writerCapability = Reflect.get(identity, "writerCapability");
101
- return compatibilityState === "supported" && PERSISTED_WRITER_CAPABILITIES.has(writerCapability);
102
- }
103
- function validServerLogIdentity(identity) {
104
- return [
105
- validRegistryIdentity(identity),
106
- validDigestIdentity(identity),
107
- validBuildIdentity(identity),
108
- validProductIdentity(identity),
109
- validWriterIdentity(identity),
110
- isActivityLogProcessId(identity.pid),
111
- isActivityLogInstanceId(identity.instanceId),
112
- isActivityLogSequence(identity.seq),
113
- ].every(Boolean);
114
- }
115
- function validateServerLogIdentity(identity) {
116
- if (!validServerLogIdentity(identity)) {
117
- throw new ActivityLogEventValidationError("invalid-identity");
118
- }
119
- }
120
- const NULL_SINK = {
121
- write(_event) {
122
- // Explicit noop for tests and for environments without a state directory.
123
- },
124
- };
125
- export function nullServerLogSink() {
126
- return NULL_SINK;
127
- }
128
- // Turns an unknown thrown value into a content-free classification: a coded error's `code`, else
129
- // its content-free CLASS, else `unknown`. The MESSAGE is never read — that is the whole point, and
130
- // it is why instrumentation sites should call this instead of `String(error)`. It lives here rather
131
- // than beside the logger because the file sink below classifies its own failures too, and this
132
- // module is the one both sides already depend on.
133
- //
134
- // Delegates to `error-classification.ts`'s `safeProperty`/`machineToken`/`contentFreeErrorClass`
135
- // (ADR-0173 D11) instead of maintaining a second, less-hardened regex-based reader: this used to
136
- // read `code`/`name` off a plain cast with no try/catch, so a hostile `code`/`name` accessor that
137
- // THROWS on read (rather than merely returning prose) crashed classification itself; the shared
138
- // helpers already wrap every reflective read.
139
- //
140
- // `code` is read off ANY object, `Error` or not — this function's contract has always been "read
141
- // the field if it is there", and gating that read on `instanceof Error` would silently drop a
142
- // conforming `code` carried by a plain thrown object (e.g. `{ code: "SQLITE_BUSY" }`), which the
143
- // pre-hardening reader classified correctly.
144
- //
145
- // The `Error`-vs-not split matters only for the FALLBACK once `code` is absent or non-conforming.
146
- // An actual `Error` instance goes through `contentFreeErrorClass`, which trusts `.name` only for a
147
- // specific, curated set of built-ins and otherwise reads the CODE-DECLARED class off the
148
- // prototype — `.name` is a plain mutable own property a hostile thrown value can load with
149
- // request-derived text, and `diagnostics-log.test.ts`'s "degrades an overridden name on a plain
150
- // Error and never serializes it" pins exactly this for every producer that shares this leaf, this
151
- // function included. A non-`Error` object has no declared class to recover, so its own `.name` is
152
- // read through the same shape gate (`classifyErrorKind`) every other package's reducer already
153
- // applies — restoring the pre-hardening reader's fidelity for that shape without reopening the
154
- // `Error`-name hardening above. Either branch still floors on the fixed string `"unknown"` for a
155
- // non-conforming candidate, pinned by `server-logger.test.ts`.
156
- export function errorKindOf(error) {
157
- const safeArtifactKind = safeArtifactErrorKind(error);
158
- if (safeArtifactKind !== undefined)
159
- return safeArtifactKind;
160
- if (typeof error !== "object" || error === null)
161
- return "unknown";
162
- const code = machineToken(safeProperty(error, "code"));
163
- if (code !== undefined)
164
- return code;
165
- if (error instanceof Error)
166
- return contentFreeErrorClass(error);
167
- return classifyErrorKind(safeProperty(error, "name")) ?? "unknown";
168
- }
169
- const SAFE_ARTIFACT_ERROR_KINDS = new Set(SAFE_ARTIFACT_FILE_FAILURE_KINDS);
170
- function safeArtifactErrorKind(error) {
171
- try {
172
- if (!(error instanceof SafeArtifactFileError))
173
- return undefined;
174
- }
175
- catch {
176
- return undefined;
177
- }
178
- const kind = safeProperty(error, "kind");
179
- return typeof kind === "string" && SAFE_ARTIFACT_ERROR_KINDS.has(kind) ? kind : "open-failed";
180
- }
181
- // LAST-RESORT FAILURE NOTICE
182
- //
183
- // Every layer below the caller swallows its own failures on purpose: a log line is evidence about
184
- // an operation and must never become a new failure mode for it. Swallowed SILENTLY, though, a
185
- // permanently broken log looks exactly like a quiet system — which is the precise silence this
186
- // module exists to end, and the reason four releases shipped against a stuck indexing run.
187
- //
188
- // So a failure is reported once, on an INDEPENDENT channel: stderr, never the sink that just
189
- // failed. A full disk cannot be diagnosed by writing to the disk. The notice carries the same
190
- // body-free shape as a log line — a classification, the op, the correlation id — and is throttled,
191
- // because the failures this catches sit inside per-item loops: a broken descriptor must not turn
192
- // one flood into another. Suppressed notices are counted and reported on the next one, so the
193
- // throttle never hides the SCALE of the failure, only its repetition.
194
- const LOG_FAILURE_NOTICE_OP = "server-log.write-failed";
195
- export const LOG_FAILURE_NOTICE_WINDOW_MS = 60_000;
196
- const SERVER_LOG_FAILURE_OPERATION = defineActivityLogOperation({
197
- contractKind: "activity-log-operation",
198
- schemaVersion: 1,
199
- op: "server-log.write-failed",
200
- category: "diagnostic",
201
- owner: "keiko-server",
202
- emitter: "observability/server-log.failureNoticeEvent",
203
- fields: {
204
- failedOp: { type: "string", dataClass: "opaque-id", required: false, maxLength: 160 },
205
- rejectionKind: {
206
- type: "string",
207
- dataClass: "closed-enum",
208
- required: false,
209
- values: [
210
- "unregistered-operation",
211
- "registration-mismatch",
212
- "missing-identity",
213
- "invalid-identity",
214
- "fields-not-object",
215
- "missing-field",
216
- "unknown-field",
217
- "invalid-field-type",
218
- "invalid-field-bound",
219
- "invalid-field-vocabulary",
220
- ],
221
- },
222
- completeness: { type: "string", dataClass: "completeness-state", required: true },
223
- loss: { type: "string", dataClass: "loss-state", required: true },
224
- reason: {
225
- type: "string",
226
- dataClass: "closed-enum",
227
- required: false,
228
- values: ["shutdown-flush"],
229
- },
230
- suppressedNotices: { type: "integer", dataClass: "count", required: false },
231
- },
232
- causal: "correlation",
233
- lifecycle: "loss",
234
- analyzerProjection: "failure-cluster",
235
- failureClasses: ["activity-log-persistence", "activity-log-contract"],
236
- proofIds: ["server-log.write-failed.stderr-line"],
237
- releaseImpact: "patch",
238
- });
239
- const SERVER_LOG_LINE_DROPPED_OPERATION = defineActivityLogOperation({
240
- contractKind: "activity-log-operation",
241
- schemaVersion: 1,
242
- op: "server-log.line-dropped",
243
- category: "diagnostic",
244
- owner: "keiko-server",
245
- emitter: "observability/server-log.oversizedLine",
246
- fields: {
247
- failedOp: { type: "string", dataClass: "opaque-id", required: true, maxLength: 160 },
248
- droppedLineBytes: { type: "integer", dataClass: "count", required: true },
249
- completeness: { type: "string", dataClass: "completeness-state", required: true },
250
- loss: { type: "string", dataClass: "loss-state", required: true },
251
- },
252
- causal: "correlation",
253
- lifecycle: "loss",
254
- analyzerProjection: "failure-cluster",
255
- failureClasses: ["activity-log-contract"],
256
- proofIds: ["server-log.line-dropped.registered-line"],
257
- releaseImpact: "patch",
258
- });
259
- const SERVER_LOG_ARTIFACT_CLASS_FIELD = {
260
- type: "string",
261
- dataClass: "closed-enum",
262
- required: true,
263
- values: ["activity-log"],
264
- };
265
- const SERVER_LOG_TARGET_ASSURANCE_FIELDS = {
266
- permissionAssurance: {
267
- type: "string",
268
- dataClass: "closed-enum",
269
- required: true,
270
- values: ["verified-private", "platform-inherited"],
271
- },
272
- containmentAssurance: {
273
- type: "string",
274
- dataClass: "closed-enum",
275
- required: true,
276
- values: ["private-root-guarded", "platform-inherited"],
277
- },
278
- completeness: { type: "string", dataClass: "completeness-state", required: true },
279
- loss: { type: "string", dataClass: "loss-state", required: true },
280
- };
281
- const SERVER_LOG_TARGET_MUTATED_OPERATION = defineActivityLogOperation({
282
- contractKind: "activity-log-operation",
283
- schemaVersion: 1,
284
- op: "server-log.target-mutated",
285
- category: "diagnostic",
286
- owner: "keiko-server",
287
- emitter: "observability/server-log.mutationEvidence",
288
- fields: {
289
- failedOp: { type: "string", dataClass: "opaque-id", required: true, maxLength: 160 },
290
- artifactClass: SERVER_LOG_ARTIFACT_CLASS_FIELD,
291
- ...SERVER_LOG_TARGET_ASSURANCE_FIELDS,
292
- },
293
- causal: "correlation",
294
- lifecycle: "loss",
295
- analyzerProjection: "failure-cluster",
296
- failureClasses: ["activity-log-persistence"],
297
- proofIds: ["server-log.target-mutated.registered-line"],
298
- releaseImpact: "patch",
299
- });
300
- const failureNotice = { lastAt: null, suppressed: 0 };
301
- // Tests reset this so one suite's notice cannot silence the next suite's assertion; the server
302
- // resets it on shutdown for the same reason. Either caller is clearing `suppressed` — a count that
303
- // otherwise only ever surfaces on the NEXT unthrottled failure — so a suppressed count sitting here
304
- // when the reset runs is flushed to stderr first: without this, a clean shutdown (or a suite that
305
- // never sees another failure) would clear the counter with nothing ever having reported it, and
306
- // `reportServerLogFailure`'s "suppressed notices are counted and reported on the next one" promise
307
- // would be broken for whatever window was still open.
308
- export function resetServerLogFailureNotices() {
309
- if (failureNotice.suppressed > 0) {
310
- emitShutdownFlushNotice(failureNotice.suppressed, Date.now());
311
- }
312
- failureNotice.lastAt = null;
313
- failureNotice.suppressed = 0;
314
- }
315
- function noticeIsThrottled(now) {
316
- const last = failureNotice.lastAt;
317
- if (last === null)
318
- return false;
319
- const elapsed = now - last;
320
- // A backwards system-clock adjustment must not silence the notice for a minute: an elapsed time
321
- // we cannot trust fails toward visibility.
322
- return elapsed >= 0 && elapsed < LOG_FAILURE_NOTICE_WINDOW_MS;
323
- }
324
- export function reportServerLogFailure(error, context = {}) {
325
- const now = Date.now();
326
- if (noticeIsThrottled(now)) {
327
- failureNotice.suppressed += 1;
328
- return;
329
- }
330
- const suppressed = failureNotice.suppressed;
331
- failureNotice.lastAt = now;
332
- failureNotice.suppressed = 0;
333
- emitFailureNotice(error, context, suppressed, now, context.identity ?? allocateServerLogIdentity());
334
- }
335
- // Shared by every stderr notice this module emits: a diagnostic that cannot itself be delivered
336
- // must not fail the operation (or the shutdown) it was describing. When stderr itself is
337
- // unavailable (a closed descriptor, a broken pipe, ...) the notice still reaches an operator
338
- // through an INDEPENDENT channel — `process.emitWarning` dispatches the 'warning' event
339
- // synchronously to any listener, which fires even when stderr is closed; Node's own default
340
- // handler happens to also print to stderr, but that is Node's problem to swallow, not this
341
- // module's. This is genuinely the last channel: if a 'warning' listener itself throws, or every
342
- // stream this process owns is gone, the notice is lost.
343
- function writeStderrNotice(notice) {
344
- try {
345
- process.stderr.write(`${JSON.stringify(notice)}\n`);
346
- }
347
- catch {
348
- emitLogNoticeFailedWarning(notice);
349
- }
350
- }
351
- function emitLogNoticeFailedWarning(notice) {
352
- try {
353
- process.emitWarning("keiko server log notice could not be written to stderr", {
354
- code: "KEIKO_LOG_NOTICE_FAILED",
355
- // Named `noticeOp`, not `op`: this is a description of a notice, not a log event, and the
356
- // op-catalog generator indexes every `op:` property in product code.
357
- detail: JSON.stringify({
358
- noticeOp: notice.op,
359
- failedOp: notice.failedOp,
360
- correlationId: notice.correlationId,
361
- errorKind: notice.errorKind,
362
- rejectionKind: notice.rejectionKind,
363
- writerCapability: notice.writerCapability,
364
- compatibilityState: notice.compatibilityState,
365
- completeness: notice.completeness,
366
- loss: notice.loss,
367
- suppressedNotices: notice.suppressedNotices,
368
- }),
369
- });
370
- }
371
- catch {
372
- // No channel left to report through; nothing further to do.
373
- }
374
- }
375
- function emitFailureNotice(error, context, suppressed, now, identity) {
376
- try {
377
- const validationFailure = activityLogValidationFailure(error);
378
- const event = failureNoticeEvent(error, context, suppressed, validationFailure);
379
- writeStderrNotice(stderrEventRecord(event, identity, now));
380
- }
381
- catch {
382
- writeStderrNotice(emergencyFailureNotice(identity, now));
383
- }
384
- }
385
- function emergencyFailureNotice(identity, now) {
386
- return {
387
- ts: new Date(now).toISOString(),
388
- ...failureNoticeIdentity(identity),
389
- level: "error",
390
- category: "diagnostic",
391
- op: LOG_FAILURE_NOTICE_OP,
392
- correlationId: correlationIdOrUnknown(undefined),
393
- errorKind: "internal",
394
- compatibilityState: "incomplete",
395
- writerCapability: "unavailable",
396
- completeness: "unknown",
397
- loss: "event-dropped",
398
- };
399
- }
400
- function failureNoticeEvent(error, context, suppressed, rejectionKind) {
401
- return activityLogEvent(SERVER_LOG_FAILURE_OPERATION, {
402
- level: "error",
403
- correlationId: correlationIdOrUnknown(context.correlationId),
404
- errorKind: closedFailureNoticeErrorKind(error),
405
- }, {
406
- ...(rejectionKind === undefined && context.op !== undefined
407
- ? { failedOp: redactLogLabel(context.op) }
408
- : {}),
409
- ...(rejectionKind === undefined ? {} : { rejectionKind }),
410
- completeness: "unknown",
411
- loss: context.loss ?? "event-dropped",
412
- ...(suppressed > 0 ? { suppressedNotices: suppressed } : {}),
413
- });
414
- }
415
- function stderrEventRecord(event, identity, now) {
416
- return {
417
- ts: new Date(now).toISOString(),
418
- ...failureNoticeIdentity(identity),
419
- // The emergency line is written beside the log, never through it: the sink that would stamp these
420
- // envelope states is the one that failed, so the notice states them itself.
421
- compatibilityState: "incomplete",
422
- writerCapability: "unavailable",
423
- level: event.level,
424
- category: event.category,
425
- ["op"]: event.op,
426
- correlationId: event.correlationId,
427
- errorKind: event.errorKind,
428
- ...event.extra,
429
- };
430
- }
431
- function activityLogValidationFailure(error) {
432
- return error instanceof ActivityLogEventValidationError ? error.kind : undefined;
433
- }
434
- function closedFailureNoticeErrorKind(error) {
435
- if (error instanceof ActivityLogEventValidationError)
436
- return "validation-failed";
437
- return activityLogErrorKindOr(errorKindOf(error), "internal");
438
- }
439
- function failureNoticeIdentity(identity) {
440
- return {
441
- schemaVersion: identity.schemaVersion,
442
- registryVersion: identity.registryVersion,
443
- schemaDigest: identity.schemaDigest,
444
- catalogDigest: identity.catalogDigest,
445
- buildClass: identity.buildClass,
446
- releaseClass: identity.releaseClass,
447
- platformClass: identity.platformClass,
448
- productVersion: identity.productVersion,
449
- pid: identity.pid,
450
- instanceId: identity.instanceId,
451
- seq: identity.seq,
452
- };
453
- }
454
- // The last-resort flush: whatever `suppressed` count was still sitting unreported when the notice
455
- // state was reset (a clean process shutdown, or a suite boundary) is announced here, ONCE, before
456
- // `resetServerLogFailureNotices` clears it. This has the same body-free shape as a throttled
457
- // failure notice, plus `reason` so a reader can tell "reported because another failure arrived"
458
- // from "reported because the counter was about to be cleared with nothing else coming."
459
- //
460
- // This still cannot promise EXACT accounting across every possible exit: a hard kill (SIGKILL,
461
- // power loss, or any crash the process never gets to handle) skips this flush entirely, same as it
462
- // skips every other cleanup path. The `seq` gap for such a window still marks that a write failed;
463
- // only the count of how many is not recoverable after that kind of exit.
464
- function emitShutdownFlushNotice(suppressed, now) {
465
- const identity = allocateServerLogIdentity();
466
- try {
467
- const event = activityLogEvent(SERVER_LOG_FAILURE_OPERATION, {
468
- level: "error",
469
- correlationId: correlationIdOrUnknown(undefined),
470
- errorKind: "unknown",
471
- }, {
472
- completeness: "unknown",
473
- loss: "event-dropped",
474
- reason: "shutdown-flush",
475
- suppressedNotices: suppressed,
476
- });
477
- writeStderrNotice(stderrEventRecord(event, identity, now));
478
- }
479
- catch {
480
- writeStderrNotice(emergencyFailureNotice(identity, now));
481
- }
482
- }
483
- function eventLevel(event) {
484
- return event.level ?? DEFAULT_SERVER_LOG_LEVEL;
485
- }
486
- function finiteOrUndefined(value) {
487
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
488
- }
489
- function applyEnvelopeFields(record, event) {
490
- if (event.correlationId !== undefined)
491
- record.correlationId = redactLogLabel(event.correlationId);
492
- // Shape-guarded, not merely redacted: a `parentCorrelationId` that does not fit
493
- // `isValidCorrelationId`'s shape is dropped outright rather than written under a marker — an
494
- // unshaped value here is evidence of a producer bug, never content worth preserving a trace of.
495
- if (event.parentCorrelationId !== undefined && isValidCorrelationId(event.parentCorrelationId)) {
496
- record.parentCorrelationId = redactLogLabel(event.parentCorrelationId);
497
- }
498
- const durationMs = finiteOrUndefined(event.durationMs);
499
- if (durationMs !== undefined)
500
- record.durationMs = durationMs;
501
- const status = finiteOrUndefined(event.status);
502
- if (status !== undefined)
503
- record.status = status;
504
- if (event.errorKind !== undefined)
505
- record.errorKind = redactLogLabel(event.errorKind);
506
- }
507
- // `ts`, `schemaVersion`, `pid`, `instanceId`, `seq`, `level`, `category` and `op` are written first
508
- // and are reserved inside `redactLogFields`, so `extra` cannot spoof the identity of a line. The
509
- // remaining envelope fields are applied AFTER `extra` so an explicit `durationMs`/`status`/
510
- // `errorKind` on the event wins, while an instrumentation site that carries the same name in its
511
- // field list still gets it logged.
512
- //
513
- // `identity` is optional so the in-memory buffered sink (tests only) can format a line without a
514
- // process/sequence context; the file sink below always supplies one, so every line that actually
515
- // reaches disk carries the full v2 envelope.
516
- export function formatServerLogLine(event, now = new Date(), identity) {
517
- const record = { ts: now.toISOString() };
518
- if (identity !== undefined) {
519
- record.schemaVersion = identity.schemaVersion;
520
- record.registryVersion = identity.registryVersion;
521
- record.schemaDigest = identity.schemaDigest;
522
- record.catalogDigest = identity.catalogDigest;
523
- record.buildClass = identity.buildClass;
524
- record.releaseClass = identity.releaseClass;
525
- record.platformClass = identity.platformClass;
526
- record.productVersion = identity.productVersion;
527
- record.compatibilityState = identity.compatibilityState;
528
- record.writerCapability = identity.writerCapability;
529
- record.pid = identity.pid;
530
- record.instanceId = identity.instanceId;
531
- record.seq = identity.seq;
532
- }
533
- record.level = eventLevel(event);
534
- record.category = event.category;
535
- record.op = redactLogLabel(event.op);
536
- const extra = redactLogFields(event.extra);
537
- if (extra !== undefined)
538
- Object.assign(record, extra);
539
- applyEnvelopeFields(record, event);
540
- const line = `${JSON.stringify(record)}\n`;
541
- // One byte measurement on the happy path; the second only on the line that is being replaced.
542
- return serverLogLineWithinCap(line) ? line : oversizedLine(record, serverLogLineBytes(line));
543
- }
544
- export function formatRegisteredServerLogLine(event, now = new Date(), identity) {
545
- if (identity === undefined) {
546
- throw new ActivityLogEventValidationError("missing-identity");
547
- }
548
- validateServerLogIdentity(identity);
549
- validateRegisteredActivityLogEvent(event);
550
- return formatServerLogLine(event, now, identity);
551
- }
552
- function formatEventLine(event, now, identity) {
553
- // Every production persistence path supplies an identity and therefore requires a typed
554
- // registration. The identity-less branch exists only for the in-memory test sink's redacted
555
- // line projection; it cannot write a production file.
556
- return identity === undefined
557
- ? formatServerLogLine(event, now)
558
- : formatRegisteredServerLogLine(event, now, identity);
559
- }
560
- // The cap is a cap on BYTES, because the write below encodes UTF-8 and a log shipper's line limit
561
- // counts bytes. `line.length` counts UTF-16 code units, so comparing it against the cap admitted a
562
- // line up to three times the stated size — and multi-byte text is exactly what makes a line
563
- // oversized in the first place, since a document body is the only thing that gets there.
564
- //
565
- // The value guards in `log-redaction.ts` currently refuse a non-ASCII field value outright, so in
566
- // today's wiring the two counts agree. That is a second layer, not a reason to measure the wrong
567
- // thing here: this module's cap must hold on its own for whatever a future producer, or a relaxed
568
- // value guard, puts on a line.
569
- export function serverLogLineBytes(line) {
570
- return Buffer.byteLength(line, "utf8");
571
- }
572
- export function serverLogLineWithinCap(line) {
573
- return serverLogLineBytes(line) <= MAX_LOG_LINE_BYTES;
574
- }
575
- function oversizedLine(record, lineBytes) {
576
- // The identity fields ride along when present: an agent joining lines by (pid, instanceId, seq)
577
- // must not see a gap in that join key just because the ORIGINAL event happened to be oversized.
578
- const replacement = { ts: record.ts };
579
- for (const field of SERVER_LOG_IDENTITY_FIELDS) {
580
- if (record[field] !== undefined)
581
- replacement[field] = record[field];
582
- }
583
- const event = activityLogEvent(SERVER_LOG_LINE_DROPPED_OPERATION, {
584
- level: "error",
585
- correlationId: typeof record.correlationId === "string"
586
- ? correlationIdOrUnknown(record.correlationId)
587
- : correlationIdOrUnknown(undefined),
588
- errorKind: "write-failed",
589
- }, {
590
- failedOp: typeof record.op === "string" ? redactLogLabel(record.op) : "unknown",
591
- droppedLineBytes: lineBytes,
592
- completeness: "unknown",
593
- loss: "event-dropped",
594
- });
595
- replacement.level = event.level;
596
- replacement.category = event.category;
597
- replacement.op = event.op;
598
- Object.assign(replacement, event.extra);
599
- applyEnvelopeFields(replacement, event);
600
- return `${JSON.stringify(replacement)}\n`;
601
- }
602
- const SERVER_LOG_IDENTITY_FIELDS = [
603
- "schemaVersion",
604
- "registryVersion",
605
- "schemaDigest",
606
- "catalogDigest",
607
- "buildClass",
608
- "releaseClass",
609
- "platformClass",
610
- "productVersion",
611
- "compatibilityState",
612
- "writerCapability",
613
- "pid",
614
- "instanceId",
615
- "seq",
616
- ];
617
- // PROCESS-WIDE `seq` ALLOCATOR — one counter, one module, for the life of the process.
618
- //
619
- // It must NOT live on `ActiveLog`. Two independent state directories in the same process (a CLI
620
- // pointed at a workspace-local state dir, and the server logger's own default) each resolve to a
621
- // DIFFERENT `ActiveLog`; a counter kept per `ActiveLog` restarts at 1 for each one, so two lines
622
- // written moments apart — one to each directory — can carry the identical `(pid, instanceId, seq)`
623
- // tuple. That tuple is the join key ADR-0173 (D2) promises an agent a total monotonic order on, and
624
- // a duplicate breaks the promise regardless of how many log directories the process happens to
625
- // have open. One allocator shared by every `ActiveLog` and every sink built on top of any of them
626
- // is what keeps the tuple unique process-wide while gaps expose failed persistence attempts.
627
- //
628
- // Each non-filtered facade call claims one identity before boundary handling or opening. Its first
629
- // persisted record uses that identity; further records claim in physical-write order. Claims are
630
- // never rolled back after failure. A gap is therefore not a counter bug: it marks a facade call or
631
- // subsequent evidence record that could not persist its next line. Monotonic per process; never
632
- // reused.
633
- let nextProcessSeq = 1;
634
- function resolvePlatformClass() {
635
- const platform = SUPPORTED_PLATFORMS.has(process.platform) ? process.platform : "other";
636
- const architecture = SUPPORTED_ARCHITECTURES.has(process.arch) ? process.arch : "other";
637
- return `${platform}-${architecture}`;
638
- }
639
- const PLATFORM_CLASS = resolvePlatformClass();
640
- function allocateServerLogSeq() {
641
- const seq = nextProcessSeq;
642
- nextProcessSeq += 1;
643
- return seq;
644
- }
645
- /**
646
- * The identity every line of this process carries, without the per-line `seq`. Exported so a test
647
- * fixture derives the release and platform classes from here instead of restating their rules.
648
- */
649
- export function serverLogProcessIdentity(writerCapability = "active") {
650
- return {
651
- schemaVersion: SERVER_LOG_SCHEMA_VERSION,
652
- registryVersion: ACTIVITY_LOG_REGISTRY_VERSION,
653
- schemaDigest: ACTIVITY_LOG_SCHEMA_DIGEST,
654
- catalogDigest: ACTIVITY_LOG_CATALOG_DIGEST,
655
- buildClass: "node-esm",
656
- releaseClass: KEIKO_PRODUCT_VERSION.includes("-") ? "prerelease" : "stable",
657
- platformClass: PLATFORM_CLASS,
658
- productVersion: KEIKO_PRODUCT_VERSION,
659
- compatibilityState: "supported",
660
- writerCapability,
661
- pid: process.pid,
662
- instanceId: INSTANCE_ID,
663
- };
664
- }
665
- function allocateServerLogIdentity(writerCapability = "active") {
666
- return { ...serverLogProcessIdentity(writerCapability), seq: allocateServerLogSeq() };
667
- }
668
- // ─── Physical write primitives ─────────────────────────────────────────────────────────────────
669
- class PostWriteMutationError extends SafeArtifactFileError {
670
- constructor() {
671
- super("activity-log", "target-mutated");
672
- }
673
- }
674
- // A descriptor that stopped accepting bytes (a zero-byte write or EAGAIN): write backpressure.
675
- class ActivityLogBackpressureError extends SafeArtifactFileError {
676
- constructor() {
677
- super("activity-log", "write-failed");
678
- }
679
- }
680
- // The filesystem refused the bytes (ENOSPC, EDQUOT, EFBIG): the disk or quota is full.
681
- class ActivityLogDiskFullError extends SafeArtifactFileError {
682
- constructor() {
683
- super("activity-log", "write-failed");
684
- }
685
- }
686
- // Retention could not make room for a new segment inside the byte budget: the event is dropped
687
- // rather than let the Activity Log exceed its bound.
688
- class ActivityLogBudgetError extends Error {
689
- name = "ActivityLogBudgetError";
690
- code = "unavailable";
691
- constructor() {
692
- super("activity log byte budget exhausted");
693
- }
694
- }
695
- const DISK_FULL_CODES = new Set(["ENOSPC", "EDQUOT", "EFBIG"]);
696
- function writeChunk(handle, payload, offset) {
697
- try {
698
- return writeSync(handle, payload, offset, payload.length - offset);
699
- }
700
- catch (error) {
701
- const code = machineToken(safeProperty(error, "code"));
702
- if (code !== undefined && DISK_FULL_CODES.has(code))
703
- throw new ActivityLogDiskFullError();
704
- if (code === "EAGAIN")
705
- throw new ActivityLogBackpressureError();
706
- throw error;
707
- }
708
- }
709
- // `writeSync` may report a short write, so loop until the whole line has landed. A descriptor that
710
- // reports ZERO bytes has stopped accepting them: looping would spin, and simply returning would
711
- // leave a partial JSON record behind whose bytes then merge with the NEXT record — one stalled line
712
- // silently costing two. So the stall throws and the line is dropped. A dropped line is the honest
713
- // outcome; a truncated one is not, because it damages a record that was never in trouble.
714
- function writeAll(handle, payload) {
715
- let offset = 0;
716
- while (offset < payload.length) {
717
- const written = writeChunk(handle, payload, offset);
718
- if (written <= 0)
719
- throw new ActivityLogBackpressureError();
720
- offset += written;
721
- }
722
- }
723
- // The bytes a stalled write already handed to the kernel cannot be recalled, so the damage is
724
- // bounded from the other side: the store remembers that its active segment ends mid-record and the
725
- // next record opens with a newline. That is deterministic — unlike writing a terminator, which asks a
726
- // descriptor that is refusing bytes to accept one more.
727
- function writeRecord(active, handle, line) {
728
- const payload = Buffer.from(active.pendingNewline ? `\n${line}` : line, "utf8");
729
- // Cleared only once the whole record has landed; a throw from `writeAll` leaves it set.
730
- active.pendingNewline = true;
731
- writeAll(handle, payload);
732
- active.pendingNewline = false;
733
- }
734
- // ─── Registered storage evidence ───────────────────────────────────────────────────────────────
735
- const SERVER_LOG_SAFE_OPEN_OPERATION = defineActivityLogOperation({
736
- contractKind: "activity-log-operation",
737
- schemaVersion: 1,
738
- op: "server-log.safe-open",
739
- category: "diagnostic",
740
- owner: "keiko-server",
741
- emitter: "observability/server-log.safeOpenEvidence",
742
- fields: {
743
- artifactClass: SERVER_LOG_ARTIFACT_CLASS_FIELD,
744
- persistenceStatus: {
745
- type: "string",
746
- dataClass: "closed-enum",
747
- required: true,
748
- values: ["opened"],
749
- },
750
- ...SERVER_LOG_TARGET_ASSURANCE_FIELDS,
751
- },
752
- causal: "correlation",
753
- lifecycle: "state",
754
- analyzerProjection: "capability",
755
- failureClasses: ["activity-log-persistence"],
756
- proofIds: ["server-log.safe-open.emitted-line"],
757
- releaseImpact: "patch",
758
- });
759
- const ACTIVITY_LOG_SEGMENT_SEALED_OPERATION = defineActivityLogOperation({
760
- contractKind: "activity-log-operation",
761
- schemaVersion: 1,
762
- op: "activity-log.segment.sealed",
763
- category: "diagnostic",
764
- owner: "keiko-server",
765
- emitter: "observability/server-log.segmentSealedEvidence",
766
- fields: {
767
- sealReason: {
768
- type: "string",
769
- dataClass: "closed-enum",
770
- required: true,
771
- values: ["size-limit", "age-limit", "clock-change", "close", "pin-request"],
772
- },
773
- segmentIndex: { type: "integer", dataClass: "count", required: true },
774
- segmentFirstSeq: { type: "integer", dataClass: "count", required: true },
775
- segmentLastSeq: { type: "integer", dataClass: "count", required: true },
776
- segmentLineCount: { type: "integer", dataClass: "count", required: true },
777
- segmentBytes: { type: "integer", dataClass: "count", required: true },
778
- segmentDurationMs: { type: "integer", dataClass: "duration", required: true },
779
- droppedEventCount: { type: "integer", dataClass: "count", required: true },
780
- segmentByteLimit: { type: "integer", dataClass: "count", required: true },
781
- segmentSecondsLimit: { type: "integer", dataClass: "count", required: true },
782
- },
783
- causal: "correlation",
784
- lifecycle: "end",
785
- analyzerProjection: "capability",
786
- failureClasses: ["activity-log-segment"],
787
- proofIds: ["activity-log.segment.sealed.emitted-line"],
788
- releaseImpact: "patch",
789
- });
790
- const ACTIVITY_LOG_SEGMENT_RECOVERED_OPERATION = defineActivityLogOperation({
791
- contractKind: "activity-log-operation",
792
- schemaVersion: 1,
793
- op: "activity-log.segment.recovered",
794
- category: "diagnostic",
795
- owner: "keiko-server",
796
- emitter: "observability/server-log.segmentRecoveredEvidence",
797
- fields: {
798
- recoveryStatus: {
799
- type: "string",
800
- dataClass: "closed-enum",
801
- required: true,
802
- values: ["sealed", "failed"],
803
- },
804
- recoveryKind: {
805
- type: "string",
806
- dataClass: "closed-enum",
807
- required: true,
808
- values: ["unsealed", "interrupted-seal"],
809
- },
810
- ownerState: {
811
- type: "string",
812
- dataClass: "closed-enum",
813
- required: true,
814
- values: ["exited", "stale", "same-process"],
815
- },
816
- tailState: {
817
- type: "string",
818
- dataClass: "closed-enum",
819
- required: true,
820
- values: ["terminated", "truncated", "unknown"],
821
- },
822
- truncatedBytes: { type: "integer", dataClass: "count", required: true },
823
- segmentBytes: { type: "integer", dataClass: "count", required: true },
824
- segmentIndex: { type: "integer", dataClass: "count", required: true },
825
- recoveredInstanceId: {
826
- type: "string",
827
- dataClass: "opaque-id",
828
- required: true,
829
- maxLength: 8,
830
- },
831
- },
832
- causal: "correlation",
833
- lifecycle: "loss",
834
- analyzerProjection: "failure-cluster",
835
- failureClasses: ["activity-log-segment"],
836
- proofIds: ["activity-log.segment.recovered.emitted-line"],
837
- releaseImpact: "patch",
838
- });
839
- const ACTIVITY_LOG_RETENTION_PRUNED_OPERATION = defineActivityLogOperation({
840
- contractKind: "activity-log-operation",
841
- schemaVersion: 1,
842
- op: "activity-log.retention.pruned",
843
- category: "diagnostic",
844
- owner: "keiko-server",
845
- emitter: "observability/server-log.retentionPrunedEvidence",
846
- fields: {
847
- retentionStatus: {
848
- type: "string",
849
- dataClass: "closed-enum",
850
- required: true,
851
- values: ["pruned", "partial", "failed"],
852
- },
853
- prunedSegmentCount: { type: "integer", dataClass: "count", required: true },
854
- prunedLegacyFileCount: { type: "integer", dataClass: "count", required: true },
855
- prunedBytes: { type: "integer", dataClass: "count", required: true },
856
- prunedByAgeCount: { type: "integer", dataClass: "count", required: true },
857
- prunedByBudgetCount: { type: "integer", dataClass: "count", required: true },
858
- failedDeletionCount: { type: "integer", dataClass: "count", required: true },
859
- retainedFileCount: { type: "integer", dataClass: "count", required: true },
860
- retainedBytes: { type: "integer", dataClass: "count", required: true },
861
- protectedPinnedBytes: { type: "integer", dataClass: "count", required: true },
862
- retentionBudgetBytes: { type: "integer", dataClass: "count", required: true },
863
- retentionDays: { type: "integer", dataClass: "count", required: true },
864
- },
865
- causal: "correlation",
866
- lifecycle: "state",
867
- analyzerProjection: "capability",
868
- failureClasses: ["activity-log-retention"],
869
- proofIds: ["activity-log.retention.pruned.emitted-line"],
870
- releaseImpact: "patch",
871
- });
872
- const ACTIVITY_LOG_PRESSURE_OPERATION = defineActivityLogOperation({
873
- contractKind: "activity-log-operation",
874
- schemaVersion: 1,
875
- op: "activity-log.pressure",
876
- category: "diagnostic",
877
- owner: "keiko-server",
878
- emitter: "observability/server-log.pressureEvidence",
879
- fields: {
880
- pressureState: {
881
- type: "string",
882
- dataClass: "closed-enum",
883
- required: true,
884
- values: [
885
- "low-disk-space",
886
- "disk-full",
887
- "backpressure",
888
- "budget-exceeded",
889
- "retention-blocked",
890
- "cleared",
891
- ],
892
- },
893
- previousState: {
894
- type: "string",
895
- dataClass: "closed-enum",
896
- required: false,
897
- values: ["low-disk-space", "retention-blocked"],
898
- },
899
- droppedEventCount: { type: "integer", dataClass: "count", required: true },
900
- usedBytes: { type: "integer", dataClass: "count", required: false },
901
- budgetBytes: { type: "integer", dataClass: "count", required: true },
902
- pinQuotaBytes: { type: "integer", dataClass: "count", required: true },
903
- freeBytes: { type: "integer", dataClass: "count", required: false },
904
- },
905
- causal: "correlation",
906
- lifecycle: "state",
907
- analyzerProjection: "capability",
908
- failureClasses: ["activity-log-pressure"],
909
- proofIds: ["activity-log.pressure.emitted-line"],
910
- releaseImpact: "patch",
911
- });
912
- const ACTIVITY_LOG_PIN_CREATED_OPERATION = defineActivityLogOperation({
913
- contractKind: "activity-log-operation",
914
- schemaVersion: 1,
915
- op: "activity-log.pin.created",
916
- category: "diagnostic",
917
- owner: "keiko-server",
918
- emitter: "observability/server-log.pinCreatedEvidence",
919
- fields: {
920
- pinId: { type: "string", dataClass: "opaque-id", required: false, maxLength: 24 },
921
- pinStatus: {
922
- type: "string",
923
- dataClass: "closed-enum",
924
- required: true,
925
- values: ["created", "rejected"],
926
- },
927
- rejectionReason: {
928
- type: "string",
929
- dataClass: "closed-enum",
930
- required: false,
931
- values: ["invalid-request", "pin-limit-reached", "storage-unavailable"],
932
- },
933
- pinKind: {
934
- type: "string",
935
- dataClass: "closed-enum",
936
- required: true,
937
- values: ["window", "segments"],
938
- },
939
- pinReason: {
940
- type: "string",
941
- dataClass: "closed-enum",
942
- required: true,
943
- values: ["incident", "durable-batch"],
944
- },
945
- pinnedSegmentCount: { type: "integer", dataClass: "count", required: true },
946
- pinnedBytes: { type: "integer", dataClass: "count", required: true },
947
- windowSeconds: { type: "integer", dataClass: "count", required: false },
948
- expiresInSeconds: { type: "integer", dataClass: "count", required: true },
949
- quotaStatus: {
950
- type: "string",
951
- dataClass: "closed-enum",
952
- required: false,
953
- values: ["within-quota", "exceeded"],
954
- },
955
- },
956
- causal: "correlation",
957
- lifecycle: "start",
958
- analyzerProjection: "capability",
959
- failureClasses: ["activity-log-pin"],
960
- proofIds: ["activity-log.pin.created.emitted-line"],
961
- releaseImpact: "patch",
962
- });
963
- const ACTIVITY_LOG_PIN_EXPIRED_OPERATION = defineActivityLogOperation({
964
- contractKind: "activity-log-operation",
965
- schemaVersion: 1,
966
- op: "activity-log.pin.expired",
967
- category: "diagnostic",
968
- owner: "keiko-server",
969
- emitter: "observability/server-log.pinExpiredEvidence",
970
- fields: {
971
- pinId: { type: "string", dataClass: "opaque-id", required: true, maxLength: 24 },
972
- expiryReason: {
973
- type: "string",
974
- dataClass: "closed-enum",
975
- required: true,
976
- values: ["expired", "invalid-record", "released"],
977
- },
978
- removalStatus: {
979
- type: "string",
980
- dataClass: "closed-enum",
981
- required: true,
982
- values: ["removed", "failed"],
983
- },
984
- releasedSegmentCount: { type: "integer", dataClass: "count", required: true },
985
- releasedBytes: { type: "integer", dataClass: "count", required: true },
986
- },
987
- causal: "correlation",
988
- lifecycle: "end",
989
- analyzerProjection: "capability",
990
- failureClasses: ["activity-log-pin"],
991
- proofIds: ["activity-log.pin.expired.emitted-line"],
992
- releaseImpact: "patch",
993
- });
994
- const ACTIVITY_LOG_PIN_QUOTA_EXHAUSTED_OPERATION = defineActivityLogOperation({
995
- contractKind: "activity-log-operation",
996
- schemaVersion: 1,
997
- op: "activity-log.pin.quota-exhausted",
998
- category: "diagnostic",
999
- owner: "keiko-server",
1000
- emitter: "observability/server-log.pinQuotaExhaustedEvidence",
1001
- fields: {
1002
- pinQuotaBytes: { type: "integer", dataClass: "count", required: true },
1003
- requestedPinnedBytes: { type: "integer", dataClass: "count", required: true },
1004
- protectedPinnedBytes: { type: "integer", dataClass: "count", required: true },
1005
- protectedSegmentCount: { type: "integer", dataClass: "count", required: true },
1006
- unprotectedSegmentCount: { type: "integer", dataClass: "count", required: true },
1007
- unprotectedBytes: { type: "integer", dataClass: "count", required: true },
1008
- unprotectedSeqSpan: { type: "integer", dataClass: "count", required: true },
1009
- unknownSpanSegmentCount: { type: "integer", dataClass: "count", required: true },
1010
- activePinCount: { type: "integer", dataClass: "count", required: true },
1011
- },
1012
- causal: "correlation",
1013
- lifecycle: "loss",
1014
- analyzerProjection: "failure-cluster",
1015
- failureClasses: ["activity-log-pin"],
1016
- proofIds: ["activity-log.pin.quota-exhausted.emitted-line"],
1017
- releaseImpact: "patch",
1018
- });
1019
- // A cooperating process's own env disagreed with the store's governing policy (#3554): it either
1020
- // adopted the stored bounds, or — the sole live writer, e.g. a clean restart with a changed env —
1021
- // replaced them. Never fired when nothing disagreed.
1022
- const ACTIVITY_LOG_POLICY_CONFLICT_OPERATION = defineActivityLogOperation({
1023
- contractKind: "activity-log-operation",
1024
- schemaVersion: 1,
1025
- op: "activity-log.policy.conflict",
1026
- category: "diagnostic",
1027
- owner: "keiko-server",
1028
- emitter: "observability/server-log.policyConflictEvidence",
1029
- fields: {
1030
- policyResolution: {
1031
- type: "string",
1032
- dataClass: "closed-enum",
1033
- required: true,
1034
- values: ["adopted", "replaced"],
1035
- },
1036
- conflictingSettings: {
1037
- type: "string-array",
1038
- dataClass: "closed-enum",
1039
- required: true,
1040
- values: ["retentionBytes", "retentionDays", "pinQuotaBytes"],
1041
- maxItems: 3,
1042
- },
1043
- storedRetentionBytes: { type: "integer", dataClass: "count", required: true },
1044
- requestedRetentionBytes: { type: "integer", dataClass: "count", required: true },
1045
- storedRetentionDays: { type: "integer", dataClass: "count", required: true },
1046
- requestedRetentionDays: { type: "integer", dataClass: "count", required: true },
1047
- storedPinQuotaBytes: { type: "integer", dataClass: "count", required: true },
1048
- requestedPinQuotaBytes: { type: "integer", dataClass: "count", required: true },
1049
- },
1050
- causal: "correlation",
1051
- lifecycle: "state",
1052
- analyzerProjection: "capability",
1053
- failureClasses: ["activity-log-policy"],
1054
- proofIds: ["activity-log.policy.conflict.emitted-line"],
1055
- releaseImpact: "patch",
1056
- });
1057
- /**
1058
- * The operations the Activity Log store writes about itself (opening, sealing, recovering, pruning,
1059
- * pressure, pins, policy), derived from their registrations. A reader that wants only the
1060
- * producers' evidence filters these out instead of restating the list.
1061
- */
1062
- export const ACTIVITY_LOG_STORAGE_OPERATIONS = new Set([
1063
- SERVER_LOG_SAFE_OPEN_OPERATION.op,
1064
- ACTIVITY_LOG_SEGMENT_SEALED_OPERATION.op,
1065
- ACTIVITY_LOG_SEGMENT_RECOVERED_OPERATION.op,
1066
- ACTIVITY_LOG_RETENTION_PRUNED_OPERATION.op,
1067
- ACTIVITY_LOG_PRESSURE_OPERATION.op,
1068
- ACTIVITY_LOG_PIN_CREATED_OPERATION.op,
1069
- ACTIVITY_LOG_PIN_EXPIRED_OPERATION.op,
1070
- ACTIVITY_LOG_PIN_QUOTA_EXHAUSTED_OPERATION.op,
1071
- ACTIVITY_LOG_POLICY_CONFLICT_OPERATION.op,
1072
- ]);
1073
- const SEAL_RESERVE_BYTES = MAX_LOG_LINE_BYTES + 1;
1074
- // `seq` can gain digits between measuring a line and writing it; never more than this many.
1075
- const SEQ_GROWTH_MARGIN_BYTES = 16;
1076
- const MAX_ROLLOVERS_PER_WRITE = 8;
1077
- const MAX_QUEUED_EVIDENCE = 256;
1078
- const CLOCK_TOLERANCE_MS = 5_000;
1079
- const ADMISSION_RETRY_MS = 1_000;
1080
- const SEALED_SEGMENT_MODE = 0o400;
1081
- const activeLogs = new Map();
1082
- function activeLogKey(directory) {
1083
- try {
1084
- return realpathSync(directory);
1085
- }
1086
- catch {
1087
- return resolvePath(directory);
1088
- }
1089
- }
1090
- // Merges the store's governing policy outcome into a per-process, env-resolved config: segment
1091
- // size/age stay per-writer, but retention bytes/days and the pin quota are always the GOVERNED
1092
- // values, re-clamping segmentBytes against them with the exact invariant
1093
- // `resolveActivityLogStorageConfig` itself applies (never restated — #3554).
1094
- function applyGovernedPolicy(envConfig, governed) {
1095
- return {
1096
- ...envConfig,
1097
- retentionBytes: governed.retentionBytes,
1098
- retentionDays: governed.retentionDays,
1099
- pinQuotaBytes: governed.pinQuotaBytes,
1100
- segmentBytes: clampActivityLogSegmentBytes(envConfig.segmentBytes, governed.retentionBytes),
1101
- };
1102
- }
1103
- function resolveActiveLog(directory, config) {
1104
- const key = activeLogKey(directory);
1105
- const existing = activeLogs.get(key);
1106
- if (existing !== undefined)
1107
- return existing;
1108
- const created = {
1109
- directory,
1110
- trustedRoot: directory,
1111
- config,
1112
- envConfig: config,
1113
- policyResolved: false,
1114
- governed: undefined,
1115
- segment: undefined,
1116
- nextIndex: 1,
1117
- lastStartMs: 0,
1118
- pendingNewline: false,
1119
- pendingEvidence: [],
1120
- blocked: new Map(),
1121
- admissionRetryAtMs: 0,
1122
- standingPressure: undefined,
1123
- quotaExhaustedReported: false,
1124
- recoveredSegments: 0,
1125
- failedDeletions: new Map(),
1126
- failedPinRemovals: new Map(),
1127
- failedRecoveries: new Map(),
1128
- sealTimer: undefined,
1129
- };
1130
- activeLogs.set(key, created);
1131
- return created;
1132
- }
1133
- // Merges the store's ONE governing policy (#3554) into this directory's config, evidencing a
1134
- // disagreement, the first time real storage work is imminent for it in this process — never at
1135
- // sink creation, so a sink that never logs a passing-threshold event never touches the policy
1136
- // file (the below-threshold burst-cost invariant this file's own header documents). Idempotent:
1137
- // a pin request or durable batch append calls this eagerly (never speculative, unlike sink
1138
- // creation), and an ordinary write calls it once its threshold check has already passed.
1139
- function ensureGovernedPolicy(active, correlationId) {
1140
- if (active.policyResolved)
1141
- return;
1142
- active.policyResolved = true;
1143
- const outcome = resolveActivityLogStorePolicy(active.directory, active.trustedRoot, {
1144
- retentionBytes: active.config.retentionBytes,
1145
- retentionDays: active.config.retentionDays,
1146
- pinQuotaBytes: active.config.pinQuotaBytes,
1147
- }, { pid: process.pid, instanceId: INSTANCE_ID, isAlive: processIsAlive });
1148
- active.governed = governedValues(outcome);
1149
- active.config = applyGovernedPolicy(active.envConfig, outcome);
1150
- if (outcome.conflict !== undefined) {
1151
- queueEvidence(active, policyConflictEvidence(outcome.conflict, correlationId));
1152
- }
1153
- }
1154
- function governedValues(values) {
1155
- return {
1156
- retentionBytes: values.retentionBytes,
1157
- retentionDays: values.retentionDays,
1158
- pinQuotaBytes: values.pinQuotaBytes,
1159
- };
1160
- }
1161
- // Every maintenance pass re-applies the store's CURRENT governing policy before it deletes anything
1162
- // (#3554). A record another process replaced after this one resolved it (a sole-writer restart while
1163
- // this process held no active segment) governs this process's retention from its next pass on, so
1164
- // no two processes prune under different budgets beyond one pass, and a disagreement with this
1165
- // process's own env is evidenced again.
1166
- function refreshGovernedPolicy(active, correlationId) {
1167
- if (active.governed === undefined)
1168
- return;
1169
- const stored = readActivityLogPolicyRecord(active.directory, active.trustedRoot);
1170
- const current = active.governed;
1171
- if (stored === undefined ||
1172
- ACTIVITY_LOG_POLICY_SETTINGS.every((key) => stored[key] === current[key])) {
1173
- return;
1174
- }
1175
- active.governed = governedValues(stored);
1176
- active.config = applyGovernedPolicy(active.envConfig, stored);
1177
- const requested = governedValues(active.envConfig);
1178
- const conflictingSettings = ACTIVITY_LOG_POLICY_SETTINGS.filter((key) => stored[key] !== requested[key]);
1179
- if (conflictingSettings.length === 0)
1180
- return;
1181
- queueEvidence(active, policyConflictEvidence({ resolution: "adopted", conflictingSettings, stored: active.governed, requested }, correlationId));
1182
- }
1183
- // Real storage work is never speculative here (a pin request or a durable batch append IS the
1184
- // work), so this resolves the store's governing policy eagerly instead of waiting for a write that
1185
- // always follows at once.
1186
- function resolveGovernedActiveLog(directory, env) {
1187
- const active = resolveActiveLog(directory, resolveActivityLogStorageConfig(env));
1188
- ensureGovernedPolicy(active, undefined);
1189
- return active;
1190
- }
1191
- function peekIdentity(cursor, capability) {
1192
- const claimed = cursor.claimed;
1193
- if (claimed !== undefined)
1194
- return { ...claimed, writerCapability: capability };
1195
- return { ...serverLogProcessIdentity(capability), seq: nextProcessSeq };
1196
- }
1197
- function nextIdentity(cursor, capability) {
1198
- const claimed = cursor.claimed;
1199
- if (claimed === undefined)
1200
- return allocateServerLogIdentity(capability);
1201
- cursor.claimed = undefined;
1202
- return { ...claimed, writerCapability: capability };
1203
- }
1204
- function queueEvidence(active, event, capability = "active") {
1205
- if (active.pendingEvidence.length >= MAX_QUEUED_EVIDENCE) {
1206
- recordActivityLogLoss("persistence-failed");
1207
- reportServerLogFailure(new SafeArtifactFileError("activity-log", "write-failed"), {
1208
- op: event.op,
1209
- correlationId: event.correlationId,
1210
- loss: "event-dropped",
1211
- });
1212
- return;
1213
- }
1214
- active.pendingEvidence.push({ event, capability });
1215
- }
1216
- function closeQuietly(handle) {
1217
- try {
1218
- closeSync(handle);
1219
- }
1220
- catch {
1221
- // A descriptor we can no longer close is a descriptor we must stop using either way.
1222
- }
1223
- }
1224
- function trustedLogIdentity(stat) {
1225
- if (!stat.isFile() || stat.nlink !== 1 || !Number.isSafeInteger(stat.size) || stat.size < 0) {
1226
- return undefined;
1227
- }
1228
- return {
1229
- dev: Number(stat.dev),
1230
- ino: Number(stat.ino),
1231
- size: Number(stat.size),
1232
- mtimeMs: Number(stat.mtimeMs),
1233
- };
1234
- }
1235
- function pathLogIdentity(path) {
1236
- const stat = lstatSync(path);
1237
- if (!stat.isFile() || stat.nlink !== 1 || !Number.isSafeInteger(stat.size) || stat.size < 0) {
1238
- return undefined;
1239
- }
1240
- return { dev: stat.dev, ino: stat.ino, size: stat.size, mtimeMs: stat.mtimeMs };
1241
- }
1242
- function sameLogNode(left, right) {
1243
- return left.dev === right.dev && left.ino === right.ino && left.size === right.size;
1244
- }
1245
- // The segment's current size when its cached descriptor still names the inode at its active path,
1246
- // else `undefined`. Checked before and after every append, so a peer or operator that replaced or
1247
- // removed the path forces a new segment instead of bytes landing on a stale or unlinked inode.
1248
- function currentSegmentSize(segment) {
1249
- if (segment.handle === null)
1250
- return undefined;
1251
- try {
1252
- const opened = trustedLogIdentity(fstatSync(segment.handle));
1253
- const pathname = pathLogIdentity(segment.activePath);
1254
- return opened !== undefined && pathname !== undefined && sameLogNode(opened, pathname)
1255
- ? opened.size
1256
- : undefined;
1257
- }
1258
- catch {
1259
- return undefined;
1260
- }
1261
- }
1262
- function stopSealTimer(active) {
1263
- if (active.sealTimer === undefined)
1264
- return;
1265
- clearInterval(active.sealTimer);
1266
- active.sealTimer = undefined;
1267
- }
1268
- // A live owner seals its own idle segment within one segment window, which is what lets another
1269
- // process treat an active segment older than two windows as abandoned (pid reuse) without ever
1270
- // taking over a healthy writer's file.
1271
- function startSealTimer(active) {
1272
- stopSealTimer(active);
1273
- const periodMs = Math.max(1_000, Math.min(60_000, active.config.segmentSeconds * 250));
1274
- const timer = setInterval(() => {
1275
- sealIfExpired(active, { claimed: undefined, correlationId: undefined });
1276
- }, periodMs);
1277
- timer.unref();
1278
- active.sealTimer = timer;
1279
- }
1280
- function abandonSegment(active) {
1281
- const segment = active.segment;
1282
- if (segment === undefined)
1283
- return;
1284
- active.segment = undefined;
1285
- stopSealTimer(active);
1286
- if (segment.handle !== null)
1287
- closeQuietly(segment.handle);
1288
- segment.handle = null;
1289
- active.pendingNewline = false;
1290
- }
1291
- function noteSegmentLine(segment, seq) {
1292
- segment.firstSeq ??= seq;
1293
- segment.lastSeq = seq;
1294
- segment.lineCount += 1;
1295
- }
1296
- // ─── Evidence builders ─────────────────────────────────────────────────────────────────────────
1297
- function safeOpenEvidence(correlationId) {
1298
- return activityLogEvent(SERVER_LOG_SAFE_OPEN_OPERATION, { correlationId: correlationIdOrUnknown(correlationId) }, {
1299
- artifactClass: "activity-log",
1300
- persistenceStatus: "opened",
1301
- permissionAssurance: safeArtifactPermissionAssurance(),
1302
- containmentAssurance: safeArtifactContainmentAssurance(),
1303
- completeness: "complete",
1304
- loss: "none",
1305
- });
1306
- }
1307
- function mutationEvidence(event) {
1308
- return activityLogEvent(SERVER_LOG_TARGET_MUTATED_OPERATION, {
1309
- level: "error",
1310
- correlationId: correlationIdOrUnknown(event.correlationId),
1311
- errorKind: "target-mutated",
1312
- }, {
1313
- failedOp: redactLogLabel(event.op),
1314
- artifactClass: "activity-log",
1315
- permissionAssurance: safeArtifactPermissionAssurance(),
1316
- containmentAssurance: safeArtifactContainmentAssurance(),
1317
- completeness: "unknown",
1318
- loss: "event-location-unknown",
1319
- });
1320
- }
1321
- function segmentSealedEvidence(segment, facts, config) {
1322
- const dropped = segment.droppedEvents;
1323
- return activityLogEvent(ACTIVITY_LOG_SEGMENT_SEALED_OPERATION, { correlationId: correlationIdOrUnknown(facts.correlationId) }, {
1324
- sealReason: facts.reason,
1325
- segmentIndex: segment.identity.index,
1326
- segmentFirstSeq: segment.firstSeq ?? facts.seq,
1327
- segmentLastSeq: facts.seq,
1328
- segmentLineCount: segment.lineCount,
1329
- segmentBytes: facts.segmentBytes,
1330
- segmentDurationMs: Math.max(0, Math.round(performance.now() - segment.monotonicStartMs)),
1331
- droppedEventCount: dropped,
1332
- segmentByteLimit: config.segmentBytes,
1333
- segmentSecondsLimit: config.segmentSeconds,
1334
- completeness: dropped > 0 ? "partial" : "complete",
1335
- loss: dropped > 0 ? "event-dropped" : "none",
1336
- });
1337
- }
1338
- function recoveryLoss(outcome) {
1339
- return outcome.tail?.tailState === "truncated" ? "event-dropped" : "none";
1340
- }
1341
- function recoveredTailFields(outcome) {
1342
- const tail = outcome.tail;
1343
- return tail === undefined
1344
- ? { tailState: "unknown", truncatedBytes: 0, segmentBytes: outcome.segmentBytes }
1345
- : {
1346
- tailState: tail.tailState,
1347
- truncatedBytes: tail.truncatedBytes,
1348
- segmentBytes: tail.sizeBytes,
1349
- };
1350
- }
1351
- function segmentRecoveredEvidence(outcome, correlationId) {
1352
- const failed = outcome.status === "failed";
1353
- const tail = recoveredTailFields(outcome);
1354
- return activityLogEvent(ACTIVITY_LOG_SEGMENT_RECOVERED_OPERATION, {
1355
- level: failed ? "error" : "warn",
1356
- correlationId: correlationIdOrUnknown(correlationId),
1357
- ...(outcome.errorKind === undefined ? {} : { errorKind: outcome.errorKind }),
1358
- }, {
1359
- recoveryStatus: outcome.status,
1360
- recoveryKind: outcome.kind,
1361
- ownerState: outcome.owner,
1362
- tailState: tail.tailState,
1363
- truncatedBytes: tail.truncatedBytes,
1364
- segmentBytes: tail.segmentBytes,
1365
- segmentIndex: outcome.segment.index,
1366
- recoveredInstanceId: outcome.segment.instanceId,
1367
- // An orphan's owner never recorded its own end, so its completeness cannot be proven; only a
1368
- // seal whose rename alone was interrupted carries the owner's own complete seal line.
1369
- completeness: outcome.kind === "interrupted-seal" && !failed ? "complete" : "unknown",
1370
- loss: recoveryLoss(outcome),
1371
- });
1372
- }
1373
- function retentionStatus(outcome) {
1374
- if (outcome.failedNames.length === 0)
1375
- return "pruned";
1376
- return outcome.prunedSegmentCount + outcome.prunedLegacyFileCount > 0 ? "partial" : "failed";
1377
- }
1378
- function retentionPrunedEvidence(outcome, config, correlationId) {
1379
- const status = retentionStatus(outcome);
1380
- return activityLogEvent(ACTIVITY_LOG_RETENTION_PRUNED_OPERATION, {
1381
- level: status === "pruned" ? "info" : "warn",
1382
- correlationId: correlationIdOrUnknown(correlationId),
1383
- ...(status === "pruned" ? {} : { errorKind: "durability-failed" }),
1384
- }, {
1385
- retentionStatus: status,
1386
- prunedSegmentCount: outcome.prunedSegmentCount,
1387
- prunedLegacyFileCount: outcome.prunedLegacyFileCount,
1388
- prunedBytes: outcome.prunedBytes,
1389
- prunedByAgeCount: outcome.prunedByAgeCount,
1390
- prunedByBudgetCount: outcome.prunedByBudgetCount,
1391
- failedDeletionCount: outcome.failedNames.length,
1392
- retainedFileCount: outcome.retainedFileCount,
1393
- retainedBytes: outcome.retainedBytes,
1394
- protectedPinnedBytes: outcome.protection.protectedBytes,
1395
- retentionBudgetBytes: config.retentionBytes,
1396
- retentionDays: config.retentionDays,
1397
- completeness: status === "pruned" ? "complete" : "partial",
1398
- loss: "none",
1399
- });
1400
- }
1401
- const PRESSURE_ERROR_KIND = {
1402
- "low-disk-space": "unavailable",
1403
- "disk-full": "write-failed",
1404
- backpressure: "write-failed",
1405
- "budget-exceeded": "unavailable",
1406
- "retention-blocked": "durability-failed",
1407
- };
1408
- function pressureEvidence(facts, config, correlationId) {
1409
- const lost = facts.droppedEventCount > 0;
1410
- return activityLogEvent(ACTIVITY_LOG_PRESSURE_OPERATION, {
1411
- level: facts.state === "cleared" ? "info" : "warn",
1412
- correlationId: correlationIdOrUnknown(correlationId),
1413
- ...(facts.state === "cleared" ? {} : { errorKind: PRESSURE_ERROR_KIND[facts.state] }),
1414
- }, {
1415
- pressureState: facts.state,
1416
- ...(facts.previousState === undefined ? {} : { previousState: facts.previousState }),
1417
- droppedEventCount: facts.droppedEventCount,
1418
- ...(facts.usedBytes === undefined ? {} : { usedBytes: facts.usedBytes }),
1419
- budgetBytes: config.retentionBytes,
1420
- pinQuotaBytes: config.pinQuotaBytes,
1421
- ...(facts.freeBytes === undefined ? {} : { freeBytes: facts.freeBytes }),
1422
- completeness: lost ? "partial" : "complete",
1423
- loss: lost ? "event-dropped" : "none",
1424
- });
1425
- }
1426
- function pinWindowSeconds(scope) {
1427
- return scope?.kind === "window" ? Math.ceil((scope.toMs - scope.fromMs) / 1000) : undefined;
1428
- }
1429
- function pinOptionalFields(facts) {
1430
- const windowSeconds = pinWindowSeconds(facts.scope);
1431
- return {
1432
- ...(facts.pinId === undefined ? {} : { pinId: facts.pinId }),
1433
- ...(facts.rejectionReason === undefined ? {} : { rejectionReason: facts.rejectionReason }),
1434
- ...(windowSeconds === undefined ? {} : { windowSeconds }),
1435
- ...(facts.quotaStatus === undefined ? {} : { quotaStatus: facts.quotaStatus }),
1436
- };
1437
- }
1438
- function pinCreatedEvidence(facts, correlationId) {
1439
- const rejected = facts.status === "rejected";
1440
- const degraded = rejected || facts.quotaStatus === "exceeded";
1441
- return activityLogEvent(ACTIVITY_LOG_PIN_CREATED_OPERATION, {
1442
- level: degraded ? "warn" : "info",
1443
- correlationId: correlationIdOrUnknown(correlationId),
1444
- ...(rejected ? { errorKind: pinRejectionErrorKind(facts.rejectionReason) } : {}),
1445
- }, {
1446
- ...pinOptionalFields(facts),
1447
- pinStatus: facts.status,
1448
- pinKind: facts.scope?.kind === "window" ? "window" : "segments",
1449
- pinReason: facts.reason,
1450
- pinnedSegmentCount: facts.pinnedSegmentCount,
1451
- pinnedBytes: facts.pinnedBytes,
1452
- expiresInSeconds: facts.expiresInSeconds,
1453
- completeness: degraded ? "partial" : "complete",
1454
- loss: "none",
1455
- });
1456
- }
1457
- function pinRejectionErrorKind(reason) {
1458
- if (reason === "invalid-request")
1459
- return "invalid-request";
1460
- return reason === "pin-limit-reached" ? "rate-limited" : "unavailable";
1461
- }
1462
- function pinExpiredEvidence(facts, correlationId) {
1463
- return activityLogEvent(ACTIVITY_LOG_PIN_EXPIRED_OPERATION, {
1464
- level: facts.removed ? "info" : "warn",
1465
- correlationId: correlationIdOrUnknown(correlationId),
1466
- ...(facts.removed ? {} : { errorKind: "durability-failed" }),
1467
- }, {
1468
- pinId: facts.pinId,
1469
- expiryReason: facts.reason,
1470
- removalStatus: facts.removed ? "removed" : "failed",
1471
- releasedSegmentCount: facts.releasedSegmentCount,
1472
- releasedBytes: facts.releasedBytes,
1473
- completeness: facts.removed ? "complete" : "partial",
1474
- loss: "none",
1475
- });
1476
- }
1477
- function pinQuotaExhaustedEvidence(facts, config, correlationId) {
1478
- const protection = facts.protection;
1479
- return activityLogEvent(ACTIVITY_LOG_PIN_QUOTA_EXHAUSTED_OPERATION, {
1480
- level: "error",
1481
- correlationId: correlationIdOrUnknown(correlationId),
1482
- errorKind: "unavailable",
1483
- }, {
1484
- pinQuotaBytes: config.pinQuotaBytes,
1485
- requestedPinnedBytes: protection.requestedBytes,
1486
- protectedPinnedBytes: protection.protectedBytes,
1487
- protectedSegmentCount: protection.protectedNames.size,
1488
- unprotectedSegmentCount: protection.unprotected.length,
1489
- unprotectedBytes: protection.unprotected.reduce((sum, entry) => sum + entry.sizeBytes, 0),
1490
- unprotectedSeqSpan: facts.seqSpan,
1491
- unknownSpanSegmentCount: facts.unknownSpanSegmentCount,
1492
- activePinCount: facts.pinCount,
1493
- completeness: "partial",
1494
- loss: "event-dropped",
1495
- });
1496
- }
1497
- // A cooperating process's own env disagreed with the store's one governing policy: "adopted" means
1498
- // the stored bounds won (this process's own view is overridden); "replaced" means this process was
1499
- // the store's sole live writer and its own bounds now govern (e.g. a clean restart with a changed
1500
- // `KEIKO_LOG_RETENTION_BYTES`).
1501
- function policyConflictEvidence(conflict, correlationId) {
1502
- const replaced = conflict.resolution === "replaced";
1503
- return activityLogEvent(ACTIVITY_LOG_POLICY_CONFLICT_OPERATION, {
1504
- level: replaced ? "info" : "warn",
1505
- correlationId: correlationIdOrUnknown(correlationId),
1506
- ...(replaced ? {} : { errorKind: "conflict" }),
1507
- }, {
1508
- policyResolution: conflict.resolution,
1509
- conflictingSettings: conflict.conflictingSettings,
1510
- storedRetentionBytes: conflict.stored.retentionBytes,
1511
- requestedRetentionBytes: conflict.requested.retentionBytes,
1512
- storedRetentionDays: conflict.stored.retentionDays,
1513
- requestedRetentionDays: conflict.requested.retentionDays,
1514
- storedPinQuotaBytes: conflict.stored.pinQuotaBytes,
1515
- requestedPinQuotaBytes: conflict.requested.pinQuotaBytes,
1516
- completeness: "complete",
1517
- loss: "none",
1518
- });
1519
- }
1520
- // ─── Maintenance: recovery, pin expiry, retention, quota, pressure ─────────────────────────────
1521
- function sharesInode(left, right) {
1522
- try {
1523
- const a = lstatSync(left);
1524
- const b = lstatSync(right);
1525
- return a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino;
1526
- }
1527
- catch {
1528
- return false;
1529
- }
1530
- }
1531
- function pathMissing(path) {
1532
- try {
1533
- lstatSync(path);
1534
- return false;
1535
- }
1536
- catch (error) {
1537
- return machineToken(safeProperty(error, "code")) === "ENOENT";
1538
- }
1539
- }
1540
- function closedErrorKind(error) {
1541
- return activityLogErrorKindOr(errorKindOf(error), "internal");
1542
- }
1543
- function sealedTwinPath(active, segment) {
1544
- return join(active.directory, activityLogSegmentFileName(segment, "sealed"));
1545
- }
1546
- function readSealedTail(path, trustedRoot) {
1547
- let descriptor;
1548
- try {
1549
- descriptor = openSafeArtifactFile(path, {
1550
- artifactClass: "activity-log",
1551
- mode: "read",
1552
- trustedRoot,
1553
- });
1554
- return inspectActivityLogSegmentTail(descriptor, ACTIVITY_LOG_SEGMENT_SEALED_OPERATION.op);
1555
- }
1556
- catch {
1557
- return undefined;
1558
- }
1559
- finally {
1560
- if (descriptor !== undefined)
1561
- closeQuietly(descriptor);
1562
- }
1563
- }
1564
- function archiveOptions(active) {
1565
- return { artifactClass: "activity-log", trustedRoot: active.trustedRoot };
1566
- }
1567
- // A crash between the hard link and the unlink of a seal leaves both names on one inode; finishing
1568
- // the archive removes only the active name, and the sealed segment is then inspected as it stands.
1569
- function finishInterruptedSeal(active, entry, owner, sealedPath) {
1570
- const base = { owner, segment: entry.file, segmentBytes: entry.sizeBytes };
1571
- try {
1572
- archiveSafeArtifactFile(entry.path, sealedPath, archiveOptions(active));
1573
- const tail = readSealedTail(sealedPath, active.trustedRoot);
1574
- return { ...base, status: "sealed", kind: "interrupted-seal", tail, errorKind: undefined };
1575
- }
1576
- catch (error) {
1577
- return {
1578
- ...base,
1579
- status: "failed",
1580
- kind: "interrupted-seal",
1581
- tail: undefined,
1582
- errorKind: closedErrorKind(error),
1583
- };
1584
- }
1585
- }
1586
- // Durability and read-only mode are best effort for a file another process wrote: the content is
1587
- // never modified, and a platform that cannot apply either still leaves a private sealed segment.
1588
- function settleOrphanDescriptor(descriptor) {
1589
- try {
1590
- fsyncSync(descriptor);
1591
- }
1592
- catch {
1593
- // Some platforms refuse fsync on a read-only descriptor; the sealing rename still proceeds.
1594
- }
1595
- try {
1596
- fchmodSync(descriptor, SEALED_SEGMENT_MODE);
1597
- }
1598
- catch {
1599
- // The segment stays owner-private (0600); retention and readers accept that mode.
1600
- }
1601
- }
1602
- function sealOrphanDescriptor(active, entry, descriptor, sealedPath) {
1603
- const tail = inspectActivityLogSegmentTail(descriptor, ACTIVITY_LOG_SEGMENT_SEALED_OPERATION.op);
1604
- settleOrphanDescriptor(descriptor);
1605
- const result = archiveSafeArtifactFile(entry.path, sealedPath, archiveOptions(active));
1606
- if (result === "archive-exists")
1607
- throw new SafeArtifactFileError("activity-log", "target-exists");
1608
- return { tail, archived: result !== "source-missing" };
1609
- }
1610
- function recoverOrphanedSegment(active, entry, owner) {
1611
- const sealedPath = sealedTwinPath(active, entry.file);
1612
- if (sharesInode(entry.path, sealedPath)) {
1613
- return finishInterruptedSeal(active, entry, owner, sealedPath);
1614
- }
1615
- const base = { owner, segment: entry.file, segmentBytes: entry.sizeBytes };
1616
- let descriptor;
1617
- try {
1618
- descriptor = openSafeArtifactFile(entry.path, { ...archiveOptions(active), mode: "read" });
1619
- }
1620
- catch (error) {
1621
- if (pathMissing(entry.path))
1622
- return undefined;
1623
- const errorKind = closedErrorKind(error);
1624
- return { ...base, status: "failed", kind: "unsealed", tail: undefined, errorKind };
1625
- }
1626
- try {
1627
- const sealed = sealOrphanDescriptor(active, entry, descriptor, sealedPath);
1628
- if (!sealed.archived)
1629
- return undefined;
1630
- const kind = sealed.tail.sealLinePresent ? "interrupted-seal" : "unsealed";
1631
- return { ...base, status: "sealed", kind, tail: sealed.tail, errorKind: undefined };
1632
- }
1633
- catch (error) {
1634
- const errorKind = closedErrorKind(error);
1635
- return { ...base, status: "failed", kind: "unsealed", tail: undefined, errorKind };
1636
- }
1637
- finally {
1638
- closeQuietly(descriptor);
1639
- }
1640
- }
1641
- // A failed seal, recovery, or deletion is retried after this backoff, never skipped for the life of
1642
- // the process: a transient lock or permission blip must not strand bytes the budget keeps counting.
1643
- // Only the first failure of a name is evidenced; its retries stay quiet until one succeeds.
1644
- const FAILED_MUTATION_RETRY_MS = 60_000;
1645
- function retryDue(failures, key, nowMs) {
1646
- const retryAtMs = failures.get(key);
1647
- return retryAtMs === undefined || retryAtMs <= nowMs;
1648
- }
1649
- // Records a failure and returns whether it is the first one for `key`.
1650
- function recordMutationFailure(failures, key, nowMs) {
1651
- const first = !failures.has(key);
1652
- failures.set(key, nowMs + FAILED_MUTATION_RETRY_MS);
1653
- return first;
1654
- }
1655
- // Forgets failures whose target no longer exists (a peer or an operator removed it).
1656
- function forgetVanished(failures, present) {
1657
- for (const key of failures.keys()) {
1658
- if (!present.has(key))
1659
- failures.delete(key);
1660
- }
1661
- }
1662
- // Whether a recovery outcome is evidenced: every success, and the first failure of a segment.
1663
- function noteRecoveryOutcome(active, name, outcome, nowMs) {
1664
- if (outcome.status === "failed")
1665
- return recordMutationFailure(active.failedRecoveries, name, nowMs);
1666
- active.failedRecoveries.delete(name);
1667
- active.recoveredSegments += 1;
1668
- return true;
1669
- }
1670
- function recoverOrphanedSegments(active, cursor, listing, nowMs) {
1671
- const context = {
1672
- pid: process.pid,
1673
- instanceId: INSTANCE_ID,
1674
- currentName: active.segment?.activeName,
1675
- nowMs,
1676
- segmentSeconds: active.config.segmentSeconds,
1677
- isAlive: processIsAlive,
1678
- };
1679
- forgetVanished(active.failedRecoveries, new Set(listing.files.map((entry) => entry.file.name)));
1680
- let changed = false;
1681
- for (const entry of listing.files) {
1682
- if (!isActivityLogSegmentEntry(entry))
1683
- continue;
1684
- if (!retryDue(active.failedRecoveries, entry.file.name, nowMs))
1685
- continue;
1686
- const owner = activityLogOrphanOwner(entry, context);
1687
- if (owner === undefined)
1688
- continue;
1689
- const outcome = recoverOrphanedSegment(active, entry, owner);
1690
- if (outcome === undefined)
1691
- continue;
1692
- changed = true;
1693
- if (noteRecoveryOutcome(active, entry.file.name, outcome, nowMs)) {
1694
- queueEvidence(active, segmentRecoveredEvidence(outcome, cursor.correlationId));
1695
- }
1696
- }
1697
- return changed;
1698
- }
1699
- function pinCoverage(pin, files) {
1700
- let count = 0;
1701
- let bytes = 0;
1702
- if (pin === undefined)
1703
- return { count, bytes };
1704
- for (const entry of files) {
1705
- if (entry.file.kind !== "sealed" || !isActivityLogSegmentEntry(entry))
1706
- continue;
1707
- if (!activityLogPinCovers(pin, entry))
1708
- continue;
1709
- count += 1;
1710
- bytes += entry.sizeBytes;
1711
- }
1712
- return { count, bytes };
1713
- }
1714
- function removePinRecordQuietly(active, read) {
1715
- try {
1716
- removeActivityLogFile(read.entry.path, active.trustedRoot);
1717
- active.failedPinRemovals.delete(read.entry.path);
1718
- return true;
1719
- }
1720
- catch {
1721
- return false;
1722
- }
1723
- }
1724
- // Expired and unreadable pin records protect nothing; removing them is bounded cleanup. A removal
1725
- // that fails is retried after the backoff; each record's removal and first failure are evidenced.
1726
- // Returns the paths removed in this pass.
1727
- function expireActivityLogPins(active, cursor, listing, reads, nowMs) {
1728
- const removedPaths = new Set();
1729
- forgetVanished(active.failedPinRemovals, new Set(reads.map((read) => read.entry.path)));
1730
- for (const read of reads) {
1731
- if (read.record !== undefined && read.record.expiresAtMs > nowMs)
1732
- continue;
1733
- if (!retryDue(active.failedPinRemovals, read.entry.path, nowMs))
1734
- continue;
1735
- const coverage = pinCoverage(read.record, listing.files);
1736
- const removed = removePinRecordQuietly(active, read);
1737
- if (removed)
1738
- removedPaths.add(read.entry.path);
1739
- else if (!recordMutationFailure(active.failedPinRemovals, read.entry.path, nowMs))
1740
- continue;
1741
- const facts = {
1742
- pinId: read.entry.pinId,
1743
- reason: read.record === undefined ? "invalid-record" : "expired",
1744
- removed,
1745
- releasedSegmentCount: coverage.count,
1746
- releasedBytes: coverage.bytes,
1747
- };
1748
- queueEvidence(active, pinExpiredEvidence(facts, cursor.correlationId));
1749
- }
1750
- return removedPaths;
1751
- }
1752
- function tightenLegacyFile(path, trustedRoot) {
1753
- try {
1754
- // The shared open primitive narrows a non-private owned file to 0600 before handing back a
1755
- // verified descriptor; no byte is read or written.
1756
- closeSync(openSafeArtifactFile(path, {
1757
- artifactClass: "activity-log",
1758
- mode: "read-write-existing",
1759
- trustedRoot,
1760
- }));
1761
- return true;
1762
- }
1763
- catch {
1764
- return false;
1765
- }
1766
- }
1767
- function removeRetentionTarget(active, entry) {
1768
- try {
1769
- removeActivityLogFile(entry.path, active.trustedRoot);
1770
- active.failedDeletions.delete(entry.file.name);
1771
- return true;
1772
- }
1773
- catch (error) {
1774
- const permissionUnsafe = error instanceof SafeArtifactFileError && error.kind === "permission-unsafe";
1775
- if (!permissionUnsafe || !tightenLegacyFile(entry.path, active.trustedRoot))
1776
- return false;
1777
- }
1778
- try {
1779
- removeActivityLogFile(entry.path, active.trustedRoot);
1780
- active.failedDeletions.delete(entry.file.name);
1781
- return true;
1782
- }
1783
- catch {
1784
- return false;
1785
- }
1786
- }
1787
- function queueRetentionEvidence(active, cursor, outcome, firstFailures) {
1788
- const pruned = outcome.prunedSegmentCount + outcome.prunedLegacyFileCount;
1789
- if (pruned === 0 && firstFailures === 0)
1790
- return;
1791
- queueEvidence(active, retentionPrunedEvidence(outcome, active.config, cursor.correlationId));
1792
- }
1793
- function unprotectedSpan(active, protection) {
1794
- let seqSpan = 0;
1795
- let unknown = 0;
1796
- for (const entry of protection.unprotected) {
1797
- const span = activityLogSegmentSeqSpan(entry.path, active.trustedRoot);
1798
- if (span === undefined)
1799
- unknown += 1;
1800
- else
1801
- seqSpan += span;
1802
- }
1803
- return { seqSpan, unknown };
1804
- }
1805
- // Exactly one loss marker per exhaustion episode: the first pass that finds pinned evidence the
1806
- // quota cannot hold reports it — measured before retention may delete those segments — and later
1807
- // passes stay quiet until the quota holds every pin again.
1808
- function queueQuotaEvidence(active, cursor, protection, pinCount) {
1809
- if (protection.unprotected.length === 0) {
1810
- active.quotaExhaustedReported = false;
1811
- return;
1812
- }
1813
- if (active.quotaExhaustedReported)
1814
- return;
1815
- active.quotaExhaustedReported = true;
1816
- const span = unprotectedSpan(active, protection);
1817
- const facts = {
1818
- protection,
1819
- pinCount,
1820
- seqSpan: span.seqSpan,
1821
- unknownSpanSegmentCount: span.unknown,
1822
- };
1823
- queueEvidence(active, pinQuotaExhaustedEvidence(facts, active.config, cursor.correlationId));
1824
- }
1825
- // Blocked while any deletion is still pending retry, not only in the pass that first failed.
1826
- function standingPressure(active, freeBytes) {
1827
- if (active.failedDeletions.size > 0)
1828
- return "retention-blocked";
1829
- const lowDisk = activityLogLowDiskThresholdBytes(active.config);
1830
- return freeBytes !== undefined && freeBytes < lowDisk ? "low-disk-space" : undefined;
1831
- }
1832
- // Standing conditions are reported on entry and once more when they clear; conditions that block
1833
- // writing (disk full, backpressure, an exhausted budget) are reported when writing resumes, with the
1834
- // exact number of events they cost.
1835
- function queuePressureTransition(active, cursor, outcome) {
1836
- const freeBytes = activityLogFreeBytes(active.directory);
1837
- const state = standingPressure(active, freeBytes);
1838
- const previous = active.standingPressure;
1839
- if (state === previous)
1840
- return;
1841
- active.standingPressure = state;
1842
- const facts = state === undefined
1843
- ? { state: "cleared", previousState: previous, droppedEventCount: 0, freeBytes }
1844
- : { state, droppedEventCount: 0, usedBytes: outcome.usageBytes, freeBytes };
1845
- queueEvidence(active, pressureEvidence(facts, active.config, cursor.correlationId));
1846
- }
1847
- // Every pin record still on disk counts toward the byte budget, including one this process could
1848
- // not remove; only the records removed in this pass are gone.
1849
- function remainingPinRecordBytes(reads, removed) {
1850
- return reads
1851
- .filter((read) => !removed.has(read.entry.path))
1852
- .reduce((sum, read) => sum + read.entry.sizeBytes, 0);
1853
- }
1854
- // Names whose failed deletion is not yet due for a retry; failures of files that no longer exist are
1855
- // forgotten first, so the set only ever holds real, still-present targets.
1856
- function pendingRetries(failures, listing, nowMs) {
1857
- forgetVanished(failures, new Set(listing.files.map((entry) => entry.file.name)));
1858
- return new Set([...failures.entries()].filter(([, retryAtMs]) => retryAtMs > nowMs).map(([name]) => name));
1859
- }
1860
- function applyRetention(active, cursor, nowMs, reserveBytes) {
1861
- const listing = listActivityLogDirectory(active.directory);
1862
- const reads = readActivityLogPins(listing, active.trustedRoot);
1863
- const removedPins = expireActivityLogPins(active, cursor, listing, reads, nowMs);
1864
- const pins = activeActivityLogPins(reads, nowMs);
1865
- queueQuotaEvidence(active, cursor, planActivityLogPinProtection(listing.files, pins, active.config.pinQuotaBytes), pins.length);
1866
- const outcome = applyActivityLogRetention({
1867
- files: listing.files,
1868
- pins,
1869
- pinRecordBytes: remainingPinRecordBytes(reads, removedPins),
1870
- config: active.config,
1871
- nowMs,
1872
- reserveBytes,
1873
- skipNames: pendingRetries(active.failedDeletions, listing, nowMs),
1874
- ownInstanceId: INSTANCE_ID,
1875
- }, (entry) => removeRetentionTarget(active, entry));
1876
- const firstFailures = outcome.failedNames.filter((name) => recordMutationFailure(active.failedDeletions, name, nowMs)).length;
1877
- queueRetentionEvidence(active, cursor, outcome, firstFailures);
1878
- queuePressureTransition(active, cursor, outcome);
1879
- return outcome;
1880
- }
1881
- // Runs before every new segment: recover orphans, expire pins, apply retention with the new
1882
- // segment's reservation, and report quota and pressure. Returns whether the reservation fits.
1883
- function runMaintenance(active, cursor, reserveBytes) {
1884
- // Never list, recover, or prune through a redirected directory: a symlink at the log path is
1885
- // refused before one name behind it is read.
1886
- if (!durableLogDirectory(active.directory)) {
1887
- throw new SafeArtifactFileError("activity-log", "unsafe-ancestor");
1888
- }
1889
- refreshGovernedPolicy(active, cursor.correlationId);
1890
- const nowMs = Date.now();
1891
- recoverOrphanedSegments(active, cursor, listActivityLogDirectory(active.directory), nowMs);
1892
- return applyRetention(active, cursor, nowMs, reserveBytes).admitted;
1893
- }
1894
- // ─── Segment lifecycle ─────────────────────────────────────────────────────────────────────────
1895
- function nextSegmentIdentity(active) {
1896
- // Monotonic per instance even when the wall clock steps backwards, so an instance's segments
1897
- // never sort out of index order.
1898
- const startMs = Math.max(Date.now(), active.lastStartMs);
1899
- active.lastStartMs = startMs;
1900
- const index = active.nextIndex;
1901
- active.nextIndex += 1;
1902
- return { startMs, pid: process.pid, instanceId: INSTANCE_ID, index };
1903
- }
1904
- function installSegment(active, identity, handle, cursor) {
1905
- const activeName = activityLogSegmentFileName(identity, "active");
1906
- const segment = {
1907
- identity,
1908
- segmentId: formatActivityLogSegmentId(identity),
1909
- activeName,
1910
- activePath: join(active.directory, activeName),
1911
- sealedPath: sealedTwinPath(active, identity),
1912
- wallStartMs: Date.now(),
1913
- monotonicStartMs: performance.now(),
1914
- handle,
1915
- firstSeq: undefined,
1916
- lastSeq: undefined,
1917
- lineCount: 0,
1918
- droppedEvents: 0,
1919
- };
1920
- active.segment = segment;
1921
- active.pendingNewline = false;
1922
- // The segment's first line is its own safe-open evidence, ahead of any queued maintenance record.
1923
- active.pendingEvidence.unshift({
1924
- event: safeOpenEvidence(cursor.correlationId),
1925
- capability: "active",
1926
- });
1927
- startSealTimer(active);
1928
- return segment;
1929
- }
1930
- function admissionBlocked(active, nowMs) {
1931
- return active.blocked.has("budget-exceeded") && nowMs < active.admissionRetryAtMs;
1932
- }
1933
- function admitNewSegment(active, cursor) {
1934
- const nowMs = Date.now();
1935
- if (admissionBlocked(active, nowMs))
1936
- throw new ActivityLogBudgetError();
1937
- if (runMaintenance(active, cursor, active.config.segmentBytes))
1938
- return;
1939
- active.admissionRetryAtMs = nowMs + ADMISSION_RETRY_MS;
1940
- throw new ActivityLogBudgetError();
1941
- }
1942
- // Creates the next segment's file under its active name, empty and not yet installed.
1943
- function createSegmentHandle(active) {
1944
- for (let attempt = 0; attempt < 3; attempt += 1) {
1945
- const identity = nextSegmentIdentity(active);
1946
- const path = join(active.directory, activityLogSegmentFileName(identity, "active"));
1947
- try {
1948
- const handle = openSafeArtifactFile(path, {
1949
- artifactClass: "activity-log",
1950
- mode: "exclusive-create",
1951
- trustedRoot: active.trustedRoot,
1952
- });
1953
- return { identity, handle };
1954
- }
1955
- catch (error) {
1956
- // Only a leftover of this very instance can own the name; skip to the next index.
1957
- if (!(error instanceof SafeArtifactFileError) || error.kind !== "target-exists")
1958
- throw error;
1959
- }
1960
- }
1961
- throw new SafeArtifactFileError("activity-log", "target-exists");
1962
- }
1963
- function createSegmentFile(active, cursor) {
1964
- const created = createSegmentHandle(active);
1965
- return installSegment(active, created.identity, created.handle, cursor);
1966
- }
1967
- // Gives back a segment whose admission a concurrent process invalidated. It is still empty, so the
1968
- // store never held more bytes than its budget; its queued safe-open line is withdrawn with it.
1969
- function withdrawSegment(active, segment, safeOpen) {
1970
- abandonSegment(active);
1971
- const queued = active.pendingEvidence.indexOf(safeOpen);
1972
- if (queued >= 0)
1973
- active.pendingEvidence.splice(queued, 1);
1974
- try {
1975
- removeActivityLogFile(segment.activePath, active.trustedRoot);
1976
- }
1977
- catch {
1978
- // Left in place, it is this process's own abandoned segment and the next maintenance seals it.
1979
- }
1980
- }
1981
- // The re-check once a new segment exists: it sees every peer's new segment, and this one, at its
1982
- // full reservation and prunes further or withdraws this still empty segment, so the bytes on disk
1983
- // never exceed the budget.
1984
- // A re-check that throws (a redirected directory, a failed listing) admitted nothing either: the
1985
- // still empty segment is withdrawn before the error propagates, so no later write lands in a
1986
- // segment whose reservation was never confirmed (#3557 review).
1987
- function confirmAdmission(active, cursor, segment) {
1988
- const safeOpen = active.pendingEvidence[0];
1989
- let admitted;
1990
- try {
1991
- admitted = runMaintenance(active, cursor, 0);
1992
- }
1993
- catch (error) {
1994
- if (safeOpen !== undefined)
1995
- withdrawSegment(active, segment, safeOpen);
1996
- throw error;
1997
- }
1998
- if (admitted)
1999
- return;
2000
- if (safeOpen !== undefined)
2001
- withdrawSegment(active, segment, safeOpen);
2002
- active.admissionRetryAtMs = Date.now() + ADMISSION_RETRY_MS;
2003
- throw new ActivityLogBudgetError();
2004
- }
2005
- // Admission is checked before the exclusive create and again after it: two processes can observe
2006
- // the same free reservation, but only while their new segments are still empty.
2007
- function openSegment(active, cursor) {
2008
- admitNewSegment(active, cursor);
2009
- const segment = createSegmentFile(active, cursor);
2010
- confirmAdmission(active, cursor, segment);
2011
- return segment;
2012
- }
2013
- // Replaces a full or expired segment make-before-break (#3557): the next segment's file exists
2014
- // before the full one gives up its active name, so a process that keeps writing always holds an
2015
- // active segment. That file is the one sign of a live writer a starting peer can see when it decides
2016
- // whether it may replace the store's governing policy (`isSoleActivityLogWriter`); sealing first and
2017
- // opening only after a maintenance pass left a busy writer invisible for that whole pass. The new
2018
- // file stays empty until the re-check admits it, so the byte bound is unchanged.
2019
- function rotateSegment(active, cursor, reason) {
2020
- let next;
2021
- try {
2022
- if (!admissionBlocked(active, Date.now()))
2023
- next = createSegmentHandle(active);
2024
- }
2025
- finally {
2026
- // Sealed whether or not the next segment could be created, exactly as before.
2027
- sealSegment(active, cursor, reason);
2028
- }
2029
- if (next === undefined)
2030
- throw new ActivityLogBudgetError();
2031
- confirmAdmission(active, cursor, installSegment(active, next.identity, next.handle, cursor));
2032
- }
2033
- function ensureSegment(active, cursor) {
2034
- const current = active.segment;
2035
- if (current !== undefined) {
2036
- const sizeBytes = currentSegmentSize(current);
2037
- if (sizeBytes !== undefined)
2038
- return { segment: current, sizeBytes };
2039
- abandonSegment(active);
2040
- }
2041
- const segment = openSegment(active, cursor);
2042
- return { segment, sizeBytes: currentSegmentSize(segment) ?? 0 };
2043
- }
2044
- function restrictSealedMode(handle) {
2045
- try {
2046
- fchmodSync(handle, SEALED_SEGMENT_MODE);
2047
- }
2048
- catch {
2049
- // The sealed segment stays owner-private (0600); it is still never opened for writing again.
2050
- }
2051
- }
2052
- function descriptorAtPath(handle, path) {
2053
- try {
2054
- const opened = fstatSync(handle);
2055
- const pathname = lstatSync(path);
2056
- return pathname.isFile() && opened.dev === pathname.dev && opened.ino === pathname.ino;
2057
- }
2058
- catch {
2059
- return false;
2060
- }
2061
- }
2062
- function writeSealLine(active, segment, handle, cursor, reason) {
2063
- const segmentBytes = currentSegmentSize(segment);
2064
- if (segmentBytes === undefined)
2065
- throw new SafeArtifactFileError("activity-log", "target-mutated");
2066
- const identity = nextIdentity(cursor, "active");
2067
- const facts = {
2068
- reason,
2069
- seq: identity.seq,
2070
- segmentBytes,
2071
- correlationId: cursor.correlationId,
2072
- };
2073
- const event = segmentSealedEvidence(segment, facts, active.config);
2074
- writeRecord(active, handle, formatRegisteredServerLogLine(event, new Date(), identity));
2075
- noteSegmentLine(segment, identity.seq);
2076
- }
2077
- function publishSealedSegment(active, segment, handle) {
2078
- fsyncSync(handle);
2079
- archiveSafeArtifactFile(segment.activePath, segment.sealedPath, archiveOptions(active));
2080
- if (!descriptorAtPath(handle, segment.sealedPath)) {
2081
- throw new SafeArtifactFileError("activity-log", "target-mutated");
2082
- }
2083
- // Applied after the rename: on Windows the read-only attribute would otherwise follow the inode
2084
- // into the unlink of the active name.
2085
- restrictSealedMode(handle);
2086
- }
2087
- // Seals the active segment: a final registered seal line, fsync, the guarded rename that drops
2088
- // `.active`, then read-only mode. On any failure the file keeps its active name and this process's
2089
- // next maintenance pass seals it as its own abandoned segment; the writer never appends to it again.
2090
- function sealSegment(active, cursor, reason) {
2091
- const segment = active.segment;
2092
- if (segment === undefined)
2093
- return;
2094
- active.segment = undefined;
2095
- stopSealTimer(active);
2096
- const handle = segment.handle;
2097
- let sealLineWritten = false;
2098
- try {
2099
- if (handle === null)
2100
- throw new SafeArtifactFileError("activity-log", "target-mutated");
2101
- writeSealLine(active, segment, handle, cursor, reason);
2102
- sealLineWritten = true;
2103
- publishSealedSegment(active, segment, handle);
2104
- }
2105
- catch (error) {
2106
- // A seal line already on disk is not lost: recovery completes the interrupted seal later.
2107
- if (!sealLineWritten)
2108
- recordPersistenceLoss(error);
2109
- reportServerLogFailure(error, {
2110
- op: ACTIVITY_LOG_SEGMENT_SEALED_OPERATION.op,
2111
- correlationId: cursor.correlationId,
2112
- loss: sealLineWritten ? "event-location-unknown" : "event-dropped",
2113
- });
2114
- }
2115
- finally {
2116
- segment.handle = null;
2117
- if (handle !== null)
2118
- closeQuietly(handle);
2119
- active.pendingNewline = false;
2120
- }
2121
- }
2122
- function segmentExpiryReason(segment, config) {
2123
- const wallElapsed = Date.now() - segment.wallStartMs;
2124
- if (wallElapsed < -CLOCK_TOLERANCE_MS)
2125
- return "clock-change";
2126
- const elapsed = Math.max(wallElapsed, performance.now() - segment.monotonicStartMs);
2127
- return elapsed >= config.segmentSeconds * 1000 ? "age-limit" : undefined;
2128
- }
2129
- function sealIfExpired(active, cursor) {
2130
- const segment = active.segment;
2131
- if (segment === undefined)
2132
- return;
2133
- const reason = segmentExpiryReason(segment, active.config);
2134
- if (reason !== undefined)
2135
- sealSegment(active, cursor, reason);
2136
- }
2137
- function persistPostWriteMutation(active, event, cursor) {
2138
- abandonSegment(active);
2139
- queueEvidence(active, mutationEvidence(event));
2140
- try {
2141
- writeQueued(active, cursor, undefined);
2142
- }
2143
- catch {
2144
- // The caller reports the event whose location is unknown; the evidence stays queued.
2145
- }
2146
- }
2147
- // Appends `record` when it fits below the byte bound with room for the seal line; returns the bytes
2148
- // it added, or 0 when the segment must be sealed first. The line is formatted once with the
2149
- // identity it will carry: nothing can claim a `seq` between measuring and writing it.
2150
- function appendIfFits(active, open, cursor, record) {
2151
- const identity = peekIdentity(cursor, record.capability);
2152
- const line = formatEventLine(record.event, undefined, identity);
2153
- const bytes = serverLogLineBytes(line) + (active.pendingNewline ? 1 : 0);
2154
- if (open.sizeBytes + bytes + SEQ_GROWTH_MARGIN_BYTES + SEAL_RESERVE_BYTES >
2155
- active.config.segmentBytes) {
2156
- return 0;
2157
- }
2158
- const claimed = nextIdentity(cursor, record.capability);
2159
- const handle = open.segment.handle;
2160
- if (handle === null)
2161
- throw new SafeArtifactFileError("activity-log", "target-mutated");
2162
- writeRecord(active, handle, claimed.seq === identity.seq ? line : formatEventLine(record.event, undefined, claimed));
2163
- noteSegmentLine(open.segment, claimed.seq);
2164
- if (currentSegmentSize(open.segment) === undefined) {
2165
- persistPostWriteMutation(active, record.event, cursor);
2166
- throw new PostWriteMutationError();
2167
- }
2168
- return bytes;
2169
- }
2170
- // Order inside one segment: queued storage evidence (safe-open first), then the loss a blocking
2171
- // condition caused while writing was impossible, then the caller's own record. A blocking count is
2172
- // cleared only once its line is on disk, so a still-full disk accumulates one exact count instead of
2173
- // queueing a line per failed attempt.
2174
- function nextRecord(active, cursor, caller) {
2175
- const queued = active.pendingEvidence[0];
2176
- if (queued !== undefined)
2177
- return { kind: "queued", record: queued };
2178
- const blocked = [...active.blocked.entries()][0];
2179
- if (blocked !== undefined) {
2180
- const [state, droppedEventCount] = blocked;
2181
- const event = pressureEvidence({ state, droppedEventCount }, active.config, cursor.correlationId);
2182
- return { kind: "blocked", state, record: { event, capability: "degraded" } };
2183
- }
2184
- return caller === undefined
2185
- ? undefined
2186
- : { kind: "caller", record: { event: caller, capability: "active" } };
2187
- }
2188
- function consumeRecord(active, source) {
2189
- if (source.kind === "queued")
2190
- active.pendingEvidence.shift();
2191
- else if (source.kind === "blocked")
2192
- active.blocked.delete(source.state);
2193
- }
2194
- function placeRecord(active, open, cursor, source) {
2195
- let bytes;
2196
- try {
2197
- bytes = appendIfFits(active, open, cursor, source.record);
2198
- }
2199
- catch (error) {
2200
- if (source.kind === "caller" || !(error instanceof ActivityLogEventValidationError))
2201
- throw error;
2202
- // A storage-evidence record the registry rejects is dropped and reported; it must never block
2203
- // every later write behind it.
2204
- consumeRecord(active, source);
2205
- recordActivityLogLoss("schema-rejected");
2206
- reportServerLogFailure(error, { op: source.record.event.op, loss: "event-dropped" });
2207
- return { status: "skipped" };
2208
- }
2209
- if (bytes === 0)
2210
- return { status: "full" };
2211
- consumeRecord(active, source);
2212
- return { status: "placed", bytes };
2213
- }
2214
- function rollOver(active, cursor, rollovers) {
2215
- if (rollovers >= MAX_ROLLOVERS_PER_WRITE)
2216
- throw new ActivityLogBackpressureError();
2217
- rotateSegment(active, cursor, "size-limit");
2218
- return rollovers + 1;
2219
- }
2220
- // Writes every queued evidence record and blocking-loss count, then `caller`, rolling over to a new
2221
- // segment whenever the next record would pass the byte bound. Bounded: a write that cannot be placed
2222
- // after a handful of rollovers is dropped and reported rather than looping.
2223
- function writeQueued(active, cursor, caller) {
2224
- let pendingCaller = caller;
2225
- let rollovers = 0;
2226
- let open;
2227
- for (;;) {
2228
- open ??= ensureSegment(active, cursor);
2229
- const source = nextRecord(active, cursor, pendingCaller);
2230
- if (source === undefined)
2231
- return;
2232
- const placement = placeRecord(active, open, cursor, source);
2233
- if (placement.status === "full") {
2234
- rollovers = rollOver(active, cursor, rollovers);
2235
- open = undefined;
2236
- continue;
2237
- }
2238
- if (placement.status === "placed") {
2239
- open = { segment: open.segment, sizeBytes: open.sizeBytes + placement.bytes };
2240
- }
2241
- if (source.kind === "caller")
2242
- pendingCaller = undefined;
2243
- }
2244
- }
2245
- function blockingPressure(error) {
2246
- if (error instanceof ActivityLogDiskFullError)
2247
- return "disk-full";
2248
- if (error instanceof ActivityLogBackpressureError)
2249
- return "backpressure";
2250
- return error instanceof ActivityLogBudgetError ? "budget-exceeded" : undefined;
2251
- }
2252
- // Counts lost events in the process-wide loss ledger (#3532) that the loss summary and readiness
2253
- // read: a registry rejection as schema-rejected, every other failure as persistence-failed.
2254
- function recordPersistenceLoss(error, count = 1) {
2255
- recordActivityLogLoss(error instanceof ActivityLogEventValidationError ? "schema-rejected" : "persistence-failed", count);
2256
- }
2257
- function recordDroppedEvent(active, error) {
2258
- recordPersistenceLoss(error);
2259
- if (active.segment !== undefined)
2260
- active.segment.droppedEvents += 1;
2261
- const state = blockingPressure(error);
2262
- if (state === undefined)
2263
- return;
2264
- active.blocked.set(state, (active.blocked.get(state) ?? 0) + 1);
2265
- }
2266
- // A write rotates an expired segment make-before-break; only the idle-segment timer seals one
2267
- // without opening the next.
2268
- function rotateIfExpired(active, cursor) {
2269
- const segment = active.segment;
2270
- if (segment === undefined)
2271
- return;
2272
- const reason = segmentExpiryReason(segment, active.config);
2273
- if (reason !== undefined)
2274
- rotateSegment(active, cursor, reason);
2275
- }
2276
- function persistCallerEvent(active, event, cursor) {
2277
- rotateIfExpired(active, cursor);
2278
- writeQueued(active, cursor, event);
2279
- }
2280
- function closeActiveLog(active) {
2281
- const cursor = { claimed: undefined, correlationId: undefined };
2282
- if (active.pendingEvidence.length > 0 || active.blocked.size > 0) {
2283
- try {
2284
- writeQueued(active, cursor, undefined);
2285
- }
2286
- catch (error) {
2287
- // Nothing can be persisted for this directory now; the loss is reported once, not retried at
2288
- // every later close. Each queued record and each blocked-loss line is one lost event.
2289
- recordPersistenceLoss(error, active.pendingEvidence.length + active.blocked.size);
2290
- active.pendingEvidence.length = 0;
2291
- active.blocked.clear();
2292
- reportServerLogFailure(error, {
2293
- op: SERVER_LOG_SAFE_OPEN_OPERATION.op,
2294
- loss: "event-dropped",
2295
- });
2296
- }
2297
- }
2298
- sealSegment(active, cursor, "close");
2299
- }
2300
- // Seals every open Activity Log segment. Called by the server logger's shutdown/reset path, and by
2301
- // tests so a suite does not leave descriptors behind. A subsequent write opens a new segment:
2302
- // closing releases an OS resource and completes a segment, it never disables the log.
2303
- //
2304
- // The registry entries themselves are KEPT so a sink created after a shutdown shares the same
2305
- // per-directory state (segment index, pressure, failure memory) instead of building a second one.
2306
- export function closeFileServerLogSinks() {
2307
- for (const active of activeLogs.values())
2308
- closeActiveLog(active);
2309
- }
2310
- export function createFileServerLogSink(stateDir, options = {}) {
2311
- const directory = join(stateDir, "logs");
2312
- try {
2313
- mkdirSync(directory, { recursive: true, mode: 0o700 });
2314
- }
2315
- catch {
2316
- // A configured production Activity Log is mandatory reconstruction evidence. Returning the
2317
- // null sink here made startup appear healthy while every later operation was silently
2318
- // unevidenced. Fail with the existing closed filesystem classification instead; callers that
2319
- // intentionally need no persistence must choose nullServerLogSink() explicitly.
2320
- throw new SafeArtifactFileError("activity-log", "open-failed");
2321
- }
2322
- const env = options.env ?? process.env;
2323
- const active = resolveActiveLog(directory, resolveActivityLogStorageConfig(env));
2324
- const threshold = options.level ?? resolveServerLogThreshold(env);
2325
- return createFileSinkFacade(active, threshold, stateDir);
2326
- }
2327
- function failureLoss(error) {
2328
- return error instanceof PostWriteMutationError ? "event-location-unknown" : "event-dropped";
2329
- }
2330
- // Split out so `createFileServerLogSink` stays inside the 50-line ceiling.
2331
- function createFileSinkFacade(active, threshold, stateDir) {
2332
- return {
2333
- write(event) {
2334
- // The threshold check comes before any formatting: a filtered event costs one comparison.
2335
- if (!serverLogLevelEnabled(eventLevel(event), threshold))
2336
- return;
2337
- ensureGovernedPolicy(active, event.correlationId);
2338
- const identity = allocateServerLogIdentity();
2339
- try {
2340
- persistCallerEvent(active, event, {
2341
- claimed: identity,
2342
- correlationId: event.correlationId,
2343
- });
2344
- }
2345
- catch (error) {
2346
- // Writing must never take the server down; a full disk, an exhausted budget or a file
2347
- // removed under us drops the line. It does NOT drop the fact that it happened: a log that
2348
- // has stopped working is exactly the condition an operator cannot infer from the absence
2349
- // of lines, so the loss is counted for the next persisted pressure line and announced on
2350
- // the independent stderr channel now.
2351
- recordDroppedEvent(active, error);
2352
- reportServerLogFailure(error, {
2353
- op: event.op,
2354
- correlationId: event.correlationId,
2355
- identity,
2356
- loss: failureLoss(error),
2357
- });
2358
- return;
2359
- }
2360
- // #3533: a persisted, eligible failure becomes a local incident candidate. Never throws; a
2361
- // dropped line (above) never triggers, so a failing store cannot amplify its own failure.
2362
- observeSupportIncidentTrigger(stateDir, event);
2363
- },
2364
- flush() {
2365
- // `writeSync` leaves nothing in user space, so a flush is already complete on return.
2366
- },
2367
- close() {
2368
- // The segment belongs to the shared per-directory store, so this seals it for every sink on
2369
- // the directory. That is correct for a shutdown path and harmless otherwise: the next write
2370
- // opens a new segment.
2371
- closeActiveLog(active);
2372
- },
2373
- };
2374
- }
2375
- function validPinRequest(request, nowMs) {
2376
- const expiresAtMs = Reflect.get(request, "expiresAtMs");
2377
- const reason = Reflect.get(request, "reason");
2378
- return (isActivityLogPinScope(Reflect.get(request, "scope")) &&
2379
- typeof expiresAtMs === "number" &&
2380
- Number.isSafeInteger(expiresAtMs) &&
2381
- expiresAtMs > nowMs &&
2382
- expiresAtMs - nowMs <= MAX_ACTIVITY_LOG_PIN_DURATION_MS &&
2383
- (reason === undefined || reason === "incident" || reason === "durable-batch"));
2384
- }
2385
- function copyPinScope(scope) {
2386
- return scope.kind === "window"
2387
- ? { kind: "window", fromMs: scope.fromMs, toMs: scope.toMs }
2388
- : { kind: "segments", segmentIds: [...scope.segmentIds] };
2389
- }
2390
- function rejectedPin(request, reason, scope) {
2391
- return {
2392
- result: { status: "rejected", reason },
2393
- facts: {
2394
- pinId: undefined,
2395
- status: "rejected",
2396
- rejectionReason: reason,
2397
- scope,
2398
- reason: request.reason === "durable-batch" ? "durable-batch" : "incident",
2399
- pinnedSegmentCount: 0,
2400
- pinnedBytes: 0,
2401
- expiresInSeconds: 0,
2402
- quotaStatus: undefined,
2403
- },
2404
- };
2405
- }
2406
- // The pin API is reachable from a sink's own write path, which never throws, so a directory that
2407
- // cannot be listed (EACCES, EMFILE, …) becomes a closed outcome here instead of an exception.
2408
- function listingOrUndefined(directory) {
2409
- try {
2410
- return listActivityLogDirectory(directory);
2411
- }
2412
- catch {
2413
- return undefined;
2414
- }
2415
- }
2416
- function pinOutcome(active, record, nowMs, preSealListing) {
2417
- // The record is already published, so a listing that fails after the seal still reports the pin,
2418
- // from the listing taken before it.
2419
- const listing = listingOrUndefined(active.directory) ?? preSealListing;
2420
- const reads = readActivityLogPins(listing, active.trustedRoot);
2421
- const protection = planActivityLogPinProtection(listing.files, activeActivityLogPins(reads, nowMs), active.config.pinQuotaBytes);
2422
- const covered = listing.files.filter((entry) => entry.file.kind === "sealed" &&
2423
- isActivityLogSegmentEntry(entry) &&
2424
- activityLogPinCovers(record, entry));
2425
- const quotaStatus = covered.every((entry) => protection.protectedNames.has(entry.file.name))
2426
- ? "within-quota"
2427
- : "exceeded";
2428
- const pinnedBytes = covered.reduce((sum, entry) => sum + entry.sizeBytes, 0);
2429
- return {
2430
- result: {
2431
- status: "pinned",
2432
- pinId: record.pinId,
2433
- pinnedSegmentCount: covered.length,
2434
- pinnedBytes,
2435
- quotaStatus,
2436
- },
2437
- facts: {
2438
- pinId: record.pinId,
2439
- status: "created",
2440
- rejectionReason: undefined,
2441
- scope: record.scope,
2442
- reason: record.reason,
2443
- pinnedSegmentCount: covered.length,
2444
- pinnedBytes,
2445
- expiresInSeconds: Math.ceil((record.expiresAtMs - nowMs) / 1000),
2446
- quotaStatus,
2447
- },
2448
- };
2449
- }
2450
- function createPin(active, request, cursor, nowMs) {
2451
- if (!validPinRequest(request, nowMs))
2452
- return rejectedPin(request, "invalid-request", undefined);
2453
- const scope = copyPinScope(request.scope);
2454
- const listing = listingOrUndefined(active.directory);
2455
- if (listing === undefined)
2456
- return rejectedPin(request, "storage-unavailable", scope);
2457
- const pins = activeActivityLogPins(readActivityLogPins(listing, active.trustedRoot), nowMs);
2458
- if (pins.length >= MAX_ACTIVITY_LOG_PINS)
2459
- return rejectedPin(request, "pin-limit-reached", scope);
2460
- const record = {
2461
- schemaVersion: 1,
2462
- pinId: randomBytes(12).toString("hex"),
2463
- reason: request.reason ?? "incident",
2464
- createdAtMs: nowMs,
2465
- expiresAtMs: request.expiresAtMs,
2466
- scope,
2467
- };
2468
- try {
2469
- // Published before the seal, so the retention pass the next segment runs already honors it.
2470
- writeActivityLogPinRecord(active.directory, active.trustedRoot, record);
2471
- }
2472
- catch {
2473
- return rejectedPin(request, "storage-unavailable", scope);
2474
- }
2475
- sealSegment(active, cursor, "pin-request");
2476
- return pinOutcome(active, record, nowMs, listing);
2477
- }
2478
- function storeForStateDir(stateDir, env) {
2479
- const directory = join(stateDir, "logs");
2480
- mkdirSync(directory, { recursive: true, mode: 0o700 });
2481
- return resolveGovernedActiveLog(directory, env);
2482
- }
2483
- function persistPinLine(active, cursor, op, build) {
2484
- let queued = false;
2485
- try {
2486
- queueEvidence(active, build());
2487
- queued = true;
2488
- writeQueued(active, cursor, undefined);
2489
- }
2490
- catch (error) {
2491
- // Queued evidence survives a failed write: the next write persists it, and a close that still
2492
- // cannot write counts and reports it as lost. Only evidence that never reached the queue is lost.
2493
- if (queued)
2494
- return;
2495
- recordPersistenceLoss(error);
2496
- reportServerLogFailure(error, {
2497
- op,
2498
- correlationId: cursor.correlationId,
2499
- loss: failureLoss(error),
2500
- });
2501
- }
2502
- }
2503
- function persistPinEvidence(active, cursor, facts) {
2504
- persistPinLine(active, cursor, ACTIVITY_LOG_PIN_CREATED_OPERATION.op, () => pinCreatedEvidence(facts, cursor.correlationId));
2505
- }
2506
- /**
2507
- * Pins a bounded time window (across every process instance, including segments sealed later
2508
- * inside it) or an explicit set of segments against retention until `expiresAtMs`. Seals this
2509
- * process's active segment, publishes one closed-grammar pin record, and evidences the request.
2510
- * Pinned segments are protected only within the reserved pin quota; a pin the quota cannot hold is
2511
- * still recorded, reports `quotaStatus: "exceeded"`, and produces one quota-exhaustion loss marker.
2512
- */
2513
- export function pinActivityLogWindow(stateDir, request, env = process.env) {
2514
- let active;
2515
- try {
2516
- active = storeForStateDir(stateDir, env);
2517
- }
2518
- catch (error) {
2519
- recordActivityLogLoss("persistence-failed");
2520
- reportServerLogFailure(error, {
2521
- op: ACTIVITY_LOG_PIN_CREATED_OPERATION.op,
2522
- correlationId: request.correlationId,
2523
- loss: "event-dropped",
2524
- });
2525
- return { status: "rejected", reason: "storage-unavailable" };
2526
- }
2527
- const cursor = { claimed: undefined, correlationId: request.correlationId };
2528
- const attempt = createPin(active, request, cursor, Date.now());
2529
- persistPinEvidence(active, cursor, attempt.facts);
2530
- return attempt.result;
2531
- }
2532
- function persistPinExpiry(active, cursor, facts) {
2533
- persistPinLine(active, cursor, ACTIVITY_LOG_PIN_EXPIRED_OPERATION.op, () => pinExpiredEvidence(facts, cursor.correlationId));
2534
- }
2535
- function releaseFacts(pinId, removed, coverage) {
2536
- return {
2537
- pinId,
2538
- reason: "released",
2539
- removed,
2540
- releasedSegmentCount: coverage.count,
2541
- releasedBytes: coverage.bytes,
2542
- };
2543
- }
2544
- function releaseListedPin(active, cursor, pinId) {
2545
- const listing = listingOrUndefined(active.directory);
2546
- if (listing === undefined) {
2547
- persistPinExpiry(active, cursor, releaseFacts(pinId, false, { count: 0, bytes: 0 }));
2548
- return { status: "rejected", reason: "storage-unavailable" };
2549
- }
2550
- const read = readActivityLogPins(listing, active.trustedRoot).find((candidate) => candidate.entry.pinId === pinId);
2551
- if (read === undefined)
2552
- return { status: "rejected", reason: "not-found" };
2553
- const coverage = pinCoverage(read.record, listing.files);
2554
- const removed = removePinRecordQuietly(active, read);
2555
- persistPinExpiry(active, cursor, releaseFacts(pinId, removed, coverage));
2556
- return removed
2557
- ? { status: "released", releasedSegmentCount: coverage.count, releasedBytes: coverage.bytes }
2558
- : { status: "rejected", reason: "removal-failed" };
2559
- }
2560
- /**
2561
- * Releases one retention pin before its expiry, for example once the incident it protected was
2562
- * reported or dismissed (#3533). The closed-grammar record is removed through the guarded,
2563
- * identity-bound unlink and evidenced as `activity-log.pin.expired` with `expiryReason:
2564
- * "released"`; the segments it protected return to normal retention. Never throws: an unknown pin
2565
- * is `not-found`, and an unlistable directory or a failed removal is a closed, evidenced rejection.
2566
- */
2567
- export function releaseActivityLogPin(stateDir, request, env = process.env) {
2568
- if (!isActivityLogPinId(Reflect.get(request, "pinId"))) {
2569
- return { status: "rejected", reason: "invalid-request" };
2570
- }
2571
- let active;
2572
- try {
2573
- active = storeForStateDir(stateDir, env);
2574
- }
2575
- catch (error) {
2576
- recordActivityLogLoss("persistence-failed");
2577
- reportServerLogFailure(error, {
2578
- op: ACTIVITY_LOG_PIN_EXPIRED_OPERATION.op,
2579
- correlationId: request.correlationId,
2580
- loss: "event-dropped",
2581
- });
2582
- return { status: "rejected", reason: "storage-unavailable" };
2583
- }
2584
- const cursor = { claimed: undefined, correlationId: request.correlationId };
2585
- return releaseListedPin(active, cursor, request.pinId);
2586
- }
2587
- const PRESSURE_SEVERITY = {
2588
- none: "none",
2589
- "low-disk-space": "elevated",
2590
- "retention-blocked": "elevated",
2591
- backpressure: "elevated",
2592
- "disk-full": "critical",
2593
- "budget-exceeded": "critical",
2594
- };
2595
- function ownedDirectory(path, requireOwnerOnly) {
2596
- try {
2597
- const stat = lstatSync(path);
2598
- if (!stat.isDirectory() || stat.isSymbolicLink())
2599
- return false;
2600
- if (process.platform === "win32")
2601
- return true;
2602
- const owner = process.geteuid?.();
2603
- if (owner === undefined || stat.uid !== owner)
2604
- return false;
2605
- return !requireOwnerOnly || (stat.mode & 0o777) === 0o700;
2606
- }
2607
- catch {
2608
- return false;
2609
- }
2610
- }
2611
- function storageWritable(stateDir, directory) {
2612
- return pathMissing(directory) ? ownedDirectory(stateDir, false) : ownedDirectory(directory, true);
2613
- }
2614
- function orphanedSegmentCount(files, config, currentName) {
2615
- const context = {
2616
- pid: process.pid,
2617
- instanceId: INSTANCE_ID,
2618
- currentName,
2619
- nowMs: Date.now(),
2620
- segmentSeconds: config.segmentSeconds,
2621
- isAlive: processIsAlive,
2622
- };
2623
- return files.filter((entry) => isActivityLogSegmentEntry(entry) && activityLogOrphanOwner(entry, context) !== undefined).length;
2624
- }
2625
- function derivedPressure(active, unprotectedBytes, config, freeBytes) {
2626
- const blocked = active === undefined ? undefined : [...active.blocked.keys()][0];
2627
- if (blocked !== undefined)
2628
- return blocked;
2629
- if (active?.standingPressure !== undefined)
2630
- return active.standingPressure;
2631
- if (unprotectedBytes > config.retentionBytes)
2632
- return "budget-exceeded";
2633
- return freeBytes !== undefined && freeBytes < activityLogLowDiskThresholdBytes(config)
2634
- ? "low-disk-space"
2635
- : "none";
2636
- }
2637
- function countKind(files, kinds) {
2638
- return files.filter((entry) => kinds.has(entry.file.kind)).length;
2639
- }
2640
- function storageSnapshot(stateDir, directory, config) {
2641
- const listing = listActivityLogDirectory(directory);
2642
- const reads = readActivityLogPins(listing, directory);
2643
- const protection = planActivityLogPinProtection(listing.files, activeActivityLogPins(reads, Date.now()), config.pinQuotaBytes);
2644
- const pinRecordSize = reads.reduce((sum, read) => sum + read.entry.sizeBytes, 0);
2645
- return {
2646
- listing,
2647
- usedBytes: listing.files.reduce((sum, entry) => sum + entry.sizeBytes, 0) + pinRecordSize,
2648
- pinnedBytes: protection.protectedBytes,
2649
- freeBytes: activityLogFreeBytes(pathMissing(directory) ? stateDir : directory),
2650
- };
2651
- }
2652
- /**
2653
- * A cheap, read-only snapshot of the Activity Log store: one directory listing, the small pin
2654
- * records, and one `statfs`. Never creates, seals, or deletes anything.
2655
- */
2656
- // Read-only: never publishes or replaces the stored policy, only prefers it when present so a
2657
- // probe run before this process has become a writer (e.g. `keiko status`) still reports the
2658
- // governing budget instead of this process's own unreconciled env view.
2659
- function peekGovernedStorageConfig(directory, env) {
2660
- const envConfig = resolveActivityLogStorageConfig(env);
2661
- const stored = readActivityLogPolicyRecord(directory, directory);
2662
- return stored === undefined ? envConfig : applyGovernedPolicy(envConfig, stored);
2663
- }
2664
- export function activityLogStorageHealth(stateDir, env = process.env) {
2665
- const directory = join(stateDir, "logs");
2666
- const active = activeLogs.get(activeLogKey(directory));
2667
- const config = active?.config ?? peekGovernedStorageConfig(directory, env);
2668
- const snapshot = storageSnapshot(stateDir, directory, config);
2669
- const writer = writerView(active);
2670
- const files = snapshot.listing.files;
2671
- const unprotectedBytes = snapshot.usedBytes - snapshot.pinnedBytes;
2672
- const pressureState = derivedPressure(active, unprotectedBytes, config, snapshot.freeBytes);
2673
- return {
2674
- writable: storageWritable(stateDir, directory) && !writer.blocked,
2675
- usedBytes: snapshot.usedBytes,
2676
- budgetBytes: config.retentionBytes,
2677
- pinQuotaBytes: config.pinQuotaBytes,
2678
- pinnedBytes: snapshot.pinnedBytes,
2679
- ...(snapshot.freeBytes === undefined ? {} : { freeBytes: snapshot.freeBytes }),
2680
- activeSegments: countKind(files, new Set(["active"])),
2681
- sealedSegments: countKind(files, new Set(["sealed"])),
2682
- legacyFiles: countKind(files, new Set(["legacy-archive", "legacy-current"])),
2683
- orphanedSegments: orphanedSegmentCount(files, config, writer.currentName),
2684
- pressure: PRESSURE_SEVERITY[pressureState],
2685
- pressureState,
2686
- recoveredSegments: writer.recoveredSegments,
2687
- };
2688
- }
2689
- function writerView(active) {
2690
- if (active === undefined)
2691
- return { blocked: false, currentName: undefined, recoveredSegments: 0 };
2692
- return {
2693
- blocked: active.blocked.size > 0,
2694
- currentName: active.segment?.activeName,
2695
- recoveredSegments: active.recoveredSegments,
2696
- };
2697
- }
2698
- /**
2699
- * Every Activity Log file of `stateDir` a reader reads, legacy and segmented, in logical-log order:
2700
- * one name per segment, so a seal caught between its link and unlink is never read twice.
2701
- */
2702
- export function listActivityLogFiles(stateDir) {
2703
- const entries = listActivityLogDirectory(join(stateDir, "logs")).files;
2704
- const readable = new Set(readableActivityLogFileNames(entries.map((entry) => entry.file)));
2705
- return entries
2706
- .filter((entry) => readable.has(entry.file))
2707
- .map((entry) => ({
2708
- name: entry.file.name,
2709
- path: entry.path,
2710
- kind: entry.file.kind,
2711
- sizeBytes: entry.sizeBytes,
2712
- }));
2713
- }
2714
- function durableLogDirectory(directory) {
2715
- try {
2716
- const stat = lstatSync(directory);
2717
- return stat.isDirectory() && !stat.isSymbolicLink();
2718
- }
2719
- catch {
2720
- return false;
2721
- }
2722
- }
2723
- function openLogDirectoryGuard(path) {
2724
- const before = lstatSync(path);
2725
- if (!before.isDirectory() || before.isSymbolicLink())
2726
- return undefined;
2727
- let handle;
2728
- try {
2729
- const directoryFlag = typeof constants.O_DIRECTORY === "number" ? constants.O_DIRECTORY : 0;
2730
- const noFollowFlag = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
2731
- handle = openSync(path, constants.O_RDONLY | directoryFlag | noFollowFlag);
2732
- return validateOpenedLogDirectory(path, before.dev, before.ino, handle);
2733
- }
2734
- catch {
2735
- if (handle !== undefined)
2736
- closeSync(handle);
2737
- return windowsLogDirectoryGuard(path, before.dev, before.ino);
2738
- }
2739
- }
2740
- function validateOpenedLogDirectory(path, dev, ino, handle) {
2741
- const opened = fstatSync(handle);
2742
- const pathname = lstatSync(path);
2743
- if (!opened.isDirectory() ||
2744
- !pathname.isDirectory() ||
2745
- pathname.isSymbolicLink() ||
2746
- opened.dev !== pathname.dev ||
2747
- opened.ino !== pathname.ino ||
2748
- opened.dev !== dev ||
2749
- opened.ino !== ino) {
2750
- throw new Error("log directory changed");
2751
- }
2752
- return { path, dev: opened.dev, ino: opened.ino, handle };
2753
- }
2754
- function windowsLogDirectoryGuard(path, dev, ino) {
2755
- if (process.platform !== "win32")
2756
- return undefined;
2757
- const after = lstatSync(path);
2758
- if (!after.isDirectory() || after.isSymbolicLink() || after.dev !== dev || after.ino !== ino) {
2759
- return undefined;
2760
- }
2761
- return { path, dev: after.dev, ino: after.ino, handle: undefined };
2762
- }
2763
- function logDirectoryStillSame(guard) {
2764
- try {
2765
- const pathname = lstatSync(guard.path);
2766
- if (!pathname.isDirectory() ||
2767
- pathname.isSymbolicLink() ||
2768
- pathname.dev !== guard.dev ||
2769
- pathname.ino !== guard.ino) {
2770
- return false;
2771
- }
2772
- if (guard.handle === undefined)
2773
- return process.platform === "win32";
2774
- const opened = fstatSync(guard.handle);
2775
- return opened.isDirectory() && opened.dev === guard.dev && opened.ino === guard.ino;
2776
- }
2777
- catch {
2778
- return false;
2779
- }
2780
- }
2781
- function closeLogDirectoryGuards(guards) {
2782
- for (const guard of guards) {
2783
- if (guard.handle !== undefined)
2784
- closeSync(guard.handle);
2785
- }
2786
- }
2787
- // Legacy files and segments pinned for durable batches: the only places a completed earlier batch
2788
- // can live, and a set whose size is bounded by the legacy window and the pin quota.
2789
- function durableBatchScope(active, nowMs) {
2790
- const listing = listActivityLogDirectory(active.directory);
2791
- const pinned = new Set();
2792
- for (const pin of activeActivityLogPins(readActivityLogPins(listing, active.trustedRoot), nowMs)) {
2793
- if (pin.reason !== "durable-batch" || pin.scope.kind !== "segments")
2794
- continue;
2795
- for (const segmentId of pin.scope.segmentIds)
2796
- pinned.add(segmentId);
2797
- }
2798
- return listing.files
2799
- .filter((entry) => !isActivityLogSegmentEntry(entry) || pinned.has(entry.file.segmentId))
2800
- .map((entry) => entry.file.name);
2801
- }
2802
- // Formats every event once with a provisional identity before anything is written, so an invalid or
2803
- // oversized event defers the whole batch instead of leaving half of it in the log.
2804
- function batchIsWritable(events) {
2805
- try {
2806
- return events.every((event) => {
2807
- const line = formatEventLine(event, undefined, {
2808
- ...serverLogProcessIdentity(),
2809
- seq: nextProcessSeq,
2810
- });
2811
- return serverLogLineWithinCap(line) && line.includes(`"op":"${redactLogLabel(event.op)}"`);
2812
- });
2813
- }
2814
- catch {
2815
- return false;
2816
- }
2817
- }
2818
- function syncActiveSegment(active) {
2819
- const handle = active.segment?.handle;
2820
- if (handle === undefined || handle === null)
2821
- return false;
2822
- try {
2823
- fsyncSync(handle);
2824
- return true;
2825
- }
2826
- catch {
2827
- return false;
2828
- }
2829
- }
2830
- function writeDurableEvents(active, events, segmentIds) {
2831
- for (const event of events) {
2832
- const cursor = { claimed: undefined, correlationId: event.correlationId };
2833
- try {
2834
- writeQueued(active, cursor, event);
2835
- }
2836
- catch (error) {
2837
- recordDroppedEvent(active, error);
2838
- return false;
2839
- }
2840
- const segmentId = active.segment?.segmentId;
2841
- if (segmentId !== undefined)
2842
- segmentIds.add(segmentId);
2843
- }
2844
- return true;
2845
- }
2846
- function pinDurableBatch(active, segmentIds, correlationId) {
2847
- const cursor = { claimed: undefined, correlationId };
2848
- const pinned = createPin(active, {
2849
- scope: { kind: "segments", segmentIds: [...segmentIds] },
2850
- expiresAtMs: Date.now() + MAX_ACTIVITY_LOG_PIN_DURATION_MS,
2851
- reason: "durable-batch",
2852
- }, cursor, Date.now());
2853
- persistPinEvidence(active, cursor, pinned.facts);
2854
- return pinned.result.status === "pinned";
2855
- }
2856
- function appendInspectedBatch(active, events, guards, options) {
2857
- if (events.some((event) => !serverLogLevelEnabled(eventLevel(event), options.level))) {
2858
- return { status: "deferred", reason: "level-filtered" };
2859
- }
2860
- if (events.length === 0)
2861
- return { status: "appended", appendedCount: 0 };
2862
- if (!batchIsWritable(events))
2863
- return { status: "deferred", reason: "append-failed" };
2864
- const segmentIds = new Set();
2865
- if (!writeDurableEvents(active, events, segmentIds)) {
2866
- return { status: "deferred", reason: "append-failed" };
2867
- }
2868
- if (!syncActiveSegment(active))
2869
- return { status: "deferred", reason: "durability-uncertain" };
2870
- if (!guards.every(logDirectoryStillSame)) {
2871
- return { status: "deferred", reason: "destination-mutated" };
2872
- }
2873
- if (options.retention === "pinned" &&
2874
- !pinDurableBatch(active, segmentIds, events[0]?.correlationId)) {
2875
- return { status: "deferred", reason: "durability-uncertain" };
2876
- }
2877
- return { status: "appended", appendedCount: events.length };
2878
- }
2879
- function prepareDurableDirectory(stateDir, guards) {
2880
- const stateGuard = openLogDirectoryGuard(stateDir);
2881
- if (stateGuard === undefined)
2882
- return undefined;
2883
- guards.push(stateGuard);
2884
- const directory = join(stateDir, "logs");
2885
- mkdirSync(directory, { recursive: true, mode: 0o700 });
2886
- if (!durableLogDirectory(directory))
2887
- return undefined;
2888
- const logGuard = openLogDirectoryGuard(directory);
2889
- if (logGuard === undefined)
2890
- return undefined;
2891
- guards.push(logGuard);
2892
- return resolveGovernedActiveLog(directory, process.env);
2893
- }
2894
- function inspectAndAppendDurableBatch(active, guards, options) {
2895
- const inspection = options.inspect(active.directory, durableBatchScope(active, Date.now()));
2896
- if (!guards.every(logDirectoryStillSame)) {
2897
- return { status: "deferred", reason: "destination-mutated" };
2898
- }
2899
- if (inspection.status === "already-complete")
2900
- return { status: "already-complete" };
2901
- if (inspection.status === "deferred")
2902
- return { status: "inspection-deferred" };
2903
- return appendInspectedBatch(active, inspection.events, guards, options);
2904
- }
2905
- // Synchronous by design: `inspect` and the append share one JavaScript stack. The batch is written
2906
- // through the ordinary segment writer (bounds, rollover and evidence apply unchanged), fsynced, and
2907
- // its segments are then pinned with reason `durable-batch`, so a later inspection finds the
2908
- // completed batch among a bounded set of files and retention can never age it out. Concurrent
2909
- // imports by two processes can still append duplicate physical records; callers obtain semantic
2910
- // deduplication from their stable record identities, never an exactly-once filesystem claim.
2911
- export function appendDurableServerLogBatch(stateDir, options) {
2912
- if (!serverLogLevelEnabled("info", options.level)) {
2913
- return { status: "deferred", reason: "level-filtered" };
2914
- }
2915
- const guards = [];
2916
- try {
2917
- const active = prepareDurableDirectory(stateDir, guards);
2918
- return active === undefined
2919
- ? { status: "deferred", reason: "destination-unsafe" }
2920
- : inspectAndAppendDurableBatch(active, guards, options);
2921
- }
2922
- catch {
2923
- return { status: "deferred", reason: "destination-unsafe" };
2924
- }
2925
- finally {
2926
- closeLogDirectoryGuards(guards);
2927
- }
2928
- }
2929
- // Test-only helper: buffered sink that keeps every event in memory so tests can assert on
2930
- // order and content without touching the filesystem. It captures RAW events and applies no
2931
- // threshold of its own, so a test can tell "the logger filtered this" from "the sink did".
2932
- //
2933
- // "Test-only" is enforced by where it is reachable from, not by the comment: it is exported from
2934
- // this module and from the in-package `observability/` barrel that every keiko-server test imports,
2935
- // and deliberately NOT from the package's public entry point. Nothing outside this package has a
2936
- // use for it, and a packaged export is a promise that has to be kept.
2937
- export function createBufferedServerLogSink() {
2938
- const events = [];
2939
- return {
2940
- events,
2941
- write(event) {
2942
- events.push(event);
2943
- },
2944
- lines() {
2945
- return events.map((event) => formatEventLine(event));
2946
- },
2947
- clear() {
2948
- events.length = 0;
2949
- },
2950
- };
2951
- }