create-principles-disciple 1.150.2 → 1.150.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/admission.js +2 -0
  3. package/codex-adapter/dist/pd-hook.d.ts +7 -5
  4. package/codex-adapter/dist/pd-hook.js +18 -7
  5. package/codex-adapter/dist/tool-semantics.js +5 -1
  6. package/codex-adapter/dist/worker/workspace-worker.js +4 -2
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/lib/utils.js +16 -1
  9. package/console/dist/web/assets/app.css +147 -46
  10. package/console/dist/web/assets/app.js +35 -32
  11. package/console/package.json +2 -0
  12. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  13. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  14. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  15. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  16. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  17. package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
  18. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  19. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  20. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  21. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  22. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  23. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  24. package/core/dist/runtime/adapter/context-budget.js +127 -0
  25. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  26. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  27. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  28. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  29. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  30. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  31. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
  32. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  33. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  34. package/core/dist/runtime/candidate-audit.js +2 -1
  35. package/core/dist/runtime/candidate-audit.js.map +1 -1
  36. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  37. package/core/dist/runtime/config/pd-config-effective.js +2 -0
  38. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  39. package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
  40. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  41. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  42. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  43. package/core/dist/runtime/config/pd-config-validate.js +134 -0
  44. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  45. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  46. package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
  47. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  48. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  49. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
  50. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  51. package/core/dist/runtime/index.d.ts +2 -0
  52. package/core/dist/runtime/index.d.ts.map +1 -1
  53. package/core/dist/runtime/index.js +2 -0
  54. package/core/dist/runtime/index.js.map +1 -1
  55. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
  56. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
  58. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  59. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
  60. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
  62. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  63. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
  64. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
  66. package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
  67. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
  69. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  70. package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
  72. package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
  73. package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
  74. package/core/dist/runtime/operator-health-read-model.js +2 -2
  75. package/core/dist/runtime/operator-health-read-model.js.map +1 -1
  76. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-recall-read-model.js +4 -3
  78. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  79. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  80. package/core/dist/runtime/pruning-read-model.js +3 -2
  81. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  82. package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
  83. package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
  84. package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
  85. package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
  86. package/core/dist/runtime/schema-conformance-read-model.js +2 -2
  87. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  88. package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
  89. package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
  90. package/core/dist/runtime/store/sqlite-connection.js +4 -12
  91. package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
  92. package/core/dist/runtime/store/storage-paths.d.ts +17 -0
  93. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
  94. package/core/dist/runtime/store/storage-paths.js +52 -0
  95. package/core/dist/runtime/store/storage-paths.js.map +1 -0
  96. package/core/dist/runtime/trajectory-retention.d.ts +257 -0
  97. package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
  98. package/core/dist/runtime/trajectory-retention.js +598 -0
  99. package/core/dist/runtime/trajectory-retention.js.map +1 -0
  100. package/core/dist/telemetry-event.d.ts +2 -2
  101. package/core/dist/telemetry-event.d.ts.map +1 -1
  102. package/core/dist/telemetry-event.js +5 -0
  103. package/core/dist/telemetry-event.js.map +1 -1
  104. package/core/dist/trajectory-store.d.ts +9 -9
  105. package/core/dist/trajectory-store.d.ts.map +1 -1
  106. package/core/dist/trajectory-store.js +9 -12
  107. package/core/dist/trajectory-store.js.map +1 -1
  108. package/core/package.json +1 -1
  109. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  110. package/dist/installers/codex-host-installer.js +92 -5
  111. package/dist/installers/codex-host-installer.js.map +1 -1
  112. package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
  113. package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
  114. package/dist/installers/mcp-binding-shape-mirror.js +105 -0
  115. package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
  116. package/dist/skill-catalog.d.ts +35 -0
  117. package/dist/skill-catalog.d.ts.map +1 -0
  118. package/dist/skill-catalog.js +85 -0
  119. package/dist/skill-catalog.js.map +1 -0
  120. package/dist/skill-delivery-parity.d.ts +22 -0
  121. package/dist/skill-delivery-parity.d.ts.map +1 -0
  122. package/dist/skill-delivery-parity.js +31 -0
  123. package/dist/skill-delivery-parity.js.map +1 -0
  124. package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
  125. package/host-runtime/dist/active-principle-prompt.js +15 -5
  126. package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
  127. package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
  128. package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
  129. package/host-runtime/dist/adaptive-priority-provider.js +65 -62
  130. package/host-runtime/dist/adaptive-selection.d.ts +67 -62
  131. package/host-runtime/dist/adaptive-selection.js +218 -301
  132. package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
  133. package/host-runtime/dist/adaptive-skip-decision.js +33 -29
  134. package/host-runtime/dist/codex-rule-context-provider.js +4 -1
  135. package/host-runtime/dist/governance-observation-store.d.ts +40 -1
  136. package/host-runtime/dist/governance-observation-store.js +188 -9
  137. package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
  138. package/host-runtime/dist/governance-signal-admission.js +12 -4
  139. package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
  140. package/host-runtime/dist/host-tool-declaration.js +67 -11
  141. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
  142. package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
  143. package/host-runtime/dist/index.d.ts +3 -0
  144. package/host-runtime/dist/index.js +14 -0
  145. package/host-runtime/dist/production-rulehost-gate.js +36 -4
  146. package/host-runtime/dist/trajectory-retention.d.ts +147 -0
  147. package/host-runtime/dist/trajectory-retention.js +907 -0
  148. package/host-runtime/package.json +1 -1
  149. package/install-layout/dist/index.d.ts +9 -2
  150. package/install-layout/dist/index.js +26 -9
  151. package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
  152. package/install-layout/dist/mcp-binding-contract.js +230 -0
  153. package/install-layout/package.json +1 -1
  154. package/package.json +4 -4
  155. package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
  156. package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
  157. package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
  158. package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
  159. package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
  160. package/pd-cli/dist/commands/codex-reconcile.js +11 -2
  161. package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
  162. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  163. package/pd-cli/dist/commands/codex-worker.js +35 -0
  164. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  165. package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
  166. package/pd-cli/dist/commands/command-helpers.js +1 -1
  167. package/pd-cli/dist/commands/errors-list.d.ts +1 -1
  168. package/pd-cli/dist/commands/errors-list.js +1 -1
  169. package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
  170. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  171. package/pd-cli/dist/commands/health-mcp.js +81 -22
  172. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  173. package/pd-cli/dist/commands/health.d.ts +1 -1
  174. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  175. package/pd-cli/dist/commands/health.js +12 -5
  176. package/pd-cli/dist/commands/health.js.map +1 -1
  177. package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
  178. package/pd-cli/dist/commands/principles-stats.js +1 -1
  179. package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
  180. package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
  181. package/pd-cli/dist/commands/trajectory-retention.js +159 -0
  182. package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
  183. package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
  184. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
  185. package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
  186. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
  187. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  188. package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
  189. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  190. package/pd-cli/dist/index.d.ts +1 -7
  191. package/pd-cli/dist/index.d.ts.map +1 -1
  192. package/pd-cli/dist/index.js +15 -1201
  193. package/pd-cli/dist/index.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts +17 -0
  195. package/pd-cli/dist/program.d.ts.map +1 -0
  196. package/pd-cli/dist/program.js +1263 -0
  197. package/pd-cli/dist/program.js.map +1 -0
  198. package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
  199. package/pd-cli/dist/services/delivery-surfaces.js +7 -5
  200. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  201. package/pd-cli/dist/services/version-report.d.ts.map +1 -1
  202. package/pd-cli/dist/services/version-report.js +30 -4
  203. package/pd-cli/dist/services/version-report.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/pd-mcp-server/dist/version.d.ts +1 -1
  206. package/pd-mcp-server/dist/version.js +1 -1
  207. package/pd-mcp-server/package.json +3 -1
  208. package/plugin/dist/bundle.js +477 -471
  209. package/plugin/dist/constants/tools.d.ts +8 -1
  210. package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
  211. package/plugin/dist/core/trajectory.d.ts +14 -0
  212. package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
  213. package/plugin/dist/hooks/gate.d.ts +7 -2
  214. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
  215. package/plugin/dist/index.d.ts +5 -0
  216. package/plugin/dist/openclaw.plugin.json +1 -1
  217. package/plugin/dist/rulehost-evidence.js +29 -23
  218. package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  219. package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  220. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  221. package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  222. package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  223. package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  224. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  225. package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  226. package/plugin/openclaw.plugin.json +1 -1
  227. package/plugin/package.json +1 -1
  228. package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  229. package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  230. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  231. package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  232. package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  233. package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  234. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  235. package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  236. package/release-manager/dist/installers/codex-host-installer.js +92 -5
  237. package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
  238. package/release-manager/package.json +1 -1
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
  241. package/workbuddy-adapter/dist/host-adapter.js +1 -0
  242. package/workbuddy-adapter/dist/index.d.ts +1 -0
  243. package/workbuddy-adapter/dist/index.js +1 -0
  244. package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
  245. package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
  246. package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
  247. package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
  248. package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
  249. package/workbuddy-adapter/dist/ingestion/index.js +13 -0
  250. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
  251. package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
  252. package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
  253. package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
  254. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
  255. package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
  256. package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
  257. package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
  258. package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
  259. package/workbuddy-adapter/dist/pd-hook.js +59 -2
  260. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
  261. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
  262. package/workbuddy-adapter/package.json +1 -1
  263. package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
  264. package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
  265. package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
  266. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
  267. package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
@@ -0,0 +1,554 @@
1
+ /**
2
+ * WorkBuddy session-transcript incremental decoder (PRI-1171 P2; SPEC v0.2
3
+ * §4.4, tech design §5.2–§5.4).
4
+ *
5
+ * WorkBuddy appends flat JSONL records (one record per line, no envelope
6
+ * wrapper) under `~/.workbuddy/projects/<encoded-cwd>/<sessionId>.jsonl`.
7
+ * The record-type baseline is frozen from the cross-period forensics in
8
+ * docs/plans/2026-08-28-workbuddy-session-transcript-access.md §8.1
9
+ * (message ×5 variants, function_call ×3, reasoning ×2,
10
+ * function_call_result / file-history-snapshot / ai-title / resend-fork-notice
11
+ * ×1) plus the `session-meta` head record observed on 2026-11-11 (absent
12
+ * from the Aug-28 census — tolerated as a known skip, see the mapping in
13
+ * projectRecord).
14
+ *
15
+ * Failure classes inherit the seam taxonomy (host-runtime
16
+ * conversation-ingestion/source.ts): an incomplete final line at EOF is a
17
+ * transient append boundary (checkpoint holds); a newline-terminated line
18
+ * that does not parse is a stable malformed record (stop, never advance
19
+ * past it); unknown-but-well-formed types are skipped with an aggregated,
20
+ * bounded warning and DO advance (rc-9: no silent skips).
21
+ *
22
+ * Privacy/semantics guardrails from the tech design:
23
+ * - `compactionTimestamp` is ALWAYS null — WorkBuddy compaction only
24
+ * APPENDS a summary record (forensics §8.2); history stays valid on
25
+ * disk, and the store treats that parameter as an active tombstone
26
+ * (tech design §5.4), so passing it would destroy live evidence.
27
+ * Markers surface as the aggregated `wb_compaction_marker` warning.
28
+ * - reasoning attribution never guesses: the parentId chain resolves
29
+ * within the decoded window or the observation lands
30
+ * partial + phase `unattributed` (tech design §4.8).
31
+ * - Ordinals are synthesized (the host file carries none): the caller
32
+ * seeds `startOrdinal` from the committed checkpoint so replays are
33
+ * stable; the durable replay identity is byte-based
34
+ * (`wb|<sessionId>|<byteOffset>`, tech design §5.3).
35
+ * - Host context is NOT Owner conversation: a user record wraps the real
36
+ * utterance in `<system-reminder>...</system-reminder>` blocks followed by
37
+ * `<user_query>...</user_query>` (forensic samples, 2026-11-11). Only the
38
+ * Owner utterance may become `visibleText`. Projecting the whole blob
39
+ * would persist host prompts as Owner behavior evidence, and the store's
40
+ * 200-char head-only bound would truncate the actual utterance away.
41
+ */
42
+ import { CONVERSATION_INGESTION_MAX_BATCH_RECORDS, planJsonlWindow, } from '@principles/host-runtime';
43
+ /** Distinct aggregated warning tokens per window (mirrors the Codex 16-warning bound). */
44
+ const MAX_WARNING_TOKENS = 16;
45
+ /** Max hops when resolving a reasoning parentId chain to its assistant record. */
46
+ const MAX_PARENT_CHAIN_HOPS = 8;
47
+ /** WorkBuddy user records: host context blocks + the Owner's utterance block. */
48
+ const USER_QUERY_BLOCK = /<user_query>([\s\S]*?)<\/user_query>/g;
49
+ const SYSTEM_REMINDER_BLOCK = /<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/g;
50
+ /** Runtime-contract guard (rc-1): a non-null, non-array object is the only trusted record shape. */
51
+ function isRecord(value) {
52
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
53
+ }
54
+ /** Read an OWN property only (rc-5): inherited names must never look like record fields. */
55
+ function own(value, key) {
56
+ return Object.hasOwn(value, key) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
57
+ }
58
+ /** Accept a string only when it carries content; empty strings are treated as absent. */
59
+ function nonEmptyString(value) {
60
+ return typeof value === 'string' && value.length > 0 ? value : null;
61
+ }
62
+ /** Join the `text` of content parts (input_text / output_text / reasoning_text all carry `.text`). */
63
+ function joinContentText(content) {
64
+ if (!Array.isArray(content))
65
+ return null;
66
+ const parts = [];
67
+ for (const item of content) {
68
+ if (!isRecord(item))
69
+ continue;
70
+ const text = own(item, 'text');
71
+ if (typeof text === 'string')
72
+ parts.push(text);
73
+ }
74
+ return parts.length > 0 ? parts.join('') : null;
75
+ }
76
+ /** Extract a bounded result preview: `{type:'text',text}` object or plain string (store sanitizes). */
77
+ function resultOutputPreview(output) {
78
+ if (typeof output === 'string')
79
+ return output;
80
+ if (isRecord(output))
81
+ return nonEmptyString(own(output, 'text'));
82
+ return null;
83
+ }
84
+ /**
85
+ * Count one occurrence of an aggregated warning token, bounded to
86
+ * MAX_WARNING_TOKENS distinct tokens so a hostile transcript cannot inflate
87
+ * diagnostics without bound. Overflow tokens are dropped — the cap itself is
88
+ * visible through the tokens already recorded.
89
+ */
90
+ function warnAggregated(context, token) {
91
+ if (context.warningCounts.size >= MAX_WARNING_TOKENS && !context.warningCounts.has(token))
92
+ return;
93
+ context.warningCounts.set(token, (context.warningCounts.get(token) ?? 0) + 1);
94
+ }
95
+ function warningList(context) {
96
+ return [...context.warningCounts.entries()].map(([token, count]) => `${token}:${count}`);
97
+ }
98
+ /**
99
+ * Project ONLY the Owner utterance from a WorkBuddy user record.
100
+ *
101
+ * A real user record is ~15KB of `<system-reminder>` host context (AGENTS,
102
+ * identity files, tool declarations, connector state) with the Owner's words
103
+ * in a trailing `<user_query>` block. Projecting that whole blob would persist
104
+ * host prompts as Owner behavior evidence AND lose the utterance: the store's
105
+ * `sanitizeString` keeps a 200-char head-only preview, which in 24/24 sampled
106
+ * real records contained none of the Owner's words.
107
+ *
108
+ * FAIL-CLOSED (P1 review): only the structured `<user_query>` boundary is
109
+ * trusted. Anything else — a renamed wrapper, a bare legacy record, an
110
+ * unclosed block — yields `null` (observation `partial`, warning, no
111
+ * visibleText). Never guess Owner intent from text shape.
112
+ */
113
+ function projectUserText(context, text) {
114
+ if (text === null)
115
+ return null;
116
+ // The ONLY accepted Owner boundary is the host's explicit <user_query>
117
+ // wrapper. A match INSIDE a <system-reminder> block belongs to host context
118
+ // (tool declarations or quoted transcripts can carry the token), never to
119
+ // the Owner, so those matches are ignored. An Owner who literally pasted
120
+ // `<system-reminder>` inside their query keeps it verbatim — we never strip
121
+ // inside the query block.
122
+ const hostContextRanges = [...text.matchAll(SYSTEM_REMINDER_BLOCK)].map((match) => {
123
+ const start = match.index ?? 0;
124
+ return [start, start + match[0].length];
125
+ });
126
+ const queryMatches = [...text.matchAll(USER_QUERY_BLOCK)].filter((match) => {
127
+ const start = match.index ?? 0;
128
+ return !hostContextRanges.some(([begin, end]) => start >= begin && start < end);
129
+ });
130
+ // Structure check (P2 review): a `<system-reminder>` without its closing tag,
131
+ // or a nested reminder, makes "inside host context" undecidable — an
132
+ // unclosed host block leaves a crafted `<user_query>` outside every matched
133
+ // range and promotes host instructions to Owner text. Validate the ENVELOPE
134
+ // (the text with accepted query blocks blanked out), so an Owner who pasted
135
+ // a literal `<system-reminder>` inside their query keeps it verbatim.
136
+ // Single pass over the original offsets (P2 review): rebuilding the whole
137
+ // payload per query block is O(blocks × length) and can time out the
138
+ // synchronous Stop hook on a large transcript.
139
+ const sortedQueries = [...queryMatches].sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
140
+ const blankedParts = [];
141
+ let cursor = 0;
142
+ for (const match of sortedQueries) {
143
+ const start = match.index ?? 0;
144
+ blankedParts.push(text.slice(cursor, start), ' '.repeat(match[0].length));
145
+ cursor = start + match[0].length;
146
+ }
147
+ blankedParts.push(text.slice(cursor));
148
+ const blanked = blankedParts.join('');
149
+ const envelopeRanges = [...blanked.matchAll(SYSTEM_REMINDER_BLOCK)].map((match) => {
150
+ const start = match.index ?? 0;
151
+ return [start, start + match[0].length];
152
+ });
153
+ const openerCount = [...blanked.matchAll(/<system-reminder\b/g)].length;
154
+ const closerCount = [...blanked.matchAll(/<\/system-reminder>/g)].length;
155
+ const nestedReminder = [...blanked.matchAll(/<system-reminder\b/g)].some((match) => {
156
+ const start = match.index ?? 0;
157
+ return envelopeRanges.some(([begin, end]) => start > begin && start < end);
158
+ });
159
+ if (openerCount !== closerCount || nestedReminder) {
160
+ warnAggregated(context, 'wb_user_context_unconfirmed');
161
+ return null;
162
+ }
163
+ const queries = queryMatches
164
+ .map((match) => match[1]?.trim() ?? '')
165
+ .filter((part) => part.length > 0);
166
+ if (queries.length > 0)
167
+ return queries.join('\n');
168
+ // Fail-closed default: without the structured boundary a legacy plain
169
+ // utterance and an UNRECOGNISED host wrapper (e.g. <system-prompt>, a
170
+ // renamed reminder) are indistinguishable from here. Projecting the blob is
171
+ // the observed P1 failure mode: host prompts enter the governance store as
172
+ // Owner evidence AND the real utterance is lost behind the store's 200-char
173
+ // preview. The observation still lands as `partial` with this warning and
174
+ // NO visibleText, so the degradation is visible instead of silent (rc-9).
175
+ warnAggregated(context, 'wb_user_context_unconfirmed');
176
+ return null;
177
+ }
178
+ /** Convert an epoch-millisecond host stamp to ISO, falling back when absent or invalid. */
179
+ function epochMsToIso(value, fallbackIso) {
180
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
181
+ return fallbackIso;
182
+ const date = new Date(value);
183
+ return Number.isNaN(date.getTime()) ? fallbackIso : date.toISOString();
184
+ }
185
+ /** Extract the record's `providerData` object, or null when absent/malformed. */
186
+ function providerDataOf(record) {
187
+ const providerData = own(record, 'providerData');
188
+ return isRecord(providerData) ? providerData : null;
189
+ }
190
+ /**
191
+ * Resolve the host turn container: provider messageId, then record id, then
192
+ * the session identity (always non-empty, so the observation stays keyable).
193
+ */
194
+ function hostTurnIdOf(record, id, sessionIdentity) {
195
+ const providerData = providerDataOf(record);
196
+ const messageId = providerData !== null ? nonEmptyString(own(providerData, 'messageId')) : null;
197
+ // Callers guard id !== null before projecting; the session identity is the
198
+ // durable last-resort container so hostTurnId is always a non-empty string.
199
+ return messageId ?? id ?? sessionIdentity;
200
+ }
201
+ /** Detect a WorkBuddy compaction marker (providerData.compType / isCompacted; forensics §8.2). */
202
+ function hasCompactionMarker(providerData) {
203
+ if (providerData === null)
204
+ return false;
205
+ return own(providerData, 'isCompacted') === true || nonEmptyString(own(providerData, 'compactType')) !== null;
206
+ }
207
+ function observationBase(context, record) {
208
+ return {
209
+ hostKind: 'workbuddy',
210
+ rolloutIdentity: context.sessionIdentity,
211
+ rootSessionId: context.sessionIdentity,
212
+ hostTurnId: hostTurnIdOf(record.record, record.id, context.sessionIdentity),
213
+ };
214
+ }
215
+ /** Follow the parentId chain to the owning assistant message record id, in-window only; never guess. */
216
+ function resolveAssistantAncestor(context, parentId) {
217
+ let current = nonEmptyString(parentId);
218
+ for (let hop = 0; hop < MAX_PARENT_CHAIN_HOPS && current !== null; hop += 1) {
219
+ const seen = context.seenRecords.get(current);
220
+ if (seen === undefined)
221
+ return null;
222
+ if (seen.role === 'assistant')
223
+ return current;
224
+ current = seen.parentId;
225
+ }
226
+ return null;
227
+ }
228
+ /** Remember id → {parentId, role} for in-window reasoning attribution; id-less records are not indexable. */
229
+ function noteRecordIdentity(context, record) {
230
+ const id = nonEmptyString(own(record, 'id'));
231
+ if (id === null)
232
+ return;
233
+ const role = own(record, 'role');
234
+ context.seenRecords.set(id, {
235
+ parentId: nonEmptyString(own(record, 'parentId')),
236
+ role: typeof role === 'string' ? role : null,
237
+ });
238
+ }
239
+ /** Flag (aggregated) a record whose sessionId contradicts the locator's durable identity. */
240
+ function noteSessionIdMismatch(context, record) {
241
+ const recordSessionId = nonEmptyString(own(record, 'sessionId'));
242
+ if (recordSessionId !== null && recordSessionId !== context.sessionIdentity) {
243
+ warnAggregated(context, 'wb_session_id_mismatch');
244
+ }
245
+ }
246
+ /**
247
+ * Project one validated record into governance observations (the type switch).
248
+ *
249
+ * Every branch either produces observations or records an explicit aggregated
250
+ * warning: known skips, compaction markers, unpaired results and unknown types
251
+ * all stay observable (rc-9). Keys are always built from the durable session
252
+ * identity, never from a record-supplied sessionId.
253
+ */
254
+ function projectRecord(context, record) {
255
+ const raw = record.record;
256
+ const { type } = record;
257
+ noteSessionIdMismatch(context, raw);
258
+ // Known structural records with no governance projection (rc-9: counted, never silent).
259
+ if (type === 'session-meta' || type === 'file-history-snapshot' || type === 'ai-title') {
260
+ warnAggregated(context, `wb_skipped:${type}`);
261
+ noteRecordIdentity(context, raw);
262
+ return;
263
+ }
264
+ if (type === 'resend-fork-notice') {
265
+ // Session fork notice — branch marker only; old rows are never rewritten (§4.7).
266
+ warnAggregated(context, 'wb_fork_notice');
267
+ noteRecordIdentity(context, raw);
268
+ return;
269
+ }
270
+ if (type === 'message') {
271
+ noteRecordIdentity(context, raw);
272
+ if (record.id === null) {
273
+ warnAggregated(context, 'wb_observation_skipped_missing_identity');
274
+ return;
275
+ }
276
+ const role = own(raw, 'role');
277
+ const providerData = providerDataOf(raw);
278
+ if (hasCompactionMarker(providerData)) {
279
+ // §5.4: append-only compaction — warn, never tombstone (compactionTimestamp stays null).
280
+ warnAggregated(context, 'wb_compaction_marker');
281
+ }
282
+ if (role !== 'user' && role !== 'assistant') {
283
+ warnAggregated(context, 'wb_skipped_message_role');
284
+ return;
285
+ }
286
+ // Compaction summaries are HOST-authored text that happens to reuse the
287
+ // user role. Projecting them as `user_turn` would file host content as
288
+ // Owner behavior evidence (the same failure mode the <user_query> boundary
289
+ // guards against). Keep the record observable via the warning, but never
290
+ // emit an Owner turn for it.
291
+ if (role === 'user' && providerData !== null && own(providerData, 'isSummary') === true) {
292
+ warnAggregated(context, 'wb_skipped:compaction_summary');
293
+ return;
294
+ }
295
+ const joined = joinContentText(own(raw, 'content'));
296
+ // Only user turns carry the host-context wrapper; assistant turns keep the
297
+ // existing verbatim projection (no wrapper observed in forensic samples).
298
+ const text = role === 'user' ? projectUserText(context, joined) : joined;
299
+ context.observations.push({
300
+ ...observationBase(context, record),
301
+ kind: role === 'user' ? 'user_turn' : 'assistant_turn',
302
+ logicalObservationKey: `wb|${context.sessionIdentity}|${record.id}`,
303
+ transcriptRecordKey: `wb|${context.sessionIdentity}|${record.recordByteStart}`,
304
+ recordOrdinal: record.ordinal,
305
+ recordByteStart: record.recordByteStart,
306
+ ...(role === 'assistant' ? { assistantItemId: record.id } : {}),
307
+ ...(role === 'assistant' ? { toolFacts: { model: providerData !== null ? nonEmptyString(own(providerData, 'model')) : null } } : {}),
308
+ ...(text !== null ? { visibleText: text } : {}),
309
+ source: 'transcript',
310
+ completeness: text !== null ? 'complete' : 'partial',
311
+ observedAt: record.timestampIso,
312
+ });
313
+ return;
314
+ }
315
+ if (type === 'reasoning') {
316
+ noteRecordIdentity(context, raw);
317
+ if (record.id === null) {
318
+ warnAggregated(context, 'wb_observation_skipped_missing_identity');
319
+ return;
320
+ }
321
+ const text = joinContentText(own(raw, 'content')) ?? joinContentText(own(raw, 'rawContent'));
322
+ const assistantAncestor = resolveAssistantAncestor(context, own(raw, 'parentId'));
323
+ context.observations.push({
324
+ ...observationBase(context, record),
325
+ kind: 'reasoning',
326
+ logicalObservationKey: `wb|${context.sessionIdentity}|${record.id}`,
327
+ transcriptRecordKey: `wb|${context.sessionIdentity}|${record.recordByteStart}`,
328
+ recordOrdinal: record.ordinal,
329
+ recordByteStart: record.recordByteStart,
330
+ ...(assistantAncestor !== null ? { assistantItemId: assistantAncestor } : { phase: 'unattributed' }),
331
+ ...(text !== null ? { visibleText: text } : {}),
332
+ source: 'transcript',
333
+ completeness: text !== null && assistantAncestor !== null ? 'complete' : 'partial',
334
+ observedAt: record.timestampIso,
335
+ });
336
+ return;
337
+ }
338
+ if (type === 'function_call') {
339
+ noteRecordIdentity(context, raw);
340
+ if (record.id === null) {
341
+ warnAggregated(context, 'wb_observation_skipped_missing_identity');
342
+ return;
343
+ }
344
+ const providerData = providerDataOf(raw);
345
+ const callId = nonEmptyString(own(raw, 'callId'));
346
+ if (callId === null)
347
+ warnAggregated(context, 'wb_missing_call_id');
348
+ // Execution identity is the transcript RECORD, never the window (P2
349
+ // review). `seenCallIds` was window-scoped, so two executions reusing one
350
+ // callId in different windows both derived `call:<callId>` and the second
351
+ // was absorbed into the first. The host does not dedupe callIds, so the
352
+ // record id is the only identity that is stable across windows AND unique
353
+ // per execution. The store reconnects a later window's result to the one
354
+ // unambiguous partial row via `tool_use_id`; results stay `callId`-tagged.
355
+ const observation = {
356
+ ...observationBase(context, record),
357
+ kind: 'tool_call',
358
+ logicalObservationKey: `wb|${context.sessionIdentity}|${record.id}`,
359
+ transcriptRecordKey: `wb|${context.sessionIdentity}|${record.recordByteStart}`,
360
+ recordOrdinal: record.ordinal,
361
+ recordByteStart: record.recordByteStart,
362
+ ...(callId !== null ? { toolUseId: callId } : {}),
363
+ toolFacts: {
364
+ toolName: nonEmptyString(own(raw, 'name')),
365
+ params: nonEmptyString(own(raw, 'arguments')),
366
+ model: providerData !== null ? nonEmptyString(own(providerData, 'model')) : null,
367
+ },
368
+ source: 'transcript',
369
+ // 'partial' until the matching function_call_result lands — in this
370
+ // window (in-memory backfill) or a LATER one (same logical key, the
371
+ // store upgrades the committed row to complete).
372
+ completeness: 'partial',
373
+ observedAt: record.timestampIso,
374
+ };
375
+ const index = context.observations.push(observation) - 1;
376
+ if (callId !== null) {
377
+ const pending = context.pendingToolCalls.get(callId);
378
+ if (pending === undefined)
379
+ context.pendingToolCalls.set(callId, [index]);
380
+ else
381
+ pending.push(index);
382
+ }
383
+ return;
384
+ }
385
+ if (type === 'function_call_result') {
386
+ noteRecordIdentity(context, raw);
387
+ const callId = nonEmptyString(own(raw, 'callId'));
388
+ const status = nonEmptyString(own(raw, 'status'));
389
+ const outputPreview = resultOutputPreview(own(raw, 'output'));
390
+ // FIFO: the first still-unpaired call with this callId owns this result.
391
+ // Duplicate callIds therefore pair in file order instead of collapsing.
392
+ const pending = callId !== null ? context.pendingToolCalls.get(callId) : undefined;
393
+ const pairedIndex = pending !== undefined && pending.length > 0 ? pending[0] : undefined;
394
+ const pairedCall = pairedIndex !== undefined ? context.observations[pairedIndex] : undefined;
395
+ if (callId !== null && pending !== undefined && pairedIndex !== undefined && pairedCall !== undefined) {
396
+ // Result side backfills its in-window call observation (anchored on the
397
+ // call record id — replay converges on ONE logical key per execution).
398
+ pending.shift();
399
+ if (pending.length === 0)
400
+ context.pendingToolCalls.delete(callId);
401
+ context.observations[pairedIndex] = {
402
+ ...pairedCall,
403
+ completeness: 'complete',
404
+ toolFacts: {
405
+ ...(isRecord(pairedCall.toolFacts) ? pairedCall.toolFacts : {}),
406
+ resultStatus: status,
407
+ ...(outputPreview !== null ? { output: outputPreview } : {}),
408
+ },
409
+ };
410
+ return;
411
+ }
412
+ if (record.id === null) {
413
+ warnAggregated(context, 'wb_observation_skipped_missing_identity');
414
+ return;
415
+ }
416
+ // Out-of-window result: the call record lives in an already-committed
417
+ // earlier batch (or is genuinely missing). Key it by ITS OWN record id so
418
+ // it can never collide with another execution's call row; the store then
419
+ // reconnects it to the single unambiguous partial row via `tool_use_id`.
420
+ // The warning stays because the pairing happened outside this window.
421
+ warnAggregated(context, 'wb_unpaired_tool_result');
422
+ context.observations.push({
423
+ ...observationBase(context, record),
424
+ kind: 'tool_call',
425
+ logicalObservationKey: `wb|${context.sessionIdentity}|${record.id}`,
426
+ transcriptRecordKey: `wb|${context.sessionIdentity}|${record.recordByteStart}`,
427
+ recordOrdinal: record.ordinal,
428
+ recordByteStart: record.recordByteStart,
429
+ ...(callId !== null ? { toolUseId: callId } : {}),
430
+ toolFacts: {
431
+ toolName: nonEmptyString(own(raw, 'name')),
432
+ resultStatus: status,
433
+ ...(outputPreview !== null ? { output: outputPreview } : {}),
434
+ },
435
+ source: 'transcript',
436
+ completeness: 'complete',
437
+ observedAt: record.timestampIso,
438
+ });
439
+ return;
440
+ }
441
+ // Unknown-but-well-formed type: explicit degradation, checkpoint still
442
+ // advances (rc-9; a new host variant must be visible, not swallowed).
443
+ warnAggregated(context, `wb_unknown_record_type:${type.slice(0, 40)}`);
444
+ }
445
+ /** Parse one newline-delimited line into the flat envelope contract, or reject it as malformed. */
446
+ function decodeLine(lineBytes) {
447
+ let parsed;
448
+ try {
449
+ parsed = JSON.parse(lineBytes.toString('utf8'));
450
+ }
451
+ catch {
452
+ return { ok: false };
453
+ }
454
+ if (!isRecord(parsed))
455
+ return { ok: false };
456
+ // Envelope contract: a flat record with a non-empty string `type`. A line
457
+ // without it is a stable malformed record (seam taxonomy) — never skipped.
458
+ const type = nonEmptyString(own(parsed, 'type'));
459
+ if (type === null)
460
+ return { ok: false };
461
+ return { ok: true, record: parsed, type, id: nonEmptyString(own(parsed, 'id')), timestamp: own(parsed, 'timestamp') };
462
+ }
463
+ function finish(context, cursor, stop) {
464
+ return {
465
+ observations: context.observations,
466
+ stop,
467
+ nextByteOffset: cursor.nextByteOffset,
468
+ lastOrdinal: cursor.lastOrdinal,
469
+ warnings: warningList(context),
470
+ };
471
+ }
472
+ /**
473
+ * Decode one byte window of a WorkBuddy transcript into governance
474
+ * observations plus a byte-exact resume cursor.
475
+ *
476
+ * Newline-terminated lines advance the ordinal/offset; an incomplete EOF tail
477
+ * holds the checkpoint (transient append boundary); a malformed terminated
478
+ * line stops BEFORE itself; unknown types advance with a warning. The batch
479
+ * cap applies to both terminated lines and the EOF tail.
480
+ */
481
+ export function decodeWorkbuddyTranscriptWindow(input) {
482
+ const context = {
483
+ sessionIdentity: input.sessionIdentity,
484
+ nowIso: input.nowIso,
485
+ observations: [],
486
+ seenRecords: new Map(),
487
+ pendingToolCalls: new Map(),
488
+ warningCounts: new Map(),
489
+ };
490
+ const { bytes } = input;
491
+ if (bytes.length === 0) {
492
+ return finish(context, { nextByteOffset: input.fileOffset, lastOrdinal: input.startOrdinal - 1 }, { kind: 'eof' });
493
+ }
494
+ // Byte-exact newline-window split from the seam — the incomplete-tail
495
+ // semantics every host inherits (a half-line at EOF never advances).
496
+ const plan = planJsonlWindow(bytes, input.fileOffset);
497
+ let lastOrdinal = input.startOrdinal - 1;
498
+ let nextOrdinal = input.startOrdinal;
499
+ let recordsConsumed = 0;
500
+ const consume = (line, recordByteStart) => {
501
+ lastOrdinal = nextOrdinal;
502
+ nextOrdinal += 1;
503
+ recordsConsumed += 1;
504
+ projectRecord(context, {
505
+ record: line.record,
506
+ type: line.type,
507
+ id: line.id,
508
+ ordinal: lastOrdinal,
509
+ recordByteStart,
510
+ timestampIso: epochMsToIso(line.timestamp, input.nowIso),
511
+ });
512
+ };
513
+ for (const { bytes: lineBytes, recordByteStart } of plan.lines) {
514
+ if (lineBytes.length === 0 || lineBytes.toString('utf8').trim().length === 0)
515
+ continue;
516
+ if (recordsConsumed >= CONVERSATION_INGESTION_MAX_BATCH_RECORDS) {
517
+ return finish(context, { nextByteOffset: recordByteStart, lastOrdinal }, { kind: 'byte_bound' });
518
+ }
519
+ const line = decodeLine(lineBytes);
520
+ if (!line.ok) {
521
+ // Stable malformed record: stop without advancing past it. The would-be
522
+ // ordinal of the malformed line is reported (the file carries none).
523
+ return finish(context, { nextByteOffset: recordByteStart, lastOrdinal }, { kind: 'malformed', ordinal: nextOrdinal });
524
+ }
525
+ consume(line, recordByteStart);
526
+ }
527
+ if (plan.tail !== null) {
528
+ const tailStart = plan.tail.startOffset;
529
+ if (input.byteBoundReached) {
530
+ // Window cut mid-line by the byte bound — bounded lag, never a verdict on the line.
531
+ if (plan.lines.length === 0) {
532
+ return finish(context, { nextByteOffset: input.fileOffset, lastOrdinal }, { kind: 'oversized_record' });
533
+ }
534
+ return finish(context, { nextByteOffset: tailStart, lastOrdinal }, { kind: 'byte_bound' });
535
+ }
536
+ const line = decodeLine(plan.tail.bytes);
537
+ if (line.ok) {
538
+ // The hard batch cap also applies to the EOF tail (P2 review): a
539
+ // parseable final line without a trailing newline used to bypass
540
+ // MAX_BATCH_RECORDS, so 128 newline-terminated records + 1 EOF record
541
+ // consumed 129. Stop BEFORE the tail; the next read starts there and the
542
+ // cap resets, so the record is never lost — only deferred.
543
+ if (recordsConsumed >= CONVERSATION_INGESTION_MAX_BATCH_RECORDS) {
544
+ return finish(context, { nextByteOffset: tailStart, lastOrdinal }, { kind: 'byte_bound' });
545
+ }
546
+ // Parseable final line without a trailing newline: complete record at EOF.
547
+ consume(line, tailStart);
548
+ return finish(context, { nextByteOffset: tailStart + plan.tail.bytes.length, lastOrdinal }, { kind: 'eof' });
549
+ }
550
+ // Incomplete final line: transient append/flush boundary — hold the checkpoint.
551
+ return finish(context, { nextByteOffset: tailStart, lastOrdinal }, { kind: 'incomplete_tail' });
552
+ }
553
+ return finish(context, { nextByteOffset: plan.completeEndOffset, lastOrdinal }, input.byteBoundReached ? { kind: 'byte_bound' } : { kind: 'eof' });
554
+ }
@@ -0,0 +1,39 @@
1
+ /** File identity captured at validation; the seam port re-proves it post-open. */
2
+ export interface WorkbuddyTranscriptFileIdentity {
3
+ readonly dev: number;
4
+ readonly ino: number;
5
+ readonly size: number;
6
+ readonly mtimeMs: number;
7
+ }
8
+ export type WorkbuddyTranscriptPathValidation = {
9
+ ok: true;
10
+ canonicalPath: string;
11
+ sessionIdentity: string;
12
+ identity: WorkbuddyTranscriptFileIdentity;
13
+ } | {
14
+ ok: false;
15
+ reason: 'transcript_path_invalid' | 'transcript_path_outside_projects_root' | 'transcript_path_not_main_session';
16
+ nextAction: string;
17
+ };
18
+ /** Projects root: `<home>/.workbuddy/projects` (engine-side join, forensics §2.2). */
19
+ export declare function workbuddyProjectsRoot(home: string): string;
20
+ /**
21
+ * Authorize one transcript path against the WorkBuddy projects root.
22
+ *
23
+ * Rejects non-absolute input, `..` segments, non-`<uuid>.jsonl` names, paths
24
+ * whose native canonical form escapes the root, non-regular files and
25
+ * subagent-nested files. On success returns the native canonical path, the
26
+ * parsed session identity and the pre-open file identity.
27
+ */
28
+ export declare function validateWorkbuddyTranscriptPath(transcriptPath: string, projectsRoot: string): WorkbuddyTranscriptPathValidation;
29
+ /**
30
+ * Deterministic derivation (fallback when no hook payload path exists):
31
+ * `<home>/.workbuddy/projects/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns
32
+ * null when the session identity or cwd cannot produce a contract-shaped
33
+ * path — the caller degrades, it never scans for a "latest" file.
34
+ */
35
+ export declare function deriveWorkbuddyTranscriptPath(input: {
36
+ home: string;
37
+ cwd: string;
38
+ sessionId: string;
39
+ }): string | null;