@yunhozz/arc 0.3.3 → 0.3.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 (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,198 +0,0 @@
1
- # Writing Good Tests
2
-
3
- **Load this reference when:** writing or changing tests, adding mocks, or
4
- adding cleanup/helper methods for tests.
5
-
6
- ## Overview
7
-
8
- A test exists to catch a specific break. Two principles govern everything
9
- here:
10
-
11
- ```
12
- 1. Every test names the break it catches
13
- 2. Every test exercises the real thing
14
- ```
15
-
16
- Strict TDD produces both naturally: a test written first and watched
17
- failing against real code has already proven it can fail, and only earns
18
- a mock when the real dependency proves slow or external.
19
-
20
- ## Principle 1: Name the Break
21
-
22
- Before writing the test body, answer: **what production change should
23
- make this test fail — and is that change a bug or a decision?** A test
24
- earns its place by catching a wrong branch, missing side effect, wrong
25
- argument, boundary case, or broken contract.
26
-
27
- **Derive expectations independently.** Use literals and hand-checked
28
- fixtures; table-driven tests with literal `want` values are the preferred
29
- shape. An expectation computed by the code under test — or its helpers —
30
- passes no matter what that code does:
31
-
32
- ```typescript
33
- // ❌ Mirror assertion: the same builder computes both sides — always true
34
- const expected = buildSearchQuery({ tag: 'urgent' });
35
- expect(buildSearchQuery({ tag: 'urgent' })).toBe(expected);
36
-
37
- // ✅ Hand-derived literal
38
- expect(buildSearchQuery({ tag: 'urgent' })).toBe('tag:"urgent"');
39
- ```
40
-
41
- **No change detectors.** If only intentional decisions can fail a test —
42
- a constant's value, exact message wording, private structure — it fires
43
- on redesign and sleeps through bugs. Test the behavior that depends on
44
- the decision: not `expect(MAX_RETRIES).toBe(5)` but "a failing call is
45
- retried 5 times and the 6th attempt never happens."
46
-
47
- **Behavior, not text.** Asserting that a script, skill, or config
48
- contains an exact line proves only that the source is the source. Run
49
- scripts against controlled inputs and assert outputs, side effects, or
50
- exit codes. Documents that instruct agents are tested by the consuming
51
- agent's behavior (superpowers:writing-skills); prose for humans earns no
52
- test at all.
53
-
54
- **Your code, not the framework.** Test the contract your code makes at
55
- its boundaries — the route you register, the query you emit, the payload
56
- you produce. Upstream mechanics are their maintainers' tests to write
57
- (the classic: asserting your router invokes a registered handler — that
58
- is the framework's test, not yours). When upstream behavior genuinely
59
- surprised you, write one narrow characterization test naming the
60
- assumption. The same boundary applies inside your code: constructors,
61
- getters, constants, and trivial forwarding earn tests only when they
62
- validate, normalize, default, derive, enforce, or cause side effects —
63
- otherwise assert the first consumer-visible result that depends on them.
64
-
65
- ### Gate Function
66
-
67
- ```
68
- BEFORE writing the test body:
69
- Name the production change that would make this test fail.
70
-
71
- Cannot name one → redesign around an observable behavior
72
- "The source text changed" → run the artifact and assert its effects
73
- Only intentional decisions → change detector; test the behavior
74
- that depends on the decision
75
-
76
- Confirm the expected value is derived without the code under test.
77
- IF it reuses the code's logic or helpers:
78
- Replace it with a literal or hand-checked fixture
79
- ```
80
-
81
- ## Principle 2: Exercise the Real Thing
82
-
83
- **The mock earns no assertions.** A mock assertion passes when the mock
84
- is present and fails when it is absent — it says nothing about the
85
- component. Assert the real component's behavior; if the mock is what you
86
- are checking, unmock it or delete the assertion.
87
-
88
- ```typescript
89
- // ✅ Real behavior
90
- expect(screen.getByRole('navigation')).toBeInTheDocument();
91
-
92
- // ❌ Mock existence
93
- expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
94
- ```
95
-
96
- **your human partner's correction:** "Are we testing the behavior of a
97
- mock?"
98
-
99
- **Mock at the right level.** Learn every side effect of the real method
100
- before replacing it; mock the slow or external operation and keep what
101
- the test depends on real. When unsure, run the test against the real
102
- implementation first and observe what actually needs to happen.
103
-
104
- ```typescript
105
- // ❌ The mock swallows the config write that duplicate detection reads
106
- vi.mock('ToolCatalog', () => ({
107
- discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
108
- }));
109
-
110
- // ✅ Mock only the slow server startup; the config write stays real
111
- vi.mock('MCPServerManager');
112
- ```
113
-
114
- **Make doubles specific.** When arguments, call counts, or ordering are
115
- part of the contract, assert them — a fake that accepts anything verifies
116
- nothing. Give each branch (success, error, malformed) its own fixture or
117
- spy, so the wrong branch cannot satisfy the expectation.
118
-
119
- **Mirror real data completely.** Mock the complete structure as it exists
120
- in reality — all documented fields — not just the ones your test reads.
121
- Partial mocks fail silently when downstream code reads an omitted field:
122
- the test passes while integration breaks.
123
-
124
- **Production classes carry production methods only.** Cleanup that only
125
- tests need lives in test utilities, never as a `destroy()` on the
126
- production class. Ask: is this method called only from tests? Does this
127
- class own this resource's lifecycle? Wrong answers → test utility.
128
-
129
- **Prefer real components over complex mocks.** When mock setup outgrows
130
- the test logic, mocks miss methods the real components have, or tests
131
- break when the mock changes, switch to an integration test with real
132
- components. **your human partner's question:** "Do we need to be using a
133
- mock here?"
134
-
135
- ### Gate Function
136
-
137
- ```
138
- BEFORE adding a mock or test helper:
139
- List the real method's side effects; keep the ones the test
140
- depends on real — mock the slow/external level below them.
141
-
142
- Mock responses mirror the complete real structure.
143
-
144
- A method only tests call lives in test utilities, not production.
145
-
146
- About to assert on the mock itself?
147
- Unmock it or delete the assertion.
148
- ```
149
-
150
- ## Tests Ship With the Implementation
151
-
152
- The TDD cycle — failing test, minimal implementation, refactor — is what
153
- "complete" means. Ship the tests the behavior needs and only those:
154
- trivial code and human prose earn none, and a test written to satisfy
155
- process costs maintenance forever.
156
-
157
- ## The Mutation Check
158
-
159
- Before finishing, mentally mutate the production code; at least one test
160
- should fail for each realistic mutation:
161
-
162
- - Wrong constant or argument
163
- - Wrong branch handler
164
- - Missing state change or side effect
165
- - Empty or default return
166
- - Missing validation for zero, empty, nil, unauthorized, or malformed input
167
-
168
- A mutation nothing catches marks the behavior as unprotected — or the
169
- test as tautological.
170
-
171
- ## Quick Reference
172
-
173
- | When you... | Do |
174
- |-------------|-----|
175
- | Write any test | Name the break it catches — a bug, not a decision |
176
- | Build an expected value | Derive it by hand; never with the code under test |
177
- | Test a script or document | Run it / pressure-test its consumer; never grep its text |
178
- | Reach for a dependency test | Test your boundary contract, not their documented mechanics |
179
- | Want to assert on a mocked element | Test the real component, or unmock it |
180
- | Are about to mock a method | Learn its side effects; mock the slow/external level |
181
- | Build a mock response | Mirror the real structure completely |
182
- | Need cleanup only tests use | Put it in test utilities |
183
- | Watch mock setup balloon | Switch to an integration test with real components |
184
- | Finish a test file | Run the mutation check |
185
-
186
- ## Warning Signs
187
-
188
- - Setup and assertion share the same object, guaranteeing equality
189
- - The test can fail only through a panic, crash, or missing selector
190
- - The test fails on every intentional change, never on accidental breakage
191
- - Expected values are hidden behind loops, builders, or helpers
192
- - The test greps source text, or asserts a removed symbol stays removed
193
- - The test would still matter if only the framework remained
194
- - The test exists for coverage, checking no side effect or outcome
195
- - An assertion checks a `*-mock` test ID, or fails if you remove the mock
196
- - A method is called only from test files
197
- - Mock setup is more than half the test, or you can't explain why the mock is needed
198
- - Mocking "just to be safe"
@@ -1,204 +0,0 @@
1
- ---
2
- name: writing-plans
3
- description: Use when you have a spec or requirements for a multi-step task, before touching code
4
- ---
5
-
6
- # Writing Plans
7
-
8
- ## Overview
9
-
10
- Write implementation plans for an engineer who has not seen this codebase or this spec. Assume they write idiomatic code in the project's language once they know the exact interface and the exact test, and that they will make a reasonable choice wherever the plan leaves one open. What they cannot know is what you decided: which files, which names and signatures, which values from the spec, which tests prove each task. Document those. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits.
11
-
12
- **Announce at start:** "I'm using the writing-plans skill to create the implementation plan."
13
-
14
- **Context:** If working in an isolated worktree, it should have been created via the `superpowers:using-git-worktrees` skill at execution time.
15
-
16
- **Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
17
- - (User preferences for plan location override this default)
18
-
19
- ## Scope Check
20
-
21
- If the spec covers multiple independent subsystems, it should have been broken into sub-project specs during brainstorming. If it wasn't, suggest breaking this into separate plans — one per subsystem. Each plan should produce working, testable software on its own.
22
-
23
- ## File Structure
24
-
25
- Before defining tasks, map out which files will be created or modified and what each one is responsible for. This is where decomposition decisions get locked in.
26
-
27
- - Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.
28
- - You reason best about code you can hold in context at once, and your edits are more reliable when files are focused. Prefer smaller, focused files over large ones that do too much.
29
- - Files that change together should live together. Split by responsibility, not by technical layer.
30
- - In existing codebases, follow established patterns. If the codebase uses large files, don't unilaterally restructure - but if a file you're modifying has grown unwieldy, including a split in the plan is reasonable.
31
-
32
- This structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.
33
-
34
- ## Task Right-Sizing
35
-
36
- A task is the smallest unit that carries its own test cycle and is worth a
37
- fresh reviewer's gate. When drawing task boundaries: fold setup,
38
- configuration, scaffolding, and documentation steps into the task whose
39
- deliverable needs them; split only where a reviewer could meaningfully
40
- reject one task while approving its neighbor. Each task ends with an
41
- independently testable deliverable.
42
-
43
- ## Step Granularity
44
-
45
- **Each step is one action with a checkable result:**
46
- - "Write the failing test" - step
47
- - "Run it to make sure it fails" - step
48
- - "Implement the minimal code to make the test pass" - step
49
- - "Run the tests and make sure they pass" - step
50
- - "Commit" - step
51
-
52
- ## Plan Document Header
53
-
54
- **Every plan MUST start with this header:**
55
-
56
- ```markdown
57
- # [Feature Name] Implementation Plan
58
-
59
- > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
60
-
61
- **Goal:** [One sentence describing what this builds]
62
-
63
- **Architecture:** [2-3 sentences about approach]
64
-
65
- **Tech Stack:** [Key technologies/libraries]
66
-
67
- **Spec:** [path to the spec/design doc this plan implements — the plan
68
- argues from the spec, so the spec travels with it; executors read both]
69
-
70
- ## Global Constraints
71
-
72
- [The spec's project-wide requirements — version floors, dependency limits,
73
- naming and copy rules, platform requirements — one line each, with exact
74
- values copied verbatim from the spec. Every task's requirements implicitly
75
- include this section.]
76
-
77
- ## Review Focus
78
-
79
- [The five input classes or failure modes the spec implies but no task's
80
- tests exercise that are most likely to bite a person using this software
81
- — one line each, naming the input or condition and the behavior a
82
- reasonable person would expect, most likely first. The spec is a vision
83
- document: it says what the software must do, not everything it will
84
- meet, and its silence on an input is not permission for that input to
85
- break the program. Write the list here, once, with the spec in front of
86
- you. Then, for each line, add the test that pins it to the task that
87
- owns the code, in that task's own step style.]
88
-
89
- ---
90
- ```
91
-
92
- ## Task Structure
93
-
94
- ````markdown
95
- ### Task N: [Component Name]
96
-
97
- **Files:**
98
- - Create: `exact/path/to/file.py`
99
- - Modify: `exact/path/to/existing.py:123-145`
100
- - Test: `tests/exact/path/to/test.py`
101
-
102
- **Interfaces:**
103
- - Consumes: [what this task uses from earlier tasks — exact signatures]
104
- - Produces: [what later tasks rely on — exact function names, parameter
105
- and return types. A task's implementer sees only their own task; this
106
- block is how they learn the names and types neighboring tasks use.]
107
-
108
- - [ ] **Step 1: Write the failing test**
109
-
110
- ```python
111
- def test_specific_behavior():
112
- result = function(input)
113
- assert result == expected
114
- ```
115
-
116
- - [ ] **Step 2: Run test to verify it fails**
117
-
118
- Run: `pytest tests/path/test.py::test_name -v`
119
- Expected: FAIL with "function not defined"
120
-
121
- - [ ] **Step 3: Implement `function(input: InputType) -> ResultType` in `exact/path/to/file.py`**
122
-
123
- One line on the approach when the signature and the test leave a choice
124
- (which library call, which data structure); a code block only for an
125
- algorithm they do not determine.
126
-
127
- - [ ] **Step 4: Run test to verify it passes**
128
-
129
- Run: `pytest tests/path/test.py::test_name -v`
130
- Expected: PASS
131
-
132
- - [ ] **Step 5: Commit**
133
-
134
- ```bash
135
- git add tests/path/test.py src/path/file.py
136
- git commit -m "feat: add specific feature"
137
- ```
138
- ````
139
-
140
- ## What a Step Contains
141
-
142
- A step is done when the implementer can write exactly one reasonable thing
143
- from it. That is the whole requirement: unambiguous, not complete. Each kind
144
- of step carries what makes it unambiguous and nothing more:
145
-
146
- - **A test step:** the test's name and its assertions, as code, with the
147
- spec's exact values in them.
148
- - **A code step:** the exact signature (name, parameters, return type), the
149
- file it lives in, and the specific values the spec pins. The implementer
150
- writes the body. A body appears only for an algorithm the signature and
151
- tests do not determine, or for exact copy the spec fixes.
152
- - **A verification step:** the command to run and the output that means it
153
- passed.
154
- - **A reference to another task:** that task's Interfaces block says what
155
- to use; the plan does not repeat that task's code.
156
-
157
- A plan is the set of decisions the implementer cannot make alone. A plan
158
- longer than the code it describes has written the code instead. Lines that
159
- decide nothing ("TBD", "handle edge cases", "add appropriate validation",
160
- "write tests for the above", a type or function no task defines) are the
161
- opposite failure, and the self-review catches both.
162
-
163
- ## Self-Review
164
-
165
- After writing the complete plan, look at the spec with fresh eyes and check the plan against it. This is a checklist you run yourself — not a subagent dispatch.
166
-
167
- **1. Spec coverage:** Skim each section/requirement in the spec. Can you point to a task that implements it? List any gaps.
168
-
169
- **2. Step scan:** Every step must let the implementer write exactly one reasonable thing, and no step may carry more than that: a line that decides nothing is a gap, a function body the signature and tests already determine is a transcript. Fix both.
170
-
171
- **3. Type consistency:** Do the types, method signatures, and property names you used in later tasks match what you defined in earlier tasks? A function called `clearLayers()` in Task 3 but `clearFullLayers()` in Task 7 is a bug.
172
-
173
- **4. Review Focus:** For each input class or failure mode the spec implies, is there a task whose tests exercise it? The five uncovered ones most likely to bite a person go in the Review Focus section, and each line there gets its test added to the owning task. An empty section means you checked and found none, not that you skipped the check.
174
-
175
- **5. Proportion:** Compare the plan's length to the spec's. A plan several times longer than the spec it implements is a transcript of the program, not a plan. If code blocks are most of the document, replace bodies with signatures, test names and assertions, and check that each step is still unambiguous.
176
-
177
- If you find issues, fix them inline. No need to re-review — just fix and move on. If you find a spec requirement with no task, add the task.
178
-
179
- ## Execution Handoff
180
-
181
- After saving and self-reviewing the plan, link it for your human partner
182
- to read. If they have already explicitly supplied an execution method, ask
183
- them to review the plan and confirm it captures what they want; wait for that
184
- review before implementation, then use the preserved method. Otherwise, ask
185
- them to review the plan and choose an execution method before implementation.
186
-
187
- **When no execution method has already been supplied:**
188
-
189
- **"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Please review the plan. Which execution approach would you prefer?**
190
-
191
- - **Subagent-driven** - A fresh subagent implements each task and a fresh reviewer checks it before the next one starts, then a whole-branch review at the end. Most thorough; costs a fresh context per task and per review.
192
- - **Native** - I implement every task myself in this session, the way this harness runs work, then one fresh reviewer on the most capable model checks the whole branch. Cheapest and fastest; no independent review until the end. Runs well with a mid-tier session model, since the plan carries the design.
193
-
194
- **For this plan I recommend <one of the two>, because <one sentence from the plan: how much the tasks depend on each other's interfaces, how many there are, what a shipped mistake would cost>. Does the plan capture what you want, and which approach should we use?"**
195
-
196
- **When an execution method has already been supplied:**
197
-
198
- **"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Please review the plan. Does it capture what you want?"**
199
-
200
- **If Subagent-driven chosen:**
201
- - **REQUIRED SUB-SKILL:** Use superpowers:subagent-driven-development
202
-
203
- **If Native chosen:**
204
- - **REQUIRED SUB-SKILL:** Use superpowers:executing-plans
@@ -1,68 +0,0 @@
1
- import path from 'node:path';
2
- import {fingerprintRequest} from './store.mjs';
3
- import {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
4
- import {within} from './scope.mjs';
5
- const reconciliations=new WeakMap();
6
- export function verifiedCooperativeReconciliation(decision,state){const proof=reconciliations.get(decision);return !!proof&&proof.before===fingerprintRequest(state)&&proof.after===fingerprintRequest(decision.proposedTransition);}
7
- const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
8
- const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
9
- const text=v=>typeof v==='string'&&v.length>0;
10
- const list=v=>Array.isArray(v)&&v.every(text)&&new Set(v).size===v.length;
11
- const exact=(a,b)=>list(a)&&list(b)&&same([...a].sort(),[...b].sort());
12
- const fields=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).every(k=>keys.includes(k));
13
- const semanticLimit='Semantically unrelated hunks inside the same file require Orchestrator inspection; path and byte evidence cannot distinguish them automatically.';
14
- const base=state=>({expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},semanticLimit,requiredEvidence:[],nextActions:[],proposedTransition:null});
15
- const hold=(state,reason)=>({...base(state),decision:'hold',ruleIds:['cooperative.acceptance'],reason});
16
- const allow=(state,transition)=>({...base(state),decision:'allow',ruleIds:['cooperative.acceptance'],proposedTransition:transition});
17
- const approval=(state,id)=>state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(id))).at(-1);
18
- function authorized(state,task){const a=approval(state,task?.id);return state.mode==='plan'&&task&&!task.invalidated&&a?.source==='operator-attested'&&a.targetVersion===state.targetVersion&&task.targetVersion===state.targetVersion&&task.scopeVersion===a.scopeVersion&&task.approvalRef===a.messageRef&&task.approvalVersion===a.data.approvalVersion&&task.documentVersion===a.data.documentVersion;}
19
- function checkEvidence(state,task,a,changes){
20
- if(!same(a.criteria,task.criteria)||!task.criteria.length||!list(a.checkIds)||!list(a.findingIds)||a.changeFingerprint!==changes?.tasks?.[task.id])return false;
21
- const checks=state.checks.filter(c=>c.scope==='task'&&c.taskId===task.id);
22
- const latest=task.requiredChecks.map(d=>checks.filter(c=>same(c.descriptor,d)).at(-1));
23
- if(!task.requiredChecks.length||latest.some(c=>!c||c.stale||c.status!=='passed'||c.verdict!=='proven'||!text(c.resultRef)||c.source!=='operator-attested'||c.verificationActor?.role!=='qa'||!text(c.verificationActor.id)||state.assignments.some(a=>a.agentId===c.verificationActor.id)||c.changeFingerprint!==a.changeFingerprint)||!exact(a.checkIds,latest.map(c=>c?.id)))return false;
24
- const findings=state.findings.filter(f=>f.scope==='task'&&f.taskId===task.id);
25
- return exact(a.findingIds,findings.map(f=>f.id))&&findings.every(f=>f.status==='closed'&&text(f.resolutionRef)&&text(f.recheckRef)&&f.resolutionActor?.role==='implementer'&&f.recheckActor?.role==='qa'&&f.changeFingerprint===a.changeFingerprint);
26
- }
27
- function waitingFor(state,task,predecessor){
28
- if(task.status!=='pending'||state.intents.some(i=>i.taskId===task.id&&i.operation==='assign-agent'&&['prepared','unknown','mismatch','succeeded'].includes(i.status)))return false;
29
- const seen=new Set(),queue=[...(task.dependencies??[])];while(queue.length){const id=queue.pop();if(id===predecessor)return true;if(seen.has(id))continue;seen.add(id);queue.push(...(state.tasks.find(t=>t.id===id)?.dependencies??[]));}return false;
30
- }
31
- function dirtyOtherTask(state,task,git){return git.stagedPaths?.some(name=>state.tasks.some(t=>t.id!==task.id&&!completed(state,t.id)&&!waitingFor(state,t,task.id)&&t.paths.some(p=>within(p,path.join(state.target.realpath,...name.split('/'))))));}
32
- function freshAcceptance(state,task,acceptance,changes){return acceptance&&!acceptance.stale&&authorized(state,task)&&acceptance.taskFingerprint===fingerprintRequest({...task,status:'pending'})&&same(acceptance.approval,approval(state,task.id))&&same(acceptance.target,state.target)&&same(acceptance.versions,state.versions)&&checkEvidence(state,task,acceptance,changes);}
33
- /** Operator attests semantic sufficiency; code binds exact current evidence only. */
34
- export function evaluateCooperativeAcceptance({state,request,evidence}={}){
35
- const task=state?.tasks?.find(t=>t.id===request?.taskId),a=request?.arguments,g=evidence?.git;
36
- if(request?.expectedRevision!==state?.revision||request.actor?.role!=='orchestrator'||!authorized(state,task)||task.status!=='pending'||state.acceptances.some(v=>v.taskId===task.id&&!v.stale)||state.commits.some(v=>v.taskId===task.id))return hold(state,'Current pending approved task and Orchestrator acceptance required');
37
- if(!fields(a,['messageRef','criteria','checkIds','findingIds','changeFingerprint'])||!text(a.messageRef)||!checkEvidence(state,task,a,evidence?.changes)||state.checks.some(c=>a.checkIds?.includes(c.id)&&c.verificationActor?.id===request.actor.id))return hold(state,'Exact criteria, current required QA checks and closed findings required');
38
- const descriptor={kind:'task',parent:state.target.head,indexTree:g?.indexTree,fingerprint:g?.stagedFingerprint,paths:g?.stagedPaths};
39
- const invalid=validateGitPreflight({target:state.target,descriptor,scope:task.paths,gitEvidence:g});
40
- if(invalid||dirtyOtherTask(state,task,g))return hold(state,invalid??'Index includes another task changes');
41
- return allow(state,{acceptance:{...structuredClone(a),id:request.requestId,taskId:task.id,actor:structuredClone(request.actor),source:'operator-attested',descriptor:structuredClone(descriptor),taskFingerprint:fingerprintRequest({...task,status:'pending'}),approval:structuredClone(approval(state,task.id)),target:structuredClone(state.target),versions:structuredClone(state.versions)}});
42
- }
43
- /** Prepares a durable intent; never stages or executes a commit. */
44
- export function prepareCooperativeCommit({state,request,gitEvidence,evidence}={}){
45
- const task=state?.tasks?.find(t=>t.id===request?.taskId),a=state?.acceptances?.find(a=>a.id===request?.arguments?.acceptanceId&&a.taskId===request.taskId);
46
- if(request?.expectedRevision!==state?.revision||request.actor?.role!=='orchestrator'||!fields(request.arguments,['acceptanceId'])||task?.status!=='accepted'||!freshAcceptance(state,task,a,evidence?.changes)||state.commits.some(c=>c.taskId===task.id)||state.intents.some(i=>i.operation==='commit'&&i.taskId===task.id&&['prepared','unknown','mismatch'].includes(i.status)))return hold(state,'Exact current acceptance and no prior task commit or unresolved commit required');
47
- const invalid=validateGitPreflight({target:state.target,descriptor:a.descriptor,scope:task.paths,gitEvidence});
48
- if(invalid||dirtyOtherTask(state,task,gitEvidence))return hold(state,invalid??'Index includes another task changes');
49
- const expected={parent:a.descriptor.parent,tree:a.descriptor.indexTree,paths:[...a.descriptor.paths],fingerprint:a.descriptor.fingerprint,remainingPaths:[...new Set([...gitEvidence.workingPaths,...gitEvidence.untrackedPaths])].sort()};
50
- return allow(state,{intent:{requestId:request.requestId,operation:'commit',taskId:task.id,status:'prepared',acceptanceId:a.id,acceptanceFingerprint:fingerprintRequest(a),expected,target:structuredClone(state.target),versions:structuredClone(state.versions),fingerprint:fingerprintRequest(request),source:'operator-attested'}});
51
- }
52
- /** Results are local Git observations, correlated with an operator statement.
53
- * Mismatch observations remain historical evidence and never rebind the target. */
54
- export function reconcileCooperativeCommit({state,intent,result,gitEvidence}={}){
55
- if(!intent||intent.operation!=='commit'||!['prepared','unknown','mismatch'].includes(intent.status)||state.commits.some(c=>c.taskId===intent.taskId))return hold(state,'Matching unresolved commit intent required; replay cannot authorize another effect');
56
- const task=state.tasks.find(t=>t.id===intent.taskId),a=state.acceptances.find(a=>a.id===intent.acceptanceId),g=gitEvidence;
57
- const observation=g?structuredClone(g):null;
58
- const transition={observation,result:{...structuredClone(result),status:'mismatch',source:'operator-attested'}};
59
- const reject=reason=>({...hold(state,reason),proposedTransition:transition});
60
- if(!result||!text(result.messageRef)||!fields(result.data,['commit'])||!['succeeded','failed','unknown','mismatch'].includes(result.status))return reject('Exact commit result statement required');
61
- if(result.status!=='succeeded'){transition.result.status=result.status;return reject('Execution did not establish a successful commit');}
62
- if(task?.status!=='accepted'||!authorized(state,task)||a?.stale||!a||intent.acceptanceFingerprint!==fingerprintRequest(a)||a.taskFingerprint!==fingerprintRequest({...task,status:'pending'})||!same(a.approval,approval(state,task.id))||!checkEvidence(state,task,a,{tasks:{[task.id]:a.changeFingerprint}})||!same(intent.target,state.target)||!same(intent.versions,state.versions)||!g?.commit||result.data.commit!==g.commit.commit||g.stagedPaths?.length||g.indexTree!==g.commit.tree)return reject('Acceptance, observed commit or clean resulting index mismatch');
63
- const actual={...g.commit,target:g.target,remainingPaths:[...new Set([...g.workingPaths??[],...g.untrackedPaths??[]])].sort()};
64
- const invalid=validateGitCommitResult({target:state.target,expected:intent.expected,result:actual,scope:task.paths});
65
- if(invalid)return reject(invalid);
66
- transition.result.status='succeeded';transition.commit={...actual,taskId:task.id,requestId:intent.requestId,acceptanceId:a.id,source:'operator-attested',observationSource:'local-git',fingerprint:a.changeFingerprint};transition.target=structuredClone(g.target);
67
- const decision=allow(state,transition);reconciliations.set(decision,{before:fingerprintRequest(state),after:fingerprintRequest(transition)});return decision;
68
- }
@@ -1,86 +0,0 @@
1
- import {evaluate} from '../evaluate.mjs';
2
- import {evaluateCapability,plannerHookContextStatus} from '../capabilities.mjs';
3
- import {recordPlannerAgentObservation} from '../identity.mjs';
4
- import {transactWorkflow, fingerprintRequest} from '../store.mjs';
5
- import {runGate} from '../gate.mjs';
6
- import {classifyGitCommand} from '../git-query.mjs';
7
-
8
- const text=v=>typeof v==='string'&&v.length>0;
9
- const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
10
- const supported=new Set(['Read','Glob','Grep','Bash','Write','Edit','MultiEdit','Agent']);
11
- // A bridge child carries this marker; its Hook events are observation-only and never recorded.
12
- const bridgeChild=context=>text((context?.env??process.env).ARC_BRIDGE_CHILD);
13
- const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.claude'],proposedTransition:null});
14
- /** Host-verified support for this installed version is required. A config value
15
- * alone cannot establish hook failure blocking; provider wiring belongs to T6. */
16
- export function claudeFailureBlockingReady(support){
17
- const version=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(support?.platformVersion??'');
18
- const supported=version&&(Number(version[1])>2||Number(version[1])===2&&(Number(version[2])>1||Number(version[2])===1&&Number(version[3])>=295));
19
- return Boolean(supported&&support?.status==='verified'&&support.onFailure==='block'&&text(support.verificationRef));
20
- }
21
- /** Context is a trusted host dependency, never deserialized from stdin/tool_input.
22
- * describeTool must parse the complete tool invocation conservatively, and supply
23
- * semantic operation, paths and descriptor. No native provider is assumed here. */
24
- export function normalizeClaudeEvent(input,context={}){
25
- const status=plannerHookContextStatus({platform:'claude',input,context});if(status.missing.length)throw Error('Missing trusted hook inputs: '+status.missing.join(', '));
26
- 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');
27
- const toolPath=input.tool_name;
28
- const coverage={...evaluateCapability({platform:'claude',toolPath,sessionRef:context.sessionRef}),enforcement:'hook-response-only',nativeVerified:false,startupTimeout:'unknown',existingSessionInput:'unsupported',specializedPaths:'unknown',hostedTools:'unsupported'};
29
- if(!claudeFailureBlockingReady(context.failureBlocking))throw Error('Verified current-version onFailure block contract required');
30
- if(!supported.has(input.tool_name))return {request:null,coverage};
31
- if(typeof context.describeTool!=='function')throw Error('Trusted semantic tool provider unavailable');
32
- const semantic=context.describeTool(structuredClone(input));
33
- if(!object(semantic)||!text(semantic.operation)||!Array.isArray(semantic.paths)||!object(semantic.descriptor))throw Error('Complete semantic tool descriptor required');
34
- if(input.tool_name==='Agent'&&semantic.operation!=='assign-agent')throw Error('Agent tool requires assignment validation');
35
- return {request:{requestId:context.requestId,platform:'claude',actorRef:context.actorRef,taskId:context.taskId,cwd:input.cwd,toolName:input.tool_name,arguments:structuredClone(input.tool_input),operation:semantic.operation,paths:structuredClone(semantic.paths),descriptor:structuredClone(semantic.descriptor)},coverage};
36
- }
37
- /** Only documented PreToolUse fields are emitted. hold is a native deny. */
38
- export function renderClaudeDecision(decision){
39
- if(decision?.decision==='allow')return {};
40
- const permissionDecision='deny';
41
- return {hookSpecificOutput:{hookEventName:'PreToolUse',permissionDecision,permissionDecisionReason:typeof decision?.reason==='string'?decision.reason:'Runtime gate could not verify permission'}};
42
- }
43
- /** This returns a response, not proof the host applied it. Startup failures,
44
- * timeout, hosted/specialized paths and existing write_stdin are outside it. */
45
- export async function runClaudeGate(input,context={}){
46
- if(input?.hook_event_name==='PostToolUse'){
47
- if(bridgeChild(context))return {};
48
- // Result recording cannot authorize assignment/start or prevent a completed call.
49
- try{if(input.session_id===context.sessionRef&&input.tool_use_id===context.toolUseId&&text(context.actorRef)&&typeof context.recordToolResult==='function')await context.recordToolResult(structuredClone(input));}catch{}
50
- return {};
51
- }
52
- if(input?.hook_event_name==='SubagentStart'){
53
- if(bridgeChild(context))return {};
54
- // SubagentStart cannot prevent startup. Only a trusted provider can correlate
55
- // agent_id with a pending assignment; tool/event agent_type is not authority.
56
- try{
57
- if(input.session_id===context.sessionRef&&text(input.agent_id)&&text(context.statePath)){
58
- let observation;try{if(typeof context.observeAgent==='function')observation=await context.observeAgent(structuredClone(input));}catch{}
59
- const decision=await recordPlannerAgentObservation({statePath:context.statePath,expectedRevision:context.state?.revision,input,platform:'claude',sessionRef:context.sessionRef,observation});
60
- if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
61
- }
62
- }catch{/* Observation failure never claims startup was blocked. */}
63
- return {};
64
- }
65
- try{
66
- const {request,coverage}=normalizeClaudeEvent(input,context);
67
- if(!request)return renderClaudeDecision(deny('Tool path has no verified pre-action coverage'));
68
- if(!text(context.statePath))return renderClaudeDecision(deny('Trusted durable workflow store unavailable'));
69
- const result=await transactWorkflow({statePath:context.statePath,expectedRevision:context.state?.revision,requestId:request.requestId,request,requestFingerprint:fingerprintRequest(request),decide:async state=>{
70
- const decision=evaluate(context.policy,state,request,context.evidence);
71
- if(decision.decision!=='allow')return {...decision,coverage};
72
- const actor=state.identities.find(identity=>identity.actorRef===request.actorRef);
73
- if(request.toolName==='Bash'&&actor?.role!=='orchestrator'){
74
- const query=classifyGitCommand(request.arguments.command,context.policy.git);
75
- if(!query.allowed)return {...deny('Specialist Git guard: '+query.reason),coverage};
76
- }
77
- if(request.operation==='commit'){
78
- const git=await runGate({phase:'preflight',state,request,gitEvidence:context.gitEvidence});
79
- if(git.decision!=='allow')return {...git,coverage};
80
- return {...decision,expectedCommit:git.expectedCommit,coverage};
81
- }
82
- return {...decision,coverage};
83
- }});
84
- return renderClaudeDecision(result.decision);
85
- }catch(error){return renderClaudeDecision(deny('Runtime validation unavailable: '+error.message));}
86
- }
@@ -1,65 +0,0 @@
1
- import {evaluate} from '../evaluate.mjs';
2
- import {evaluateCapability,plannerHookContextStatus} from '../capabilities.mjs';
3
- import {recordPlannerAgentObservation} from '../identity.mjs';
4
- import {transactWorkflow, fingerprintRequest} from '../store.mjs';
5
- import {runGate} from '../gate.mjs';
6
-
7
- const text=v=>typeof v==='string'&&v.length>0;
8
- const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
9
- const supported=new Set(['Read','Glob','Grep','Bash','Write','Edit','MultiEdit','exec_command','apply_patch','Agent','spawn_agent']);
10
- // A bridge child carries this marker; its Hook events are observation-only and never recorded.
11
- const bridgeChild=context=>text((context?.env??process.env).ARC_BRIDGE_CHILD);
12
- const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.codex'],proposedTransition:null});
13
- /** Context is a trusted host dependency, never deserialized from stdin/tool_input.
14
- * describeTool must parse the complete tool invocation conservatively, and supply
15
- * semantic operation, paths and descriptor. No native provider is assumed here. */
16
- export function normalizeCodexEvent(input,context={}){
17
- const status=plannerHookContextStatus({platform:'codex',input,context});if(status.missing.length)throw Error('Missing trusted hook inputs: '+status.missing.join(', '));
18
- 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');
19
- const toolPath=['Agent','spawn_agent'].includes(input.tool_name)?'spawn_agent':input.tool_name;
20
- const coverage={...evaluateCapability({platform:'codex',toolPath,sessionRef:context.sessionRef}),enforcement:'hook-response-only',nativeVerified:false,startupTimeout:'unknown',existingSessionInput:'unsupported',specializedPaths:'unknown',hostedTools:'unsupported'};
21
- if(!supported.has(input.tool_name))return {request:null,coverage};
22
- if(typeof context.describeTool!=='function')throw Error('Trusted semantic tool provider unavailable');
23
- const semantic=context.describeTool(structuredClone(input));
24
- if(!object(semantic)||!text(semantic.operation)||!Array.isArray(semantic.paths)||!object(semantic.descriptor))throw Error('Complete semantic tool descriptor required');
25
- if(['Agent','spawn_agent'].includes(input.tool_name)&&semantic.operation!=='assign-agent')throw Error('Agent tool requires assignment validation');
26
- return {request:{requestId:context.requestId,platform:'codex',actorRef:context.actorRef,taskId:context.taskId,cwd:input.cwd,toolName:input.tool_name,arguments:structuredClone(input.tool_input),operation:semantic.operation,paths:structuredClone(semantic.paths),descriptor:structuredClone(semantic.descriptor)},coverage};
27
- }
28
- /** Only documented PreToolUse fields are emitted. hold is a native deny. */
29
- export function renderCodexDecision(decision){
30
- const permissionDecision=decision?.decision==='allow'?'allow':'deny';
31
- return {hookSpecificOutput:{hookEventName:'PreToolUse',permissionDecision,permissionDecisionReason:typeof decision?.reason==='string'?decision.reason:'Runtime gate could not verify permission'}};
32
- }
33
- /** This returns a response, not proof the host applied it. Startup failures,
34
- * timeout, hosted/specialized paths and existing write_stdin are outside it. */
35
- export async function runCodexGate(input,context={}){
36
- if(input?.hook_event_name==='SubagentStart'){
37
- if(bridgeChild(context))return {};
38
- // SubagentStart cannot prevent startup. Only a trusted provider can correlate
39
- // agent_id with a pending assignment; tool/event agent_type is not authority.
40
- try{
41
- if(input.session_id===context.sessionRef&&text(input.agent_id)&&text(context.statePath)){
42
- let observation;try{if(typeof context.observeAgent==='function')observation=await context.observeAgent(structuredClone(input));}catch{}
43
- const decision=await recordPlannerAgentObservation({statePath:context.statePath,expectedRevision:context.state?.revision,input,platform:'codex',sessionRef:context.sessionRef,observation});
44
- if(decision.decision==='allow'&&decision.proposedTransition&&typeof context.persistObservation==='function')await context.persistObservation(decision,observation);
45
- }
46
- }catch{/* Observation failure never claims startup was blocked. */}
47
- return {};
48
- }
49
- try{
50
- const {request,coverage}=normalizeCodexEvent(input,context);
51
- if(!request)return renderCodexDecision(deny('Tool path has no verified pre-action coverage'));
52
- if(!text(context.statePath))return renderCodexDecision(deny('Trusted durable workflow store unavailable'));
53
- const result=await transactWorkflow({statePath:context.statePath,expectedRevision:context.state?.revision,requestId:request.requestId,request,requestFingerprint:fingerprintRequest(request),decide:async state=>{
54
- const decision=evaluate(context.policy,state,request,context.evidence);
55
- if(decision.decision!=='allow')return {...decision,coverage};
56
- if(request.operation==='commit'){
57
- const git=await runGate({phase:'preflight',state,request,gitEvidence:context.gitEvidence});
58
- if(git.decision!=='allow')return {...git,coverage};
59
- return {...decision,expectedCommit:git.expectedCommit,coverage};
60
- }
61
- return {...decision,coverage};
62
- }});
63
- return renderCodexDecision(result.decision);
64
- }catch(error){return renderCodexDecision(deny('Runtime validation unavailable: '+error.message));}
65
- }