pantheon-opencode 1.6.1 → 1.6.2-beta.10

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 (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
package/src/plugin-v2.ts CHANGED
@@ -2,12 +2,14 @@
2
2
  * Pantheon V2 Plugin — full orchestration plugin for OpenCode V2.
3
3
  *
4
4
  * Registers:
5
- * - 3 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
- * pantheon_cost, pantheon_model) plus up to 2 host-dependent ones: native
5
+ * - 4 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
+ * pantheon_cost, pantheon_model, pantheon_local_decision) plus up to 2 host-dependent ones: native
7
7
  * `vision_describe` when the host exposes the V2 model catalog (it resolves
8
8
  * OpenCode Zen auth and sends images directly to the selected multimodal
9
9
  * model), and `pantheon_bounded_read` when the host exposes its permission
10
10
  * and session APIs (root Zeus sessions only).
11
+ * `pantheon_local_decision` is advisory and rejects execution unless the
12
+ * host tool context identifies the caller as Zeus.
11
13
  * The goal tools need V1 infrastructure and are absent from this surface.
12
14
  * - 5 event subscriptions (session.created, idle, deleted, error, compacted)
13
15
  * - Session hooks (prompt, context, compaction)
@@ -71,6 +73,11 @@
71
73
  * If the SDK ever exposes these host domains, replacing `hostDomains` with the real
72
74
  * type is a one-line change. Do NOT make that change while 1.18.x lacks them.
73
75
  *
76
+ * The separate offline native Decisions scaffold is typed against
77
+ * `@opencode/plugin@2.2.5`. It intentionally has no production call site and
78
+ * does not claim native Decisions support for V1 or OpenCode V2.0/2.1. The
79
+ * legacy plugin registrations are not migrated as part of that scaffold.
80
+ *
74
81
  * V2_UNSUPPORTED_FEATURES distinguishes adapter limitations from observed
75
82
  * host-absent APIs; setup handles optional registrations on a best-effort basis.
76
83
  *
@@ -108,12 +115,9 @@ import {
108
115
  } from './pantheon/delegation-enforce.ts'
109
116
  import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
110
117
  import { createGuardPathResolver } from './pantheon/guard-path.ts'
111
- import {
112
- applyMemoryInjection,
113
- MemoryInjectionCache,
114
- resolveMemoryInjectionConfig,
115
- warnInvalidMemoryInjectionConfig,
116
- } from './pantheon/memory-context.ts'
118
+ import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
119
+ import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
120
+ import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
117
121
  import { getSharedBoard } from './pantheon/shared-board.ts'
118
122
  import {
119
123
  TODO_ENFORCER_DEFAULTS,
@@ -138,6 +142,16 @@ import {
138
142
  registerV2Bridge,
139
143
  type V2ContextLike,
140
144
  } from './pantheon/v2-bridge.ts'
145
+ import { createP7LoopPoint, p7LoopEnabledFromEnv } from './pantheon/v2-decision-points/p7-loop.ts'
146
+ import {
147
+ createP8Guardrail,
148
+ p8GuardrailEnabledFromEnv,
149
+ } from './pantheon/v2-decision-points/p8-guardrail.ts'
150
+ import { evaluateCompactionMemoryPoint } from './pantheon/v2-decision-points/p9-memory-compaction.ts'
151
+ import { evaluateCatalogPoint } from './pantheon/v2-decision-points/p11-catalog.ts'
152
+ import { DECISION_POINT_REGISTRY } from './pantheon/v2-decision-points.ts'
153
+ import { observePromptSurface } from './pantheon/v2-decision-prompt-surface.ts'
154
+ import { createTelemetrySink, type TelemetrySink } from './pantheon/v2-decision-telemetry.ts'
141
155
  import {
142
156
  type AuthoritativeSession,
143
157
  evaluateV2Delegation,
@@ -147,13 +161,15 @@ import {
147
161
  v2ResourceTarget,
148
162
  } from './pantheon/v2-delegation-enforce.ts'
149
163
  import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
164
+ import { runSecretScanInProcess } from './pantheon/v2-hook-engine.ts'
150
165
  import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
166
+ import type { NativeDecisionRequest } from './pantheon/v2-native-decisions.ts'
151
167
  import { createV2ShellHooks, type V2ShellRunner } from './pantheon/v2-shell-hooks.ts'
152
168
  import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
153
169
  import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
154
170
  import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/v2-vision.ts'
155
171
  import { sanitizeVisionHistory } from './pantheon/vision.ts'
156
- import { type HookPayload, type HookResult, runHook } from './plugins/hook-runner.ts'
172
+ import type { HookPayload, HookResult } from './plugins/hook-runner.ts'
157
173
 
158
174
  // ─── Unsupported Features Registry ───────────────────────────────────────
159
175
 
@@ -343,6 +359,16 @@ interface V2GenerateDomain {
343
359
  text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
344
360
  }
345
361
 
362
+ /**
363
+ * The host's experimental generation domain. Only `decisions` is declared: the
364
+ * native Jev route feature-detects it, and every other member stays unknown.
365
+ */
366
+ interface V2ExperimentalDomain {
367
+ generate?: {
368
+ decisions?: (request: NativeDecisionRequest) => Promise<unknown>
369
+ }
370
+ }
371
+
346
372
  /** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
347
373
  interface HostPluginContext extends PluginContext {
348
374
  tool?: V2ToolDomain
@@ -351,6 +377,7 @@ interface HostPluginContext extends PluginContext {
351
377
  session?: V2SessionDomain
352
378
  model?: V2ModelDomain
353
379
  generate?: V2GenerateDomain
380
+ experimental?: V2ExperimentalDomain
354
381
  location?: V2LocationDomain
355
382
  }
356
383
 
@@ -661,12 +688,65 @@ async function registerV2Tools(
661
688
  // it, and the host rejects a definition whose result shape cannot satisfy
662
689
  // the declaration it makes.
663
690
  const model = host.model
664
- const visionReady = typeof model?.list === 'function'
691
+ const modelListFn = model?.list
692
+ const visionReady = typeof modelListFn === 'function'
665
693
  if (!visionReady) markUnsupported('vision-tool')
666
694
  const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
667
- const toolDefs = createV2ToolDefinitions(visionRuntime)
695
+ // The native Jev tool needs BOTH the V2 model catalog (route resolution)
696
+ // and the host's native Decisions API. A host without either simply does
697
+ // not get the tool — same feature-detect discipline as vision_describe.
698
+ const decisionsFn = host.experimental?.generate?.decisions
699
+ const jevReady = visionReady && typeof decisionsFn === 'function'
700
+ if (!jevReady) markUnsupported('jev-decision-tool')
701
+ const permissionAssertFn = host.permission?.assert
702
+ let jevRuntime: V2JevDecisionRuntime | undefined
703
+ if (jevReady && typeof decisionsFn === 'function' && typeof modelListFn === 'function') {
704
+ const decisionsOwner = host.experimental?.generate
705
+ const decide = decisionsFn
706
+ const listModels = modelListFn
707
+ // The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
708
+ // types this file sees declare skill as the registration hook, so the
709
+ // runtime shape is read through one narrow, feature-detected cast.
710
+ const skillDomain = (host as { skill?: { list?: () => unknown } }).skill
711
+ const skillList = skillDomain?.list
712
+ const permissionAssert =
713
+ typeof permissionAssertFn === 'function'
714
+ ? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
715
+ : undefined
716
+ jevRuntime = {
717
+ // Every host method is invoked with its owning domain as receiver:
718
+ // the canary records `ctx.model.list()` (bound) succeeding on 2.2.5
719
+ // while a detached reference threw in the field and surfaced only as
720
+ // CATALOG_UNAVAILABLE. Same discipline as permissionAssert above.
721
+ listModels: () => listModels.call(host.model),
722
+ decide: (request: NativeDecisionRequest) => decide.call(decisionsOwner, request),
723
+ // Sync-or-async host skill list; absent/throwing falls back to the
724
+ // catalog-only preset inside the tool.
725
+ listSkills: async () => skillList?.call(skillDomain),
726
+ ...(permissionAssert === undefined ? {} : { permissionAssert }),
727
+ }
728
+ }
729
+ // P3 (complexity) declares `tool.invoke`; its construction site is the
730
+ // local selector's execute, fed by that tool's own input schema. The sink
731
+ // is the 0b record path (in-memory, bounded, I/O-free) and every record
732
+ // carries `mode: 'shadow'` — the mode the registry declares.
733
+ const p3Sink = createTelemetrySink()
734
+ p3TelemetrySink = p3Sink
735
+ const toolDefs = createV2ToolDefinitions(
736
+ visionRuntime,
737
+ {
738
+ complexitySink: (record) => {
739
+ p3Sink.emit({ ...record, mode: 'shadow' })
740
+ },
741
+ },
742
+ jevRuntime,
743
+ )
668
744
  if (boundedRead !== undefined) toolDefs.push(boundedRead)
669
745
 
746
+ // P11's record sink, created per registration (in-memory, bounded, I/O-free).
747
+ const p11Sink = createTelemetrySink()
748
+ p11TelemetrySink = p11Sink
749
+
670
750
  await toolCtx.transform((draft: V2ToolDraft) => {
671
751
  // Catalog grouping only. The host computes a tool's registration id as
672
752
  // `options.namespace === undefined ? name : `${namespace}_${name}``, and
@@ -688,6 +768,24 @@ async function registerV2Tools(
688
768
  execute: def.execute,
689
769
  })
690
770
  }
771
+
772
+ // P11 (catalog) shadow observation on the only measured catalogue
773
+ // surface: the draft the host hands this callback — `{list, get,
774
+ // namespace, add, update, remove}`, 20 host tools, 46 with MCP servers
775
+ // registered (F-07). `ctx.catalog` is absent at every measured point
776
+ // (F-05) and is not used. The adapter reads and nothing else: `list()` is
777
+ // called, the six members are type-checked, and no add/update/remove is
778
+ // ever invoked, so the registration above is the only mutation. Shadow
779
+ // has no responder, so the record names the validated `choice` question
780
+ // (`catalog.no.answer`) instead of inventing a selection. Runs after the
781
+ // adds so the draft it reads is the one the host will keep.
782
+ try {
783
+ evaluateCatalogPoint(draft, (record) => {
784
+ p11Sink.emit({ ...record, mode: 'shadow' })
785
+ })
786
+ } catch {
787
+ // Observation must never fail the tool registration.
788
+ }
691
789
  })
692
790
  return true
693
791
  } catch {
@@ -697,6 +795,105 @@ async function registerV2Tools(
697
795
 
698
796
  // ─── V2 Event Subscription ──────────────────────────────────────────────
699
797
 
798
+ /**
799
+ * The P7 telemetry sink created by the most recent event subscription.
800
+ *
801
+ * P7 writes through the 0b record path (`createTelemetrySink`): in-memory,
802
+ * bounded and I/O-free by design, so a test that asserts "the decision was
803
+ * actually recorded" has to read the same collector the wiring wrote to.
804
+ * Exported only for tests/pantheon/plugin-v2-contract.test.ts — production has
805
+ * no caller, and nothing in the plugin reads this back.
806
+ */
807
+ export function getP7TelemetrySinkForTests(): TelemetrySink | undefined {
808
+ return p7TelemetrySink
809
+ }
810
+
811
+ let p7TelemetrySink: TelemetrySink | undefined
812
+
813
+ /**
814
+ * The P8 telemetry sink created by the most recent permission-hook
815
+ * registration.
816
+ *
817
+ * P8 records every outcome it is responsible for — `guardrail.narrow`,
818
+ * `guardrail.keep`, `guardrail.refusal`, `p8.write.rejected`,
819
+ * `p8.write.delegation` and `p8.write.unconfirmed` — through the 0b record path
820
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free). A guardrail that
821
+ * narrows without a record is indistinguishable from an inert one, which is
822
+ * exactly the defect PH5-1 closed. Every record carries the P8 registry `mode`
823
+ * (`off`), never `active`, and a `narrow` is recorded only when a re-read of
824
+ * the event still holds it (N9/N10). Exported only for
825
+ * tests/pantheon/plugin-v2-contract.test.ts.
826
+ */
827
+ export function getP8TelemetrySinkForTests(): TelemetrySink | undefined {
828
+ return p8TelemetrySink
829
+ }
830
+
831
+ let p8TelemetrySink: TelemetrySink | undefined
832
+
833
+ /**
834
+ * The prompt-surface telemetry sink created by the most recent prompt-hook
835
+ * registration.
836
+ *
837
+ * P1 and P2 observe the same admission payload through `observePromptSurface`;
838
+ * each shadow record is reduced through the 0b record path
839
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free) and carries
840
+ * `mode: 'shadow'` — the registry mode both declare. Nothing in production
841
+ * reads this collector back, so the write is only a claim if a reader can
842
+ * assert it: this accessor is that reader, and
843
+ * tests/pantheon/plugin-v2-contract.test.ts is its only caller.
844
+ */
845
+ export function getPromptSurfaceTelemetrySinkForTests(): TelemetrySink | undefined {
846
+ return promptSurfaceTelemetrySink
847
+ }
848
+
849
+ let promptSurfaceTelemetrySink: TelemetrySink | undefined
850
+
851
+ /**
852
+ * The P3 telemetry sink created by the most recent tool registration.
853
+ *
854
+ * P3 is constructed at `tool.invoke`: `pantheon_local_decision`'s execute calls
855
+ * the adapter with the tool input, which carries `complexity` and `gateStatus`.
856
+ * Records are reduced through the same in-memory 0b path and carry the P3
857
+ * registry `mode` (`shadow`). Exported only for
858
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
859
+ */
860
+ export function getP3TelemetrySinkForTests(): TelemetrySink | undefined {
861
+ return p3TelemetrySink
862
+ }
863
+
864
+ let p3TelemetrySink: TelemetrySink | undefined
865
+
866
+ /**
867
+ * The P9 telemetry sink created by the most recent compaction-hook
868
+ * registration.
869
+ *
870
+ * P9 declares `session.hook('compaction')` and observes the MEASURED carrier
871
+ * only: the top-level `sessionID` and the `system` part array (F-01, F-02).
872
+ * Records go through the same in-memory, bounded 0b path and carry the P9
873
+ * registry `mode` (`shadow`). Exported only for
874
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
875
+ */
876
+ export function getP9TelemetrySinkForTests(): TelemetrySink | undefined {
877
+ return p9TelemetrySink
878
+ }
879
+
880
+ let p9TelemetrySink: TelemetrySink | undefined
881
+
882
+ /**
883
+ * The P11 telemetry sink created by the most recent tool registration.
884
+ *
885
+ * P11 declares `tool.transform` and reads the draft the host hands that
886
+ * callback (F-07) — the only measured catalogue surface, since `ctx.catalog` is
887
+ * absent (F-05). Records go through the in-memory, bounded 0b path and carry the
888
+ * P11 registry `mode` (`shadow`). Exported only for
889
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
890
+ */
891
+ export function getP11TelemetrySinkForTests(): TelemetrySink | undefined {
892
+ return p11TelemetrySink
893
+ }
894
+
895
+ let p11TelemetrySink: TelemetrySink | undefined
896
+
700
897
  /**
701
898
  * Attempt to subscribe to session events via V2 ctx.event.subscribe.
702
899
  *
@@ -715,12 +912,45 @@ function subscribeV2Events(
715
912
  return undefined
716
913
  }
717
914
 
915
+ // P7 loop adapter (PLAN §5.1 branch 1, selected by PROBE-D §7). Constructed
916
+ // here but inert unless PANTHEON_V2_P7_LOOP is set: the flag is OFF by
917
+ // default, and activation is Phase 4b — not this change. Observation is
918
+ // synchronous and self-contained, so it cannot block the stream, cannot
919
+ // throw into the dispatch, and does not alter the cleanup below.
920
+ //
921
+ // The sink is the 0b telemetry record path (`createTelemetrySink`, in-memory
922
+ // and bounded, no I/O). Each shadow record is reduced to its own allowlisted
923
+ // fields plus `mode: 'migration'` — the P7 registry mode — and nothing else:
924
+ // the execution count is not on the allowlist, so it is not recorded, and no
925
+ // prompt, response or user content can reach the record. A disabled adapter
926
+ // never calls the sink, so flag-off still emits zero records.
927
+ const telemetrySink = createTelemetrySink()
928
+ p7TelemetrySink = telemetrySink
929
+ const loopPoint = createP7LoopPoint({
930
+ enabled: p7LoopEnabledFromEnv(),
931
+ sink: (record) => {
932
+ telemetrySink.emit({ ...record, mode: 'migration' })
933
+ },
934
+ })
935
+
718
936
  const controller = new AbortController()
719
937
  void (async () => {
720
938
  try {
721
939
  // biome-ignore lint/style/noNonNullAssertion: subscribe guaranteed by guard above
722
940
  for await (const event of eventCtx.subscribe!({ signal: controller.signal })) {
723
941
  await handleV2SessionEvent(event)
942
+ try {
943
+ loopPoint.observe(event)
944
+ } catch {
945
+ // The adapter contains its own failures; this keeps a future
946
+ // regression out of the dispatch loop.
947
+ }
948
+ // KNOWN DEFECT, out of scope for Phase 4a: this branch and
949
+ // `handleV2SessionEvent`'s `session.compacted` case key on types the
950
+ // measured host never delivers — `session.idle` 0/11 runs and
951
+ // `session.compacted` 0/11 (PROBE-C, F-12). The live turn-end signal
952
+ // is `session.execution.succeeded`, observed above. The branches are
953
+ // left untouched on purpose; removing them is a separate change.
724
954
  if (event.type === 'session.idle' || event.type === 'session.deleted') {
725
955
  const properties = event.properties ?? {}
726
956
  const info = properties.info
@@ -895,7 +1125,6 @@ async function onSessionDeleted(event: V2SessionEvent): Promise<void> {
895
1125
  return
896
1126
  }
897
1127
  readOnlyRegistry.unregister(sessionID)
898
- memoryInjectionCache.delete(sessionID)
899
1128
  }
900
1129
 
901
1130
  /**
@@ -918,17 +1147,35 @@ async function onSessionCompacted(_event: V2SessionEvent): Promise<void> {}
918
1147
 
919
1148
  // ─── V2 Session Hooks ───────────────────────────────────────────────────
920
1149
 
921
- /**
922
- * One-line prune stats entry through the existing hooks.log channel only when
923
- * a pass actually rewrote something. Silent no-ops (below threshold, protected
924
- * window, already-pruned) stay silent so a compaction does not add noise for
925
- * every request.
926
- */
927
- function logContextPrune(stats: PruneStats): void {
928
- if (!stats.changed) return
1150
+ /** One entry per no-op reason and session/site; successful passes retain each saving. */
1151
+ const pruneSkipSessions = new Set<string>()
1152
+ const PRUNE_SKIP_SESSIONS_MAX = 256
1153
+
1154
+ function logContextPrune(stats: PruneStats, sessionID: unknown): void {
1155
+ if (stats.changed) {
1156
+ appendV2HookLog(
1157
+ `[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
1158
+ `parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
1159
+ )
1160
+ return
1161
+ }
1162
+ if (
1163
+ stats.skipReason === null ||
1164
+ stats.skipReason === 'not-array' ||
1165
+ stats.skipReason === 'malformed'
1166
+ ) {
1167
+ return
1168
+ }
1169
+
1170
+ const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : 'unknown'
1171
+ const key = `${stats.site}:${session}:${stats.skipReason}`
1172
+ if (pruneSkipSessions.has(key)) return
1173
+ if (pruneSkipSessions.size >= PRUNE_SKIP_SESSIONS_MAX) pruneSkipSessions.clear()
1174
+ pruneSkipSessions.add(key)
929
1175
  appendV2HookLog(
930
- `[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
931
- `parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
1176
+ `[context-pruner] site=${stats.site} skip=${stats.skipReason} ` +
1177
+ `messages=${stats.messagesTouched} parts=${stats.partsPruned} ` +
1178
+ `est_tokens_saved=${stats.estimatedTokensSaved}`,
932
1179
  )
933
1180
  }
934
1181
 
@@ -989,17 +1236,6 @@ function warnContextPrunerConfigOnce(options: unknown): void {
989
1236
  }
990
1237
  }
991
1238
 
992
- // ─── Ambient memory injection (opt-in, V2 context hook) ─────────────────
993
-
994
- /**
995
- * One payload per session, computed on the session's first request. Bounded by
996
- * `MEMORY_CACHE_MAX_SESSIONS` inside the cache (FIFO), so a long-lived host
997
- * cannot grow it without limit. The payload is built, rendered and logged by
998
- * `memory-context.ts`; this module only supplies the hook wiring and the
999
- * `hooks.log` channel.
1000
- */
1001
- const memoryInjectionCache = new MemoryInjectionCache()
1002
-
1003
1239
  /**
1004
1240
  * Empty description cache for {@link sanitizeVisionHistory}.
1005
1241
  *
@@ -1024,8 +1260,8 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1024
1260
  // Config validity is independent of hook availability; warn before the early
1025
1261
  // return so a typo is visible even on a host that registers no session hook.
1026
1262
  warnContextPrunerConfigOnce(context.options)
1027
- warnInvalidMemoryInjectionConfig(context.options, appendV2HookLog)
1028
- const sessionCtx = hostDomains(context).session
1263
+ const host = hostDomains(context)
1264
+ const sessionCtx = host.session
1029
1265
 
1030
1266
  if (!sessionCtx?.hook) {
1031
1267
  return false
@@ -1037,11 +1273,6 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1037
1273
  // applies the rules unconditionally.
1038
1274
  const prunerConfig = resolveContextPrunerConfig(context.options)
1039
1275
 
1040
- // Ambient memory injection is opt-in and default OFF: with `enabled: false`
1041
- // this hook adds nothing, so `system` stays byte-identical to the policy-only
1042
- // output. Resolved here (not per request) for the same reason as the pruner.
1043
- const memoryConfig = resolveMemoryInjectionConfig(context.options)
1044
-
1045
1276
  let registered = false
1046
1277
 
1047
1278
  try {
@@ -1078,23 +1309,6 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1078
1309
  normalized.push({ type: 'text', text: POLICY } satisfies SystemPart)
1079
1310
  }
1080
1311
  }
1081
- // Opt-in ambient memory injection: the top-K memories relevant to the
1082
- // session's first user message, computed once per session and re-added
1083
- // verbatim on later requests. Deliberately OUTSIDE the block above: with
1084
- // `enabled: true` and no usable `system` there is nowhere to push, and
1085
- // the module reports `skip=no-system` once per session instead of the
1086
- // feature going silently inert. Off by default, so this is the only
1087
- // thing `enabled: false` skips.
1088
- if (memoryConfig.enabled) {
1089
- applyMemoryInjection(
1090
- normalized ?? ctx.system,
1091
- ctx.messages,
1092
- ctx.sessionID,
1093
- memoryConfig,
1094
- memoryInjectionCache,
1095
- appendV2HookLog,
1096
- )
1097
- }
1098
1312
  // Vision history sanitization (V1
1099
1313
  // `experimental.chat.messages.transform` parity, #266). Image parts are
1100
1314
  // replaced with their cached description, or with the same placeholder
@@ -1120,7 +1334,7 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1120
1334
  if (prunerConfig.enabled) {
1121
1335
  try {
1122
1336
  const stats = pruneMessages(ctx.messages, prunerConfig, 'context')
1123
- logContextPrune(stats)
1337
+ logContextPrune(stats, ctx.sessionID)
1124
1338
  logPruneShapeIssue(stats, ctx.sessionID, 'context')
1125
1339
  } catch (error) {
1126
1340
  logPruneFailureOnce(ctx.sessionID, 'context', error)
@@ -1136,10 +1350,17 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1136
1350
  }
1137
1351
 
1138
1352
  try {
1353
+ // Prompt-surface shadow points (P1 and P2) share this payload. P3 moved to
1354
+ // `tool.invoke`, where its input actually carries a complexity vector; P6
1355
+ // and P10 are unwired because no measured surface carries their inputs.
1356
+ // The sink is in-memory and bounded, exactly like P7/P8; it is created per
1357
+ // registration so one setup cannot observe another's records.
1358
+ const promptSurfaceSink = createTelemetrySink()
1359
+ promptSurfaceTelemetrySink = promptSurfaceSink
1139
1360
  // "prompt" hook — preserve attached image references and add model-visible
1140
1361
  // instructions so Zeus can inspect visual context and pass it to the
1141
1362
  // implementation specialist before editing.
1142
- await sessionCtx.hook('prompt', (event: unknown) => {
1363
+ await sessionCtx.hook('prompt', async (event: unknown) => {
1143
1364
  try {
1144
1365
  // 2.0.29 host payload: `{ sessionID, messageID, prompt: { text,
1145
1366
  // files, agents, skills }, metadata, delivery }`. The session id is
@@ -1147,17 +1368,33 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1147
1368
  // data: attachment's panic-free moment also relays it to the MCP.
1148
1369
  const admission = event as {
1149
1370
  sessionID?: unknown
1150
- prompt?: { text?: unknown; files?: unknown }
1371
+ messageID?: unknown
1372
+ prompt?: { text?: unknown; files?: unknown; skills?: unknown }
1151
1373
  } | null
1152
1374
  const prompt = admission?.prompt
1153
1375
  if (!prompt || typeof prompt.text !== 'string') return
1154
- if (prompt.text.includes('<!-- pantheon-v2-visual-context -->')) return
1155
- const sessionID =
1156
- typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
1157
- ? admission.sessionID
1158
- : undefined
1159
- const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
1160
- if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
1376
+ const userRequest = prompt.text
1377
+ if (!prompt.text.includes('<!-- pantheon-v2-visual-context -->')) {
1378
+ const sessionID =
1379
+ typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
1380
+ ? admission.sessionID
1381
+ : undefined
1382
+ const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
1383
+ if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
1384
+ }
1385
+
1386
+ // Local deterministic recommendations are advisory only. This path
1387
+ // never consults provider consent/credentials or invokes remote egress.
1388
+ await applyDecisionRouterToPrompt(admission, userRequest)
1389
+
1390
+ // Shadow observation only. The projection carries `prompt.agents` and
1391
+ // `prompt.skills` and nothing else, so no prompt text or file bytes
1392
+ // reach a record; observeShadow clones and freezes it, so admission is
1393
+ // not mutated. A failure here is contained by the outer catch and never
1394
+ // reaches the host.
1395
+ observePromptSurface(admission, (record) => {
1396
+ promptSurfaceSink.emit({ ...record, mode: 'shadow' })
1397
+ })
1161
1398
  } catch {
1162
1399
  // Fail-open: malformed/unsupported prompt shapes must not block input.
1163
1400
  }
@@ -1429,10 +1666,17 @@ function evaluateSecretScanResult(scan: HookResult): SecretScanDecision {
1429
1666
  return { action: 'fail-closed', reason: 'scanner-unexpected-exit' }
1430
1667
  }
1431
1668
 
1432
- /** Invocation of scripts/hooks/scan-secrets.sh used by the tool guard. */
1669
+ /** Invocation of the secret scan used by the tool guard. */
1433
1670
  type SecretScanRunner = (payload: HookPayload) => Promise<HookResult>
1434
1671
 
1435
- const defaultSecretScanRunner: SecretScanRunner = (payload) => runHook('scan-secrets.sh', payload)
1672
+ /**
1673
+ * The scan runs IN-PROCESS (src/pantheon/v2-hook-engine.ts, same patterns and
1674
+ * exit-code contract as the former scripts/hooks/scan-secrets.sh) so a tool
1675
+ * call no longer spawns a bash child. The runner signature and the classifier
1676
+ * below are unchanged; {@link setV2SecretScanRunnerForTests} still injects
1677
+ * structured results the in-process path cannot produce on its own.
1678
+ */
1679
+ const defaultSecretScanRunner: SecretScanRunner = async (payload) => runSecretScanInProcess(payload)
1436
1680
 
1437
1681
  let secretScanRunner: SecretScanRunner = defaultSecretScanRunner
1438
1682
 
@@ -1797,6 +2041,23 @@ async function registerV2ToolHooks(
1797
2041
 
1798
2042
  // ─── V2 Permission Hook ─────────────────────────────────────────────────
1799
2043
 
2044
+ /**
2045
+ * Read `event.effect` after P8 wrote to it, for the record.
2046
+ *
2047
+ * A hostile getter reads as `null`, which can only downgrade a recorded
2048
+ * `narrow` to `keep`, never upgrade one — the failure direction is "the record
2049
+ * claims less", never "the record claims an effect the event does not hold".
2050
+ */
2051
+ function readPermissionEffect(event: unknown): string | null {
2052
+ try {
2053
+ if (event === null || typeof event !== 'object') return null
2054
+ const effect = (event as { readonly effect?: unknown }).effect
2055
+ return typeof effect === 'string' ? effect : null
2056
+ } catch {
2057
+ return null
2058
+ }
2059
+ }
2060
+
1800
2061
  /**
1801
2062
  * Register permission hook via V2 ctx.permission.hook.
1802
2063
  *
@@ -1819,6 +2080,48 @@ async function registerV2PermissionHook(
1819
2080
  return false
1820
2081
  }
1821
2082
 
2083
+ // P8 guardrail (PLAN §5 P8, Phase 5). Constructed once at registration and
2084
+ // inert by default: `PANTHEON_V2_P8_GUARDRAIL` is absent in a default
2085
+ // install, and absent means disabled — this ships no behavioural change.
2086
+ // Enabled, it may only replace a wider effect with `deny`; it is synchronous,
2087
+ // never throws, and never runs for `decision.egress` or an existing deny.
2088
+ // Its outcome is recorded through the 0b telemetry path (in-memory, bounded,
2089
+ // I/O-free) so a narrow, a refusal and a rejected write are observable; the
2090
+ // disabled guardrail emits nothing.
2091
+ const p8Guardrail = createP8Guardrail({ enabled: p8GuardrailEnabledFromEnv() })
2092
+ const p8Sink = createTelemetrySink()
2093
+ p8TelemetrySink = p8Sink
2094
+ // The record's `mode` mirrors the P8 registry entry — `off` today — instead
2095
+ // of asserting `active` (N10a). A record may never advertise an activation
2096
+ // the registry and C8 deny, and deriving the value from the registry means
2097
+ // the two cannot drift apart again. `mode` describes the point's declared
2098
+ // mode; `decision`/`reason` carry the observation.
2099
+ const p8RegistryMode = DECISION_POINT_REGISTRY.find((point) => point.id === 'P8')?.mode ?? 'off'
2100
+ /**
2101
+ * Record one P8 outcome.
2102
+ *
2103
+ * `event` is re-read immediately before emitting: `narrowed`/`wrote` are the
2104
+ * guardrail's own post-write read, and a `Proxy` whose descriptor trap lies
2105
+ * can make that read and the next one disagree (N9). A `narrow` is therefore
2106
+ * recorded only when the event still holds `deny`; otherwise the record
2107
+ * states the effect that is actually there (`guardrail.keep` with
2108
+ * `p8.write.unconfirmed`), so sink and proof cannot contradict each other.
2109
+ */
2110
+ const recordP8 = (result: ReturnType<typeof p8Guardrail.apply>, event: unknown): void => {
2111
+ if (!p8Guardrail.enabled) return
2112
+ try {
2113
+ const unconfirmed = result.narrowed && readPermissionEffect(event) !== 'deny'
2114
+ p8Sink.emit({
2115
+ point: 'P8',
2116
+ decision: unconfirmed ? 'guardrail.keep' : result.decision,
2117
+ reason: unconfirmed ? 'p8.write.unconfirmed' : result.reason,
2118
+ mode: p8RegistryMode,
2119
+ })
2120
+ } catch {
2121
+ // Telemetry is best-effort and must not affect permission flow.
2122
+ }
2123
+ }
2124
+
1822
2125
  try {
1823
2126
  await permCtx.hook('evaluate', async (rawEvent: unknown) => {
1824
2127
  const event = rawEvent as V2PermissionEvent | null
@@ -1878,6 +2181,17 @@ async function registerV2PermissionHook(
1878
2181
  deny('permission event is missing')
1879
2182
  return
1880
2183
  }
2184
+ // `decision.egress` is Pantheon's own custom action. It is NOT decided
2185
+ // here: the user-level config/consent is the source of truth, and the
2186
+ // host's own permission rules are the kill-switch (see
2187
+ // local-decision-egress-gate). The v2.2.0 canary observed this hook runs
2188
+ // on the allow path of `permission.assert` and is skipped for an explicit
2189
+ // deny, so egress must never depend on it. Leaving the effect untouched
2190
+ // preserves whatever the host decided.
2191
+ if (event.action === DECISION_EGRESS_ACTION) {
2192
+ writeProof()
2193
+ return
2194
+ }
1881
2195
  if (!Array.isArray(event.resources) || event.resources.length === 0) {
1882
2196
  deny('permission resources are missing or malformed')
1883
2197
  return
@@ -1929,8 +2243,29 @@ async function registerV2PermissionHook(
1929
2243
  // Native-only resources remain under host policy. If a Pantheon target
1930
2244
  // appears anywhere, the shared policy evaluates the complete resource set.
1931
2245
  decision = evaluateV2Delegation(event, session, event.effect, origin)
1932
- if (decision === 'deny') deny('caller or target is not allowed by delegation policy')
1933
- else writeProof()
2246
+
2247
+ // P8 (Phase 5): read the effect left in place and, only when the flag is
2248
+ // on and a declared rule matches, replace it with `deny`. Off by default,
2249
+ // synchronous, contained — it cannot grant, delay or throw into admission.
2250
+ //
2251
+ // Apply BEFORE recording (PH5-1): `writeProof` reads `event.effect`, so a
2252
+ // proof written first recorded `effectAfter: allow` for an event P8 then
2253
+ // narrowed. The order below is apply → final effect → record, and the
2254
+ // record carries the post-apply effect plus the guardrail outcome.
2255
+ //
2256
+ // Record only after the effect is final (N10b). `deny()` below rewrites
2257
+ // the effect, and a record emitted before it would describe a state the
2258
+ // handler never leaves behind; when the delegation policy already denies,
2259
+ // the deny is the policy's, so P8 claims no narrowing at all — it changed
2260
+ // nothing about that outcome. `deny()` also throws on an immutable event,
2261
+ // and a record emitted after a throw would describe an unreached state.
2262
+ const p8Result = p8Guardrail.apply(event)
2263
+ if (decision === 'deny') {
2264
+ deny('caller or target is not allowed by delegation policy')
2265
+ return
2266
+ }
2267
+ writeProof()
2268
+ recordP8(p8Result, event)
1934
2269
  })
1935
2270
  return true
1936
2271
  } catch {
@@ -2133,7 +2468,13 @@ export const plugin = define({
2133
2468
  const boundedRead = await prepareV2BoundedRead(context).catch(() => undefined)
2134
2469
  if (boundedRead === undefined) markUnsupported('bounded-read')
2135
2470
 
2136
- // ─── Phase 2: V2 Event Subscription (best-effort) ────────────────
2471
+ // ─── Phase 2: V2 Permission Hook (best-effort) ───────────────────
2472
+ // Registered before the event subscription and session hooks so the
2473
+ // delegation matrix is enforced before any turn runs. Egress never depends
2474
+ // on this hook: the user-level config plus the host's own rules gate it.
2475
+ await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
2476
+
2477
+ // ─── Phase 3: V2 Event Subscription (best-effort) ────────────────
2137
2478
  const eventCleanup = subscribeV2Events(context, boundedRead?.clearSession)
2138
2479
  if (eventCleanup) {
2139
2480
  activeCleanups.push(eventCleanup)
@@ -2141,13 +2482,13 @@ export const plugin = define({
2141
2482
  markUnsupported('event-stream')
2142
2483
  }
2143
2484
 
2144
- // ─── Phase 3: V2 Session Hooks (best-effort) ─────────────────────
2485
+ // ─── Phase 4: V2 Session Hooks (best-effort) ─────────────────────
2145
2486
  const sessionHooksRegistered = await registerV2SessionHooks(context).catch(() => false)
2146
2487
  if (!sessionHooksRegistered) {
2147
2488
  markUnsupported('session-hooks')
2148
2489
  }
2149
2490
 
2150
- // ─── Phase 4: V2 Tool Hooks (best-effort) ────────────────────────
2491
+ // ─── Phase 5: V2 Tool Hooks (best-effort) ────────────────────────
2151
2492
  const toolHookResult = await registerV2ToolHooks(
2152
2493
  context,
2153
2494
  subagentOrigins,
@@ -2157,7 +2498,7 @@ export const plugin = define({
2157
2498
  markUnsupported('tool-execute-hooks')
2158
2499
  }
2159
2500
 
2160
- // ─── Phase 5: V2 Tool Registration (best-effort) ─────────────────
2501
+ // ─── Phase 6: V2 Tool Registration (best-effort) ─────────────────
2161
2502
  const boundedReadDefinition = toolHookResult.beforeRegistered
2162
2503
  ? boundedRead?.definition
2163
2504
  : undefined
@@ -2167,9 +2508,6 @@ export const plugin = define({
2167
2508
  const toolsRegistered = await registerV2Tools(context, boundedReadDefinition).catch(() => false)
2168
2509
  if (!toolsRegistered) markUnsupported('tool-transform')
2169
2510
 
2170
- // ─── Phase 6: V2 Permission Hook (best-effort) ───────────────────
2171
- await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
2172
-
2173
2511
  // ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
2174
2512
  const compactionCtx = hostDomains(context).session
2175
2513
  if (compactionCtx?.hook) {
@@ -2177,6 +2515,10 @@ export const plugin = define({
2177
2515
  // active goals per session, and the store needs no host API (same
2178
2516
  // `.pantheon/goals` directory V1 uses).
2179
2517
  const goalStore = new GoalStore({ dir: '.pantheon/goals' })
2518
+ // P9's record sink, created per registration (in-memory, bounded,
2519
+ // I/O-free) so one setup cannot observe another's records.
2520
+ const p9Sink = createTelemetrySink()
2521
+ p9TelemetrySink = p9Sink
2180
2522
  try {
2181
2523
  // 2.0.16 `SessionHooks` key is `compaction` (the migration doc maps
2182
2524
  // `experimental.session.compacting` → `ctx.session.hook("compaction")`).
@@ -2225,9 +2567,37 @@ export const plugin = define({
2225
2567
  : typeof payload?.session?.id === 'string'
2226
2568
  ? payload.session.id
2227
2569
  : undefined
2570
+
2571
+ // P9 (compaction) shadow observation, on the MEASURED carrier only.
2572
+ // The 2.2.5 compaction payload carries a TOP-LEVEL `sessionID` and
2573
+ // no nested `session` object at all (PROBE-A, 11/11 runs), so the
2574
+ // event is handed to the adapter as-is and it reads
2575
+ // `payload.sessionID` — never `session.id`, which is absent there.
2576
+ // A payload that carries only a nested id therefore produces NO
2577
+ // decision (fail-closed) rather than being keyed by a carrier the
2578
+ // host was never observed to send. This runs BEFORE the pruner and
2579
+ // the context injection below, so `systemPartCount` describes the
2580
+ // host payload and not the blocks Pantheon appends; the adapter
2581
+ // clones what it reads and pushes nothing itself, so the injected
2582
+ // context is unchanged — shadow is the record, nothing else.
2583
+ // Child-session compaction is measured and needs no separate path:
2584
+ // PROBE-G §3.1 fired this hook on a real child 3/3 with the CHILD
2585
+ // sessionID at top level and the same payload shape (7 keys, no
2586
+ // nested `session`, `system` array of 4). Compaction with
2587
+ // `reason:"overflow"` was NOT inducible in 6 error shapes (PROBE-G
2588
+ // §3.2 — the host retried and completed, and the one
2589
+ // failure-recovery compaction was persisted as `reason:"auto"`), so
2590
+ // that path remains unmeasured and is not designed for here.
2591
+ try {
2592
+ evaluateCompactionMemoryPoint({ payload }, (record) => {
2593
+ p9Sink.emit({ ...record, mode: 'shadow' })
2594
+ })
2595
+ } catch {
2596
+ // Observation must never reach the compaction request.
2597
+ }
2228
2598
  const prunerConfig = resolveContextPrunerConfig(context.options)
2229
2599
  const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
2230
- logContextPrune(stats)
2600
+ logContextPrune(stats, sessionID)
2231
2601
  logPruneShapeIssue(stats, sessionID, 'compaction')
2232
2602
 
2233
2603
  // Compaction context (V1 `experimental.session.compacting`