pantheon-opencode 2.0.2 โ†’ 2.0.4

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.
@@ -26,6 +26,7 @@ permission:
26
26
  grep: allow
27
27
  glob: allow
28
28
  webfetch: allow
29
+ question: allow
29
30
  task:
30
31
  "*": deny
31
32
  apollo: allow
@@ -110,17 +111,19 @@ Use `webfetch` to verify availability before proposing model updates to other ag
110
111
  - Make multiple planning attempts
111
112
  - Search or inspect `.pantheon/**`, `.pantheon/deepwork/**`, `.git/**` or `.pantheon-worktrees/**`
112
113
 
113
- ## Plan Structure (Visual, Actionable & Token-Efficient)
114
+ ## Plan Structure (Didactic Executive Summary + Disk Blueprint)
114
115
 
115
- Use this template whenever the user asks for a plan or Zeus requests one. Keep it
116
- visual, actionable, and token-efficient โ€” modeled after Claude Code and ChatGPT Agent plan modes:
116
+ Whenever creating a plan, format your output in two clear, modular sections:
117
117
 
118
118
  ```markdown
119
119
  # ๐Ÿ“ Architecture Plan: [Feature Name]
120
120
 
121
121
  > **Architect:** @athena ยท **Review Gate:** @themis ยท **Execution Mode:** Strict TDD with Sub-10s Test Slicing
122
122
 
123
- ### Architecture & Execution Flow
123
+ ### ๐Ÿ“‹ Executive Summary (Chat Contract)
124
+ - **Goal:** One crisp sentence describing the concrete outcome.
125
+ - **Estimated Effort:** [X minutes / low or medium risk]
126
+
124
127
  ```mermaid
125
128
  flowchart LR
126
129
  P1["Phase 1: Model / Schema (@demeter)"] --> P2["Phase 2: Core Logic (@hermes)"]
@@ -128,36 +131,41 @@ flowchart LR
128
131
  P3 --> P4["Phase 4: Verification (@themis)"]
129
132
  ```
130
133
 
131
- ### Goal & Scope
134
+ | Phase | Specialist | Key Deliverable | Test Slice |
135
+ |---|---|---|---|
136
+ | **1. Data / Contract** | @demeter | Schemas, models & migrations | `npm test tests/models/...` |
137
+ | **2. Core Logic** | @hermes | Service implementation & business rules | `npm test tests/services/...` |
138
+ | **3. Interface / UI** | @aphrodite | Components, styling & accessibility | `npm test tests/ui/...` |
139
+ | **4. Verification** | @themis | Security review & full integration gate | `npm run test:e2e` |
140
+
141
+ ---
142
+
143
+ ### ๐Ÿ› ๏ธ Technical Implementation Blueprint (Saved to Disk)
144
+
145
+ #### Goal, Scope & Context
132
146
  - **Goal:** One sentence describing what this plan achieves.
133
- - **In scope:** [Concrete outcomes]
134
- - **Out of scope:** [Important exclusions]
135
- - **Assumptions:** [Key assumptions; unverified facts]
136
- - **Open Questions:** [Critical decisions the user must make, with recommended defaults]
147
+ - **In scope / Out of scope:** Concrete outcomes and exclusions.
148
+ - **Assumptions & Open Questions:** Key assumptions; critical decisions with recommended defaults.
137
149
 
138
- ### Phases (3-5 max)
150
+ #### Phases & Quality Gates (3-5 max)
139
151
  1. **[Phase Name] โ†’ @agent**
140
152
  - **Goal & Actions:** Outcome and concrete steps (TDD: RED โ†’ GREEN โ†’ REFACTOR)
141
153
  - **Affected files or areas:** Known paths or explicitly mark unknown paths instead of guessing
142
154
  - **Dependencies:** Earlier phases or external systems
143
- - **Tests & Test Slicing:** Exact targeted slice (e.g. `node --test tests/foo.test.mjs`), focused checks, lint-first gate, and applicable quality gates
144
- - **Risks & Mitigation:** Specific risk โ†’ concrete mitigation
145
-
146
- 2. **[Phase Name] โ†’ @agent**
147
- ...
155
+ - **Tests & Test Slicing:** Exact targeted slice (< 10s), focused checks, lint-first gate
156
+ - **Risks & Mitigation:** Specific risk โ†’ concrete prevention
148
157
 
149
- ### Acceptance Criteria & Verification
158
+ #### Acceptance Criteria & Verification
150
159
  - [ ] Observable completion criterion
151
- - [ ] Verification criterion (all targeted tests green, 0 lint warnings)
160
+ - [ ] Verification criterion (targeted tests green, 0 lint warnings)
152
161
 
153
- ### Rollback & Contingency Plan
154
- - **Failure Trigger:** Conditions under which execution aborts (e.g. test slice failure, unexpected schema corruption).
155
- - **Rollback Steps:** Revert commit / feature flag toggle / database rollback migration.
162
+ #### Rollback & Contingency Plan
163
+ - **Failure Trigger:** Conditions under which execution aborts
164
+ - **Rollback Steps:** Revert commit / feature flag toggle / database rollback migration
156
165
  ```
157
166
 
158
- The complete plan is the deliverable. Include it in your final response to the
159
- caller; do not replace it with a summary, a file path, a status such as
160
- "approval requested", or content available only in your child-session transcript.
167
+ ### Interactive Question Gate
168
+ When directly invoked by the user, if you need trade-off confirmation or final approval, always call the native `question` tool with structured choices (e.g., `["Aprovar e executar", "Ajustar plano"]`), rather than relying solely on unstructured chat text.
161
169
  Keep unknown paths and unverified assumptions explicit rather than fabricating
162
170
  detail.
163
171
 
@@ -51,32 +51,11 @@ mcp_tools:
51
51
  - **Code-mode / infrastructure reads** โ€” cheap and on demand; never for
52
52
  decisions the ladder already answers.
53
53
 
54
- ## Verification Tiers
54
+ ## Fast-Path Execution Contract
55
55
 
56
- Small bounded fix โ†’ change + one targeted proof, no ceremony. Material change โ†’ full test discipline. Match the tier to the change.
57
-
58
-
59
- ## Core Capabilities
60
-
61
- ### 1. Rapid Repairs
62
- - Single-file fixes (< 10 lines)
63
- - Multi-file fixes (max 2 files)
64
- - CSS, typo, import, and minor logic fixes
65
-
66
- ### 2. No TDD Ceremony
67
- - Hotfixes skip the RED->GREEN->REFACTOR cycle
68
- - Fix and run the narrowest relevant existing test/check; do not run a full suite for a micro-edit
69
- - Document the root cause inline
70
-
71
- ### 3. Escalation Rules
72
- Escalate to @zeus if:
73
- - Fix requires > 2 files or > 10 lines changed
74
- - Has security implications
75
- - Requires database migration
76
- - Touches authentication, security-sensitive behavior, production data, global configuration, or broad permissions
77
- - Breaks existing tests unexpectedly
78
-
79
- Full-auto does not permit Talos to perform push/merge/deploy, destructive/global changes, or sensitive work; escalate for required specialist review and explicit human approval.
56
+ - **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes).
57
+ - **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`.
58
+ - **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly.
80
59
 
81
60
  ## Requested Artifact Completion
82
61
 
@@ -84,19 +63,10 @@ Full-auto does not permit Talos to perform push/merge/deploy, destructive/global
84
63
  - Searching the MCP Code Mode catalog only discovers MCP tools. A missing MCP match does not mean native file tools are unavailable.
85
64
  - Verify the write succeeded and, when practical, read the artifact back. If a native file tool is actually unavailable or denies the write, state that specific limitation and do not claim completion.
86
65
 
87
- ## Constraints
88
- - No orchestration: you work standalone
89
- - No Themis review needed (low-risk)
90
- - Return subtask_summary format
91
- - If complexity exceeds threshold, escalate immediately
92
-
93
- ## Auto-Continue (Embedded: Hotfix)
94
-
95
- - Auto-continue through quick fix cycles (identify โ†’ fix โ†’ verify)
96
- - No checkpoint needed (single-file fixes, low complexity)
97
- - Escalate to Zeus if fix takes > 3 turns or requires > 2 files / > 10 lines
98
- - If fix breaks existing tests, stop immediately and escalate
99
- - No partial results โ€” either fix is applied or escalate
66
+ ## Escalation Boundaries
100
67
 
101
- ## Skills
102
- `code-review-checklist`, `git-workflow-and-versioning`
68
+ Escalate to @zeus immediately if:
69
+ - Change requires > 2 files or > 10 lines
70
+ - Touches security, authentication, credentials, migrations, or broad permissions
71
+ - Fix takes > 3 turns or causes unexpected test regression
72
+ - Full-auto never permits push/merge/deploy or destructive operations without specialist review and human approval.
@@ -183,6 +183,14 @@ Estimated time: ~60% of review effort
183
183
  - [ ] IntentGate passed (code solves the right problem)
184
184
  - [ ] Auth/security, data/schema, and sensitive actions preserve applicable tests, specialist review, and human approval
185
185
 
186
+ ## Local Reflex Loop (Self-Healing)
187
+
188
+ When Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails:
189
+ - Themis executes a direct local reflex loop with the implementer (up to 2 retry attempts).
190
+ - Emits `themis:reflex:discrepancy` with the exact failing slice/rules.
191
+ - Does NOT escalate to Zeus unless the 2-retry reflex budget is exhausted or an architectural/IntentGate mismatch occurs.
192
+ - On successful remediation, emits `themis:reflex:resolved` and issues PASS / PASS_WITH_NOTES.
193
+
186
194
  ## Verdict
187
195
 
188
196
  After review, return one of these:
@@ -11,6 +11,7 @@ permission:
11
11
  vision_describe: allow
12
12
  pantheon_jev_decide: allow
13
13
  pantheon_skill_search: allow
14
+ question: allow
14
15
  task:
15
16
  "*": allow
16
17
  temperature: 0.2
@@ -97,9 +98,13 @@ Before every dispatch, send the target a concise brief with the objective/result
97
98
  ## Plan Handoff and Approval
98
99
 
99
100
  Whenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:
100
- 1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return the complete Markdown plan in the final subagent result; Zeus owns the user-facing approval gate.
101
- 2. Check that the returned subagent result contains the full plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria. If the plan is missing or incomplete, do not ask for approval, and tell the user the handoff did not contain a reviewable plan.
102
- 3. Publish the **entire returned plan as a normal assistant message in the main conversation** without summarizing. The plan message must be visible in the conversation before you trigger any approval UI.
103
- 4. After the plan has been published, request approval. If the runtime cannot guarantee that the plan message is visible before the question UI opens, leave the full plan in the conversation, ask for approval in plain text after it, and wait for the user's next message.
104
- 5. If the user requests changes, send them to Athena, then present the entire revised plan in the main conversation and repeat the approval gate.
105
- Athena is plan-only and cannot write files; write `.pantheon/deepwork/<slug>/PLAN.md` yourself right after her plan lands.
101
+ 1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.
102
+ 2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.
103
+ 3. Write the full technical blueprint to `.pantheon/deepwork/<slug>/PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.
104
+ 4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:
105
+ - **Goal & Target:** 1 crisp sentence.
106
+ - **Execution Flow:** Mermaid diagram (3-4 nodes).
107
+ - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).
108
+ - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork/<slug>/PLAN.md`.
109
+ 5. **Interactive Question Gate:** Always invoke the native `question` tool to request user approval with explicit options (e.g., `["Aprovar e iniciar execuรงรฃo", "Ajustar plano"]` / `["Approve and begin execution", "Adjust plan"]`), falling back to plain text only if the tool is not exposed.
110
+ 6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork/<slug>/PLAN.md`, and repeat the interactive gate.
@@ -13,6 +13,7 @@
13
13
  import { mkdir, rename, unlink, writeFile } from 'node:fs/promises'
14
14
  import { dirname, join } from 'node:path'
15
15
 
16
+ import { getSharedBus } from './bus.ts'
16
17
  import { createPantheonLogger } from './logger.ts'
17
18
 
18
19
  // Silence-by-default TUI policy (pantheon-hooks L42-58): console output in a
@@ -292,6 +293,14 @@ export class BackgroundJobBoard {
292
293
 
293
294
  this.jobs.set(input.taskID, record)
294
295
  await this.persistRecord(record)
296
+ getSharedBus().emit('job:created', {
297
+ taskID: record.taskID,
298
+ alias: record.alias,
299
+ agent: record.agent,
300
+ parentSessionID: record.parentSessionID,
301
+ state: record.state,
302
+ timestamp: now,
303
+ })
295
304
  return record
296
305
  }
297
306
 
@@ -364,6 +373,14 @@ export class BackgroundJobBoard {
364
373
 
365
374
  // --- write-ahead log: persist before notify ---
366
375
  await this.persistRecord(job)
376
+ getSharedBus().emit('job:updated', {
377
+ taskID: job.taskID,
378
+ alias: job.alias,
379
+ agent: job.agent,
380
+ state: job.state,
381
+ resultSummary: job.resultSummary,
382
+ timestamp: job.updatedAt,
383
+ })
367
384
 
368
385
  // --- signal on terminal states ---
369
386
  if (willBeTerminal) {
@@ -463,6 +480,11 @@ export class BackgroundJobBoard {
463
480
  // cycle deleted them. Instead, remove any still-pending wake signal so
464
481
  // reconcile leaves no `<alias>.signal.json` behind.
465
482
  await this.deleteSignal(job.alias)
483
+ getSharedBus().emit('job:reconciled', {
484
+ taskID: job.taskID,
485
+ alias: job.alias,
486
+ timestamp: job.updatedAt,
487
+ })
466
488
 
467
489
  return job
468
490
  }
@@ -728,6 +750,17 @@ export class BackgroundJobBoard {
728
750
  }
729
751
 
730
752
  private notifyTerminal(taskID: string): void {
753
+ const job = this.jobs.get(taskID)
754
+ if (job) {
755
+ getSharedBus().emit('job:terminal', {
756
+ taskID: job.taskID,
757
+ alias: job.alias,
758
+ agent: job.agent,
759
+ state: job.state,
760
+ resultSummary: job.resultSummary,
761
+ timestamp: job.completedAt ?? Date.now(),
762
+ })
763
+ }
731
764
  for (const listener of this.terminalListeners) {
732
765
  try {
733
766
  listener(taskID)
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Pantheon Event Bus (pantheon-bus) โ€” In-memory reactive event system.
3
+ *
4
+ * Eliminates disk I/O and polling loops for inter-agent communication,
5
+ * background job tracking, and reactive verification.
6
+ *
7
+ * Process-global singleton anchored in globalThis.__pantheonSharedBus,
8
+ * matching the dual-plugin deduplication architecture in shared-board.ts.
9
+ *
10
+ * Pure TypeScript โ€” zero external dependencies.
11
+ *
12
+ * @module bus
13
+ */
14
+
15
+ export interface JobEventPayload {
16
+ readonly taskID: string
17
+ readonly alias: string
18
+ readonly agent: string
19
+ readonly timestamp: number
20
+ readonly parentSessionID?: string | undefined
21
+ readonly state?: string | undefined
22
+ readonly resultSummary?: string | null | undefined
23
+ }
24
+
25
+ export interface ThemisReflexEventPayload {
26
+ readonly taskID: string
27
+ readonly agent: string
28
+ readonly file: string
29
+ readonly error: string
30
+ readonly attempt: number
31
+ readonly maxAttempts: number
32
+ readonly timestamp: number
33
+ readonly resolved?: boolean | undefined
34
+ }
35
+
36
+ export interface ExecutionReceiptPayload {
37
+ readonly receiptId: string
38
+ readonly taskID: string
39
+ readonly agent: string
40
+ readonly status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED'
41
+ readonly files: ReadonlyArray<{
42
+ readonly path: string
43
+ readonly hash: string
44
+ readonly sizeBytes: number
45
+ }>
46
+ readonly testSlice?:
47
+ | { readonly command: string; readonly exitCode: number; readonly durationMs: number }
48
+ | undefined
49
+ readonly timestamp: number
50
+ readonly signature: string
51
+ }
52
+
53
+ export interface PantheonEventMap {
54
+ 'job:created': JobEventPayload
55
+ 'job:updated': JobEventPayload
56
+ 'job:terminal': JobEventPayload
57
+ 'job:reconciled': { readonly taskID: string; readonly alias: string; readonly timestamp: number }
58
+ 'themis:reflex:discrepancy': ThemisReflexEventPayload
59
+ 'themis:reflex:resolved': ThemisReflexEventPayload
60
+ 'agent:execution:receipt': ExecutionReceiptPayload
61
+ }
62
+
63
+ export type PantheonEventName = keyof PantheonEventMap
64
+
65
+ // biome-ignore lint/suspicious/noExplicitAny: internal heterogeneous event listener storage
66
+ type AnyListener = (payload: any) => void | Promise<void>
67
+
68
+ export class PantheonBus {
69
+ private readonly listeners: Map<string, Set<AnyListener>> = new Map()
70
+
71
+ /**
72
+ * Register a persistent listener for an event.
73
+ * Returns an unsubscribe callback for easy cleanup.
74
+ */
75
+ on<E extends PantheonEventName>(
76
+ event: E,
77
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
78
+ ): () => void {
79
+ let set = this.listeners.get(event)
80
+ if (!set) {
81
+ set = new Set()
82
+ this.listeners.set(event, set)
83
+ }
84
+ set.add(listener)
85
+ return () => {
86
+ set?.delete(listener)
87
+ if (set?.size === 0) {
88
+ this.listeners.delete(event)
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Register a one-shot listener that unregisters itself after firing once.
95
+ */
96
+ once<E extends PantheonEventName>(
97
+ event: E,
98
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
99
+ ): () => void {
100
+ const unsubscribe = this.on(event, (payload) => {
101
+ unsubscribe()
102
+ return listener(payload)
103
+ })
104
+ return unsubscribe
105
+ }
106
+
107
+ /**
108
+ * Synchronously emit an event to all registered listeners.
109
+ * Listener rejections are logged safely without throwing.
110
+ */
111
+ emit<E extends PantheonEventName>(event: E, payload: PantheonEventMap[E]): void {
112
+ const set = this.listeners.get(event)
113
+ if (!set || set.size === 0) return
114
+ for (const listener of Array.from(set)) {
115
+ try {
116
+ const result = listener(payload)
117
+ if (result instanceof Promise) {
118
+ result.catch(() => {})
119
+ }
120
+ } catch {
121
+ // Safe swallow: an in-memory listener crash must not fail the emitter
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Wait asynchronously for a specific event matching a predicate, with an optional timeout.
128
+ */
129
+ waitFor<E extends PantheonEventName>(
130
+ event: E,
131
+ predicate: (payload: PantheonEventMap[E]) => boolean,
132
+ timeoutMs = 30_000,
133
+ ): Promise<PantheonEventMap[E]> {
134
+ return new Promise((resolve, reject) => {
135
+ let timer: NodeJS.Timeout | null = null
136
+ let unsubscribe: (() => void) | null = null
137
+
138
+ if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
139
+ timer = setTimeout(() => {
140
+ unsubscribe?.()
141
+ reject(new Error(`Timed out waiting for bus event "${event}" after ${timeoutMs}ms`))
142
+ }, timeoutMs)
143
+ }
144
+
145
+ unsubscribe = this.on(event, (payload) => {
146
+ try {
147
+ if (predicate(payload)) {
148
+ if (timer) clearTimeout(timer)
149
+ unsubscribe?.()
150
+ resolve(payload)
151
+ }
152
+ } catch (err) {
153
+ if (timer) clearTimeout(timer)
154
+ unsubscribe?.()
155
+ reject(err)
156
+ }
157
+ })
158
+ })
159
+ }
160
+
161
+ /** Number of active listeners for a specific event or in total. */
162
+ listenerCount(event?: PantheonEventName): number {
163
+ if (event) {
164
+ return this.listeners.get(event)?.size ?? 0
165
+ }
166
+ let total = 0
167
+ for (const set of this.listeners.values()) {
168
+ total += set.size
169
+ }
170
+ return total
171
+ }
172
+
173
+ /** Clear all listeners (primarily for unit tests). */
174
+ clear(): void {
175
+ this.listeners.clear()
176
+ }
177
+ }
178
+
179
+ const BUS_KEY = '__pantheonSharedBus'
180
+
181
+ /**
182
+ * Access the process-global PantheonBus singleton.
183
+ */
184
+ export function getSharedBus(): PantheonBus {
185
+ const host = globalThis as { [BUS_KEY]?: PantheonBus }
186
+ if (host[BUS_KEY] instanceof PantheonBus) return host[BUS_KEY]
187
+ const bus = new PantheonBus()
188
+ host[BUS_KEY] = bus
189
+ return bus
190
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Execution Proof Receipts โ€” Verifiable task completion contracts for agent execution.
3
+ *
4
+ * Implements SOTA late-2026 verification principles: subagents return cryptographic
5
+ * receipts containing deterministic content hashes of modified files and verifiable
6
+ * test-slicing proofs, eliminating false-positive completion reports.
7
+ *
8
+ * Emits reactive verification events on `PantheonBus`.
9
+ *
10
+ * Pure TypeScript โ€” stdlib crypto only.
11
+ *
12
+ * @module execution-receipt
13
+ */
14
+
15
+ import { createHash } from 'node:crypto'
16
+ import { type ExecutionReceiptPayload, getSharedBus } from './bus.ts'
17
+
18
+ export interface FileInput {
19
+ readonly path: string
20
+ readonly content: string | Buffer
21
+ }
22
+
23
+ export interface TestSliceInput {
24
+ readonly command: string
25
+ readonly exitCode: number
26
+ readonly durationMs: number
27
+ }
28
+
29
+ export interface CreateReceiptInput {
30
+ readonly taskID: string
31
+ readonly agent: string
32
+ readonly files: readonly FileInput[]
33
+ readonly testSlice?: TestSliceInput | undefined
34
+ }
35
+
36
+ /**
37
+ * Compute SHA-256 fingerprint for a string or buffer.
38
+ */
39
+ export function hashContent(content: string | Buffer): string {
40
+ return createHash('sha256').update(content).digest('hex')
41
+ }
42
+
43
+ /**
44
+ * Compute cryptographic signature binding task, agent, timestamp and file hashes.
45
+ */
46
+ export function computeReceiptSignature(
47
+ taskID: string,
48
+ agent: string,
49
+ timestamp: number,
50
+ files: ReadonlyArray<{ readonly path: string; readonly hash: string }>,
51
+ ): string {
52
+ const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path))
53
+ const payload = [
54
+ taskID,
55
+ agent,
56
+ String(timestamp),
57
+ sortedFiles.map((f) => `${f.path}:${f.hash}`).join(';'),
58
+ ].join('|')
59
+ return createHash('sha256').update(payload).digest('hex')
60
+ }
61
+
62
+ /**
63
+ * Generate a verifiable Execution Proof Receipt and emit it on the shared bus.
64
+ */
65
+ export function createExecutionReceipt(input: CreateReceiptInput): ExecutionReceiptPayload {
66
+ const timestamp = Date.now()
67
+ const files = input.files.map((f) => {
68
+ const buf = typeof f.content === 'string' ? Buffer.from(f.content, 'utf8') : f.content
69
+ return {
70
+ path: f.path,
71
+ hash: hashContent(buf),
72
+ sizeBytes: buf.length,
73
+ }
74
+ })
75
+
76
+ const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files)
77
+ const receiptId = `rcpt_${signature.slice(0, 16)}`
78
+
79
+ let status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED' = 'UNVERIFIED'
80
+ if (input.testSlice) {
81
+ status = input.testSlice.exitCode === 0 ? 'VERIFIED' : 'FAILED'
82
+ }
83
+
84
+ const receipt: ExecutionReceiptPayload = {
85
+ receiptId,
86
+ taskID: input.taskID,
87
+ agent: input.agent,
88
+ status,
89
+ files,
90
+ testSlice: input.testSlice,
91
+ timestamp,
92
+ signature,
93
+ }
94
+
95
+ getSharedBus().emit('agent:execution:receipt', receipt)
96
+ return receipt
97
+ }
98
+
99
+ /**
100
+ * Verify whether an execution receipt signature matches its declared files and metadata.
101
+ */
102
+ export function verifyExecutionReceipt(receipt: ExecutionReceiptPayload): boolean {
103
+ if (!receipt?.signature || !receipt.taskID || !receipt.agent) {
104
+ return false
105
+ }
106
+ const expected = computeReceiptSignature(
107
+ receipt.taskID,
108
+ receipt.agent,
109
+ receipt.timestamp,
110
+ receipt.files,
111
+ )
112
+ return receipt.signature === expected
113
+ }
@@ -288,8 +288,14 @@ export async function runGatedNativeJevCall(params: {
288
288
  let config: ReturnType<typeof readUserDecisionRouterConfig>
289
289
  try {
290
290
  config = readUserDecisionRouterConfig()
291
- } catch {
292
- return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE' }
291
+ } catch (error) {
292
+ const detail =
293
+ error instanceof Error && error.message.includes('group-writable')
294
+ ? 'CONFIG_PATH_GROUP_WRITABLE'
295
+ : error instanceof Error
296
+ ? error.name
297
+ : 'ConfigError'
298
+ return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE', detail }
293
299
  }
294
300
  if (!config.enabled) return { ok: false, reasonCode: 'DISABLED' }
295
301
  if (!config.egress_consent) return { ok: false, reasonCode: 'CONSENT_MISSING' }
@@ -1,5 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, type Stats } from 'node:fs'
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ type Stats,
10
+ } from 'node:fs'
3
11
  import { homedir } from 'node:os'
4
12
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
5
13
  import { performance } from 'node:perf_hooks'
@@ -1202,20 +1210,42 @@ function ensureTrustedDirectoryChain(directoryPath: string): void {
1202
1210
  }
1203
1211
  }
1204
1212
 
1213
+ function isPermittedGroupWritable(env: NodeJS.ProcessEnv = process.env): boolean {
1214
+ if (env.PANTHEON_ALLOW_GROUP_WRITABLE === '1' || env.PANTHEON_ALLOW_GROUP_WRITABLE === 'true') {
1215
+ return true
1216
+ }
1217
+ if (
1218
+ env.JUPYTERHUB_USER ||
1219
+ env.JUPYTER_IMAGE ||
1220
+ env.JUPYTER_SERVER_ROOT ||
1221
+ env.KUBERNETES_SERVICE_HOST ||
1222
+ env.container ||
1223
+ existsSync('/.dockerenv')
1224
+ ) {
1225
+ return true
1226
+ }
1227
+ return false
1228
+ }
1229
+
1205
1230
  function validateDirectoryTrust(stat: Stats, uid: number, isFinalDirectory: boolean): void {
1206
1231
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
1207
1232
  throw new Error('Budget ledger path contains a non-directory or symlink ancestor')
1208
1233
  }
1209
- if (stat.uid !== uid && stat.uid !== 0) {
1234
+ const mode = stat.mode & 0o7777
1235
+ const isSticky = (mode & 0o1000) !== 0
1236
+ const isSystemOrUser = stat.uid === uid || stat.uid === 0 || (isSticky && stat.uid === 65534)
1237
+ if (!isSystemOrUser) {
1210
1238
  throw new Error('Budget ledger path contains an untrusted owner')
1211
1239
  }
1212
1240
  if (isFinalDirectory && stat.uid !== uid) {
1213
1241
  throw new Error('Budget ledger directory must be owned by the current user')
1214
1242
  }
1215
- const mode = stat.mode & 0o7777
1216
- const writableByOthers = (mode & 0o022) !== 0
1217
- const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
1218
- if (writableByOthers && !rootStickyDirectory) {
1243
+ const worldWritable = (mode & 0o002) !== 0
1244
+ const groupWritable = (mode & 0o020) !== 0
1245
+ if (worldWritable && !isSticky) {
1246
+ throw new Error('Budget ledger path contains a group/other-writable directory')
1247
+ }
1248
+ if (groupWritable && !isSticky && !isFinalDirectory && !isPermittedGroupWritable()) {
1219
1249
  throw new Error('Budget ledger path contains a group/other-writable directory')
1220
1250
  }
1221
1251
  }
@@ -606,7 +606,7 @@ async function updateActivePreset(
606
606
  if (!options.v2Mode) {
607
607
  const env = envValue(options)
608
608
  fallbackPreset = defaultFallbackPreset()
609
- // Prefer env preset if set and known (V1 legacy behavior only).
609
+ // Prefer env preset if set and known.
610
610
  const envPreset = env.PANTHEON_MODEL_PRESET?.trim()
611
611
  if (envPreset && envPreset !== '' && envPreset !== 'none') {
612
612
  try {
@@ -1031,9 +1031,7 @@ export function createModelCommand(options: ModelCommandOptions = {}): ModelTool
1031
1031
  const args = options.v2Mode
1032
1032
  ? {
1033
1033
  ...modelArgs,
1034
- action: modelArgs.action.describe(
1035
- 'Operation: status/show, set, or reset. V1 no-args invocation runs the legacy wizard.',
1036
- ),
1034
+ action: modelArgs.action.describe('Operation: status/show, set, or reset.'),
1037
1035
  }
1038
1036
  : modelArgs
1039
1037