@yunhozz/arc 0.2.2 → 0.2.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.
Files changed (117) hide show
  1. package/MANIFEST.sha256 +107 -88
  2. package/README.md +4 -6
  3. package/claude/agents/arc-implementer.md +32 -42
  4. package/claude/agents/arc-planner.md +33 -47
  5. package/claude/agents/arc-qa.md +28 -44
  6. package/claude/agents/arc-reviewer.md +28 -41
  7. package/claude/agents/arc-scouter.md +26 -38
  8. package/claude/skill/SKILL.md +41 -59
  9. package/claude/skill/references/arc-visual-companion.md +28 -0
  10. package/claude/skill/references/commit.md +38 -70
  11. package/claude/skill/references/coordination.md +77 -126
  12. package/claude/skill/references/git-recovery.md +17 -35
  13. package/claude/skill/references/handoff-prep.md +91 -103
  14. package/claude/skill/references/handoff.md +110 -208
  15. package/claude/skill/references/limits.md +19 -31
  16. package/claude/skill/references/planning.md +93 -244
  17. package/claude/skill/references/verification.md +105 -261
  18. package/claude/skill/references/visual-companion.md +293 -15
  19. package/claude/skill/runtime/adapters/claude.mjs +10 -9
  20. package/claude/skill/runtime/adapters/codex.mjs +7 -8
  21. package/claude/skill/runtime/bootstrap.mjs +3 -2
  22. package/claude/skill/runtime/capabilities.mjs +12 -0
  23. package/claude/skill/runtime/cooperative-schema.mjs +3 -2
  24. package/claude/skill/runtime/cooperative.mjs +52 -4
  25. package/claude/skill/runtime/evaluate.mjs +115 -2
  26. package/claude/skill/runtime/identity.mjs +22 -0
  27. package/claude/skill/runtime/role-policy.json +18 -18
  28. package/claude/skill/runtime/schema.mjs +19 -0
  29. package/claude/skill/scripts/model_config.py +3 -79
  30. package/codex/agents/arc-implementer.toml +34 -30
  31. package/codex/agents/arc-planner.toml +27 -23
  32. package/codex/agents/arc-qa.toml +24 -15
  33. package/codex/agents/arc-reviewer.toml +25 -16
  34. package/codex/agents/arc-scouter.toml +20 -26
  35. package/codex/skill/SKILL.md +42 -57
  36. package/codex/skill/references/arc-visual-companion.md +33 -0
  37. package/codex/skill/references/commit.md +35 -81
  38. package/codex/skill/references/coordination.md +76 -104
  39. package/codex/skill/references/git-recovery.md +29 -51
  40. package/codex/skill/references/handoff-prep.md +76 -134
  41. package/codex/skill/references/handoff-worktree.md +32 -66
  42. package/codex/skill/references/handoff.md +111 -271
  43. package/codex/skill/references/limits.md +21 -34
  44. package/codex/skill/references/planning.md +125 -299
  45. package/codex/skill/references/verification.md +90 -272
  46. package/codex/skill/references/visual-companion.md +290 -18
  47. package/codex/skill/runtime/adapters/claude.mjs +10 -9
  48. package/codex/skill/runtime/adapters/codex.mjs +7 -8
  49. package/codex/skill/runtime/bootstrap.mjs +3 -2
  50. package/codex/skill/runtime/capabilities.mjs +12 -0
  51. package/codex/skill/runtime/cooperative-schema.mjs +3 -2
  52. package/codex/skill/runtime/cooperative.mjs +52 -4
  53. package/codex/skill/runtime/evaluate.mjs +115 -2
  54. package/codex/skill/runtime/identity.mjs +22 -0
  55. package/codex/skill/runtime/role-policy.json +18 -18
  56. package/codex/skill/runtime/schema.mjs +19 -0
  57. package/lib/installer/global-config.mjs +1 -0
  58. package/lib/installer/install.mjs +5 -7
  59. package/lib/installer/manifest.mjs +23 -8
  60. package/lib/installer/package-references.mjs +10 -5
  61. package/lib/installer/plan.mjs +1 -4
  62. package/lib/installer/superpowers.mjs +26 -1
  63. package/lib/installer/transaction.mjs +3 -3
  64. package/lib/installer/uninstall.mjs +2 -2
  65. package/lib/installer/upgrade.mjs +2 -9
  66. package/lib/management/operations.mjs +6 -8
  67. package/lib/management/update.mjs +3 -3
  68. package/lib/models/profiles.mjs +1 -40
  69. package/lib/policy/render.mjs +1 -5
  70. package/lib/policy/role-policy.json +18 -18
  71. package/lib/release/artifact.mjs +6 -4
  72. package/lib/runtime/adapters/claude.mjs +10 -9
  73. package/lib/runtime/adapters/codex.mjs +7 -8
  74. package/lib/runtime/bootstrap.mjs +3 -2
  75. package/lib/runtime/capabilities.mjs +12 -0
  76. package/lib/runtime/cooperative-schema.mjs +3 -2
  77. package/lib/runtime/cooperative.mjs +52 -4
  78. package/lib/runtime/evaluate.mjs +115 -2
  79. package/lib/runtime/identity.mjs +22 -0
  80. package/lib/runtime/schema.mjs +19 -0
  81. package/lib/tui/app.mjs +12 -8
  82. package/lib/tui/setup.mjs +5 -8
  83. package/package.json +11 -2
  84. package/scripts/update-manifest.mjs +7 -9
  85. package/claude/skill/hooks/git-policy.json +0 -208
  86. package/claude/skill/hooks/role-git-guard.mjs +0 -18
  87. package/claude/skill/hooks/runtime-gate.mjs +0 -12
  88. package/claude/skill/references/superpowers/brainstorming/visual-companion.md +0 -299
  89. package/codex/skill/hooks/runtime-gate.mjs +0 -10
  90. package/codex/skill/references/superpowers/brainstorming/visual-companion.md +0 -299
  91. package/lib/policy/claude-hook.mjs +0 -80
  92. package/scripts/probe-runtime-hooks.mjs +0 -55
  93. package/scripts/update-superpowers-local.sh +0 -4
  94. /package/claude/skill/references/{superpowers/brainstorming/SKILL.md → brainstorming.md} +0 -0
  95. /package/claude/skill/references/{superpowers/brainstorming/builder-check-prompt.md → builder-check-prompt.md} +0 -0
  96. /package/claude/skill/references/{superpowers/brainstorming/scripts → scripts}/frame-template.html +0 -0
  97. /package/claude/skill/references/{superpowers/brainstorming/scripts → scripts}/helper.js +0 -0
  98. /package/claude/skill/references/{superpowers/brainstorming/scripts → scripts}/server.cjs +0 -0
  99. /package/claude/skill/references/{superpowers/brainstorming/scripts → scripts}/start-server.sh +0 -0
  100. /package/claude/skill/references/{superpowers/brainstorming/scripts → scripts}/stop-server.sh +0 -0
  101. /package/claude/skill/references/{superpowers/LICENSE → superpowers-LICENSE} +0 -0
  102. /package/claude/skill/references/{superpowers/provenance.json → superpowers-provenance.json} +0 -0
  103. /package/claude/skill/references/{superpowers/test-driven-development/SKILL.md → test-driven-development.md} +0 -0
  104. /package/claude/skill/references/{superpowers/test-driven-development/writing-good-tests.md → writing-good-tests.md} +0 -0
  105. /package/claude/skill/references/{superpowers/writing-plans/SKILL.md → writing-plans.md} +0 -0
  106. /package/codex/skill/references/{superpowers/brainstorming/SKILL.md → brainstorming.md} +0 -0
  107. /package/codex/skill/references/{superpowers/brainstorming/builder-check-prompt.md → builder-check-prompt.md} +0 -0
  108. /package/codex/skill/references/{superpowers/brainstorming/scripts → scripts}/frame-template.html +0 -0
  109. /package/codex/skill/references/{superpowers/brainstorming/scripts → scripts}/helper.js +0 -0
  110. /package/codex/skill/references/{superpowers/brainstorming/scripts → scripts}/server.cjs +0 -0
  111. /package/codex/skill/references/{superpowers/brainstorming/scripts → scripts}/start-server.sh +0 -0
  112. /package/codex/skill/references/{superpowers/brainstorming/scripts → scripts}/stop-server.sh +0 -0
  113. /package/codex/skill/references/{superpowers/LICENSE → superpowers-LICENSE} +0 -0
  114. /package/codex/skill/references/{superpowers/provenance.json → superpowers-provenance.json} +0 -0
  115. /package/codex/skill/references/{superpowers/test-driven-development/SKILL.md → test-driven-development.md} +0 -0
  116. /package/codex/skill/references/{superpowers/test-driven-development/writing-good-tests.md → writing-good-tests.md} +0 -0
  117. /package/codex/skill/references/{superpowers/writing-plans/SKILL.md → writing-plans.md} +0 -0
@@ -1,21 +1,299 @@
1
- # Visual companion
1
+ # Visual Companion Guide
2
2
 
3
- Use a visual when it materially helps design discussion or verification. Orchestrator determines the available
4
- capability and consent required by the actual tool. Planner returns visualization needs to Orchestrator because its
5
- tools are read-only file inspection; do not invent browser or shell access for it.
6
- Other depth 2 roles must stay within their exact allowlists and may not delegate visualization to another agent.
3
+ Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
7
4
 
8
- Determine actual available browser and preview capabilities before use; do not assume the platform provides a preview tool.
9
- Use an available authorized local/browser workflow only when scoped by Orchestrator.
10
- Keep preview artifacts separate from user files, record generated side effects, preserve unrelated work,
11
- and report unavailable capabilities without claiming visual verification. MUST NOT expose secrets or publish a preview without authorization.
5
+ ## When to Use
12
6
 
13
- Upstream guide/scripts: `<installed ARC>/references/superpowers/brainstorming/visual-companion.md` and adjacent `scripts/`.
14
- ARC guide: `references/visual-companion.md`; Orchestrator briefs absolute paths and retains approval/server/browser
15
- ownership. Missing files stop dependent work. MUST NOT use a global fallback.
7
+ Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**
16
8
 
17
- ## Follow-up Verification of Approved Visual Sources
9
+ **Use the browser** when the content itself is visual:
18
10
 
19
- Each visual criterion requires the exact location, version, approval, and access state of the approved visual source; criterion IDs, properties, and comparison method; and evidence linking the actual output to its revision. An Implementer report does not replace fresh QA's direct comparison. Record results as pass, mismatch, or unverified and connect them to the existing proven/unmet/unverified criterion verdicts. Use pass only when accessible evidence meets the visual criterion; keep unsupported claims unverified. Missing output-to-revision linkage is unverified; a visible difference is a mismatch. Record these separately; do not infer the current branch UI state. Hold the comparison if the approved source or actual output is inaccessible or interpretation approval is missing.
11
+ - **UI mockups** — wireframes, layouts, navigation structures, component designs
12
+ - **Architecture diagrams** — system components, data flow, relationship maps
13
+ - **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions
14
+ - **Design polish** — when the question is about look and feel, spacing, visual hierarchy
15
+ - **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams
20
16
 
21
- Static policy, generated-file, and manifest checks are structural evidence. They do not prove actual role behavior, an installed build, Claude Code CLI runtime compliance, or visual fidelity. Reports include actual changes, exclusion rationale, checks run and omitted, each criterion's evidence and limits, and platform availability. Keep baseline failures separate; progress on independent work does not relax required checks or acceptance criteria.
17
+ **Use the terminal** when the content is text or tabular:
18
+
19
+ - **Requirements and scope questions** — "what does X mean?", "which features are in scope?"
20
+ - **Conceptual A/B/C choices** — picking between approaches described in words
21
+ - **Tradeoff lists** — pros/cons, comparison tables
22
+ - **Technical decisions** — API design, data modeling, architectural approach selection
23
+ - **Clarifying questions** — anything where the answer is words, not a visual preference
24
+
25
+ A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser.
26
+
27
+ ## How It Works
28
+
29
+ The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.
30
+
31
+ **Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, connection status, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
32
+
33
+ ## Starting a Session
34
+
35
+ ```bash
36
+ # Start AFTER the user approves the companion. --open auto-opens their browser on
37
+ # the first screen; --project-dir persists mockups and enables same-port restart.
38
+ bash scripts/start-server.sh --project-dir /path/to/project --open
39
+
40
+ # Returns: {"type":"server-started","port":52341,
41
+ # "url":"http://localhost:52341/?key=ab12…",
42
+ # "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
43
+ # "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
44
+ ```
45
+
46
+ Save `screen_dir` and `state_dir` from the response. With `--open`, the browser opens itself when you push the first screen — you don't need to ask the user to open it, but still share the URL as a fallback (headless/remote setups won't auto-open).
47
+
48
+ **The URL contains a session key (`?key=…`).** The server rejects any request
49
+ without it, so always give the user the **complete** URL from the `url` field —
50
+ never strip the query string, and never hand out a bare `http://host:port`. The
51
+ key gates HTTP and WebSocket access so a stray browser tab or another machine on
52
+ the network can't read the screens or inject events. After the first load the
53
+ browser remembers the key via a cookie, so reloads and `/files/*` assets work
54
+ without repeating it.
55
+
56
+ **Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.
57
+
58
+ **Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.
59
+
60
+ **Launching the server by platform:**
61
+
62
+ **Claude Code:**
63
+ ```bash
64
+ # Default mode works — the script backgrounds the server itself.
65
+ bash scripts/start-server.sh --project-dir /path/to/project --open
66
+ ```
67
+
68
+ On Windows, the script auto-detects and switches to foreground mode (which blocks the tool call). Use `run_in_background: true` on the Bash tool call so the server survives across conversation turns, then read `$STATE_DIR/server-info` on the next turn to get the URL and port.
69
+
70
+ **Codex:**
71
+ ```bash
72
+ # Codex reaps background processes. The script auto-detects CODEX_CI and
73
+ # switches to foreground mode. Run it normally — no extra flags needed.
74
+ bash scripts/start-server.sh --project-dir /path/to/project --open
75
+ ```
76
+
77
+ **Gemini CLI:**
78
+ ```bash
79
+ # Use --foreground and set is_background: true on your shell tool call
80
+ # so the process survives across turns
81
+ bash scripts/start-server.sh --project-dir /path/to/project --open --foreground
82
+ ```
83
+
84
+ **Copilot CLI:**
85
+ ```bash
86
+ # Start it with Copilot CLI's non-blocking/background shell mechanism so the
87
+ # server survives across turns. Keep --foreground so the harness, not the
88
+ # script, owns backgrounding. The launcher is a .sh, so invoke it via bash
89
+ # (on Windows, call Git Bash's bash.exe from the PowerShell tool).
90
+ bash scripts/start-server.sh --project-dir /path/to/project --open --foreground
91
+ ```
92
+
93
+ **Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.
94
+
95
+ If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:
96
+
97
+ ```bash
98
+ bash scripts/start-server.sh \
99
+ --project-dir /path/to/project \
100
+ --host 0.0.0.0 \
101
+ --url-host localhost
102
+ ```
103
+
104
+ Use `--url-host` to control what hostname is printed in the returned URL JSON.
105
+
106
+ ## The Loop
107
+
108
+ 1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:
109
+ - **Required: confirm the server is alive before referring to the URL or pushing a screen.** Check that `$STATE_DIR/server-info` exists and `$STATE_DIR/server-stopped` does not. If it has shut down, restart it with `start-server.sh` using the **same `--project-dir`** — it reuses the same port, so the user's open tab reconnects on its own (it shows a "paused" overlay while the server is down) and you don't need to send a new URL. The server auto-exits after 4 hours idle (configurable with `--idle-timeout-minutes`).
110
+ - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
111
+ - **Never reuse filenames** — each screen gets a fresh file
112
+ - Use your file-creation tool — **never use cat/heredoc** (dumps noise into terminal)
113
+ - Server automatically serves the newest file
114
+
115
+ 2. **Tell user what to expect and end your turn:**
116
+ - Remind them of the URL (every step, not just first)
117
+ - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
118
+ - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
119
+
120
+ 3. **On your next turn** — after the user responds in the terminal:
121
+ - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
122
+ - Merge with the user's terminal text to get the full picture
123
+ - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data
124
+
125
+ 4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
126
+
127
+ 5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:
128
+
129
+ ```html
130
+ <!-- filename: waiting.html (or waiting-2.html, etc.) -->
131
+ <div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
132
+ <p class="subtitle">Continuing in terminal...</p>
133
+ </div>
134
+ ```
135
+
136
+ This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.
137
+
138
+ 6. Repeat until done.
139
+
140
+ ## Writing Content Fragments
141
+
142
+ Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, connection status, and all interactive infrastructure).
143
+
144
+ **Minimal example:**
145
+
146
+ ```html
147
+ <h2>Which layout works better?</h2>
148
+ <p class="subtitle">Consider readability and visual hierarchy</p>
149
+
150
+ <div class="options">
151
+ <div class="option" data-choice="a" onclick="toggleSelect(this)">
152
+ <div class="letter">A</div>
153
+ <div class="content">
154
+ <h3>Single Column</h3>
155
+ <p>Clean, focused reading experience</p>
156
+ </div>
157
+ </div>
158
+ <div class="option" data-choice="b" onclick="toggleSelect(this)">
159
+ <div class="letter">B</div>
160
+ <div class="content">
161
+ <h3>Two Column</h3>
162
+ <p>Sidebar navigation with main content</p>
163
+ </div>
164
+ </div>
165
+ </div>
166
+ ```
167
+
168
+ That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
169
+
170
+ ## CSS Classes Available
171
+
172
+ The frame template provides these CSS classes for your content:
173
+
174
+ ### Options (A/B/C choices)
175
+
176
+ ```html
177
+ <div class="options">
178
+ <div class="option" data-choice="a" onclick="toggleSelect(this)">
179
+ <div class="letter">A</div>
180
+ <div class="content">
181
+ <h3>Title</h3>
182
+ <p>Description</p>
183
+ </div>
184
+ </div>
185
+ </div>
186
+ ```
187
+
188
+ **Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item's selected styling.
189
+
190
+ ```html
191
+ <div class="options" data-multiselect>
192
+ <!-- same option markup — users can select/deselect multiple -->
193
+ </div>
194
+ ```
195
+
196
+ ### Cards (visual designs)
197
+
198
+ ```html
199
+ <div class="cards">
200
+ <div class="card" data-choice="design1" onclick="toggleSelect(this)">
201
+ <div class="card-image"><!-- mockup content --></div>
202
+ <div class="card-body">
203
+ <h3>Name</h3>
204
+ <p>Description</p>
205
+ </div>
206
+ </div>
207
+ </div>
208
+ ```
209
+
210
+ ### Mockup container
211
+
212
+ ```html
213
+ <div class="mockup">
214
+ <div class="mockup-header">Preview: Dashboard Layout</div>
215
+ <div class="mockup-body"><!-- your mockup HTML --></div>
216
+ </div>
217
+ ```
218
+
219
+ ### Split view (side-by-side)
220
+
221
+ ```html
222
+ <div class="split">
223
+ <div class="mockup"><!-- left --></div>
224
+ <div class="mockup"><!-- right --></div>
225
+ </div>
226
+ ```
227
+
228
+ ### Pros/Cons
229
+
230
+ ```html
231
+ <div class="pros-cons">
232
+ <div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
233
+ <div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
234
+ </div>
235
+ ```
236
+
237
+ ### Mock elements (wireframe building blocks)
238
+
239
+ ```html
240
+ <div class="mock-nav">Logo | Home | About | Contact</div>
241
+ <div style="display: flex;">
242
+ <div class="mock-sidebar">Navigation</div>
243
+ <div class="mock-content">Main content area</div>
244
+ </div>
245
+ <button class="mock-button">Action Button</button>
246
+ <input class="mock-input" placeholder="Input field">
247
+ <div class="placeholder">Placeholder area</div>
248
+ ```
249
+
250
+ ### Typography and sections
251
+
252
+ - `h2` — page title
253
+ - `h3` — section heading
254
+ - `.subtitle` — secondary text below title
255
+ - `.section` — content block with bottom margin
256
+ - `.label` — small uppercase label text
257
+
258
+ ## Browser Events Format
259
+
260
+ When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
261
+
262
+ ```jsonl
263
+ {"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
264
+ {"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
265
+ {"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
266
+ ```
267
+
268
+ The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
269
+
270
+ If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
271
+
272
+ ## Design Tips
273
+
274
+ - **Scale fidelity to the question** — wireframes for layout, polish for polish questions
275
+ - **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
276
+ - **Iterate before advancing** — if feedback changes current screen, write a new version
277
+ - **2-4 options max** per screen
278
+ - **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
279
+ - **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
280
+
281
+ ## File Naming
282
+
283
+ - Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
284
+ - Never reuse filenames — each screen must be a new file
285
+ - For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
286
+ - Server serves newest file by modification time
287
+
288
+ ## Cleaning Up
289
+
290
+ ```bash
291
+ bash scripts/stop-server.sh $SESSION_DIR
292
+ ```
293
+
294
+ If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
295
+
296
+ ## Reference
297
+
298
+ - Frame template (CSS reference): `scripts/frame-template.html`
299
+ - Helper script (client-side): `scripts/helper.js`
@@ -1,6 +1,6 @@
1
1
  import {evaluate} from '../evaluate.mjs';
2
- import {evaluateCapability} from '../capabilities.mjs';
3
- import {registerAgentObservation} from '../identity.mjs';
2
+ import {evaluateCapability,plannerHookContextStatus} from '../capabilities.mjs';
3
+ import {recordPlannerAgentObservation} from '../identity.mjs';
4
4
  import {transactWorkflow, fingerprintRequest} from '../store.mjs';
5
5
  import {runGate} from '../gate.mjs';
6
6
  import {classifyGitCommand} from '../git-query.mjs';
@@ -12,12 +12,15 @@ const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.claude'],proposedT
12
12
  /** Host-verified support for this installed version is required. A config value
13
13
  * alone cannot establish hook failure blocking; provider wiring belongs to T6. */
14
14
  export function claudeFailureBlockingReady(support){
15
- return support?.status==='verified'&&support.onFailure==='block'&&text(support.platformVersion)&&text(support.verificationRef);
15
+ const version=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(support?.platformVersion??'');
16
+ const supported=version&&(Number(version[1])>2||Number(version[1])===2&&(Number(version[2])>1||Number(version[2])===1&&Number(version[3])>=295));
17
+ return Boolean(supported&&support?.status==='verified'&&support.onFailure==='block'&&text(support.verificationRef));
16
18
  }
17
19
  /** Context is a trusted host dependency, never deserialized from stdin/tool_input.
18
20
  * describeTool must parse the complete tool invocation conservatively, and supply
19
21
  * semantic operation, paths and descriptor. No native provider is assumed here. */
20
22
  export function normalizeClaudeEvent(input,context={}){
23
+ const status=plannerHookContextStatus({platform:'claude',input,context});if(status.missing.length)throw Error('Missing trusted hook inputs: '+status.missing.join(', '));
21
24
  if(!object(input)||input.hook_event_name!=='PreToolUse'||!text(input.session_id)||input.session_id!==context.sessionRef||!text(context.actorRef)||!text(context.taskId)||!text(context.requestId)||!text(input.tool_use_id)||input.tool_use_id!==context.toolUseId||!text(input.tool_name)||!object(input.tool_input)||!text(input.cwd))throw Error('Verified session identity and complete PreToolUse event required');
22
25
  const toolPath=input.tool_name;
23
26
  const coverage={...evaluateCapability({platform:'claude',toolPath,sessionRef:context.sessionRef}),enforcement:'hook-response-only',nativeVerified:false,startupTimeout:'unknown',existingSessionInput:'unsupported',specializedPaths:'unknown',hostedTools:'unsupported'};
@@ -47,12 +50,10 @@ export async function runClaudeGate(input,context={}){
47
50
  // SubagentStart cannot prevent startup. Only a trusted provider can correlate
48
51
  // agent_id with a pending assignment; tool/event agent_type is not authority.
49
52
  try{
50
- if(input.session_id===context.sessionRef&&text(input.agent_id)&&typeof context.observeAgent==='function'){
51
- const observation=await context.observeAgent(structuredClone(input));
52
- if(observation?.actorRef===input.agent_id&&observation.platform==='claude'){
53
- const decision=registerAgentObservation(context.state,observation);
54
- if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
55
- }
53
+ if(input.session_id===context.sessionRef&&text(input.agent_id)&&text(context.statePath)){
54
+ let observation;try{if(typeof context.observeAgent==='function')observation=await context.observeAgent(structuredClone(input));}catch{}
55
+ const decision=await recordPlannerAgentObservation({statePath:context.statePath,expectedRevision:context.state?.revision,input,platform:'claude',sessionRef:context.sessionRef,observation});
56
+ if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
56
57
  }
57
58
  }catch{/* Observation failure never claims startup was blocked. */}
58
59
  return {};
@@ -1,6 +1,6 @@
1
1
  import {evaluate} from '../evaluate.mjs';
2
- import {evaluateCapability} from '../capabilities.mjs';
3
- import {registerAgentObservation} from '../identity.mjs';
2
+ import {evaluateCapability,plannerHookContextStatus} from '../capabilities.mjs';
3
+ import {recordPlannerAgentObservation} from '../identity.mjs';
4
4
  import {transactWorkflow, fingerprintRequest} from '../store.mjs';
5
5
  import {runGate} from '../gate.mjs';
6
6
 
@@ -12,6 +12,7 @@ const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.codex'],proposedTr
12
12
  * describeTool must parse the complete tool invocation conservatively, and supply
13
13
  * semantic operation, paths and descriptor. No native provider is assumed here. */
14
14
  export function normalizeCodexEvent(input,context={}){
15
+ const status=plannerHookContextStatus({platform:'codex',input,context});if(status.missing.length)throw Error('Missing trusted hook inputs: '+status.missing.join(', '));
15
16
  if(!object(input)||input.hook_event_name!=='PreToolUse'||!text(input.session_id)||input.session_id!==context.sessionRef||!text(context.actorRef)||!text(context.taskId)||!text(context.requestId)||!text(input.tool_use_id)||input.tool_use_id!==context.toolUseId||!text(input.tool_name)||!object(input.tool_input)||!text(input.cwd))throw Error('Verified session identity and complete PreToolUse event required');
16
17
  const toolPath=['Agent','spawn_agent'].includes(input.tool_name)?'spawn_agent':input.tool_name;
17
18
  const coverage={...evaluateCapability({platform:'codex',toolPath,sessionRef:context.sessionRef}),enforcement:'hook-response-only',nativeVerified:false,startupTimeout:'unknown',existingSessionInput:'unsupported',specializedPaths:'unknown',hostedTools:'unsupported'};
@@ -34,12 +35,10 @@ export async function runCodexGate(input,context={}){
34
35
  // SubagentStart cannot prevent startup. Only a trusted provider can correlate
35
36
  // agent_id with a pending assignment; tool/event agent_type is not authority.
36
37
  try{
37
- if(input.session_id===context.sessionRef&&text(input.agent_id)&&typeof context.observeAgent==='function'){
38
- const observation=await context.observeAgent(structuredClone(input));
39
- if(observation?.actorRef===input.agent_id&&observation.platform==='codex'){
40
- const decision=registerAgentObservation(context.state,observation);
41
- if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
42
- }
38
+ if(input.session_id===context.sessionRef&&text(input.agent_id)&&text(context.statePath)){
39
+ let observation;try{if(typeof context.observeAgent==='function')observation=await context.observeAgent(structuredClone(input));}catch{}
40
+ const decision=await recordPlannerAgentObservation({statePath:context.statePath,expectedRevision:context.state?.revision,input,platform:'codex',sessionRef:context.sessionRef,observation});
41
+ if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
43
42
  }
44
43
  }catch{/* Observation failure never claims startup was blocked. */}
45
44
  return {};
@@ -6,7 +6,7 @@ import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workf
6
6
  import {saveDurableState} from './store.mjs';
7
7
  export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
8
  'cli.mjs','command.mjs','bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
9
- 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs'
9
+ 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs'
10
10
  ]);
11
11
  export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
12
12
  export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
@@ -16,7 +16,7 @@ export async function cooperativeVersions(){
16
16
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
17
17
  let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
18
18
  const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
19
- return {policy:'1',runtime:'cooperative-1',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
19
+ return {policy:'1',runtime:'cooperative-4',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
20
20
  }
21
21
  export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
22
22
  validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
@@ -28,6 +28,7 @@ export async function initializeCooperativeWorkflow({cwd,workflowId,input,observ
28
28
  lock=await fs.open(lockPath,'wx',0o600);await inspectPath(statePath,{missing:true});
29
29
  const state={schemaVersion:1,workflowKind:'cooperative',contractVersion:1,workflowId,revision:0,mode:'plan',coverage:cooperativeCoverage(),versions:await cooperativeVersions(),target,targetVersion:1,scopeVersion:0};
30
30
  for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])state[key]=[];
31
+ state.plannerLedger={version:1,stages:[]};
31
32
  state.actors.push({actor:input.actor,source:'operator-attested'});state.selections.push({...input.selection,actor:input.actor,source:'operator-attested',targetVersion:1});
32
33
  state.audit.push({command:'init',revision:0,source:'operator-attested',actor:input.actor});validateCooperativeState(state);
33
34
  await saveDurableState({statePath,state,create:true,storage});return commandResult({workflowId,state,input,persisted:true,ruleId:'cooperative.initialized'});
@@ -28,5 +28,17 @@ export function evaluateCapability({platform,toolPath,sessionRef,platformVersion
28
28
  declared:{source:'documentation',matcher:contracts[platform]?.[toolPath] ?? null},
29
29
  status:!known || observationOnly ? 'unsupported':'unknown',verifiedDeny:false,
30
30
  source:!known || observationOnly ? 'documentation':'unverified',
31
+ observation:observationOnly?'documented':toolPath==='followup_task'?'unknown':'not-verified',enforcement:observationOnly?'observation-only':'unverified',
31
32
  observedPaths:observed.toolPaths.filter(p=>p === toolPath)};
32
33
  }
34
+
35
+ /** Raw event fields identify an invocation, not its approved role or semantics. */
36
+ export function plannerHookContextStatus({platform,input,context={}}={}){
37
+ const text=v=>typeof v==='string'&&v.length>0,object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
38
+ const fields={
39
+ 'hook.hook_event_name':input?.hook_event_name==='PreToolUse','hook.session_id':text(input?.session_id),'hook.tool_use_id':text(input?.tool_use_id),'hook.tool_name':text(input?.tool_name),'hook.tool_input':object(input?.tool_input),'hook.cwd':text(input?.cwd),
40
+ 'context.sessionRef':text(context.sessionRef),'context.actorRef':text(context.actorRef),'context.taskId':text(context.taskId),'context.requestId':text(context.requestId),'context.toolUseId':text(context.toolUseId),'context.statePath':text(context.statePath),'context.state':object(context.state),'context.policy':object(context.policy),'context.evidence':object(context.evidence),'context.describeTool':typeof context.describeTool==='function',
41
+ };
42
+ const missing=Object.keys(fields).filter(k=>!fields[k]);
43
+ return {platform,available:Object.keys(fields).filter(k=>fields[k]),missing,enforcement:missing.length?'unavailable':'hook-response-only',nativeVerified:false,source:'context-validation'};
44
+ }
@@ -1,6 +1,6 @@
1
1
  import {ROLES} from './operations.mjs';
2
2
  import {assertSecretFree} from './external.mjs';
3
- import {object,text} from './schema.mjs';
3
+ import {object,text,validatePlannerLedger} from './schema.mjs';
4
4
  import {absolute,validateWorkflowId} from './scope.mjs';
5
5
  const fail=message=>{throw Error('Cooperative schema: '+message);};
6
6
  const hash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
@@ -25,7 +25,7 @@ export function validateCooperativeCommand(command){
25
25
  if(name==='record'){
26
26
  fields(input.evidence,['kind','messageRef','data']);
27
27
  if(input.evidence?.data?.affectedTaskIds!==undefined&&(!Array.isArray(input.evidence.data.affectedTaskIds)||!input.evidence.data.affectedTaskIds.every(text)||new Set(input.evidence.data.affectedTaskIds).size!==input.evidence.data.affectedTaskIds.length))fail('affected task IDs');
28
- if(!statement(input.evidence)||!['note','approval','external-approval','document','scope','check','finding','review','acceptance-evidence'].includes(input.evidence.kind))fail('evidence');
28
+ if(!statement(input.evidence)||!['note','approval','external-approval','document','scope','check','finding','review','acceptance-evidence','planner-stage','planner-evidence','planner-result','planner-review'].includes(input.evidence.kind))fail('evidence');
29
29
  }
30
30
  if(resultStatement){
31
31
  fields(input.result,['status','messageRef','data','notExecutedEvidence']);
@@ -51,5 +51,6 @@ export function validateCooperativeState(state){
51
51
  if(state.requests.some(r=>!text(r.requestId)||!hash(r.requestFingerprint)||!object(r.decision))||new Set(state.requests.map(r=>r.requestId)).size!==state.requests.length)fail('request replay');
52
52
  if(state.intents.some(i=>!text(i.requestId)||!['prepared','succeeded','failed','unknown','mismatch','cancelled'].includes(i.status)||!hash(i.fingerprint))||new Set(state.intents.map(i=>i.requestId)).size!==state.intents.length)fail('intents');
53
53
  if(state.results.some(r=>!text(r.requestId)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(r.status)||r.source!=='operator-attested'||!object(r.data)))fail('results');
54
+ if(state.plannerLedger!==undefined){validatePlannerLedger(state.plannerLedger);if(state.plannerLedger.stages.some(stage=>stage.workflowId!==state.workflowId||!Array.isArray(stage.artifacts)))fail('Planner workflow binding or artifacts');}
54
55
  assertSecretFree(state);json(state);return state;
55
56
  }
@@ -4,6 +4,9 @@ import {evaluateCooperativeVerification,invalidateAffectedEvidence,readCooperati
4
4
  import {readAssignmentGitEvidence,readCooperativeCommitGitEvidence} from './git-evidence.mjs';
5
5
  import {recordCooperativeAssignmentResult} from './assignment.mjs';
6
6
  import fs from 'node:fs/promises';
7
+ import {constants} from 'node:fs';
8
+ import path from 'node:path';
9
+ import {createHash} from 'node:crypto';
7
10
  import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
8
11
  import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath,absolute,within} from './scope.mjs';
9
12
  import {fingerprintRequest,saveDurableState,applyCooperativeCommitTransition} from './store.mjs';
@@ -23,12 +26,14 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
23
26
  if(!sameCheckout(state.target,target))return result(undefined,{decision:'hold',ruleIds:['cooperative.target']});
24
27
  const changes=state.tasks.length?await readChanges({state}):undefined;
25
28
  const evaluation=evaluateCooperative({state,request:{command,input},evidence:{target,versions:await cooperativeVersions(),changes}});
26
- const unresolved=state.unresolved.some(entry=>!entry.resolvedBy)||state.intents.some(i=>['prepared','unknown','mismatch'].includes(i.status)&&!(['check','review'].includes(i.operation)&&i.stale));
29
+ const unresolved=state.plannerLedger?.stages.some(s=>s.pending)||state.unresolved.some(entry=>!entry.resolvedBy)||state.intents.some(i=>['prepared','unknown','mismatch'].includes(i.status)&&!(['check','review'].includes(i.operation)&&i.stale));
27
30
  return {...result(state,evaluation.decision==='allow'&&unresolved?{decision:'hold',ruleIds:['cooperative.unresolved']}:evaluation,{persisted:true}),state,support:cooperativeSupport(),...(changes?{changeFingerprints:changes}:{})};
28
31
  }
29
- let lock;
32
+ let lock,plannerLock;
30
33
  try{
31
34
  lock=await fs.open(statePath+'.lock','wx',0o600);let state=await read();
35
+ const plannerWork=command==='prepare'&&input.operation==='planner-call'||command==='record'&&input.evidence.kind.startsWith('planner-');
36
+ if(plannerWork)plannerLock=await fs.open(path.join(target.gitCommonDir,'arc','planner.lock'),'wx',0o600);
32
37
  if(!sameCheckout(state.target,target))return result(state,{decision:'hold',ruleIds:['cooperative.target']});
33
38
  const requestFingerprint=fingerprintRequest({command,input});const prior=state.requests.find(r=>r.requestId===input.requestId);
34
39
  if(prior){if(prior.requestFingerprint!==requestFingerprint)throw Error('Request fingerprint conflict');return result(state,{decision:'hold',ruleIds:['cooperative.replay']},{replayed:true});}
@@ -45,9 +50,12 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
45
50
  try{git=await readCommitGit({target:currentTarget,...(commitIntent&&input.result?.data?.commit?{commit:input.result.data.commit}:{})});}catch(error){gitError=error.message;}
46
51
  }
47
52
  const changes=state.tasks.length?await readChanges({state}):undefined;
48
- let decision=evaluateCooperative({state,request:{command,input},evidence:{target:currentTarget,versions,git,changes}});
53
+ const plannerArtifacts=plannerWork?await readPlannerArtifacts(state,command==='record'&&input.evidence.kind==='planner-evidence'?input.evidence:undefined):undefined;
54
+ const plannerHistory=command==='record'&&input.evidence.kind==='planner-stage'?await readPlannerHistory(state,statePath,input.evidence.data.document?.path):{};
55
+ let decision=evaluateCooperative({state,request:{command,input},evidence:{target:currentTarget,versions,git,changes,requestFingerprint,plannerArtifacts,...plannerHistory}});
49
56
  if(gitError)decision={decision:'hold',ruleIds:[input.operation==='assign-agent'?'cooperative.documents':'cooperative.git-evidence'],reason:gitError};
50
57
  if(command==='prepare'&&decision.decision==='allow'){
58
+ if(decision.proposedTransition?.plannerLedger)state.plannerLedger=decision.proposedTransition.plannerLedger;
51
59
  if(decision.proposedTransition?.intent)state.intents.push(decision.proposedTransition.intent);
52
60
  if(decision.proposedTransition?.acceptance){state.acceptances.push(decision.proposedTransition.acceptance);state.tasks.find(t=>t.id===input.taskId).status='accepted';}
53
61
  }
@@ -100,6 +108,15 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
100
108
  if(decision.decision==='allow'&&actualResult.status==='succeeded'&&intent.operation==='assign-agent')state.assignments.push({intentId:intent.requestId,taskId:intent.taskId,agentId:actualResult.data.agentId,status:'active',source:'operator-attested',identityVerified:false});
101
109
  }
102
110
  else state.unresolved.push({kind:'unmatched-result',requestId:input.intentId,revision:state.revision+1});
111
+ }else if(command==='record'&&input.evidence.kind.startsWith('planner-')){
112
+ if(decision.proposedTransition?.plannerLedger&&(decision.decision==='allow'||decision.proposedTransition.recordUncertainty)){
113
+ state.plannerLedger=decision.proposedTransition.plannerLedger;
114
+ state.records.push({...input.evidence,actor:input.actor,source:'operator-attested',requestId:input.requestId,revision:state.revision+1,scopeVersion:state.scopeVersion,targetVersion:state.targetVersion});
115
+ if(input.evidence.kind==='planner-result'){
116
+ const intent=state.intents.find(i=>i.operation==='planner-call'&&i.requestId===input.evidence.data.callRequestId);
117
+ if(intent)intent.status=input.evidence.data.status;
118
+ }
119
+ }
103
120
  }else if(command==='record'&&decision.decision==='allow'){
104
121
  const entry={...input.evidence,actor:input.actor,source:'operator-attested',requestId:input.requestId,revision:state.revision+1,scopeVersion:state.scopeVersion,targetVersion:state.targetVersion};
105
122
  if(entry.kind==='scope'){
@@ -132,5 +149,36 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
132
149
  state.requests.push({requestId:input.requestId,requestFingerprint,request:structuredClone({command,input}),decision:output});
133
150
  state.audit.push({command,requestId:input.requestId,revision:state.revision,decision:output.decision,ruleIds:output.ruleIds,source:'operator-attested',actor:input.actor,...(input.intentId?{intentId:input.intentId,resolution:state.results.at(-1)?.status}:{}),...(input.operation?{operation:input.operation}:{})});
134
151
  validateCooperativeState(state);await inspectPath(statePath);await saveDurableState({statePath,state,storage});return output;
135
- }finally{if(lock){await lock.close();await fs.unlink(statePath+'.lock');}}
152
+ }finally{if(plannerLock){await plannerLock.close();await fs.unlink(path.join(target.gitCommonDir,'arc','planner.lock'));}if(lock){await lock.close();await fs.unlink(statePath+'.lock');}}
153
+ }
154
+
155
+ async function readPlannerArtifacts(state,newRecord){
156
+ const entries=(state.plannerLedger?.stages??[]).flatMap(s=>(s.artifacts??[]).map(a=>({...a,stageId:s.id})));
157
+ if(newRecord)entries.push({...newRecord.data,ref:newRecord.messageRef});
158
+ return Promise.all(entries.map(async artifact=>{
159
+ try{
160
+ if(!absolute(artifact.path)||!within(state.target.realpath,artifact.path))throw Error('Artifact path escapes workspace');
161
+ await inspectPath(artifact.path);const handle=await fs.open(artifact.path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let bytes;
162
+ try{const before=await handle.stat();if(!before.isFile())throw Error('Artifact must be a regular file');bytes=await handle.readFile();const after=await handle.stat(),named=await fs.lstat(artifact.path);if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||after.dev!==named.dev||after.ino!==named.ino)throw Error('Artifact changed while reading');}finally{await handle.close();}
163
+ await inspectPath(artifact.path);if(!within(state.target.realpath,await fs.realpath(artifact.path)))throw Error('Artifact realpath escapes workspace');
164
+ const hash='sha256:'+createHash('sha256').update(bytes).digest('hex');
165
+ if(artifact.hash&&artifact.hash!==hash||artifact.contentHash&&artifact.contentHash!==hash)throw Error('Artifact hash mismatch');
166
+ return {...artifact,hash,verification:{status:'verified',source:'local-bytes'}};
167
+ }catch(error){return {...artifact,verification:{status:'unverified',source:'local-bytes'},error:error.message};}
168
+ }));
169
+ }
170
+ async function readPlannerHistory(state,statePath,documentPath){
171
+ const plannerHistory=[];
172
+ try{
173
+ const root=path.dirname(path.dirname(statePath));await inspectPath(root,{directory:true});
174
+ for(const entry of await fs.readdir(root,{withFileTypes:true})){
175
+ if(entry.name===state.workflowId)continue;
176
+ if(!entry.isDirectory()||entry.isSymbolicLink())throw Error('Unsafe workflow history path');
177
+ const filename=path.join(root,entry.name,'state.json');await inspectPath(filename);const other=validateCooperativeState(JSON.parse(await fs.readFile(filename,'utf8')));
178
+ if(!sameCheckout(state.target,other.target))continue;
179
+ if(!other.plannerLedger&&other.documents.some(d=>d.path===documentPath||d.data?.path===documentPath))throw Error('Existing document history has no Planner ledger');
180
+ for(const stage of other.plannerLedger?.stages??[])plannerHistory.push({workflowId:other.workflowId,stage});
181
+ }
182
+ return {plannerHistory};
183
+ }catch(error){return {plannerHistory,plannerHistoryError:error.message};}
136
184
  }