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
@@ -0,0 +1,263 @@
1
+ /**
2
+ * P7 (loop) migration adapter — a per-EXECUTION counter on the measured event
3
+ * channel.
4
+ *
5
+ * PLAN §5.1 branch 1 was selected by measurement (PROBE-D §7): the channel
6
+ * covers child sessions and background work, so this adapter is built on
7
+ * `session.execution.succeeded`. It consumes through the 0b contract
8
+ * (`v2-decision-events.ts`, PLAN §5.2) and reads only `data.sessionID`; the
9
+ * unmetered `properties` field is never read.
10
+ *
11
+ * ## The counter is per execution, not per turn (PROBE-D §4.3)
12
+ *
13
+ * `session.execution.started` and `session.execution.succeeded` are 1:1 in
14
+ * 44/44 measured executions. An execution is the drain of a session's inbox,
15
+ * and the mapping to turns is not one-to-one:
16
+ *
17
+ * - one prompt drained at a time → +1 (T1–T4: 1 prompt = 1 execution;
18
+ * M1: 3 prompts = 3 executions);
19
+ * - a manual/scheduled compaction job gets its own execution → +1
20
+ * (C2: 2 prompts + 1 compaction = 3 executions);
21
+ * - automatic compaction happens *inside* a running execution → +0
22
+ * (C1: 1 prompt + auto compaction = 1 execution);
23
+ * - a background job notification that arrives after the parent's drain
24
+ * opens a new execution → +1 on the parent (B3/B4/B5 = 2; B1/B2 = 1,
25
+ * where the notification was folded into the running drain);
26
+ * - 46 inbox items produced 44 executions: items that arrive during a drain
27
+ * are folded into it (B1/B2), so neither prompts nor inbox items are the
28
+ * counted unit.
29
+ *
30
+ * A child session's executions are keyed by the child's own `sessionID`
31
+ * (13/13 children carry one). The event does **not** carry `parentID`
32
+ * (44/44), so this adapter never derives a parent; attribution, when a caller
33
+ * needs it, comes from `session.created.parentID` or `ctx.session.get`
34
+ * (PROBE-D §4.1).
35
+ *
36
+ * ## Fail-closed
37
+ *
38
+ * A payload without a usable `data.sessionID`, a payload of another type, and
39
+ * a malformed payload all produce **no decision** with a reason token. Nothing
40
+ * is guessed from `properties`, from a top-level field, or from a partial
41
+ * shape, and nothing is thrown into the dispatch loop.
42
+ *
43
+ * ## No effect
44
+ *
45
+ * The flag is OFF by default (`PANTHEON_V2_P7_LOOP`), so the plugin wiring is
46
+ * inert. Even when enabled, this adapter only observes and records: the shadow
47
+ * record says `effect: 'none'`, and activation is Phase 4b, not this module.
48
+ * `execute.before` remains the only hard barrier.
49
+ *
50
+ * ## The execution cap is advisory
51
+ *
52
+ * `P7_LOOP_MAX_EXECUTIONS` is a declared convention, not an enforced limit.
53
+ * `reset()` is caller-supplied, and no measured surface in the probed host
54
+ * delivers a user-input signal to call it: nothing in this process clears a
55
+ * streak, on any event. A long session therefore crosses the declared cap and
56
+ * the decision becomes `loop.stop` — which, with `effect: 'none'`, changes
57
+ * nothing the host does. The cap is not claimed to reset on any event; it
58
+ * resets only when a caller invokes `reset(sessionID)` explicitly.
59
+ */
60
+
61
+ import {
62
+ consumeDecisionEvents,
63
+ type DecisionEvent,
64
+ type DecisionEventSource,
65
+ type EventConsumptionOptions,
66
+ type EventConsumptionSummary,
67
+ P7_TURN_END_EVENT_TYPE,
68
+ readEventSessionID,
69
+ } from '../v2-decision-events.ts'
70
+ import { observeShadow, type ShadowRecord, type ShadowSink } from '../v2-decision-shadow.ts'
71
+
72
+ /** On/off switch read by the plugin wiring. Any other value means off. */
73
+ export const P7_LOOP_FLAG_ENV = 'PANTHEON_V2_P7_LOOP'
74
+
75
+ /** Execution counts at which the ordinal loop-pressure score rises. */
76
+ export const P7_LOOP_SCORE_THRESHOLDS = Object.freeze([2, 4] as const)
77
+
78
+ /** Declared, advisory cap: past this many executions the adapter reports `loop.stop`. */
79
+ export const P7_LOOP_MAX_EXECUTIONS = 12
80
+
81
+ /**
82
+ * The adapter's own policy — declared, frozen and never measured.
83
+ *
84
+ * `score` is `1 + thresholds met`, so it rises with consecutive executions and
85
+ * saturates at 3. `noul` permits a continuation up to the cap; past it, the
86
+ * declared answer is to stop. This is a deterministic convention, not a claim
87
+ * about loop quality, and the cap is **advisory**: `reset()` is caller-supplied
88
+ * and no measured surface in the probed host provides a user-input signal, so
89
+ * nothing in this process resets a streak. See the module header.
90
+ */
91
+ export const P7_LOOP_POLICY = Object.freeze({
92
+ scoreThresholds: P7_LOOP_SCORE_THRESHOLDS,
93
+ maxExecutions: P7_LOOP_MAX_EXECUTIONS,
94
+ })
95
+
96
+ /** `noul` + `score` over the per-session execution count. */
97
+ export interface P7LoopDecision {
98
+ /** `noul`: 1 permits a continuation, 0 stops at the declared cap. */
99
+ readonly continueLoop: 0 | 1
100
+ /** `score`: ordinal loop pressure, 1..3. */
101
+ readonly level: 1 | 2 | 3
102
+ }
103
+
104
+ export interface P7LoopPointResult {
105
+ /** `null` when disabled or when the payload yields no decision. */
106
+ readonly record: ShadowRecord | null
107
+ readonly enabled: boolean
108
+ /** Child or top-level session id read from `data.sessionID`; never a parent. */
109
+ readonly sessionID: string | null
110
+ /** Executions delivered for this session; never a turn or inbox-item count. */
111
+ readonly executionCount: number
112
+ /** `null` when no decision could be stated (fail-closed). */
113
+ readonly loopDecision: P7LoopDecision | null
114
+ /** Token explaining the outcome; always present. */
115
+ readonly reason: string
116
+ }
117
+
118
+ export interface P7LoopPointOptions {
119
+ /** Defaults to `false`: the adapter is inert unless explicitly enabled. */
120
+ readonly enabled?: boolean
121
+ readonly sink?: ShadowSink
122
+ }
123
+
124
+ export interface P7LoopConsumeOptions {
125
+ readonly signal: AbortSignal
126
+ /** Upper bound so a harness run cannot consume an unbounded stream. */
127
+ readonly maxEvents?: number
128
+ }
129
+
130
+ export interface P7LoopPoint {
131
+ readonly enabled: boolean
132
+ /** Observe one raw host envelope from a dispatch loop. Never throws. */
133
+ observe(payload: unknown): P7LoopPointResult
134
+ /** Consume a stream through the 0b contract, filtering client-side. */
135
+ subscribe(
136
+ source: DecisionEventSource,
137
+ options: P7LoopConsumeOptions,
138
+ ): Promise<EventConsumptionSummary>
139
+ /** Executions recorded for a session since construction (or last reset). */
140
+ executionCount(sessionID: string): number
141
+ /** Clear one session's streak. Caller-supplied only — the cap is advisory. */
142
+ reset(sessionID: string): void
143
+ }
144
+
145
+ function isRecord(value: unknown): value is Record<string, unknown> {
146
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
147
+ }
148
+
149
+ /** Whether the operator explicitly enabled the flag. Absence means off. */
150
+ export function p7LoopEnabledFromEnv(
151
+ env: Record<string, string | undefined> = process.env,
152
+ ): boolean {
153
+ const raw = (env[P7_LOOP_FLAG_ENV] ?? '').trim().toLowerCase()
154
+ return raw === '1' || raw === 'on' || raw === 'true'
155
+ }
156
+
157
+ function decisionFor(executionCount: number): P7LoopDecision {
158
+ const met = P7_LOOP_SCORE_THRESHOLDS.filter((threshold) => executionCount >= threshold).length
159
+ return Object.freeze({
160
+ continueLoop: executionCount <= P7_LOOP_MAX_EXECUTIONS ? 1 : 0,
161
+ level: Math.min(3, 1 + met) as 1 | 2 | 3,
162
+ })
163
+ }
164
+
165
+ function noDecision(
166
+ enabled: boolean,
167
+ sessionID: string | null,
168
+ executionCount: number,
169
+ reason: string,
170
+ ): P7LoopPointResult {
171
+ return Object.freeze({
172
+ record: null,
173
+ enabled,
174
+ sessionID,
175
+ executionCount,
176
+ loopDecision: null,
177
+ reason,
178
+ })
179
+ }
180
+
181
+ /**
182
+ * Create a P7 adapter instance.
183
+ *
184
+ * State is per instance and per session: one counter per `sessionID`, never a
185
+ * process-wide turn count. A child session is counted on its own id.
186
+ */
187
+ export function createP7LoopPoint(options: P7LoopPointOptions = {}): P7LoopPoint {
188
+ const enabled = options.enabled === true
189
+ const executions = new Map<string, number>()
190
+
191
+ function recordExecution(sessionID: string): P7LoopPointResult {
192
+ if (!enabled) return noDecision(false, sessionID, 0, 'p7.disabled')
193
+
194
+ const executionCount = (executions.get(sessionID) ?? 0) + 1
195
+ executions.set(sessionID, executionCount)
196
+
197
+ const record = observeShadow(
198
+ 'P7',
199
+ { sessionID, executionCount },
200
+ (isolated) => {
201
+ const count =
202
+ isRecord(isolated) && typeof isolated.executionCount === 'number'
203
+ ? isolated.executionCount
204
+ : 0
205
+ const decision = decisionFor(count)
206
+ return decision.continueLoop === 1
207
+ ? { decision: 'loop.continue', reason: 'p7.execution.counted' }
208
+ : { decision: 'loop.stop', reason: 'p7.execution.exhausted' }
209
+ },
210
+ options.sink,
211
+ )
212
+
213
+ const contained = record.decision === 'unavailable'
214
+ return Object.freeze({
215
+ record,
216
+ enabled: true,
217
+ sessionID,
218
+ executionCount,
219
+ loopDecision: contained ? null : decisionFor(executionCount),
220
+ reason: record.reason,
221
+ })
222
+ }
223
+
224
+ function observe(payload: unknown): P7LoopPointResult {
225
+ if (!enabled) return noDecision(false, null, 0, 'p7.disabled')
226
+ if (!isRecord(payload)) return noDecision(true, null, 0, 'p7.event.absent')
227
+ if (typeof payload.type !== 'string') return noDecision(true, null, 0, 'p7.event.absent')
228
+ if (payload.type !== P7_TURN_END_EVENT_TYPE) {
229
+ return noDecision(true, null, 0, 'p7.event.unrelated')
230
+ }
231
+ const sessionID = readEventSessionID(payload)
232
+ if (sessionID === null) return noDecision(true, null, 0, 'p7.session.absent')
233
+ return recordExecution(sessionID)
234
+ }
235
+
236
+ async function subscribe(
237
+ source: DecisionEventSource,
238
+ consumeOptions: P7LoopConsumeOptions,
239
+ ): Promise<EventConsumptionSummary> {
240
+ const consumption: EventConsumptionOptions = {
241
+ types: [P7_TURN_END_EVENT_TYPE],
242
+ signal: consumeOptions.signal,
243
+ onEvent: (event: DecisionEvent) => {
244
+ if (event.type !== P7_TURN_END_EVENT_TYPE) return
245
+ recordExecution(event.sessionID)
246
+ },
247
+ ...(consumeOptions.maxEvents === undefined ? {} : { maxEvents: consumeOptions.maxEvents }),
248
+ }
249
+ return consumeDecisionEvents(source, consumption)
250
+ }
251
+
252
+ return Object.freeze({
253
+ enabled,
254
+ observe,
255
+ subscribe,
256
+ executionCount(sessionID: string): number {
257
+ return executions.get(sessionID) ?? 0
258
+ },
259
+ reset(sessionID: string): void {
260
+ executions.delete(sessionID)
261
+ },
262
+ })
263
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * P8 (guardrail) — an off-by-default `noul` filter that can only narrow.
3
+ *
4
+ * `execute.before` is the only hard barrier in the V2 surface. P8 sits *below*
5
+ * it and never above it, built around one property: for every input x,
6
+ * `p8(x) ⊆ baseline(x)`. Narrowing (allow → deny) is legal; granting is not,
7
+ * under any input and any flag value. That is structural, not policy: the only
8
+ * effect this module can write is the literal `'deny'`, and the only other value
9
+ * it can report is the baseline it read. No branch produces `'allow'` or `'ask'`.
10
+ * {@link p8NarrowsOnly} states the property; the test suite enumerates it.
11
+ *
12
+ * The write path also requires the event's `effect` to be an **own writable data
13
+ * property** before `Reflect.set` runs. A descriptor that is an accessor (own
14
+ * getter/setter) or absent (the write would delegate to the prototype) is
15
+ * refused with `p8.write.delegation` instead of trusting whatever `set` the
16
+ * host installed. Without that check, "narrowing-only for every input" would
17
+ * hold for data properties only.
18
+ *
19
+ * ## Record truthfulness (N9)
20
+ *
21
+ * `wrote` and `narrowed` describe this module's own post-write read. JavaScript
22
+ * offers no way to tell an exotic target (a `Proxy` with a lying descriptor
23
+ * trap) from a plain object, and any number of in-process reads can be made to
24
+ * disagree. The guarantee is therefore not "the target accepted the write" but
25
+ * "the effect recorded is the effect the event holds when the record is
26
+ * produced": the plugin re-reads `event.effect` after the effect is final and
27
+ * records `guardrail.narrow` only if that read still says `deny`. This module
28
+ * never widens either way — a mismatch downgrades a claim, never an effect.
29
+ *
30
+ * ## Blast radius (N5) — measured: the declared rules match nothing
31
+ *
32
+ * PROBE-F (permission.evaluate paths; measured facts summarized in
33
+ * docs/reference/local-decision-router.md) delivered 24 real
34
+ * `permission.evaluate` events on the 2.2.5 host. Every one
35
+ * carries a valid `action` token and a non-empty top-level `sessionID`
36
+ * (PROBE-F §3.2), so neither declared rule can match: `action.unusable` needs a
37
+ * non-token action, `allow.unattributed` needs an `allow` with no session. With
38
+ * the flag on the outcome is `p8.rule.none` → `guardrail.keep`, i.e. **inert**
39
+ * (PROBE-F §6 I-F3: the rules were matched statically against the measured
40
+ * payload; the flag itself was never enabled). The availability risk the
41
+ * phase-5 review named — denying native events with no `action` — does not
42
+ * materialise on this host, because the host always supplies one. The real
43
+ * finding is the opposite: no narrowing.
44
+ *
45
+ * An unrecognised effect is not a barrier either. The host treats a value it
46
+ * does not recognise as `ask`, resolves it, and executes (PROBE-F §3.6), so
47
+ * "refuse and keep" does not block. `execute.before` remains the only hard
48
+ * barrier: a `throw` there denies and skips permission evaluation, while a
49
+ * `throw` here does not deny at all (PROBE-F §3.7).
50
+ *
51
+ * Off by default: `PANTHEON_V2_P8_GUARDRAIL` is absent in a default install and
52
+ * absence means disabled, so this phase ships no behavioural change. Evaluation
53
+ * is synchronous with no I/O (it cannot delay admission), and every failure —
54
+ * unreadable payload, unrecognized baseline, a host event that refuses the
55
+ * write — resolves to "leave the baseline alone". A guardrail that cannot
56
+ * narrow is a no-op, not an allow.
57
+ *
58
+ * ## Path coverage — measured host paths, no observed narrowing
59
+ *
60
+ * `PM-09` recorded that these surfaces never fired; PROBE-F fired them and
61
+ * measured 9 of the 10 rows below. A row's `measured` status means the host path
62
+ * was observed — **not** that P8 narrowed on it: no rule matched on any measured
63
+ * payload, so no narrowing exists to observe. `unmeasured` is reserved for the
64
+ * one path PROBE-F could not reach. Evidence cites the probe section; PROBE-F
65
+ * proposes `F-42…F-48` but those ids are not assigned in this change, and this
66
+ * module must not invent them (PLAN §5.4). {@link P8_PATH_COVERAGE} is the
67
+ * machine-readable form.
68
+ *
69
+ * | path | status | evidence |
70
+ * |--------------------------------------------------------|------------|----------------|
71
+ * | permission.evaluate: hook delivery | measured | PROBE-F §3.1 |
72
+ * | permission.evaluate: payload shape (action/sessionID…) | measured | PROBE-F §3.2 |
73
+ * | permission.evaluate: `event.effect` write is honored | measured | PROBE-F §3.4 |
74
+ * | permission.evaluate: ordering vs. the host rules | measured | PROBE-F §3.3 |
75
+ * | permission.evaluate: existing `deny` early return | measured | PROBE-F §3.5 |
76
+ * | permission.evaluate: `decision.egress` early return | unmeasured | PROBE-F §3.9 |
77
+ * | permission.evaluate: unknown/unrecognized baseline | measured | PROBE-F §3.6 |
78
+ * | execute.before: delivery | measured | PROBE-F §3.8 |
79
+ * | execute.before: payload shape | measured | PROBE-F §3.8 |
80
+ * | execute.before: throw-to-deny semantics | measured | PROBE-F §3.7 |
81
+ *
82
+ * `permission.evaluate.egress` is unreachable in this host: a tool that declares
83
+ * the `decision.egress` permission registers but is never advertised to the
84
+ * provider, so the action never reaches the hook (PROBE-F §3.9). Its early
85
+ * return therefore reads a branch that was never delivered.
86
+ *
87
+ * On `execute.before` P8 adds no barrier: a second barrier is the widening risk
88
+ * this phase must not take, and narrowing is optional (equality is a subset).
89
+ */
90
+
91
+ /** On/off switch read by the plugin wiring. Any other value means off. */
92
+ export const P8_GUARDRAIL_FLAG_ENV = 'PANTHEON_V2_P8_GUARDRAIL'
93
+
94
+ /** Permissiveness order. A decision may only move down this scale. */
95
+ export const P8_EFFECT_RANK = Object.freeze({ deny: 0, ask: 1, allow: 2 } as const)
96
+
97
+ export type P8PermissionEffect = keyof typeof P8_EFFECT_RANK
98
+
99
+ /**
100
+ * Declared narrowing rules — syntax only, never a measured payload semantic, so
101
+ * a rule that could widen cannot be introduced by editing a branch.
102
+ */
103
+ export const P8_RULES = Object.freeze([
104
+ /** The baseline is not attributable: no printable action token. */
105
+ 'p8.rule.action.unusable',
106
+ /** An `allow` that names no session cannot be audited. */
107
+ 'p8.rule.allow.unattributed',
108
+ ] as const)
109
+
110
+ export type P8RuleId = (typeof P8_RULES)[number]
111
+
112
+ export type P8Outcome = 'guardrail.keep' | 'guardrail.narrow' | 'guardrail.refusal'
113
+
114
+ /**
115
+ * `measured`: the host path was observed in PROBE-F and the evidence names the
116
+ * probe section (the `F-` ids for PROBE-F are proposed but not yet assigned).
117
+ * `unmeasured`: the path was never exercised. Neither value claims a P8
118
+ * narrowing — no measured payload matched a declared rule.
119
+ */
120
+ export type P8PathStatus = 'measured' | 'unmeasured'
121
+
122
+ export interface P8PathCoverage {
123
+ readonly path: string
124
+ readonly status: P8PathStatus
125
+ /** Probe section that observed the path; the premise id when unmeasured. */
126
+ readonly evidence: readonly string[]
127
+ }
128
+
129
+ /** Every path P8 touches. Frozen: a path cannot be dropped silently. */
130
+ export const P8_PATH_COVERAGE: readonly P8PathCoverage[] = Object.freeze([
131
+ { path: 'permission.evaluate.delivery', status: 'measured', evidence: ['PROBE-F §3.1'] },
132
+ { path: 'permission.evaluate.payload-shape', status: 'measured', evidence: ['PROBE-F §3.2'] },
133
+ { path: 'permission.evaluate.effect-write', status: 'measured', evidence: ['PROBE-F §3.4'] },
134
+ { path: 'permission.evaluate.ordering', status: 'measured', evidence: ['PROBE-F §3.3'] },
135
+ { path: 'permission.evaluate.existing-deny', status: 'measured', evidence: ['PROBE-F §3.5'] },
136
+ { path: 'permission.evaluate.egress', status: 'unmeasured', evidence: ['PROBE-F §3.9'] },
137
+ {
138
+ path: 'permission.evaluate.unknown-baseline',
139
+ status: 'measured',
140
+ evidence: ['PROBE-F §3.6'],
141
+ },
142
+ { path: 'execute.before.delivery', status: 'measured', evidence: ['PROBE-F §3.8'] },
143
+ { path: 'execute.before.payload-shape', status: 'measured', evidence: ['PROBE-F §3.8'] },
144
+ { path: 'execute.before.throw-to-deny', status: 'measured', evidence: ['PROBE-F §3.7'] },
145
+ ])
146
+
147
+ const ACTION_TOKEN = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/
148
+ const REASON_TOKEN = /^[a-z0-9][a-z0-9.:-]{0,63}$/
149
+
150
+ export interface P8GuardrailOptions {
151
+ /** Defaults to `false`: absence of the flag means disabled. */
152
+ readonly enabled?: boolean
153
+ }
154
+
155
+ export interface P8GuardrailInput {
156
+ /** Effect the host/delegation produced. Read, never inferred. */
157
+ readonly baseline: unknown
158
+ /** Permission event as delivered (measured shape: PROBE-F §3.2). */
159
+ readonly event?: unknown
160
+ }
161
+
162
+ export interface P8GuardrailDecision {
163
+ readonly enabled: boolean
164
+ readonly decision: P8Outcome
165
+ /** The baseline, or `deny`. Never a value the baseline did not have. */
166
+ readonly effect: P8PermissionEffect | 'unavailable'
167
+ /** True only when `deny` replaced a wider baseline. */
168
+ readonly narrowed: boolean
169
+ readonly rules: readonly string[]
170
+ /** Token explaining the outcome; always present. */
171
+ readonly reason: string
172
+ }
173
+
174
+ export interface P8ApplyResult extends P8GuardrailDecision {
175
+ /** True only when this call wrote `deny` onto the event. */
176
+ readonly wrote: boolean
177
+ }
178
+
179
+ function isRecord(value: unknown): value is Record<string, unknown> {
180
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
181
+ }
182
+
183
+ function isNonEmptyString(value: unknown): value is string {
184
+ return typeof value === 'string' && value.trim().length > 0
185
+ }
186
+
187
+ /** Rank of a known effect; `null` for anything else (unprovable baseline). */
188
+ export function p8EffectRank(effect: unknown): number | null {
189
+ if (typeof effect !== 'string' || !Object.hasOwn(P8_EFFECT_RANK, effect)) return null
190
+ return P8_EFFECT_RANK[effect as P8PermissionEffect]
191
+ }
192
+
193
+ /** `true` only when both values are recognized and `p8` is at most the baseline. */
194
+ export function p8NarrowsOnly(baseline: unknown, effect: unknown): boolean {
195
+ const base = p8EffectRank(baseline)
196
+ const next = p8EffectRank(effect)
197
+ if (base === null || next === null) return false
198
+ return next <= base
199
+ }
200
+
201
+ function readEffect(value: unknown): P8PermissionEffect | null {
202
+ const rank = p8EffectRank(value)
203
+ if (rank === null) return null
204
+ return value as P8PermissionEffect
205
+ }
206
+
207
+ /** Rules that match, in declaration order. Cannot return a wider decision. */
208
+ function matchedRules(event: unknown, baseline: P8PermissionEffect): readonly P8RuleId[] {
209
+ const record = isRecord(event) ? event : null
210
+ const matched: P8RuleId[] = []
211
+ if (typeof record?.action !== 'string' || !ACTION_TOKEN.test(record.action)) {
212
+ matched.push('p8.rule.action.unusable')
213
+ }
214
+ if (baseline === 'allow' && !isNonEmptyString(record?.sessionID)) {
215
+ matched.push('p8.rule.allow.unattributed')
216
+ }
217
+ return matched
218
+ }
219
+
220
+ function decision(
221
+ enabled: boolean,
222
+ outcome: P8Outcome,
223
+ effect: P8PermissionEffect | 'unavailable',
224
+ baseline: P8PermissionEffect | null,
225
+ rules: readonly string[],
226
+ reason: string,
227
+ ): P8GuardrailDecision {
228
+ const token = REASON_TOKEN.test(reason) ? reason : 'p8.reason.invalid'
229
+ const narrowed = effect === 'deny' && baseline !== null && baseline !== 'deny'
230
+ const safeOutcome: P8Outcome = narrowed ? 'guardrail.narrow' : outcome
231
+ return Object.freeze({
232
+ enabled,
233
+ decision: safeOutcome,
234
+ effect,
235
+ narrowed,
236
+ rules: Object.freeze([...rules]),
237
+ reason: token,
238
+ })
239
+ }
240
+
241
+ /** Evaluate P8. Disabled echoes the baseline; an unrecognized baseline refuses. */
242
+ export function evaluateP8Guardrail(
243
+ input: P8GuardrailInput,
244
+ options: P8GuardrailOptions = {},
245
+ ): P8GuardrailDecision {
246
+ const enabled = options.enabled === true
247
+ let baseline: P8PermissionEffect | null
248
+ try {
249
+ baseline = readEffect(input.baseline)
250
+ } catch {
251
+ baseline = null
252
+ }
253
+ if (baseline === null) {
254
+ return decision(
255
+ enabled,
256
+ 'guardrail.refusal',
257
+ 'unavailable',
258
+ null,
259
+ [],
260
+ 'p8.baseline.unrecognized',
261
+ )
262
+ }
263
+ if (!enabled) return decision(false, 'guardrail.keep', baseline, baseline, [], 'p8.disabled')
264
+ if (baseline === 'deny') {
265
+ return decision(true, 'guardrail.keep', 'deny', baseline, [], 'p8.baseline.deny')
266
+ }
267
+ let rules: readonly P8RuleId[]
268
+ try {
269
+ rules = matchedRules(input.event, baseline)
270
+ } catch {
271
+ // The baseline was readable, so the honest answer is "keep it": an
272
+ // unreadable event is a missing narrowing opportunity, never a grant.
273
+ return decision(true, 'guardrail.keep', baseline, baseline, [], 'p8.event.unreadable')
274
+ }
275
+ if (rules.length === 0)
276
+ return decision(true, 'guardrail.keep', baseline, baseline, [], 'p8.rule.none')
277
+ return decision(true, 'guardrail.narrow', 'deny', baseline, rules, 'p8.rule.matched')
278
+ }
279
+
280
+ /**
281
+ * Classify `event.effect` before writing it.
282
+ *
283
+ * `delegation`: the own descriptor is absent or an accessor, so an assignment
284
+ * would create a property or run a host setter — the write is refused.
285
+ * `non-writable`: an own data property that cannot be replaced — also refused,
286
+ * with the existing `p8.write.rejected` token.
287
+ * `writable`: an own writable data property, the only safe target.
288
+ */
289
+ function effectWriteKind(target: object): 'writable' | 'delegation' | 'non-writable' {
290
+ const descriptor = Object.getOwnPropertyDescriptor(target, 'effect')
291
+ if (descriptor === undefined || !Object.hasOwn(descriptor, 'value')) return 'delegation'
292
+ return descriptor.writable === true ? 'writable' : 'non-writable'
293
+ }
294
+
295
+ function refusedWrite(
296
+ enabled: boolean,
297
+ baseline: P8PermissionEffect | null,
298
+ reason: string,
299
+ ): P8ApplyResult {
300
+ return Object.freeze({
301
+ ...decision(enabled, 'guardrail.keep', baseline ?? 'unavailable', baseline, [], reason),
302
+ wrote: false,
303
+ })
304
+ }
305
+
306
+ /**
307
+ * Apply P8 to a permission event: read `event.effect`, write `'deny'` only when
308
+ * a rule matched. A refused write leaves the baseline and reports
309
+ * `p8.write.rejected` (frozen/non-writable or a throwing target) or
310
+ * `p8.write.delegation` (accessor or non-own descriptor); this never throws
311
+ * into admission.
312
+ */
313
+ export function applyP8ToPermissionEvent(
314
+ event: unknown,
315
+ options: P8GuardrailOptions = {},
316
+ ): P8ApplyResult {
317
+ const enabled = options.enabled === true
318
+ let baseline: P8PermissionEffect | null = null
319
+ try {
320
+ baseline = readEffect(isRecord(event) ? event.effect : undefined)
321
+ } catch {
322
+ baseline = null
323
+ }
324
+ const evaluated = evaluateP8Guardrail({ baseline, event }, options)
325
+ if (!evaluated.narrowed) return Object.freeze({ ...evaluated, wrote: false })
326
+ try {
327
+ if (!isRecord(event)) return refusedWrite(enabled, baseline, 'p8.write.delegation')
328
+ const kind = effectWriteKind(event)
329
+ if (kind === 'delegation') return refusedWrite(enabled, baseline, 'p8.write.delegation')
330
+ if (kind === 'non-writable') return refusedWrite(enabled, baseline, 'p8.write.rejected')
331
+ // `Reflect.set` reports a refused write instead of throwing in strict mode,
332
+ // so a frozen host object cannot turn P8 into an exception in admission.
333
+ const assigned = Reflect.set(event, 'effect', 'deny')
334
+ if (!assigned || event.effect !== 'deny') {
335
+ return refusedWrite(enabled, baseline, 'p8.write.rejected')
336
+ }
337
+ return Object.freeze({ ...evaluated, wrote: true })
338
+ } catch {
339
+ return refusedWrite(enabled, baseline, 'p8.write.rejected')
340
+ }
341
+ }
342
+
343
+ export interface P8Guardrail {
344
+ readonly enabled: boolean
345
+ /** Pure evaluation; never throws, never writes. */
346
+ evaluate(input: P8GuardrailInput): P8GuardrailDecision
347
+ /** Narrowing-only application; never throws, may write `deny` only. */
348
+ apply(event: unknown): P8ApplyResult
349
+ }
350
+
351
+ /** Whether the operator explicitly enabled the flag. Absence means off. */
352
+ export function p8GuardrailEnabledFromEnv(
353
+ env: Record<string, string | undefined> = process.env,
354
+ ): boolean {
355
+ const raw = (env[P8_GUARDRAIL_FLAG_ENV] ?? '').trim().toLowerCase()
356
+ return raw === '1' || raw === 'on' || raw === 'true'
357
+ }
358
+
359
+ /** Create a P8 instance. Disabled unless the caller says otherwise. */
360
+ export function createP8Guardrail(options: P8GuardrailOptions = {}): P8Guardrail {
361
+ const enabled = options.enabled === true
362
+ return Object.freeze({
363
+ enabled,
364
+ evaluate: (input: P8GuardrailInput) => evaluateP8Guardrail(input, { enabled }),
365
+ apply: (event: unknown) => applyP8ToPermissionEvent(event, { enabled }),
366
+ })
367
+ }