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,391 @@
1
+ /**
2
+ * V2 decision registry — P1…P11 with an explicit status per point.
3
+ *
4
+ * A `measured` status means the *surface* was measured in a runtime probe
5
+ * (presence, shape or channel). It never means the *effect* was measured:
6
+ * effect requires a mutation observed in the following turn — the criterion C6
7
+ * answered for prompt/skill/tool mutations in PROBE-E — and no point's own
8
+ * effect has been measured. `premise` means the surface or catalog
9
+ * this point needs was not measured; the premise is registered by id in
10
+ * `v2-decision-premises.ts`, and its canonical text lives in `STATUS.md` § Premissas. `deferred` means the
11
+ * final design is suspended by an open condition and no effect is authorised.
12
+ * `advisory` means the surface was measured, the specified effect was measured
13
+ * *unreachable*, and the point therefore only records an observation: it
14
+ * applies no decision and may never be described as having one.
15
+ *
16
+ * Evidence ids follow PLAN §5.4 (F-01…F-32, I-01) and are never renumbered.
17
+ * `measured` points must cite at least one `F-` id; `premise`, `advisory` and
18
+ * `deferred` points must carry the blocking condition.
19
+ * {@link auditDecisionRegistry} enforces both properties, and the harness
20
+ * treats a violation as a failure.
21
+ *
22
+ * ## Tool-vs-hook boundary (D12)
23
+ *
24
+ * Every point declares two things and they are checked against each other, so
25
+ * neither can drift alone:
26
+ *
27
+ * - `hostSurface` — the host API namespace that would carry the decision;
28
+ * - `toolOrHook` — `tool` when that namespace is the tool surface
29
+ * (`ctx.tool.transform`, a model-invocable Pantheon tool), `hook` when it
30
+ * is a host-invoked surface (a session hook, `permission.evaluate`,
31
+ * `execute.after`, the compaction hook, or the event channel).
32
+ *
33
+ * A catalog *read* (`ctx.skill`, the tool draft) never makes a point a tool
34
+ * point; the boundary is where the decision would be applied. A point that
35
+ * touched both would be ambiguous, so the declaration is exactly one of the
36
+ * two values and the audit rejects anything else. The declared `hostPoint`
37
+ * must also name the declared surface, which makes the declaration falsifiable
38
+ * without executing anything.
39
+ *
40
+ * ## Resource ids (D13)
41
+ *
42
+ * Resource ids are not stored per point: they are derived by
43
+ * `v2-decision-resource-ids.ts` from the point id, the domain surface, the
44
+ * premises and the evidence ids. The audit rejects a collision between two
45
+ * distinct ids, and the ids are always namespaced under
46
+ * `pantheon://v2-decision/`.
47
+ */
48
+
49
+ import type { AskMode } from './v2-decision-contracts.ts'
50
+ import { DECISION_POINT_REGISTRY } from './v2-decision-points.ts'
51
+ import { PREMISE_IDS, PREMISE_REGISTER, type PremiseEntry } from './v2-decision-premises.ts'
52
+ import {
53
+ decisionResourceRefs,
54
+ findDecisionResourceIdCollisions,
55
+ } from './v2-decision-resource-ids.ts'
56
+
57
+ export const DECISION_POINT_IDS = [
58
+ 'P1',
59
+ 'P2',
60
+ 'P3',
61
+ 'P4',
62
+ 'P5',
63
+ 'P6',
64
+ 'P7',
65
+ 'P8',
66
+ 'P9',
67
+ 'P10',
68
+ 'P11',
69
+ ] as const
70
+
71
+ export type DecisionPointId = (typeof DECISION_POINT_IDS)[number]
72
+ export type DecisionPointStatus = 'measured' | 'premise' | 'advisory' | 'deferred'
73
+ export type DecisionPointMode = 'shadow' | 'off' | 'migration'
74
+
75
+ export type DecisionSurface =
76
+ | 'agent'
77
+ | 'skill'
78
+ | 'complexity'
79
+ | 'memory'
80
+ | 'verification'
81
+ | 'council'
82
+ | 'loop'
83
+ | 'guardrail'
84
+ | 'compaction'
85
+ | 'claims'
86
+ | 'catalog'
87
+
88
+ export type DecisionPrimitive = AskMode | 'rank' | 'verify'
89
+
90
+ /** Host API namespace that carries the decision (D12). */
91
+ export type DecisionHostSurface =
92
+ | 'tool.invoke'
93
+ | 'tool.transform'
94
+ | 'session.hook.prompt'
95
+ | 'session.hook.context'
96
+ | 'session.hook.compaction'
97
+ | 'session.hook.execute.after'
98
+ | 'permission.evaluate'
99
+ | 'event.channel'
100
+
101
+ /** The tool-vs-hook boundary. Exactly one value per point; never both. */
102
+ export type DecisionToolOrHook = 'tool' | 'hook'
103
+
104
+ /** Every host surface the registry may declare. */
105
+ export const DECISION_HOST_SURFACES: readonly DecisionHostSurface[] = Object.freeze([
106
+ 'tool.invoke',
107
+ 'tool.transform',
108
+ 'session.hook.prompt',
109
+ 'session.hook.context',
110
+ 'session.hook.compaction',
111
+ 'session.hook.execute.after',
112
+ 'permission.evaluate',
113
+ 'event.channel',
114
+ ])
115
+
116
+ /**
117
+ * The only correct side of the boundary for each host surface.
118
+ *
119
+ * `tool.transform` is a tool point even though the host invokes the transform:
120
+ * it acts on the tool namespace. The event channel is a hook point even though
121
+ * it is not a session hook: it is host-driven and model-invocable. The rule is
122
+ * namespace membership, not invocation direction.
123
+ */
124
+ export const TOOL_OR_HOOK_BY_HOST_SURFACE: Readonly<
125
+ Record<DecisionHostSurface, DecisionToolOrHook>
126
+ > = Object.freeze({
127
+ 'tool.invoke': 'tool',
128
+ 'tool.transform': 'tool',
129
+ 'session.hook.prompt': 'hook',
130
+ 'session.hook.context': 'hook',
131
+ 'session.hook.compaction': 'hook',
132
+ 'session.hook.execute.after': 'hook',
133
+ 'permission.evaluate': 'hook',
134
+ 'event.channel': 'hook',
135
+ })
136
+
137
+ /** A token the declared `hostPoint` must contain, so the claim is falsifiable. */
138
+ const HOST_POINT_TOKENS: Readonly<Record<DecisionHostSurface, readonly string[]>> = Object.freeze({
139
+ 'tool.invoke': ['tool pantheon_local_decision'],
140
+ 'tool.transform': ['tool.transform'],
141
+ 'session.hook.prompt': ['prompt'],
142
+ 'session.hook.context': ['context'],
143
+ 'session.hook.compaction': ['compaction'],
144
+ 'session.hook.execute.after': ['execute.after'],
145
+ 'permission.evaluate': ['permission.evaluate'],
146
+ 'event.channel': ['session.execution.succeeded'],
147
+ })
148
+
149
+ export interface DecisionEventShape {
150
+ /** Event type the adapter consumes, when the point is event-driven. */
151
+ readonly type: string
152
+ /** Measured carrier path for the session id. */
153
+ readonly carrier: 'data.sessionID'
154
+ /** Envelope fields that are absent from the measured shape and must not be read. */
155
+ readonly forbiddenCarriers: readonly string[]
156
+ }
157
+
158
+ export interface DecisionPoint {
159
+ readonly id: DecisionPointId
160
+ readonly surface: DecisionSurface
161
+ /** Host API namespace that would carry the decision. */
162
+ readonly hostSurface: DecisionHostSurface
163
+ /** Explicit D12 declaration, validated against `hostSurface`. */
164
+ readonly toolOrHook: DecisionToolOrHook
165
+ readonly hostPoint: string
166
+ readonly primitives: readonly DecisionPrimitive[]
167
+ readonly mode: DecisionPointMode
168
+ readonly status: DecisionPointStatus
169
+ /**
170
+ * Whether the shipped plugin actually constructs this point's adapter.
171
+ *
172
+ * This is a claim about the source, not about a probe: the audit in
173
+ * `tests/pantheon/v2-decision-wiring.test.ts` derives the answer from the
174
+ * production import graph rooted at `src/plugin-v2.ts` and fails when this
175
+ * flag disagrees. It also derives *where* the handler is constructed and
176
+ * fails when a wired point's construction site is not its declared
177
+ * `hostSurface` — a handler called from the wrong hook is not wiring. It is
178
+ * never derived from a hand-maintained list — a second list would repeat the
179
+ * "described as active, produces nothing" defect this field exists to expose.
180
+ */
181
+ readonly wired: boolean
182
+ /**
183
+ * Set only when the measurement was narrower than the point's full scope.
184
+ * `top-level-session-only`: only top-level sessions were exercised.
185
+ * `overflow-unmeasured`: sessions (top-level and child) were exercised, but
186
+ * the context-exhaustion path that would request `reason:"overflow"` was not.
187
+ */
188
+ readonly scope?: 'top-level-session-only' | 'overflow-unmeasured'
189
+ /** Unmeasured scope, named so it cannot be mistaken for measured coverage. */
190
+ readonly unknowns?: readonly string[]
191
+ readonly evidence: readonly string[]
192
+ readonly premises: readonly string[]
193
+ /** Non-null for every `premise` and `deferred` point. */
194
+ readonly blockingCondition: string | null
195
+ readonly trigger?: string
196
+ readonly eventShape?: DecisionEventShape
197
+ /** Required for guardrail points: the hard barrier they may never widen. */
198
+ readonly securityInvariant?: string
199
+ readonly notes: string
200
+ }
201
+
202
+ export { DECISION_POINT_REGISTRY } from './v2-decision-points.ts'
203
+ export {
204
+ PREMISE_IDS,
205
+ PREMISE_REGISTER,
206
+ type PremiseEntry,
207
+ } from './v2-decision-premises.ts'
208
+
209
+ const EVIDENCE_ID = /^(?:F-\d{2}|I-\d{2})$/
210
+ const MEASURED_EVIDENCE_ID = /^F-\d{2}$/
211
+ const FORBIDDEN_CATALOG_REFERENCE = new RegExp(['ctx', 'catalog'].join('\\.'))
212
+
213
+ export type RegistryViolationCode =
214
+ | 'POINT_SET_MISMATCH'
215
+ | 'DUPLICATE_POINT'
216
+ | 'MEASURED_WITHOUT_EVIDENCE'
217
+ | 'PREMISE_WITHOUT_BLOCKING_CONDITION'
218
+ | 'ADVISORY_WITHOUT_BLOCKING_CONDITION'
219
+ | 'DEFERRED_WITHOUT_BLOCKING_CONDITION'
220
+ | 'DEFERRED_WITHOUT_TRIGGER'
221
+ | 'UNKNOWN_EVIDENCE_ID'
222
+ | 'UNKNOWN_PREMISE'
223
+ | 'MISSING_PREMISE_REGISTER_ENTRY'
224
+ | 'GUARDRAIL_WITHOUT_SECURITY_INVARIANT'
225
+ | 'CATALOG_REFERENCE_PRESENT'
226
+ | 'UNKNOWN_HOST_SURFACE'
227
+ | 'AMBIGUOUS_TOOL_OR_HOOK'
228
+ | 'TOOL_OR_HOOK_MISMATCH'
229
+ | 'HOST_SURFACE_HOST_POINT_MISMATCH'
230
+ | 'RESOURCE_ID_COLLISION'
231
+
232
+ export interface RegistryViolation {
233
+ readonly code: RegistryViolationCode
234
+ readonly pointId: string | null
235
+ readonly detail: string
236
+ }
237
+
238
+ export interface RegistryAudit {
239
+ readonly ok: boolean
240
+ readonly violations: readonly RegistryViolation[]
241
+ }
242
+
243
+ /**
244
+ * Audit the registry against the binding rules.
245
+ *
246
+ * The critical one: a point declaring `measured` with no `F-` evidence id is a
247
+ * violation. A point cannot claim a measured surface it does not cite.
248
+ */
249
+ export function auditDecisionRegistry(
250
+ points: readonly DecisionPoint[] = DECISION_POINT_REGISTRY,
251
+ premises: readonly PremiseEntry[] = PREMISE_REGISTER,
252
+ ): RegistryAudit {
253
+ const violations: RegistryViolation[] = []
254
+ const premiseIds = new Set(premises.map((premise) => premise.id))
255
+ const pointIds = new Set<string>()
256
+
257
+ if (points.length !== DECISION_POINT_IDS.length) {
258
+ violations.push({
259
+ code: 'POINT_SET_MISMATCH',
260
+ pointId: null,
261
+ detail: `expected ${DECISION_POINT_IDS.length} points, received ${points.length}`,
262
+ })
263
+ }
264
+ for (const id of DECISION_POINT_IDS) {
265
+ if (!points.some((point) => point.id === id)) {
266
+ violations.push({ code: 'POINT_SET_MISMATCH', pointId: id, detail: 'point is missing' })
267
+ }
268
+ }
269
+ for (const id of PREMISE_IDS) {
270
+ if (!premiseIds.has(id)) {
271
+ violations.push({
272
+ code: 'MISSING_PREMISE_REGISTER_ENTRY',
273
+ pointId: null,
274
+ detail: `${id} is not registered`,
275
+ })
276
+ }
277
+ }
278
+
279
+ for (const point of points) {
280
+ if (pointIds.has(point.id)) {
281
+ violations.push({ code: 'DUPLICATE_POINT', pointId: point.id, detail: 'duplicate id' })
282
+ }
283
+ pointIds.add(point.id)
284
+
285
+ if (point.status === 'measured') {
286
+ if (!point.evidence.some((id) => MEASURED_EVIDENCE_ID.test(id))) {
287
+ violations.push({
288
+ code: 'MEASURED_WITHOUT_EVIDENCE',
289
+ pointId: point.id,
290
+ detail: 'measured points must cite at least one F- evidence id',
291
+ })
292
+ }
293
+ } else {
294
+ const code =
295
+ point.status === 'deferred'
296
+ ? 'DEFERRED_WITHOUT_BLOCKING_CONDITION'
297
+ : point.status === 'advisory'
298
+ ? 'ADVISORY_WITHOUT_BLOCKING_CONDITION'
299
+ : 'PREMISE_WITHOUT_BLOCKING_CONDITION'
300
+ if (point.blockingCondition === null || point.blockingCondition.trim().length === 0) {
301
+ violations.push({ code, pointId: point.id, detail: 'blocking condition is required' })
302
+ }
303
+ if (point.status === 'deferred' && !point.trigger) {
304
+ violations.push({
305
+ code: 'DEFERRED_WITHOUT_TRIGGER',
306
+ pointId: point.id,
307
+ detail: 'deferred points must name their trigger',
308
+ })
309
+ }
310
+ }
311
+ for (const evidenceId of point.evidence) {
312
+ if (!EVIDENCE_ID.test(evidenceId)) {
313
+ violations.push({
314
+ code: 'UNKNOWN_EVIDENCE_ID',
315
+ pointId: point.id,
316
+ detail: `${evidenceId} is not an evidence id`,
317
+ })
318
+ }
319
+ }
320
+ for (const premiseId of point.premises) {
321
+ if (!premiseIds.has(premiseId)) {
322
+ violations.push({
323
+ code: 'UNKNOWN_PREMISE',
324
+ pointId: point.id,
325
+ detail: `${premiseId} is not registered`,
326
+ })
327
+ }
328
+ }
329
+ if (point.surface === 'guardrail' && !point.securityInvariant) {
330
+ violations.push({
331
+ code: 'GUARDRAIL_WITHOUT_SECURITY_INVARIANT',
332
+ pointId: point.id,
333
+ detail: 'guardrail points must carry the hard-barrier invariant',
334
+ })
335
+ }
336
+ const hostSurface = point.hostSurface
337
+ const surfaceIsKnown = DECISION_HOST_SURFACES.includes(hostSurface)
338
+ if (!surfaceIsKnown) {
339
+ violations.push({
340
+ code: 'UNKNOWN_HOST_SURFACE',
341
+ pointId: point.id,
342
+ detail: `${String(hostSurface)} is not a host surface`,
343
+ })
344
+ }
345
+ if (point.toolOrHook !== 'tool' && point.toolOrHook !== 'hook') {
346
+ violations.push({
347
+ code: 'AMBIGUOUS_TOOL_OR_HOOK',
348
+ pointId: point.id,
349
+ detail: 'a point declares exactly one side: tool or hook',
350
+ })
351
+ } else if (surfaceIsKnown && point.toolOrHook !== TOOL_OR_HOOK_BY_HOST_SURFACE[hostSurface]) {
352
+ violations.push({
353
+ code: 'TOOL_OR_HOOK_MISMATCH',
354
+ pointId: point.id,
355
+ detail: `${hostSurface} is a ${TOOL_OR_HOOK_BY_HOST_SURFACE[hostSurface]} surface, not ${point.toolOrHook}`,
356
+ })
357
+ }
358
+ if (
359
+ surfaceIsKnown &&
360
+ !HOST_POINT_TOKENS[hostSurface].some((token) => point.hostPoint.includes(token))
361
+ ) {
362
+ violations.push({
363
+ code: 'HOST_SURFACE_HOST_POINT_MISMATCH',
364
+ pointId: point.id,
365
+ detail: `hostPoint does not name the declared surface ${hostSurface}`,
366
+ })
367
+ }
368
+ if (FORBIDDEN_CATALOG_REFERENCE.test(JSON.stringify(point))) {
369
+ violations.push({
370
+ code: 'CATALOG_REFERENCE_PRESENT',
371
+ pointId: point.id,
372
+ detail: 'the host catalog context is absent from the measured surface',
373
+ })
374
+ }
375
+ }
376
+
377
+ for (const resourceId of findDecisionResourceIdCollisions(decisionResourceRefs(points))) {
378
+ violations.push({
379
+ code: 'RESOURCE_ID_COLLISION',
380
+ pointId: null,
381
+ detail: `${resourceId} is produced by more than one id`,
382
+ })
383
+ }
384
+
385
+ return { ok: violations.length === 0, violations: Object.freeze(violations) }
386
+ }
387
+
388
+ /** Convenience lookup used by the policy and the harness. */
389
+ export function findDecisionPoint(id: string): DecisionPoint | undefined {
390
+ return DECISION_POINT_REGISTRY.find((point) => point.id === id)
391
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Namespaced resource ids for the V2 decision layer (D13).
3
+ *
4
+ * Every id is derived from a kind and a raw identifier — never hand-assigned
5
+ * per point — so the same raw id always yields the same resource id, and two
6
+ * ids can only collide if their slugs collide:
7
+ *
8
+ * `pantheon://v2-decision/<kind>/<slug>`
9
+ *
10
+ * The kind segment is part of the identity: a point id `memory` and a surface
11
+ * `memory` are different resources, not a collision. {@link
12
+ * findDecisionResourceIdCollisions} reports ids that two *distinct* raw ids
13
+ * mapped onto, which is the only failure the derivation can produce.
14
+ *
15
+ * Slugs are lowercased and punctuation is folded to `-`, so `PM-09` and
16
+ * `pm 09` are the same resource. That is intentional normalisation, and it is
17
+ * why a collision check is required rather than assumed.
18
+ */
19
+
20
+ import type { DecisionPoint, DecisionPointId, DecisionSurface } from './v2-decision-registry.ts'
21
+
22
+ /** Scheme shared by every decision-layer resource id. */
23
+ export const DECISION_RESOURCE_SCHEME = 'pantheon://v2-decision'
24
+
25
+ export type DecisionResourceKind = 'point' | 'surface' | 'premise' | 'evidence'
26
+
27
+ const KIND_SEGMENT: Readonly<Record<DecisionResourceKind, string>> = Object.freeze({
28
+ point: 'points',
29
+ surface: 'surfaces',
30
+ premise: 'premises',
31
+ evidence: 'evidence',
32
+ })
33
+
34
+ const MAX_SLUG_LENGTH = 64
35
+ const RESOURCE_ID_PATTERN = new RegExp(
36
+ `^${DECISION_RESOURCE_SCHEME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}` +
37
+ '/(?:points|surfaces|premises|evidence)/[a-z0-9]+(?:-[a-z0-9]+)*$',
38
+ )
39
+
40
+ /**
41
+ * Deterministic slug for a raw identifier.
42
+ *
43
+ * Throws for input with no alphanumeric content or above the length bound: an
44
+ * empty or unbounded segment is not a resource id.
45
+ */
46
+ export function decisionResourceSlug(raw: string): string {
47
+ if (typeof raw !== 'string') throw new TypeError('resource id must be a string')
48
+ const slug = raw
49
+ .trim()
50
+ .toLowerCase()
51
+ .replace(/[^a-z0-9]+/g, '-')
52
+ .replace(/^-+|-+$/g, '')
53
+ if (slug.length === 0) throw new RangeError(`resource id ${JSON.stringify(raw)} has no slug`)
54
+ if (slug.length > MAX_SLUG_LENGTH) {
55
+ throw new RangeError(`resource id ${JSON.stringify(raw)} exceeds ${MAX_SLUG_LENGTH} characters`)
56
+ }
57
+ return slug
58
+ }
59
+
60
+ /** Build a namespaced resource id from a kind and a raw identifier. */
61
+ export function decisionResourceId(kind: DecisionResourceKind, raw: string): string {
62
+ return `${DECISION_RESOURCE_SCHEME}/${KIND_SEGMENT[kind]}/${decisionResourceSlug(raw)}`
63
+ }
64
+
65
+ export function decisionPointResourceId(id: DecisionPointId): string {
66
+ return decisionResourceId('point', id)
67
+ }
68
+
69
+ export function decisionSurfaceResourceId(surface: DecisionSurface): string {
70
+ return decisionResourceId('surface', surface)
71
+ }
72
+
73
+ export function decisionPremiseResourceId(id: string): string {
74
+ return decisionResourceId('premise', id)
75
+ }
76
+
77
+ export function decisionEvidenceResourceId(id: string): string {
78
+ return decisionResourceId('evidence', id)
79
+ }
80
+
81
+ /** Whether a string is a fully namespaced decision resource id. */
82
+ export function isDecisionResourceId(value: string): boolean {
83
+ return RESOURCE_ID_PATTERN.test(value)
84
+ }
85
+
86
+ export interface DecisionResourceRef {
87
+ readonly kind: DecisionResourceKind
88
+ readonly id: string
89
+ }
90
+
91
+ /**
92
+ * Resource ids two distinct `(kind, raw id)` pairs mapped onto.
93
+ *
94
+ * Identical refs repeated across points are not collisions: the same premise
95
+ * cited by two points is one resource. Only different raw ids resolving to the
96
+ * same resource id are reported.
97
+ */
98
+ export function findDecisionResourceIdCollisions(
99
+ refs: readonly DecisionResourceRef[],
100
+ ): readonly string[] {
101
+ const origins = new Map<string, string>()
102
+ const collisions: string[] = []
103
+ for (const ref of refs) {
104
+ const resourceId = decisionResourceId(ref.kind, ref.id)
105
+ const origin = `${ref.kind}:${ref.id}`
106
+ const previous = origins.get(resourceId)
107
+ if (previous === undefined) {
108
+ origins.set(resourceId, origin)
109
+ continue
110
+ }
111
+ if (previous !== origin && !collisions.includes(resourceId)) collisions.push(resourceId)
112
+ }
113
+ return Object.freeze(collisions)
114
+ }
115
+
116
+ /** Every resource the registry names: points, surfaces, premises and evidence. */
117
+ export function decisionResourceRefs(
118
+ points: readonly DecisionPoint[],
119
+ ): readonly DecisionResourceRef[] {
120
+ const refs: DecisionResourceRef[] = []
121
+ for (const point of points) {
122
+ refs.push({ kind: 'point', id: point.id }, { kind: 'surface', id: point.surface })
123
+ for (const premise of point.premises) refs.push({ kind: 'premise', id: premise })
124
+ for (const evidence of point.evidence) refs.push({ kind: 'evidence', id: evidence })
125
+ }
126
+ return Object.freeze(refs)
127
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * V2 shadow layer — an observable no-op.
3
+ *
4
+ * Shadow mode exists so a decision can be recorded without changing anything
5
+ * the host does. This module makes that property structural:
6
+ *
7
+ * - the decision function receives a deep copy, frozen, so it cannot mutate
8
+ * the admission payload even by accident;
9
+ * - an unclonable payload is never handed to the decision function at all;
10
+ * - every failure (throw, malformed result, throwing observer) is contained
11
+ * and reported in the record, never rethrown into admission;
12
+ * - `effect` is the literal `'none'` on every record, with no branch that can
13
+ * set anything else.
14
+ *
15
+ * The record is `{ point, decision, effect: 'none', reason }`. A sink observes
16
+ * it; the sink cannot change the outcome because there is no outcome to change.
17
+ */
18
+
19
+ import type { DecisionPointId } from './v2-decision-registry.ts'
20
+
21
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
22
+ const UNCLONABLE = Symbol('unclonable-payload')
23
+
24
+ export interface ShadowRecord {
25
+ readonly point: string
26
+ readonly decision: string
27
+ readonly effect: 'none'
28
+ readonly reason: string
29
+ }
30
+
31
+ /** Observer of shadow records. Errors thrown here are swallowed. */
32
+ export type ShadowSink = (record: ShadowRecord) => void
33
+
34
+ export interface ShadowDecision {
35
+ readonly decision: string
36
+ readonly reason: string
37
+ }
38
+
39
+ export type ShadowDecisionFunction = (payload: unknown) => ShadowDecision
40
+
41
+ function isToken(value: unknown): value is string {
42
+ return typeof value === 'string' && TOKEN.test(value)
43
+ }
44
+
45
+ function isolate(payload: unknown): unknown | typeof UNCLONABLE {
46
+ try {
47
+ return structuredClone(payload)
48
+ } catch {
49
+ return UNCLONABLE
50
+ }
51
+ }
52
+
53
+ function deepFreeze(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
54
+ if (value === null || typeof value !== 'object') return
55
+ if (seen.has(value)) return
56
+ seen.add(value)
57
+ for (const key of Object.keys(value)) {
58
+ deepFreeze((value as Record<string, unknown>)[key], seen)
59
+ }
60
+ Object.freeze(value)
61
+ }
62
+
63
+ function record(point: string, decision: string, reason: string): ShadowRecord {
64
+ return Object.freeze({
65
+ point: isToken(point) ? point : 'unknown-point',
66
+ decision: isToken(decision) ? decision : 'unavailable',
67
+ effect: 'none' as const,
68
+ reason: isToken(reason) ? reason : 'invalid_record',
69
+ })
70
+ }
71
+
72
+ /**
73
+ * Evaluate a decision in shadow mode.
74
+ *
75
+ * @param point Registry point id (validated; an invalid id is recorded as
76
+ * `unknown-point`).
77
+ * @param payload Admission payload. Never mutated, never passed by reference.
78
+ * @param decide Decision function evaluated against an isolated frozen copy.
79
+ * @param sink Optional observer; its failures never reach the caller.
80
+ */
81
+ export function observeShadow(
82
+ point: string | DecisionPointId,
83
+ payload: unknown,
84
+ decide: ShadowDecisionFunction,
85
+ sink?: ShadowSink,
86
+ ): ShadowRecord {
87
+ const isolated = isolate(payload)
88
+ if (isolated === UNCLONABLE) {
89
+ return record(String(point), 'unavailable', 'payload_not_clonable')
90
+ }
91
+ deepFreeze(isolated)
92
+
93
+ let decision: string
94
+ let reason: string
95
+ try {
96
+ const result = decide(isolated)
97
+ if (
98
+ result !== null &&
99
+ typeof result === 'object' &&
100
+ isToken(result.decision) &&
101
+ isToken(result.reason)
102
+ ) {
103
+ decision = result.decision
104
+ reason = result.reason
105
+ } else {
106
+ decision = 'unavailable'
107
+ reason = 'invalid_decision'
108
+ }
109
+ } catch {
110
+ decision = 'unavailable'
111
+ reason = 'decision_error'
112
+ }
113
+
114
+ const shadowRecord = record(String(point), decision, reason)
115
+ if (sink) {
116
+ try {
117
+ sink(shadowRecord)
118
+ } catch {
119
+ // An observer failure must not become an admission failure.
120
+ }
121
+ }
122
+ return shadowRecord
123
+ }