pantheon-opencode 1.6.2-beta.3 → 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 (71) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +209 -1
  3. package/bin/pantheon-init.mjs +22 -0
  4. package/package.json +9 -3
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +781 -0
  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 +519 -0
  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 +579 -0
  14. package/scripts/install/interactive.mjs +76 -5
  15. package/scripts/install/opencode.mjs +12 -0
  16. package/scripts/install/state.mjs +5 -0
  17. package/scripts/install/strings.mjs +4 -0
  18. package/scripts/mcp_resources.py +11 -9
  19. package/scripts/release-notes.mjs +30 -7
  20. package/scripts/versioning.mjs +41 -5
  21. package/src/agents/zeus.md +12 -0
  22. package/src/mcp/eval_store.py +11 -4
  23. package/src/mcp/mcp_resources.py +11 -9
  24. package/src/mcp/memory_mcp.py +293 -150
  25. package/src/pantheon/local-decision-agents.ts +170 -0
  26. package/src/pantheon/local-decision-budget.ts +1043 -0
  27. package/src/pantheon/local-decision-egress-gate.ts +264 -0
  28. package/src/pantheon/local-decision-prompt.ts +268 -0
  29. package/src/pantheon/local-decision-provider-matrix.ts +92 -0
  30. package/src/pantheon/local-decision-provider-protocol.ts +335 -0
  31. package/src/pantheon/local-decision-provider.internal.ts +260 -0
  32. package/src/pantheon/local-decision-router.ts +225 -0
  33. package/src/pantheon/local-decision-skills.ts +281 -0
  34. package/src/pantheon/local-decision-tool.ts +160 -0
  35. package/src/pantheon/local-decision-turn.ts +338 -0
  36. package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
  37. package/src/pantheon/local-orchestration.ts +322 -0
  38. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  39. package/src/pantheon/v2-decision-budget.ts +456 -0
  40. package/src/pantheon/v2-decision-contracts.ts +300 -0
  41. package/src/pantheon/v2-decision-egress.ts +203 -0
  42. package/src/pantheon/v2-decision-events.ts +180 -0
  43. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  44. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  45. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  46. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  47. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  48. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  49. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  50. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  51. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  52. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  53. package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
  54. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  55. package/src/pantheon/v2-decision-points.ts +242 -0
  56. package/src/pantheon/v2-decision-policy.ts +166 -0
  57. package/src/pantheon/v2-decision-premises.ts +146 -0
  58. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  59. package/src/pantheon/v2-decision-rank.ts +91 -0
  60. package/src/pantheon/v2-decision-registry.ts +391 -0
  61. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  62. package/src/pantheon/v2-decision-shadow.ts +123 -0
  63. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  64. package/src/pantheon/v2-decision-verify.ts +51 -0
  65. package/src/pantheon/v2-tools.ts +35 -15
  66. package/src/plugin-v2.ts +357 -22
  67. package/src/plugin.ts +4 -0
  68. package/src/plugins/tui/dist/tui-v2.js +3 -3
  69. package/src/plugins/tui/dist/tui.js +1 -1
  70. package/src/plugins/tui/package-lock.json +2 -2
  71. package/src/plugins/tui/package.json +1 -1
@@ -0,0 +1,121 @@
1
+ /**
2
+ * V2 decision heuristic — evidence counting with refusal as a first-class outcome.
3
+ *
4
+ * The heuristic emits no scalar certainty field. Its only inputs are candidate
5
+ * ids and the evidence ids attached to each candidate, and its only outputs are
6
+ * a unique choice or a refusal. This is intentional: a scalar would let a later
7
+ * adapter treat a guess as authorisation.
8
+ *
9
+ * A refusal is a success, not an error:
10
+ *
11
+ * - `NO_CANDIDATES` — nothing to choose from.
12
+ * - `INSUFFICIENT_EVIDENCE` — the best candidate cites less evidence than the
13
+ * caller requires.
14
+ * - `TIE` — two or more candidates cite the same maximum amount;
15
+ * the heuristic refuses instead of inventing a tie-break.
16
+ * - `INVALID_INPUT` — the request does not match the contract.
17
+ *
18
+ * Duplicate evidence ids inside one candidate are counted once, so repeating an
19
+ * id cannot manufacture support.
20
+ */
21
+
22
+ export interface HeuristicCandidate {
23
+ readonly id: string
24
+ readonly evidence: readonly string[]
25
+ }
26
+
27
+ export interface HeuristicRequest {
28
+ readonly candidates: readonly HeuristicCandidate[]
29
+ readonly minimumEvidence?: number
30
+ }
31
+
32
+ export type HeuristicRefusalReason =
33
+ | 'NO_CANDIDATES'
34
+ | 'INSUFFICIENT_EVIDENCE'
35
+ | 'TIE'
36
+ | 'INVALID_INPUT'
37
+
38
+ export type HeuristicOutcome =
39
+ | {
40
+ readonly kind: 'choice'
41
+ readonly candidateId: string
42
+ readonly evidenceCount: number
43
+ readonly reasonCode: 'UNIQUE_MAX_EVIDENCE'
44
+ }
45
+ | {
46
+ readonly kind: 'refusal'
47
+ readonly reasonCode: HeuristicRefusalReason
48
+ readonly candidateIds: readonly string[]
49
+ }
50
+
51
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
52
+ const DEFAULT_MINIMUM_EVIDENCE = 1
53
+
54
+ function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
56
+ }
57
+
58
+ function isToken(value: unknown): value is string {
59
+ return typeof value === 'string' && TOKEN.test(value)
60
+ }
61
+
62
+ function refusal(
63
+ reasonCode: HeuristicRefusalReason,
64
+ candidateIds: readonly string[] = [],
65
+ ): HeuristicOutcome {
66
+ return Object.freeze({
67
+ kind: 'refusal',
68
+ reasonCode,
69
+ candidateIds: Object.freeze([...candidateIds].sort()),
70
+ })
71
+ }
72
+
73
+ /**
74
+ * Decide from evidence counts alone.
75
+ *
76
+ * The comparison is exact and total: highest unique evidence count wins, ties
77
+ * refuse, and a winner below `minimumEvidence` refuses.
78
+ */
79
+ export function decideHeuristic(request: unknown): HeuristicOutcome {
80
+ if (!isRecord(request)) return refusal('INVALID_INPUT')
81
+ const candidates = request.candidates
82
+ if (!Array.isArray(candidates)) return refusal('INVALID_INPUT')
83
+ if (candidates.length === 0) return refusal('NO_CANDIDATES')
84
+
85
+ const minimum = request.minimumEvidence ?? DEFAULT_MINIMUM_EVIDENCE
86
+ if (!Number.isInteger(minimum) || (minimum as number) < 1 || (minimum as number) > 100) {
87
+ return refusal('INVALID_INPUT')
88
+ }
89
+
90
+ const counts = new Map<string, number>()
91
+ for (const candidate of candidates) {
92
+ if (!isRecord(candidate) || !isToken(candidate.id)) return refusal('INVALID_INPUT')
93
+ if (counts.has(candidate.id)) return refusal('INVALID_INPUT')
94
+ const evidence = candidate.evidence
95
+ if (!Array.isArray(evidence)) return refusal('INVALID_INPUT')
96
+ const unique = new Set<string>()
97
+ for (const id of evidence) {
98
+ if (!isToken(id)) return refusal('INVALID_INPUT')
99
+ unique.add(id)
100
+ }
101
+ counts.set(candidate.id, unique.size)
102
+ }
103
+
104
+ let best = 0
105
+ for (const count of counts.values()) {
106
+ if (count > best) best = count
107
+ }
108
+ const top = [...counts.entries()].filter(([, count]) => count === best).map(([id]) => id)
109
+
110
+ if (best < (minimum as number)) return refusal('INSUFFICIENT_EVIDENCE', top)
111
+ if (top.length > 1) return refusal('TIE', top)
112
+
113
+ const [candidateId] = top
114
+ if (candidateId === undefined) return refusal('NO_CANDIDATES')
115
+ return Object.freeze({
116
+ kind: 'choice',
117
+ candidateId,
118
+ evidenceCount: best,
119
+ reasonCode: 'UNIQUE_MAX_EVIDENCE',
120
+ })
121
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * P1 (agent) shadow adapter.
3
+ *
4
+ * The measured prompt payload carries `agents: "undefined"` — the string, in
5
+ * every observed prompt hook (F-08) — so the default path has no agent
6
+ * candidate at all and the heuristic refuses with `no.candidates`. A populated
7
+ * `prompt.agents` was never observed (PM-07), so any candidate list here is a
8
+ * premise, not a measurement, and no candidate carries evidence: the heuristic
9
+ * refuses with `insufficient.evidence` instead of inventing support.
10
+ *
11
+ * Shadow by construction: the admission payload is cloned and frozen by
12
+ * `observeShadow`, the record always says `effect: 'none'`, and no failure is
13
+ * rethrown into admission.
14
+ */
15
+
16
+ import { normalizeMeasuredValue } from '../local-decision-prompt.ts'
17
+ import { decideHeuristic, type HeuristicOutcome } from '../v2-decision-heuristic.ts'
18
+ import {
19
+ observeShadow,
20
+ type ShadowDecision,
21
+ type ShadowRecord,
22
+ type ShadowSink,
23
+ } from '../v2-decision-shadow.ts'
24
+
25
+ export type AgentSource = 'agents' | 'none'
26
+
27
+ export interface AgentPointResult {
28
+ readonly record: ShadowRecord
29
+ /** `agents` when the payload carried a real list, `none` otherwise. */
30
+ readonly agentSource: AgentSource
31
+ readonly agentIds: readonly string[]
32
+ /** Token explaining the decision; always present. */
33
+ readonly reason: string
34
+ }
35
+
36
+ function isRecord(value: unknown): value is Record<string, unknown> {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
38
+ }
39
+
40
+ function agentIdentifier(value: unknown): string | undefined {
41
+ if (typeof value === 'string' && value.length > 0) return value
42
+ if (!isRecord(value)) return undefined
43
+ for (const candidate of [value.name, value.id, value.slug]) {
44
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate
45
+ }
46
+ return undefined
47
+ }
48
+
49
+ /** Read `prompt.agents` with the measured sentinel normalized to absent (F-08). */
50
+ function promptAgents(admission: unknown): string[] {
51
+ if (!isRecord(admission)) return []
52
+ const prompt = admission.prompt
53
+ if (!isRecord(prompt)) return []
54
+ const list = normalizeMeasuredValue(prompt.agents)
55
+ if (!Array.isArray(list)) return []
56
+ const ids: string[] = []
57
+ for (const item of list) {
58
+ const identifier = agentIdentifier(item)
59
+ if (identifier !== undefined && !ids.includes(identifier)) ids.push(identifier)
60
+ }
61
+ return ids
62
+ }
63
+
64
+ /** Heuristic reason codes as shadow-record tokens (underscores are not tokens). */
65
+ function tokenOf(reasonCode: HeuristicOutcome['reasonCode']): string {
66
+ return reasonCode.toLowerCase().split('_').join('.')
67
+ }
68
+
69
+ /**
70
+ * Observe P1 in shadow.
71
+ *
72
+ * @param admission Host admission payload (never mutated).
73
+ * @param sink Optional shadow-record observer.
74
+ */
75
+ export function evaluateAgentPoint(admission: unknown, sink?: ShadowSink): AgentPointResult {
76
+ const agentIds = promptAgents(admission)
77
+ const outcome = decideHeuristic({
78
+ candidates: agentIds.map((id) => ({ id, evidence: [] })),
79
+ minimumEvidence: 1,
80
+ })
81
+ const decision: ShadowDecision = {
82
+ decision: outcome.kind === 'choice' ? 'choice' : 'refusal',
83
+ reason: tokenOf(outcome.reasonCode),
84
+ }
85
+ return {
86
+ record: observeShadow('P1', admission, () => decision, sink),
87
+ agentSource: agentIds.length > 0 ? 'agents' : 'none',
88
+ agentIds,
89
+ reason: decision.reason,
90
+ }
91
+ }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * P10 (claims) shadow adapter — `verify` per counsellor claim.
3
+ *
4
+ * A council member's claims are not evidence: each one carries
5
+ * `{ id, mandatory }` and the response a verifier already produced, and gets
6
+ * its own explicit `PASS | FAIL | BLOCK` verdict. A claim that produced no
7
+ * usable response is `BLOCK` when mandatory and `FAIL` when advisory; it is
8
+ * never `PASS`. Per-counsellor and council-level verdicts follow the same
9
+ * precedence, BLOCK over FAIL over PASS.
10
+ *
11
+ * Two properties are structural, because a claims adapter is exactly where
12
+ * unverified prose would otherwise be laundered into a verdict:
13
+ *
14
+ * - **No claim text is retained.** The result holds ids, verdicts and reason
15
+ * codes only, so no counsellor output can reach a sink, a log or telemetry.
16
+ * - **An incomplete council has no aggregate verdict.** A member with no
17
+ * claims, a duplicate id or a missing `mandatory` flag yields `null` for the
18
+ * council, not a PASS over claims that were never counted.
19
+ *
20
+ * Shadow: the verdicts are recorded and the record always says `effect: 'none'`.
21
+ * Per-counsellor claims were never designed or measured on the host
22
+ * (DISCOVERY §4), so this module is contract-shaped and claims no execution.
23
+ */
24
+
25
+ import {
26
+ observeShadow,
27
+ type ShadowDecision,
28
+ type ShadowRecord,
29
+ type ShadowSink,
30
+ } from '../v2-decision-shadow.ts'
31
+ import {
32
+ resolveVerify,
33
+ type VerifyOutcome,
34
+ type VerifyRequirement,
35
+ type VerifyVerdict,
36
+ } from '../v2-decision-verify.ts'
37
+
38
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
39
+
40
+ export interface ClaimVerdict {
41
+ readonly counsellorId: string
42
+ readonly claimId: string
43
+ readonly mandatory: boolean
44
+ readonly verdict: VerifyVerdict
45
+ readonly reasonCode: VerifyOutcome['reasonCode']
46
+ }
47
+
48
+ export interface CounsellorVerdict {
49
+ readonly counsellorId: string
50
+ /** `null` when the member declared no claim at all. */
51
+ readonly verdict: VerifyVerdict | null
52
+ readonly reason: string
53
+ }
54
+
55
+ export interface ClaimsPointResult {
56
+ readonly record: ShadowRecord
57
+ /** Claims verified, in declaration order; empty when none could be read. */
58
+ readonly claimVerdicts: readonly ClaimVerdict[]
59
+ /** One entry per member, including members with no claim. */
60
+ readonly byCounsellor: readonly CounsellorVerdict[]
61
+ /** Council verdict; `null` whenever any member is incomplete. */
62
+ readonly aggregate: VerifyVerdict | null
63
+ /** Token explaining the decision; always present. */
64
+ readonly reason: string
65
+ }
66
+
67
+ interface ParsedClaim extends VerifyRequirement {
68
+ readonly counsellorId: string
69
+ }
70
+
71
+ interface ParsedCounsellor {
72
+ readonly id: string
73
+ readonly claims: readonly ParsedClaim[]
74
+ }
75
+
76
+ type CouncilParse =
77
+ | { readonly ok: true; readonly counsellors: readonly ParsedCounsellor[] }
78
+ | { readonly ok: false; readonly reason: string }
79
+
80
+ function isRecord(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
82
+ }
83
+
84
+ function isToken(value: unknown): value is string {
85
+ return typeof value === 'string' && TOKEN.test(value)
86
+ }
87
+
88
+ /**
89
+ * Parse the council. Structural damage (unreadable shape, duplicate ids,
90
+ * missing flag) is fatal; a member with zero claims is kept, because it has to
91
+ * cancel the aggregate rather than disappear from it.
92
+ */
93
+ function parseCouncil(input: unknown): CouncilParse {
94
+ const counsellors = isRecord(input) ? input.counsellors : undefined
95
+ if (!Array.isArray(counsellors) || counsellors.length === 0) {
96
+ return { ok: false, reason: 'claims.absent' }
97
+ }
98
+ const parsed: ParsedCounsellor[] = []
99
+ const counsellorIds = new Set<string>()
100
+ for (const entry of counsellors) {
101
+ if (!isRecord(entry) || !isToken(entry.id)) {
102
+ return { ok: false, reason: 'claims.counsellor.invalid' }
103
+ }
104
+ if (counsellorIds.has(entry.id)) {
105
+ return { ok: false, reason: 'claims.counsellor.duplicate' }
106
+ }
107
+ counsellorIds.add(entry.id)
108
+ if (!Array.isArray(entry.claims)) {
109
+ return { ok: false, reason: 'claims.counsellor.invalid' }
110
+ }
111
+ const claims: ParsedClaim[] = []
112
+ const claimIds = new Set<string>()
113
+ for (const claim of entry.claims) {
114
+ if (!isRecord(claim) || !isToken(claim.id) || typeof claim.mandatory !== 'boolean') {
115
+ return { ok: false, reason: 'claims.claim.invalid' }
116
+ }
117
+ if (claimIds.has(claim.id)) {
118
+ return { ok: false, reason: 'claims.claim.duplicate' }
119
+ }
120
+ claimIds.add(claim.id)
121
+ claims.push({ id: claim.id, mandatory: claim.mandatory, counsellorId: entry.id })
122
+ }
123
+ parsed.push({ id: entry.id, claims })
124
+ }
125
+ return { ok: true, counsellors: parsed }
126
+ }
127
+
128
+ /** Responses are read by claim id; an unreadable map yields none at all. */
129
+ function responseFor(candidates: readonly unknown[], index: number): unknown {
130
+ const entry = candidates[index]
131
+ return isRecord(entry) ? entry.response : undefined
132
+ }
133
+
134
+ function precedence(verdicts: readonly VerifyVerdict[]): VerifyVerdict | null {
135
+ if (verdicts.length === 0) return null
136
+ if (verdicts.includes('BLOCK')) return 'BLOCK'
137
+ if (verdicts.includes('FAIL')) return 'FAIL'
138
+ return 'PASS'
139
+ }
140
+
141
+ interface ClaimsAnalysis {
142
+ readonly decision: ShadowDecision
143
+ readonly claimVerdicts: readonly ClaimVerdict[]
144
+ readonly byCounsellor: readonly CounsellorVerdict[]
145
+ readonly aggregate: VerifyVerdict | null
146
+ }
147
+
148
+ function refusal(reason: string): ClaimsAnalysis {
149
+ return {
150
+ decision: { decision: 'refusal', reason },
151
+ claimVerdicts: [],
152
+ byCounsellor: [],
153
+ aggregate: null,
154
+ }
155
+ }
156
+
157
+ function analyze(input: unknown): ClaimsAnalysis {
158
+ const parsed = parseCouncil(input)
159
+ if (!parsed.ok) return refusal(parsed.reason)
160
+
161
+ const raw = isRecord(input) && Array.isArray(input.counsellors) ? input.counsellors : []
162
+ const claimVerdicts: ClaimVerdict[] = []
163
+ const byCounsellor: CounsellorVerdict[] = []
164
+
165
+ for (const [counsellorIndex, counsellor] of parsed.counsellors.entries()) {
166
+ const rawCounsellor = raw[counsellorIndex]
167
+ const rawClaims =
168
+ isRecord(rawCounsellor) && Array.isArray(rawCounsellor.claims) ? rawCounsellor.claims : []
169
+ const memberVerdicts: VerifyVerdict[] = []
170
+ for (const [claimIndex, claim] of counsellor.claims.entries()) {
171
+ const outcome = resolveVerify(
172
+ { id: claim.id, mandatory: claim.mandatory },
173
+ responseFor(rawClaims, claimIndex),
174
+ )
175
+ claimVerdicts.push({
176
+ counsellorId: claim.counsellorId,
177
+ claimId: outcome.requirementId,
178
+ mandatory: outcome.mandatory,
179
+ verdict: outcome.verdict,
180
+ reasonCode: outcome.reasonCode,
181
+ })
182
+ memberVerdicts.push(outcome.verdict)
183
+ }
184
+ const memberVerdict = precedence(memberVerdicts)
185
+ byCounsellor.push({
186
+ counsellorId: counsellor.id,
187
+ verdict: memberVerdict,
188
+ reason:
189
+ memberVerdict === null
190
+ ? 'claims.counsellor.empty'
191
+ : `claims.${memberVerdict.toLowerCase()}`,
192
+ })
193
+ }
194
+
195
+ const incomplete = byCounsellor.some((entry) => entry.verdict === null)
196
+ if (incomplete) {
197
+ return {
198
+ decision: { decision: 'refusal', reason: 'claims.counsellor.empty' },
199
+ claimVerdicts,
200
+ byCounsellor,
201
+ aggregate: null,
202
+ }
203
+ }
204
+ const aggregate = precedence(
205
+ byCounsellor.flatMap((entry) => (entry.verdict === null ? [] : [entry.verdict])),
206
+ )
207
+ if (aggregate === null) return refusal('claims.absent')
208
+ return {
209
+ decision: { decision: `verify.${aggregate.toLowerCase()}`, reason: 'claims.verified' },
210
+ claimVerdicts,
211
+ byCounsellor,
212
+ aggregate,
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Observe P10 in shadow.
218
+ *
219
+ * @param input `{ counsellors: [{ id, claims: [{ id, mandatory, response? }] }] }`.
220
+ * Never mutated; responses are read, never retained.
221
+ * @param sink Optional shadow-record observer.
222
+ */
223
+ export function evaluateClaimsPoint(input: unknown, sink?: ShadowSink): ClaimsPointResult {
224
+ let analysis: ClaimsAnalysis = refusal('claims.absent')
225
+ const record = observeShadow(
226
+ 'P10',
227
+ input,
228
+ (isolated) => {
229
+ analysis = analyze(isolated)
230
+ return analysis.decision
231
+ },
232
+ sink,
233
+ )
234
+
235
+ const contained = record.decision === 'unavailable'
236
+ return {
237
+ record,
238
+ claimVerdicts: contained ? [] : analysis.claimVerdicts,
239
+ byCounsellor: contained ? [] : analysis.byCounsellor,
240
+ aggregate: contained ? null : analysis.aggregate,
241
+ reason: record.reason,
242
+ }
243
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * P11 (catalog) shadow adapter — `ask.choice` over the `tool.transform` draft.
3
+ *
4
+ * The host catalog context was ABSENT at every measured point (F-05) and is not
5
+ * part of this design. The only measured catalog surface is the draft handed to
6
+ * `ctx.tool.transform`: `{ list, get, namespace, add, update, remove }`, with
7
+ * entries carrying `{ name, options, description, input, output, execute, id }`
8
+ * (F-07). The draft is dynamic during a run — 20 host tools, 26 with the plugin
9
+ * and 46 after MCP servers register (PROBE-E §6) — so it is read per invocation
10
+ * and never cached.
11
+ *
12
+ * The adapter only reads: `list()` is called, the six measured members are
13
+ * checked for their measured kind (functions) and nothing is added, updated or
14
+ * removed. A draft that is absent, unreadable or shaped differently from the
15
+ * measured one fails closed with an explicit reason; it never throws into
16
+ * admission.
17
+ *
18
+ * The choice is a real validated question over the draft ids, but shadow has no
19
+ * responder: with no answer the record says `catalog.no.answer` instead of
20
+ * inventing a selection. An answer supplied by a caller is resolved through the
21
+ * shared contract, and even then the draft is not mutated.
22
+ */
23
+
24
+ import { type ChoiceQuestion, evaluateAskAnswer, validateAsk } from '../v2-decision-contracts.ts'
25
+ import {
26
+ observeShadow,
27
+ type ShadowDecision,
28
+ type ShadowRecord,
29
+ type ShadowSink,
30
+ } from '../v2-decision-shadow.ts'
31
+
32
+ export type CatalogSource = 'draft' | 'none'
33
+
34
+ export interface CatalogPointResult {
35
+ readonly record: ShadowRecord
36
+ /** `draft` when the measured draft shape was present, `none` otherwise. */
37
+ readonly catalogSource: CatalogSource
38
+ /** Draft ids in observed order, de-duplicated; empty on any failure. */
39
+ readonly toolIds: readonly string[]
40
+ /** The validated `choice` question, or `null` when no question could be built. */
41
+ readonly question: ChoiceQuestion | null
42
+ /** Label of the resolved choice, or `null` when none was made. */
43
+ readonly selectedToolId: string | null
44
+ /** Token explaining the decision; always present. */
45
+ readonly reason: string
46
+ }
47
+
48
+ /** Members of the measured `tool.transform` draft (F-07). */
49
+ const DRAFT_MEMBERS = ['list', 'get', 'namespace', 'add', 'update', 'remove'] as const
50
+ const MAX_LABEL_LENGTH = 120
51
+
52
+ interface DraftRead {
53
+ readonly ok: boolean
54
+ readonly source: CatalogSource
55
+ readonly ids: readonly string[]
56
+ readonly reason: string
57
+ }
58
+
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
61
+ }
62
+
63
+ function hasControlCharacter(value: string): boolean {
64
+ for (const character of value) {
65
+ const code = character.codePointAt(0) ?? 0
66
+ if (code < 0x20 || code === 0x7f) return true
67
+ }
68
+ return false
69
+ }
70
+
71
+ /** A label can be rendered in a `choice` line: single line, present, bounded. */
72
+ function isLabel(value: unknown): value is string {
73
+ return (
74
+ typeof value === 'string' &&
75
+ value.trim().length > 0 &&
76
+ value.length <= MAX_LABEL_LENGTH &&
77
+ !hasControlCharacter(value)
78
+ )
79
+ }
80
+
81
+ function fail(source: CatalogSource, reason: string): DraftRead {
82
+ return { ok: false, source, ids: [], reason }
83
+ }
84
+
85
+ /**
86
+ * Read the draft without trusting it.
87
+ *
88
+ * `list` is the only function invoked. A shape that differs from the measured
89
+ * one — including a missing member or a non-function member — is refused before
90
+ * any call, because a draft that cannot be recognised cannot be observed
91
+ * safely.
92
+ */
93
+ function readDraft(draft: unknown): DraftRead {
94
+ if (draft === undefined || draft === null) return fail('none', 'draft.absent')
95
+ if (!isRecord(draft)) return fail('none', 'draft.shape.unsupported')
96
+ for (const member of DRAFT_MEMBERS) {
97
+ if (typeof draft[member] !== 'function') return fail('none', 'draft.shape.unsupported')
98
+ }
99
+
100
+ const list = draft.list as () => unknown
101
+ let listed: unknown
102
+ try {
103
+ listed = list.call(draft)
104
+ } catch {
105
+ return fail('draft', 'draft.list.error')
106
+ }
107
+ if (!Array.isArray(listed)) return fail('draft', 'draft.list.invalid')
108
+
109
+ const ids: string[] = []
110
+ for (const entry of listed) {
111
+ if (!isRecord(entry)) continue
112
+ // `name` is what `remove` takes; `id` is the fallback measured on the entry.
113
+ const identifier = isLabel(entry.name) ? entry.name : isLabel(entry.id) ? entry.id : undefined
114
+ if (identifier !== undefined && !ids.includes(identifier)) ids.push(identifier)
115
+ }
116
+ if (ids.length === 0) return fail('draft', 'draft.entry.unstable')
117
+ return { ok: true, source: 'draft', ids: Object.freeze(ids), reason: 'draft.listed' }
118
+ }
119
+
120
+ /** Contract failure codes are uppercase; record tokens are lower-case dotted. */
121
+ function tokenOf(code: string): string {
122
+ return code.toLowerCase().split('_').join('.')
123
+ }
124
+
125
+ interface CatalogDecision {
126
+ readonly decision: ShadowDecision
127
+ readonly question: ChoiceQuestion | null
128
+ readonly selectedToolId: string | null
129
+ }
130
+
131
+ function buildDecision(ids: readonly string[], answer?: unknown): CatalogDecision {
132
+ const validated = validateAsk({
133
+ mode: 'choice',
134
+ id: 'p11.catalog',
135
+ text: 'Select one tool from the measured tool.transform draft.',
136
+ labels: ids,
137
+ })
138
+ if (!validated.ok) {
139
+ return {
140
+ decision: { decision: 'refusal', reason: `catalog.question.${tokenOf(validated.code)}` },
141
+ question: null,
142
+ selectedToolId: null,
143
+ }
144
+ }
145
+ const question = validated.question as ChoiceQuestion
146
+ if (answer === undefined) {
147
+ // Shadow has no responder. Recording the question is the observation; a
148
+ // selection would be a claim the adapter cannot support.
149
+ return {
150
+ decision: { decision: 'unavailable', reason: 'catalog.no.answer' },
151
+ question,
152
+ selectedToolId: null,
153
+ }
154
+ }
155
+ const resolution = evaluateAskAnswer(question, answer)
156
+ if (resolution.status === 'choice') {
157
+ return {
158
+ decision: { decision: 'choice', reason: 'catalog.choice.resolved' },
159
+ question,
160
+ selectedToolId: resolution.label,
161
+ }
162
+ }
163
+ if (resolution.status === 'refusal') {
164
+ return {
165
+ decision: { decision: 'refusal', reason: 'catalog.choice.refused' },
166
+ question,
167
+ selectedToolId: null,
168
+ }
169
+ }
170
+ return {
171
+ decision: { decision: 'refusal', reason: 'catalog.choice.failed' },
172
+ question,
173
+ selectedToolId: null,
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Observe P11 in shadow.
179
+ *
180
+ * @param draft Host `ctx.tool.transform` draft. Read only; never mutated.
181
+ * @param sink Optional shadow-record observer.
182
+ * @param answer Optional `ask` answer the caller already obtained.
183
+ */
184
+ export function evaluateCatalogPoint(
185
+ draft: unknown,
186
+ sink?: ShadowSink,
187
+ answer?: unknown,
188
+ ): CatalogPointResult {
189
+ let read: DraftRead
190
+ try {
191
+ read = readDraft(draft)
192
+ } catch {
193
+ read = fail('none', 'draft.read.error')
194
+ }
195
+
196
+ let question: ChoiceQuestion | null = null
197
+ let selectedToolId: string | null = null
198
+ const record = observeShadow(
199
+ 'P11',
200
+ { catalogSource: read.source, toolIds: read.ok ? read.ids : [] },
201
+ () => {
202
+ if (!read.ok) return { decision: 'refusal', reason: read.reason }
203
+ const decided = buildDecision(read.ids, answer)
204
+ question = decided.question
205
+ selectedToolId = decided.selectedToolId
206
+ return decided.decision
207
+ },
208
+ sink,
209
+ )
210
+
211
+ const failed = record.decision === 'unavailable' && record.reason !== 'catalog.no.answer'
212
+ return {
213
+ record,
214
+ catalogSource: failed ? 'none' : read.source,
215
+ toolIds: failed || !read.ok ? [] : read.ids,
216
+ question: failed ? null : question,
217
+ selectedToolId: failed ? null : selectedToolId,
218
+ reason: record.reason,
219
+ }
220
+ }