pantheon-opencode 1.6.2-beta.4 → 1.6.2-beta.5

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 (54) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +174 -3
  3. package/bin/pantheon-init.mjs +6 -1
  4. package/package.json +1 -1
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +3 -3
  8. package/scripts/decision-router-v2-budget.mjs +218 -0
  9. package/scripts/decision-router-v2-egress.mjs +272 -0
  10. package/scripts/decision-router.mjs +268 -46
  11. package/scripts/docs-check-changelog.mjs +5 -3
  12. package/scripts/install/decision-layer-preview.mjs +376 -0
  13. package/scripts/install/decision-router-config.mjs +158 -11
  14. package/scripts/mcp_resources.py +11 -9
  15. package/scripts/release-notes.mjs +30 -7
  16. package/scripts/versioning.mjs +41 -5
  17. package/src/mcp/eval_store.py +11 -4
  18. package/src/mcp/mcp_resources.py +11 -9
  19. package/src/mcp/memory_mcp.py +293 -150
  20. package/src/pantheon/local-decision-prompt.ts +181 -36
  21. package/src/pantheon/local-decision-skills.ts +115 -5
  22. package/src/pantheon/local-decision-tool.ts +35 -1
  23. package/src/pantheon/v2-decision-budget.ts +456 -0
  24. package/src/pantheon/v2-decision-contracts.ts +300 -0
  25. package/src/pantheon/v2-decision-egress.ts +203 -0
  26. package/src/pantheon/v2-decision-events.ts +180 -0
  27. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  28. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  29. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  30. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  31. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  32. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  33. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  34. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  35. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  36. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  37. package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
  38. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  39. package/src/pantheon/v2-decision-points.ts +242 -0
  40. package/src/pantheon/v2-decision-policy.ts +166 -0
  41. package/src/pantheon/v2-decision-premises.ts +146 -0
  42. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  43. package/src/pantheon/v2-decision-rank.ts +91 -0
  44. package/src/pantheon/v2-decision-registry.ts +391 -0
  45. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  46. package/src/pantheon/v2-decision-shadow.ts +123 -0
  47. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  48. package/src/pantheon/v2-decision-verify.ts +51 -0
  49. package/src/pantheon/v2-tools.ts +21 -2
  50. package/src/plugin-v2.ts +305 -3
  51. package/src/plugins/tui/dist/tui-v2.js +3 -3
  52. package/src/plugins/tui/dist/tui.js +1 -1
  53. package/src/plugins/tui/package-lock.json +2 -2
  54. package/src/plugins/tui/package.json +1 -1
@@ -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,366 @@
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 (`.pantheon/deepwork/decision-layer-v2/PROBE-F-permission-paths.md`)
33
+ * delivered 24 real `permission.evaluate` events on the 2.2.5 host. Every one
34
+ * carries a valid `action` token and a non-empty top-level `sessionID`
35
+ * (PROBE-F §3.2), so neither declared rule can match: `action.unusable` needs a
36
+ * non-token action, `allow.unattributed` needs an `allow` with no session. With
37
+ * the flag on the outcome is `p8.rule.none` → `guardrail.keep`, i.e. **inert**
38
+ * (PROBE-F §6 I-F3: the rules were matched statically against the measured
39
+ * payload; the flag itself was never enabled). The availability risk the
40
+ * phase-5 review named — denying native events with no `action` — does not
41
+ * materialise on this host, because the host always supplies one. The real
42
+ * finding is the opposite: no narrowing.
43
+ *
44
+ * An unrecognised effect is not a barrier either. The host treats a value it
45
+ * does not recognise as `ask`, resolves it, and executes (PROBE-F §3.6), so
46
+ * "refuse and keep" does not block. `execute.before` remains the only hard
47
+ * barrier: a `throw` there denies and skips permission evaluation, while a
48
+ * `throw` here does not deny at all (PROBE-F §3.7).
49
+ *
50
+ * Off by default: `PANTHEON_V2_P8_GUARDRAIL` is absent in a default install and
51
+ * absence means disabled, so this phase ships no behavioural change. Evaluation
52
+ * is synchronous with no I/O (it cannot delay admission), and every failure —
53
+ * unreadable payload, unrecognized baseline, a host event that refuses the
54
+ * write — resolves to "leave the baseline alone". A guardrail that cannot
55
+ * narrow is a no-op, not an allow.
56
+ *
57
+ * ## Path coverage — measured host paths, no observed narrowing
58
+ *
59
+ * `PM-09` recorded that these surfaces never fired; PROBE-F fired them and
60
+ * measured 9 of the 10 rows below. A row's `measured` status means the host path
61
+ * was observed — **not** that P8 narrowed on it: no rule matched on any measured
62
+ * payload, so no narrowing exists to observe. `unmeasured` is reserved for the
63
+ * one path PROBE-F could not reach. Evidence cites the probe section; PROBE-F
64
+ * proposes `F-42…F-48` but those ids are not assigned in this change, and this
65
+ * module must not invent them (PLAN §5.4). {@link P8_PATH_COVERAGE} is the
66
+ * machine-readable form.
67
+ *
68
+ * | path | status | evidence |
69
+ * |--------------------------------------------------------|------------|----------------|
70
+ * | permission.evaluate: hook delivery | measured | PROBE-F §3.1 |
71
+ * | permission.evaluate: payload shape (action/sessionID…) | measured | PROBE-F §3.2 |
72
+ * | permission.evaluate: `event.effect` write is honored | measured | PROBE-F §3.4 |
73
+ * | permission.evaluate: ordering vs. the host rules | measured | PROBE-F §3.3 |
74
+ * | permission.evaluate: existing `deny` early return | measured | PROBE-F §3.5 |
75
+ * | permission.evaluate: `decision.egress` early return | unmeasured | PROBE-F §3.9 |
76
+ * | permission.evaluate: unknown/unrecognized baseline | measured | PROBE-F §3.6 |
77
+ * | execute.before: delivery | measured | PROBE-F §3.8 |
78
+ * | execute.before: payload shape | measured | PROBE-F §3.8 |
79
+ * | execute.before: throw-to-deny semantics | measured | PROBE-F §3.7 |
80
+ *
81
+ * `permission.evaluate.egress` is unreachable in this host: a tool that declares
82
+ * the `decision.egress` permission registers but is never advertised to the
83
+ * provider, so the action never reaches the hook (PROBE-F §3.9). Its early
84
+ * return therefore reads a branch that was never delivered.
85
+ *
86
+ * On `execute.before` P8 adds no barrier: a second barrier is the widening risk
87
+ * this phase must not take, and narrowing is optional (equality is a subset).
88
+ */
89
+
90
+ /** On/off switch read by the plugin wiring. Any other value means off. */
91
+ export const P8_GUARDRAIL_FLAG_ENV = 'PANTHEON_V2_P8_GUARDRAIL'
92
+
93
+ /** Permissiveness order. A decision may only move down this scale. */
94
+ export const P8_EFFECT_RANK = Object.freeze({ deny: 0, ask: 1, allow: 2 } as const)
95
+
96
+ export type P8PermissionEffect = keyof typeof P8_EFFECT_RANK
97
+
98
+ /**
99
+ * Declared narrowing rules — syntax only, never a measured payload semantic, so
100
+ * a rule that could widen cannot be introduced by editing a branch.
101
+ */
102
+ export const P8_RULES = Object.freeze([
103
+ /** The baseline is not attributable: no printable action token. */
104
+ 'p8.rule.action.unusable',
105
+ /** An `allow` that names no session cannot be audited. */
106
+ 'p8.rule.allow.unattributed',
107
+ ] as const)
108
+
109
+ export type P8RuleId = (typeof P8_RULES)[number]
110
+
111
+ export type P8Outcome = 'guardrail.keep' | 'guardrail.narrow' | 'guardrail.refusal'
112
+
113
+ /**
114
+ * `measured`: the host path was observed in PROBE-F and the evidence names the
115
+ * probe section (the `F-` ids for PROBE-F are proposed but not yet assigned).
116
+ * `unmeasured`: the path was never exercised. Neither value claims a P8
117
+ * narrowing — no measured payload matched a declared rule.
118
+ */
119
+ export type P8PathStatus = 'measured' | 'unmeasured'
120
+
121
+ export interface P8PathCoverage {
122
+ readonly path: string
123
+ readonly status: P8PathStatus
124
+ /** Probe section that observed the path; the premise id when unmeasured. */
125
+ readonly evidence: readonly string[]
126
+ }
127
+
128
+ /** Every path P8 touches. Frozen: a path cannot be dropped silently. */
129
+ export const P8_PATH_COVERAGE: readonly P8PathCoverage[] = Object.freeze([
130
+ { path: 'permission.evaluate.delivery', status: 'measured', evidence: ['PROBE-F §3.1'] },
131
+ { path: 'permission.evaluate.payload-shape', status: 'measured', evidence: ['PROBE-F §3.2'] },
132
+ { path: 'permission.evaluate.effect-write', status: 'measured', evidence: ['PROBE-F §3.4'] },
133
+ { path: 'permission.evaluate.ordering', status: 'measured', evidence: ['PROBE-F §3.3'] },
134
+ { path: 'permission.evaluate.existing-deny', status: 'measured', evidence: ['PROBE-F §3.5'] },
135
+ { path: 'permission.evaluate.egress', status: 'unmeasured', evidence: ['PROBE-F §3.9'] },
136
+ {
137
+ path: 'permission.evaluate.unknown-baseline',
138
+ status: 'measured',
139
+ evidence: ['PROBE-F §3.6'],
140
+ },
141
+ { path: 'execute.before.delivery', status: 'measured', evidence: ['PROBE-F §3.8'] },
142
+ { path: 'execute.before.payload-shape', status: 'measured', evidence: ['PROBE-F §3.8'] },
143
+ { path: 'execute.before.throw-to-deny', status: 'measured', evidence: ['PROBE-F §3.7'] },
144
+ ])
145
+
146
+ const ACTION_TOKEN = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/
147
+ const REASON_TOKEN = /^[a-z0-9][a-z0-9.:-]{0,63}$/
148
+
149
+ export interface P8GuardrailOptions {
150
+ /** Defaults to `false`: absence of the flag means disabled. */
151
+ readonly enabled?: boolean
152
+ }
153
+
154
+ export interface P8GuardrailInput {
155
+ /** Effect the host/delegation produced. Read, never inferred. */
156
+ readonly baseline: unknown
157
+ /** Permission event as delivered (measured shape: PROBE-F §3.2). */
158
+ readonly event?: unknown
159
+ }
160
+
161
+ export interface P8GuardrailDecision {
162
+ readonly enabled: boolean
163
+ readonly decision: P8Outcome
164
+ /** The baseline, or `deny`. Never a value the baseline did not have. */
165
+ readonly effect: P8PermissionEffect | 'unavailable'
166
+ /** True only when `deny` replaced a wider baseline. */
167
+ readonly narrowed: boolean
168
+ readonly rules: readonly string[]
169
+ /** Token explaining the outcome; always present. */
170
+ readonly reason: string
171
+ }
172
+
173
+ export interface P8ApplyResult extends P8GuardrailDecision {
174
+ /** True only when this call wrote `deny` onto the event. */
175
+ readonly wrote: boolean
176
+ }
177
+
178
+ function isRecord(value: unknown): value is Record<string, unknown> {
179
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
180
+ }
181
+
182
+ function isNonEmptyString(value: unknown): value is string {
183
+ return typeof value === 'string' && value.trim().length > 0
184
+ }
185
+
186
+ /** Rank of a known effect; `null` for anything else (unprovable baseline). */
187
+ export function p8EffectRank(effect: unknown): number | null {
188
+ if (typeof effect !== 'string' || !Object.hasOwn(P8_EFFECT_RANK, effect)) return null
189
+ return P8_EFFECT_RANK[effect as P8PermissionEffect]
190
+ }
191
+
192
+ /** `true` only when both values are recognized and `p8` is at most the baseline. */
193
+ export function p8NarrowsOnly(baseline: unknown, effect: unknown): boolean {
194
+ const base = p8EffectRank(baseline)
195
+ const next = p8EffectRank(effect)
196
+ if (base === null || next === null) return false
197
+ return next <= base
198
+ }
199
+
200
+ function readEffect(value: unknown): P8PermissionEffect | null {
201
+ const rank = p8EffectRank(value)
202
+ if (rank === null) return null
203
+ return value as P8PermissionEffect
204
+ }
205
+
206
+ /** Rules that match, in declaration order. Cannot return a wider decision. */
207
+ function matchedRules(event: unknown, baseline: P8PermissionEffect): readonly P8RuleId[] {
208
+ const record = isRecord(event) ? event : null
209
+ const matched: P8RuleId[] = []
210
+ if (typeof record?.action !== 'string' || !ACTION_TOKEN.test(record.action)) {
211
+ matched.push('p8.rule.action.unusable')
212
+ }
213
+ if (baseline === 'allow' && !isNonEmptyString(record?.sessionID)) {
214
+ matched.push('p8.rule.allow.unattributed')
215
+ }
216
+ return matched
217
+ }
218
+
219
+ function decision(
220
+ enabled: boolean,
221
+ outcome: P8Outcome,
222
+ effect: P8PermissionEffect | 'unavailable',
223
+ baseline: P8PermissionEffect | null,
224
+ rules: readonly string[],
225
+ reason: string,
226
+ ): P8GuardrailDecision {
227
+ const token = REASON_TOKEN.test(reason) ? reason : 'p8.reason.invalid'
228
+ const narrowed = effect === 'deny' && baseline !== null && baseline !== 'deny'
229
+ const safeOutcome: P8Outcome = narrowed ? 'guardrail.narrow' : outcome
230
+ return Object.freeze({
231
+ enabled,
232
+ decision: safeOutcome,
233
+ effect,
234
+ narrowed,
235
+ rules: Object.freeze([...rules]),
236
+ reason: token,
237
+ })
238
+ }
239
+
240
+ /** Evaluate P8. Disabled echoes the baseline; an unrecognized baseline refuses. */
241
+ export function evaluateP8Guardrail(
242
+ input: P8GuardrailInput,
243
+ options: P8GuardrailOptions = {},
244
+ ): P8GuardrailDecision {
245
+ const enabled = options.enabled === true
246
+ let baseline: P8PermissionEffect | null
247
+ try {
248
+ baseline = readEffect(input.baseline)
249
+ } catch {
250
+ baseline = null
251
+ }
252
+ if (baseline === null) {
253
+ return decision(
254
+ enabled,
255
+ 'guardrail.refusal',
256
+ 'unavailable',
257
+ null,
258
+ [],
259
+ 'p8.baseline.unrecognized',
260
+ )
261
+ }
262
+ if (!enabled) return decision(false, 'guardrail.keep', baseline, baseline, [], 'p8.disabled')
263
+ if (baseline === 'deny') {
264
+ return decision(true, 'guardrail.keep', 'deny', baseline, [], 'p8.baseline.deny')
265
+ }
266
+ let rules: readonly P8RuleId[]
267
+ try {
268
+ rules = matchedRules(input.event, baseline)
269
+ } catch {
270
+ // The baseline was readable, so the honest answer is "keep it": an
271
+ // unreadable event is a missing narrowing opportunity, never a grant.
272
+ return decision(true, 'guardrail.keep', baseline, baseline, [], 'p8.event.unreadable')
273
+ }
274
+ if (rules.length === 0)
275
+ return decision(true, 'guardrail.keep', baseline, baseline, [], 'p8.rule.none')
276
+ return decision(true, 'guardrail.narrow', 'deny', baseline, rules, 'p8.rule.matched')
277
+ }
278
+
279
+ /**
280
+ * Classify `event.effect` before writing it.
281
+ *
282
+ * `delegation`: the own descriptor is absent or an accessor, so an assignment
283
+ * would create a property or run a host setter — the write is refused.
284
+ * `non-writable`: an own data property that cannot be replaced — also refused,
285
+ * with the existing `p8.write.rejected` token.
286
+ * `writable`: an own writable data property, the only safe target.
287
+ */
288
+ function effectWriteKind(target: object): 'writable' | 'delegation' | 'non-writable' {
289
+ const descriptor = Object.getOwnPropertyDescriptor(target, 'effect')
290
+ if (descriptor === undefined || !Object.hasOwn(descriptor, 'value')) return 'delegation'
291
+ return descriptor.writable === true ? 'writable' : 'non-writable'
292
+ }
293
+
294
+ function refusedWrite(
295
+ enabled: boolean,
296
+ baseline: P8PermissionEffect | null,
297
+ reason: string,
298
+ ): P8ApplyResult {
299
+ return Object.freeze({
300
+ ...decision(enabled, 'guardrail.keep', baseline ?? 'unavailable', baseline, [], reason),
301
+ wrote: false,
302
+ })
303
+ }
304
+
305
+ /**
306
+ * Apply P8 to a permission event: read `event.effect`, write `'deny'` only when
307
+ * a rule matched. A refused write leaves the baseline and reports
308
+ * `p8.write.rejected` (frozen/non-writable or a throwing target) or
309
+ * `p8.write.delegation` (accessor or non-own descriptor); this never throws
310
+ * into admission.
311
+ */
312
+ export function applyP8ToPermissionEvent(
313
+ event: unknown,
314
+ options: P8GuardrailOptions = {},
315
+ ): P8ApplyResult {
316
+ const enabled = options.enabled === true
317
+ let baseline: P8PermissionEffect | null = null
318
+ try {
319
+ baseline = readEffect(isRecord(event) ? event.effect : undefined)
320
+ } catch {
321
+ baseline = null
322
+ }
323
+ const evaluated = evaluateP8Guardrail({ baseline, event }, options)
324
+ if (!evaluated.narrowed) return Object.freeze({ ...evaluated, wrote: false })
325
+ try {
326
+ if (!isRecord(event)) return refusedWrite(enabled, baseline, 'p8.write.delegation')
327
+ const kind = effectWriteKind(event)
328
+ if (kind === 'delegation') return refusedWrite(enabled, baseline, 'p8.write.delegation')
329
+ if (kind === 'non-writable') return refusedWrite(enabled, baseline, 'p8.write.rejected')
330
+ // `Reflect.set` reports a refused write instead of throwing in strict mode,
331
+ // so a frozen host object cannot turn P8 into an exception in admission.
332
+ const assigned = Reflect.set(event, 'effect', 'deny')
333
+ if (!assigned || event.effect !== 'deny') {
334
+ return refusedWrite(enabled, baseline, 'p8.write.rejected')
335
+ }
336
+ return Object.freeze({ ...evaluated, wrote: true })
337
+ } catch {
338
+ return refusedWrite(enabled, baseline, 'p8.write.rejected')
339
+ }
340
+ }
341
+
342
+ export interface P8Guardrail {
343
+ readonly enabled: boolean
344
+ /** Pure evaluation; never throws, never writes. */
345
+ evaluate(input: P8GuardrailInput): P8GuardrailDecision
346
+ /** Narrowing-only application; never throws, may write `deny` only. */
347
+ apply(event: unknown): P8ApplyResult
348
+ }
349
+
350
+ /** Whether the operator explicitly enabled the flag. Absence means off. */
351
+ export function p8GuardrailEnabledFromEnv(
352
+ env: Record<string, string | undefined> = process.env,
353
+ ): boolean {
354
+ const raw = (env[P8_GUARDRAIL_FLAG_ENV] ?? '').trim().toLowerCase()
355
+ return raw === '1' || raw === 'on' || raw === 'true'
356
+ }
357
+
358
+ /** Create a P8 instance. Disabled unless the caller says otherwise. */
359
+ export function createP8Guardrail(options: P8GuardrailOptions = {}): P8Guardrail {
360
+ const enabled = options.enabled === true
361
+ return Object.freeze({
362
+ enabled,
363
+ evaluate: (input: P8GuardrailInput) => evaluateP8Guardrail(input, { enabled }),
364
+ apply: (event: unknown) => applyP8ToPermissionEvent(event, { enabled }),
365
+ })
366
+ }