joycraft 1.3.0 → 1.4.1

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.
package/README.md CHANGED
@@ -135,8 +135,9 @@ archive fails, the archive still counts as done.
135
135
  At the end of a session the agent checks the workspace for you. You do not run
136
136
  anything:
137
137
 
138
- - **Status.** It finds specs whose text disagrees with the queue, and features that
139
- are finished but not archived.
138
+ - **Status.** It runs the gate check (below). The check finds specs marked done with
139
+ no accepted review and specs whose text disagrees with the queue. It also finds
140
+ features that are finished but not archived.
140
141
  - **Worktrees.** It removes its worker worktrees once their spec is done and merged.
141
142
  It keeps anything unfinished, unmerged or not made by Joycraft, and says why.
142
143
  - **One coordinator.** One session coordinates each queue, so a second session's
@@ -190,6 +191,69 @@ counts as evidence; your project keeps its own tools.
190
191
  After an update, the agent checks the review loop again and asks only about what
191
192
  changed.
192
193
 
194
+ ### The gates: no spec is done without an accepted review
195
+
196
+ Joycraft's rule is that only an accepted review completes a spec. Without the
197
+ gates, this rule is an instruction in a skill. An agent can forget the rule or skip
198
+ it, for example late in a long session. The gates make the rule a check.
199
+
200
+ **What the gate stops.** The gate check finds three problems:
201
+
202
+ - A spec is marked done with no accepted review, no acceptance from you and no waiver.
203
+ - A spec has one status in the queue and a different status in the spec file.
204
+ - Joycraft cannot read a queue file or a spec file.
205
+
206
+ It sends the agent back with the spec or file name and the next step. A spec that waits at
207
+ `in-review` is not a problem.
208
+
209
+ **Why you want it.** Use the gates for long sessions and for sessions that you do
210
+ not watch. A prompt tells the agent what to do, but a prompt is not a guarantee.
211
+ With the gates on, Claude Code runs the check each time the agent tries to stop. The
212
+ agent cannot stop until the problem is gone.
213
+
214
+ **Before you turn them on.** An older project can have specs marked done with no
215
+ accepted review. The check sends each one back for a review. To see them first, say:
216
+
217
+ ```text
218
+ Run Joycraft's gate check with `node .joycraft/runtime/gate.mjs check` and show me
219
+ what it names. Change nothing yet.
220
+ ```
221
+
222
+ Do this also after you update an older project to 1.4.1, because session end now
223
+ runs the same check.
224
+
225
+ **Turn them on.** Say:
226
+
227
+ ```text
228
+ Turn on Joycraft's gates.
229
+ ```
230
+
231
+ The agent shows you the change to `.claude/settings.json` on a page. It writes the
232
+ change only on your yes. The change adds one Stop hook and no other line. Setup
233
+ also offers the gates one time.
234
+
235
+ **Turn them off.** Say:
236
+
237
+ ```text
238
+ Turn off Joycraft's gates.
239
+ ```
240
+
241
+ The agent removes Joycraft's hook. Your own hooks stay. If you remove Joycraft from
242
+ the project, the agent removes this hook first.
243
+
244
+ **What the gates do not do.**
245
+
246
+ - The hook is for Claude Code only for now. On the other agents, the session-end
247
+ skill runs the check. That step is an instruction, so the agent can still skip it.
248
+ - There is no CI check. Joycraft does not check your pull requests.
249
+ - The hook is not a sandbox. A shell command can still change the queue file. The
250
+ check finds the result at the next stop.
251
+
252
+ **A fourth review is refused.** On every agent, one spec gets at most three
253
+ reviews. A round is one set of reviewed inputs, so a new review of the same code
254
+ does not count again. Reviewer startup prints the round and refuses a fourth
255
+ review. The agent then records `## Decision needed` in the spec and asks you.
256
+
193
257
  ## Answering questions: the decision page
194
258
 
195
259
  When the agent needs you to choose between options, it asks in your question
@@ -232,8 +296,9 @@ project:
232
296
 
233
297
  All of it lives in your repository. Joycraft collects no data and does not call an AI
234
298
  model itself. Its only network use is the version check below. Joycraft adds no
235
- agent hooks and changes no agent settings. A command after an archive runs only if
236
- you asked for one.
299
+ agent hooks and changes no agent settings, except the gate hook that you turn on
300
+ ([The gates](#the-gates-no-spec-is-done-without-an-accepted-review)). A command
301
+ after an archive runs only if you asked for one.
237
302
 
238
303
  ## Updates
239
304
 
@@ -279,6 +344,8 @@ in [Prompts](docs/prompts.md):
279
344
  | Change a setting | "Keep Joycraft's specs in working/features." |
280
345
  | Connect your wiki | "Link our wiki and keep it up to date." |
281
346
  | Clean up | "Clean up the docs and the workspace." |
347
+ | Turn the gates on | "Turn on Joycraft's gates." |
348
+ | Turn the gates off | "Turn off Joycraft's gates." |
282
349
  | Undo the 1.0 upgrade | "Undo this project's upgrade to Joycraft 1.0." |
283
350
  | Remove Joycraft | "Remove Joycraft from this project." |
284
351
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "releaseVersion": "1.3.0",
3
+ "releaseVersion": "1.4.1",
4
4
  "manifestSchemas": [
5
5
  1
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joycraft",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Install and update Joycraft, a skill bundle and runtime for agent-led software work, in any project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,8 +13,8 @@
13
13
  "payload"
14
14
  ],
15
15
  "joycraft": {
16
- "release": "1.3.0",
17
- "summary": "Ask your agent instead of running commands: it changes Joycraft settings, connects your wiki and removes Joycraft on request, and the docs give a prompt for every step.",
16
+ "release": "1.4.1",
17
+ "summary": "Gates: say \"Turn on Joycraft's gates\" and Claude Code cannot stop while a spec is done without an accepted review; session end runs the same check on every agent, and a fourth review is refused.",
18
18
  "autoSafeEligible": false
19
19
  },
20
20
  "scripts": {
@@ -20,16 +20,15 @@ node .joycraft/runtime/context/cli.mjs --query "<current request>"
20
20
  Narrow discovery with `--paths docs/context src/relevant-area` when the relevant
21
21
  area is known. Retrieval excludes `docs/archive/` unless historical material is
22
22
  specifically needed; add `--history` to inspect it as reading context, never as
23
- current authority. An optional model ranker orders the results when it is
24
- installed; otherwise they come in local-search order. Read `.joycraft/references/context.md` for output
23
+ current authority. Results come in local-search order. Read `.joycraft/references/context.md` for output
25
24
  and failure details.
26
25
 
27
- Read useful ranked source files and follow their relevant links. Scores guide
28
- reading order; low scores do not remove files or define task scope. Check omitted,
29
- unreadable and unranked reasons; a provider failure still leaves local references.
26
+ Read useful source files and follow their relevant links. Local scores guide
27
+ reading order; low scores do not remove files or define task scope. Check omitted
28
+ and unreadable reasons.
30
29
  Refine the query or paths when local keyword matching misses a known dependency.
31
30
  When the requested change has an unclear state, data, or responsibility seam,
32
- trace the actual counterpart sources beyond the ranked list: for example, the
31
+ trace the actual counterpart sources beyond the result list: for example, the
33
32
  owner alongside its callers, readers, writers, or persistence boundary. Add
34
33
  discovered sources to the work's declared inputs and report any unresolved
35
34
  coverage. Read `.joycraft/references/architecture.md` only for that
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: joycraft-entry
3
3
  description: Start any Joycraft work. After Joycraft is installed, when asked to "set up Joycraft", "check the context map", change Joycraft settings or remove Joycraft, read the project, interview the user and build the context map in AGENTS.md; then turn a repair, feature, or mixed request into a context-backed brief and the next useful action.
4
- compatibility: Setup and routing helpers require Node.js 22+ and the installed .joycraft runtime only when used; ordinary brief and context navigation has no project-stack prerequisite.
4
+ compatibility: Setup helpers require Node.js 22+ and the installed .joycraft runtime only when used; ordinary brief and context navigation has no project-stack prerequisite.
5
5
  ---
6
6
 
7
7
  Run `node .joycraft/runtime/update-check.mjs check` first, once per session. If it
@@ -24,7 +24,7 @@ alone does not start a full setup.
24
24
 
25
25
  Read existing project instructions first. During an upgrade, inspect the installed
26
26
  manifest’s `legacyConflicts` and reconcile competing old skill discovery before
27
- using routing advice; preserved custom content is not a completed migration.
27
+ choosing skills; preserved custom content is not a completed migration.
28
28
  On a bare project, offer the
29
29
  [kickoff](../../../.joycraft/references/setup.md#kickoff-for-a-new-project)
30
30
  in one line before any brief or scaffold, and run it when the user asks for it on
@@ -49,7 +49,7 @@ scope or a consequential choice.
49
49
 
50
50
  When an unclear state, data, or responsibility boundary could change the work,
51
51
  do focused discovery before splitting it: inspect the actual owner and its
52
- callers, readers, writers, or other coupled counterpart. Ranking can point to
52
+ callers, readers, writers, or other coupled counterpart. Search can point to
53
53
  sources, but does not replace that trace. Keep settled product behavior in the
54
54
  brief; record only durable, source-backed navigation in the project's existing
55
55
  context homes. Read `.joycraft/references/architecture.md` for this
@@ -109,6 +109,9 @@ page, connect their wiki, see their settings or remove Joycraft, follow
109
109
  [settings](../../../.joycraft/references/settings.md). The user never edits
110
110
  `joycraft.yaml` or runs a Joycraft command by hand.
111
111
 
112
+ **Gates by request.** When the user asks to turn Joycraft's gates on or off, or
113
+ what they do, follow [gates](../../../.joycraft/references/gates.md).
114
+
112
115
  **Show documents as pages.** A brief, plan, spec set or review that the user must
113
116
  read or approve is also rendered, never left as Markdown in chat: the decision
114
117
  artifact for a brief, an HTML page for anything else. Show it as
@@ -132,20 +135,6 @@ existing direct path when it fits the request. Do not turn routine data entry
132
135
  into a code-spec factory or create per-record plans when an approved batch tool
133
136
  already owns the operation. Preserve its validation, approval and readback rules.
134
137
 
135
- When a native hook adds routing advice to the prompt, use it to select relevant
136
- skills. Keep all expressed goals even when a classifier misses a signal. Do not
137
- repeat a live routing call when the hook already provided current advice.
138
- Routing does not approve scope, answer a decision, or establish evidence.
139
-
140
138
  Use `joycraft-context` when you need to find relevant project files beyond the
141
- context map. Its deterministic search (and optional ranking) provides pointers; read the
142
- selected source before relying on it. For hook status, blocked edits or provider
143
- failures, read `.joycraft/references/hooks-runtime.md`. Treat unavailable
144
- checks as unavailable, never as approval. For a denial, compare its cited scope
145
- with the current task and the actual human question/answer. Repair missing
146
- source delivery once through the documented binding flow, then resume understood
147
- authorized work. Do not ask for the same permission again, move a chat answer to
148
- a different document as an enforcement workaround, weaken a gate, or wrap a
149
- denied command. Ask the host for the legitimate correction when needed.
150
- If native hooks are absent and routing is materially uncertain, the explicit adapter in `.joycraft/references/routing.md` remains available.
151
- When requested setup includes native hooks, use [Codex hook installation](../../../.joycraft/references/hooks-install.md) or [Claude Code hook installation](../../../.joycraft/references/hooks-claude.md) for the active host. Installation and project setup do not establish host trust or execution.
139
+ context map. Its deterministic search provides pointers; read the selected
140
+ source before relying on it.
@@ -30,10 +30,7 @@ For normal native execution, the host launches the selected worker first. The
30
30
  child bootstraps from its actual root, then runs `dispatch-start.mjs --role
31
31
  implementer` with its actual native identity before any tasked edit or mutation.
32
32
  The coordinator runs that start itself only when it is the implementer actor.
33
- Use the returned packet only when `ready` is true. A hooks-disabled/manual
34
- workflow can be ready; unavailable hook status is not a new permission gate for
35
- all work. When startup returns unenforced, hold only that claimed enforced task,
36
- report why, and continue unrelated authorized or manual/disabled workflow.
33
+ Use the returned packet only when `ready` is true.
37
34
 
38
35
  If existing independent reports reveal a possible recurring failure, follow [recurring failure guidance](../../../.joycraft/references/recurring-failures.md) before carrying it forward: inspect the current scoped sources and actual counterpart path or journey, then provide any proposed lesson as exact inputs through the existing dispatch flow. A verified repair may establish its local project fact; a broader method benefit remains pending later reuse.
39
36
 
@@ -77,9 +74,9 @@ It needs actual host session/agent identity and available current authority
77
74
  as described in [dispatch guidance](../../../.joycraft/references/dispatch.md).
78
75
  Write its packet or subject beneath a confirmed Git-ignored project-local
79
76
  directory, not among reviewed sources.
80
- If it returns unenforced, or a separate review context/capability is unavailable,
81
- leave the spec `in-review`; do not invent an ID or prompt to continue. This holds
82
- the claimed review, not unrelated authorized or hooks-disabled/manual work.
77
+ If a separate review context/capability is unavailable, leave the spec
78
+ `in-review`; do not invent an ID to continue. This holds the claimed review,
79
+ not unrelated authorized work.
83
80
 
84
81
  When a recorded tool breaks during a run (the dev server does not start, a
85
82
  port is taken, the browser or simulator crashes), repair it with what the user
@@ -101,9 +98,10 @@ Only the guarded completion path can move an `in-review` spec to `done`. Use its
101
98
 
102
99
  When a current independent review is `FAIL` or `UNVERIFIED`, first fix
103
100
  straightforward failures within the existing authorization and obtain a fresh
104
- review. A spec gets at most three reviews; state the real round number in each
105
- fix brief. Settled briefs and checked specs should make this rare. If a second FAIL
106
- on the same criterion or a "decision needed" finding still occurs, send no
101
+ review. A spec gets at most three reviews: reviewer startup prints
102
+ `reviewRound` and refuses a fourth. Settled briefs and checked specs should make
103
+ this rare. If startup refuses a review, or a second FAIL on the same criterion
104
+ or a "decision needed" finding still occurs, send no
107
105
  further fix and never amend acceptance yourself: note it under `## Decision
108
106
  needed` in the spec, leave it `in-review`, and continue independent ready work. An owner can explicitly accept the
109
107
  current findings and their stated limits through `accept-owner`; that is a
@@ -8,11 +8,6 @@ compatibility: Requires Node.js 22+ and the installed .joycraft runtime for the
8
8
 
9
9
  Use this skill when pausing or finishing an authorized queue session.
10
10
 
11
- On Claude `SessionEnd`, write only the local session summary and deduplicate the
12
- transition record. Do not call an API or archive from that hook. On other hosts,
13
- use their metrics/manual or portable summary path when available; never infer a
14
- Claude lifecycle event from a generic session boundary.
15
-
16
11
  Read each touched queue and report the real state of every affected spec: `todo`, `in-review`, or `done`. `done` must have either an accepted PASS report receipt or a completion-helper owner-acceptance record bound to a current failed or unverified report; a commit, PASS command, or implementer assertion is not acceptance. Keep blocked or failed dependency branches explicit while identifying independent ready work that can continue next.
17
12
 
18
13
  If the session stops or restarts a concurrent run, report its recorded
@@ -20,8 +15,7 @@ coordinator ownership, captured refs, known worker trees, leases, locks, and
20
15
  runtime processes. Release only resources demonstrably owned by that run;
21
16
  retain ambiguous merges, locks, processes, and trees for diagnosis. Do not
22
17
  force local state to a remote tip. Start a replacement only from the durable
23
- run journal and a newly printed dispatch plan. This guidance describes the
24
- project/native runtime boundary; it does not enforce lifecycle behavior.
18
+ run journal and a newly printed dispatch plan.
25
19
 
26
20
  For each completed spec, report the implementation revision, independent reviewer session ID, report and receipt paths, actual commands and outcomes, visual inspection status where required, and known limitations. For owner-accepted work, also report the owner-acceptance record and its inherited limits as `done, owner-accepted with <limits>`; preserve the original `FAIL` or `UNVERIFIED` report rather than calling it PASS or verified. List each spec completed under a feature waiver as `done, waived by the user: "<instruction>"`, with any report's real verdict; never call it reviewed or verified.
27
21
 
@@ -29,12 +23,13 @@ If a completion operation failed or was interrupted, do not declare success or h
29
23
 
30
24
  Leave enough project-relative paths and next actions for another session to resume the autonomous ready authorized queue without recreating settled context or decisions.
31
25
 
32
- Before ending the session, run `node .joycraft/runtime/status.mjs`. Repair
33
- lagging frontmatter of accepted specs with `--fix`; report any other drift and
34
- any feature listed as ready to archive. Then preview
35
- `node .joycraft/runtime/worktrees.mjs prune` and apply it with `--apply`: it
36
- removes only clean, integrated trees of done specs and keeps failed, blocked or
37
- unknown trees with their reason. Report kept trees and their size from `list`.
26
+ Before ending, run `node .joycraft/runtime/status.mjs --fix` (repairs lagging
27
+ frontmatter of accepted specs, lists features ready to archive) and
28
+ `node .joycraft/runtime/gate.mjs check`. Do the step each gate message names,
29
+ such as a completing command. Tell the user each message you could not clear.
30
+ Then preview `node .joycraft/runtime/worktrees.mjs prune` and apply it with
31
+ `--apply`: it removes only clean, integrated trees of done specs and keeps the
32
+ rest with their reason. Report kept trees and their size from `list`.
38
33
  When this session coordinated a queue and no work on it remains, release the
39
34
  lease with `node .joycraft/runtime/coordinator.mjs release --queue <queue> --session <your-session-id>`. See [worker isolation](../../../.joycraft/references/worktrees.md)
40
35
  when the session used parallel mutable workers.
@@ -6,12 +6,6 @@ compatibility: The optional shared evidence validator requires Node.js 22+ and t
6
6
 
7
7
  # Useful testing evidence
8
8
 
9
- Use any post-edit hook findings as candidate gaps to inspect against the active
10
- requirements and relevant tests. A flag is not proof of a defect, and no flag is
11
- not proof of coverage. Keep valid gaps visible until a useful assertion or
12
- observed interaction resolves them; missing tests during intermediate edits do
13
- not require stopping understood implementation.
14
-
15
9
  Read the active requirements and relevant existing tests. Choose the smallest
16
10
  boundary that can establish each claim: real function inputs for arithmetic,
17
11
  composed transitions for stateful behavior, rendered interaction for UI behavior.
@@ -29,10 +29,9 @@ prepare a source packet for a manual boundary, but it must not bind the child
29
29
  using the parent's identity. After launch, the reviewer child bootstraps at its
30
30
  actual root and runs `dispatch-start.mjs --role reviewer` with its own actual
31
31
  native identity, which captures the subject, preflights delivery, writes the
32
- bounded packet, and binds it. If the real ID, available authority, or a separate
33
- reviewer context is unavailable, leave the spec `in-review`; do not manufacture
34
- any of them. A hooks-disabled/manual workflow can still be ready; an unenforced
35
- result holds only the claimed review, not unrelated work.
32
+ bounded packet. If the real ID or a separate reviewer context is unavailable,
33
+ leave the spec `in-review`; do not manufacture either. This holds only the
34
+ claimed review, not unrelated work.
36
35
  Reviewer startup output also carries `trace`, the spec's criteria with the tests
37
36
  tagged `[AC:<criterion-id>]` (`node .joycraft/runtime/trace.mjs --queue <queue> --spec <id>`
38
37
  produces the same). Report untraced criteria as findings; a missing tag alone is
@@ -44,10 +43,8 @@ Dispatch `collaboration.spawn_agent` with `fork_turns: "none"` and the packet's
44
43
 
45
44
  When already dispatched as the independent reviewer, perform the review directly; do not recursively dispatch another reviewer. Read the parent brief, spec, queue entry, declared criteria and exact verification inputs. Use the supplied subject, set independence truthfully, and do not self-certify implementation from your own context.
46
45
 
47
- Inspect any hook rule/test-gap findings alongside the actual changes and
48
- requirements. Resolve supported concerns with observed evidence; a classifier
49
- score or clean hook receipt cannot establish acceptance. Check changed tests for
50
- weakened assertions that could hide the requested behavior.
46
+ Check changed tests for weakened assertions that could hide the requested
47
+ behavior.
51
48
 
52
49
  Review scope as well as behavior: determine whether the listed inputs and criteria cover the requested work, including relevant newly changed files. For a cross-boundary change, inspect the combined observable behavior across the relevant producer, consumer, state or storage boundary; separate green helpers, snapshots, or assertion counts do not establish that behavior. If a material counterpart or owning decision/context source was omitted, report the scope gap and require its exact path to be added before a fresh current review subject is prepared. Preserve the snapshot's implementation revision as provenance while checking its current bound inputs. A changed, missing, or renamed input makes the subject stale; do not substitute a newer HEAD as its identity.
53
50
 
@@ -79,10 +79,8 @@ subject or provide the reviewer with an intended verdict or implementer reasonin
79
79
  Update only affected accepted facts in their owning reference, reconciling them
80
80
  at session end before any eligible archival. Active choices remain in their
81
81
  brief; rationale links to that choice; proposals stay marked as proposals.
82
- References describe and navigate the project. They neither grant permission nor
83
- become global Jev constraints. Do not add them to global hook rule paths or make
84
- extra live classification calls merely to maintain a map. Retrieval scores and
85
- this procedure do not certify exhaustive discovery.
82
+ References describe and navigate the project. They do not grant permission.
83
+ Retrieval scores and this procedure do not certify exhaustive discovery.
86
84
 
87
85
  Keep task context bounded to relevant sources. When evaluating the change,
88
86
  record newly delivered input bytes, repeated reads/provider calls, human
@@ -43,19 +43,17 @@ and a snippet of at most 1,800 UTF-8 bytes around the first matching line.
43
43
  Snippets include source line numbers and whether they are partial. Large files
44
44
  are never described as searched or ranked. Read those separately when needed.
45
45
 
46
- Every selected candidate is retained, including a zero-scored file. Jev scores
47
- all selected candidates in batches of at most 20; there is no candidate cap or
48
- score cutoff. Encoded states over 60,000 bytes split into smaller batches, leaving
49
- room for the shared question rubric. Narrow the query or paths before calling when a large area would
50
- create unnecessary calls. A keyword search can miss paraphrases or dependencies;
51
- this result never claims exhaustive context. Refine and follow relevant links.
52
-
53
- The JSON `references` are sorted by Jev relevance, then local score/path. Each
54
- reference identifies `provenance`, `relevance` (or `null`), and its scoring batch.
55
- `batches` records candidate IDs, returned model, usage and elapsed time for each
56
- successful call. `omitted`, `unreadable`, and `unranked` explain files that were
57
- not scored. Hashes bind the result to the bytes read, not future edits. Open the
46
+ Every selected candidate is retained, including a zero-scored file; there is no
47
+ candidate cap or score cutoff. A keyword search can miss paraphrases or
48
+ dependencies; this result never claims exhaustive context. Refine and follow
49
+ relevant links.
50
+
51
+ The JSON `references` come in local-search order: local score, then path.
52
+ `status` is `local-search-only`, and `unranked` lists each candidate with the
53
+ reason `scoring-disabled`. `omitted` and `unreadable` explain files that were
54
+ not read. Hashes bind the result to the bytes read, not future edits. Open the
58
55
  current source before relying on it; a bounded snippet is not the full file.
56
+ Invalid inputs or an unavailable Git inventory exit nonzero.
59
57
 
60
58
  For an unclear state, data, or responsibility boundary, use the result as a
61
59
  starting point and inspect the actual coupled sources as well: the owner and its
@@ -63,28 +61,7 @@ callers, readers, writers, or persistence boundary as applicable. Add discovered
63
61
  paths to the brief/spec verification inputs before dispatch, and state any
64
62
  unresolved coverage. Read `architecture.md` for focused examples. This expands
65
63
  source discovery only when the seam matters; it does not make the context map a
66
- second source of product decisions or a Jev-enforced prohibition.
67
-
68
- Live scoring is the default. `.joycraft/hooks-config.json` supplies
69
- `enabled`, `timeoutMs`, and Keychain service `JEV_API_KEY`; `--keychain-service` overrides it. The
70
- shared `.joycraft/runtime/hooks/judge.mjs` primitive uses an existing
71
- environment credential first, then the configured macOS Keychain service.
72
- Credentials are never saved in the config, command arguments, result or project.
73
- No dotenv file, transcript, or whole-project model dump is used.
74
- The shared redactor removes recognizable credential patterns from outgoing
75
- query/snippet strings before the Jev call; content hashes still identify the
76
- original local bytes. Pattern redaction cannot identify arbitrary secret text.
77
- Setting `enabled: false` selects explicit `local-search-only` output without
78
- credential lookup; each candidate is marked unranked with `scoring-disabled`.
79
-
80
- Missing credentials, malformed provider output or an outage stop further model
81
- calls for that invocation. All selected references remain available in local
82
- order where unranked; previously successful scores retain their provenance.
83
- `status: incomplete-provider-ranking`, `provenance: local-search-fallback` and
84
- `fallbackReason` make this explicit. Exit success means a usable result exists,
85
- not that every candidate was scored; inspect `status` and `scoredCount`.
86
- Invalid inputs or an unavailable Git inventory exit nonzero. Provider scores
87
- advise reading order and never approve intent, authorize work or certify evidence.
64
+ second source of product decisions or a prohibition.
88
65
 
89
66
  Treat only the context homes as current authority. `docs/features/` is working
90
67
  material that can be stale until its feature is archived, and `docs/archive/` is
@@ -3,8 +3,8 @@
3
3
  For normal native work, the host launches the worker and the child then uses the
4
4
  dispatch-start entry point from its actual root before any tasked edit. A
5
5
  coordinator uses it itself only when it is the worker actor. It validates delivery
6
- and returns a ready/unenforced decision plus the bounded packet and hook-binding
7
- instructions; it never launches a worker, alters queue status, or accepts work.
6
+ and returns a ready decision plus the bounded packet; it never launches a worker,
7
+ alters queue status, or accepts work.
8
8
  For a mutable worker or stateful runtime check, first apply the conditional
9
9
  [worker-isolation policy](worktrees.md); this preflight does not create a
10
10
  worktree or a resource lease. A `read-only` workspace keeps declared source
@@ -18,7 +18,6 @@ those specs with `accept-waiver` instead.
18
18
 
19
19
  - [Start a native dispatch](#start-a-native-dispatch)
20
20
  - [Call the portable dispatch API](#call-the-portable-dispatch-api)
21
- - [Bind the hook source view](#bind-the-hook-source-view)
22
21
  - [Validate capabilities before dispatch](#validate-capabilities-before-dispatch)
23
22
  - [Check the reviewer report](#check-the-reviewer-report)
24
23
 
@@ -90,6 +89,7 @@ it before the first implementer mutation, and startup preserves it. The separate
90
89
  workspace `--base-revision` option keeps its documented topology check.
91
90
  Implementer dispatch requires each dependency to be `done`; reviewer dispatch
92
91
  does not require the target itself to be done. Unknown roles are rejected.
92
+ Reviewer startup prints `reviewRound` and `reviewLimit: 3`; a round is one distinct set of reviewed inputs, so a commit that changes none of the spec's verification inputs keeps the round, and a fourth round exits 2.
93
93
 
94
94
  When a reviewer startup exits non-zero or returns `ready: false`, run it once
95
95
  more, alone, with a fresh packet path. If it fails again, stop that spec's
@@ -101,17 +101,8 @@ cause and the repair it tried. The coordinator tells the user at the first hold,
101
101
  in the conversation, while other workers keep running; it does not wait for the
102
102
  session end. The session-end summary lists every held spec again.
103
103
 
104
- The return is `ready: true` for an available valid startup path, including a
105
- hooks-disabled/manual path. It is not a cryptographic attestation. Missing human
106
- prompt history for an enforced startup is explicit
107
- `ready: false`, exit code 2, and `unenforced`; it is not a permission request,
108
- an invented prompt, or a substitute session ID. Continue discovery and other
109
- unrelated authorized work, including manual/disabled workflows, but do not
110
- dispatch the claimed enforced worker. Do not
111
- select an arbitrary task to make a native relationship appear valid. A child
112
- binding uses its own root and a real prompt; it may inherit the same native
113
- parent session authority only when an observed linked coordinator relationship
114
- is valid. A unique new root session needs its own actual prompt.
104
+ A valid startup returns `hooks: { enabled: false, reason: "hooks-not-installed" }`
105
+ and `ready: true`. It is not a cryptographic attestation.
115
106
 
116
107
  When the host reports a native agent/invocation ID, also pass
117
108
  `--implementer-host <host> --implementer-agent <actual-agent-id>`. For a root
@@ -142,8 +133,8 @@ from a legacy self-attested call.
142
133
 
143
134
  Call the portable API from a Codex, Claude, Pi, OMP, or Copilot adapter. Normal
144
135
  native startup calls `startDispatch(options, nativeEvent)` so the runtime can
145
- validate the observed session, agent relationship, and prompt authority before
146
- it returns a packet:
136
+ validate the observed session and agent relationship before it returns a
137
+ packet:
147
138
 
148
139
  ```js
149
140
  import { startDispatch } from './.joycraft/runtime/dispatch-start.mjs';
@@ -171,30 +162,6 @@ When `AGENTS.md` has a `## Review loop` section or this machine has
171
162
  `{ path, section, local? }`, the shared section plus, when present,
172
163
  `local: { path, record }` with this machine's host tools.
173
164
 
174
- ## Bind the hook source view
175
-
176
- Dispatch-start prepares and binds its hash-bound `hookSourceView` with actual
177
- native IDs. The lower-level manual bind command remains only for an explicit
178
- non-native boundary. It uses the actual native session ID reported at startup,
179
- never a generated UUID:
180
-
181
- ```sh
182
- node .joycraft/runtime/hooks/cli.mjs bind-source \
183
- --session <actual-native-session-id> --packet <project-relative-packet.json>
184
- ```
185
-
186
- Bind a known parent session before launching children when the host exposes
187
- parent inheritance. Otherwise, bind the child after it reports its own actual
188
- session ID. For children sharing a parent session but working on different
189
- specs, add `--agent <actual-native-child-id>` when binding each child. Its task
190
- view remains separate while human prompts still inherit from the parent.
191
- Rebind after the brief changes. The hook view currently receives only
192
- hash-checked brief and decision pointers; the worker packet retains the exact
193
- decision records. An unknown ID leaves the dependent
194
- Jev check advisory and unverified; it does not permit a substitute ID. The view
195
- makes selected saved answers available to Jev, but never grants permission or
196
- an expected review outcome.
197
-
198
165
  ## Validate capabilities before dispatch
199
166
 
200
167
  `claims.capabilities` must include `filesystem:read`,
@@ -0,0 +1,60 @@
1
+ # Gates
2
+
3
+ Joycraft's rule is that only an accepted review completes a spec. The gate
4
+ check makes the rule a command, so it does not depend on the agent.
5
+
6
+ ## What the gate checks
7
+
8
+ `node .joycraft/runtime/gate.mjs check` exits 2 and names each problem on
9
+ stderr. Each message names its next step:
10
+
11
+ - a `done` spec with no accepted report, owner acceptance or waiver: set it
12
+ back to `in-review`, get an independent review, then run the completing
13
+ command that the message names;
14
+ - a spec whose queue status and frontmatter status are different: pending
15
+ journal: run the named `recover` command, stop on a conflict; accepted: run
16
+ `node .joycraft/runtime/status.mjs --fix`; unaccepted `done`: the step above
17
+ first; else set the frontmatter to the queue's status and tell the user;
18
+ - a current queue or spec file that does not parse: repair it and tell the user.
19
+
20
+ A spec held at `in-review` is never a problem. Queues older than
21
+ `schemaVersion: 1` are skipped. With no problem, it exits 0 and prints nothing.
22
+ Any agent can run the check, and the session-end skill runs it. Without a hook,
23
+ that step depends on the agent.
24
+
25
+ ## The Stop hook
26
+
27
+ The hook is for Claude Code only for now. When it is on, Claude Code runs the
28
+ gate check each time it is about to stop. On exit 2, Claude Code gives the
29
+ message to the agent, and the agent must do the step that the message names.
30
+ The hook is not a sandbox: a shell command can still write the queue file. The
31
+ check finds that result at the next stop.
32
+
33
+ ## Turn the gates on
34
+
35
+ The user says "Turn on Joycraft's gates", or says yes to the offer in setup.
36
+
37
+ 1. Run `node .joycraft/runtime/gate.mjs hook --plan`. It writes nothing.
38
+ - `change: "none"` and a `message`: tell the user the message. On a host
39
+ other than Claude Code, the message says that the hook is not available
40
+ and how to run the check by hand.
41
+ - `change: "add"`: continue.
42
+ 2. Show the change to `.claude/settings.json` (`before` and `after`) on a page,
43
+ as [showing a page](artifacts.md#showing-a-page) says. In two lines, say
44
+ what the Stop hook does and how to turn it off.
45
+ 3. On the user's yes, run `node .joycraft/runtime/gate.mjs hook --on`. Do not
46
+ edit `.claude/settings.json` by hand.
47
+
48
+ `.claude/settings.json` is the user's file. `--on` adds one Stop hook whose
49
+ command runs `gate.mjs check`, and it changes no other byte. A second `--on`
50
+ changes nothing. If the file is not valid JSON, the command stops and writes
51
+ nothing; tell the user.
52
+
53
+ ## Turn the gates off
54
+
55
+ The user says "Turn off Joycraft's gates". That request is the yes. Run
56
+ `node .joycraft/runtime/gate.mjs hook --off` and tell the user its message.
57
+ When nobody changed the file after `--on`, the file is again byte for byte as
58
+ it was before `--on`. `.joycraft/local/gate-hook.json` keeps the record for
59
+ this. Without a usable record, it removes Joycraft's Stop hook and any
60
+ `hooks.Stop` list or `hooks` object left empty, and its message names each one.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use `joycraft-retro` on a requested session worth learning from, including a
4
4
  successful session with unexpected friction. It proposes environment improvements;
5
- it does not run on every session end, change acceptance or add Jev calls.
5
+ it does not run on every session end or change acceptance.
6
6
 
7
7
  ## Prepare native session evidence
8
8
 
@@ -22,9 +22,9 @@ node .joycraft/runtime/retro.mjs prepare --source /absolute/path/session.jsonl -
22
22
  ```
23
23
 
24
24
  Line selection reduces the prepared context, not source-read memory: this small
25
- helper reads the supplied file into memory. Use an existing episode export or
26
- the evidence collector for sources too large for that approach, retaining the
27
- original source references and any selection limits.
25
+ helper reads the supplied file into memory. Use an existing episode export for
26
+ sources too large for that approach, retaining the original source references
27
+ and any selection limits.
28
28
 
29
29
  Read `coverage.json` first, then `conversation.md` and `tools.jsonl`. The source
30
30
  hash and physical line references let you return to exact raw evidence. The
@@ -45,17 +45,8 @@ inspect material before sharing it. It creates no permission or decision state.
45
45
  Other harness formats can be read directly; do not describe an unsupported
46
46
  format as normalized or invent native coverage.
47
47
 
48
- Keep any linked session/worker files, hook receipts and final review reports as
49
- separate sources. A single file may not contain all workers or continuations.
50
- Existing hook metrics can summarize explicit receipts without replaying paid
51
- checks:
52
-
53
- ```sh
54
- node .joycraft/runtime/hooks/metrics.mjs --log /absolute/path/events.jsonl
55
- ```
56
-
57
- Provider-reported usage is not an invoice; absent calls, timing or usage remain
58
- unknown. Do not equate a missing receipt with a free or absent call.
48
+ Keep any linked session/worker files and final review reports as separate
49
+ sources. A single file may not contain all workers or continuations.
59
50
 
60
51
  ## Judge a candidate
61
52
 
@@ -49,9 +49,12 @@ On "uninstall Joycraft" or "remove Joycraft":
49
49
  1. Read `.joycraft/installation.json`. Its `files` list holds each installed path
50
50
  and the `sha256` it had at install.
51
51
  2. Show the user what goes: the listed files, with each file whose bytes changed
52
- since install marked as edited, and `.joycraft/` itself. Say what stays:
53
- `AGENTS.md`, `CLAUDE.md`, `docs/` and `joycraft.yaml` are theirs.
52
+ since install marked as edited, Joycraft's Stop hook in `.claude/settings.json`
53
+ when the gates are on, and `.joycraft/` itself. Say what stays: `AGENTS.md`,
54
+ `CLAUDE.md`, `docs/` and `joycraft.yaml` are theirs.
54
55
  3. Offer to remove the Joycraft lines from `AGENTS.md` and `CLAUDE.md` (the context
55
56
  map rows that point into `.joycraft/`, and the Joycraft rules). Show that diff
56
57
  separately.
57
- 4. On the user's yes, delete the files, then `.joycraft/`. Do not commit.
58
+ 4. On the user's yes, first run `node .joycraft/runtime/gate.mjs hook --off`. It
59
+ removes Joycraft's Stop hook. When the gates are off, it changes nothing. Then
60
+ delete the files, then `.joycraft/`. Do not commit.
@@ -320,15 +320,15 @@ the owning brief and do not ask it again.
320
320
  ## Finish setup and continue
321
321
 
322
322
  Step 5 of [Set up the context map](#set-up-the-context-map) is the finish
323
- check; also check that command claims match their cited source. Setup does not approve hooks, change credentials, install
324
- dependencies, or replace the user's workflow. Read `hooks-install.md` only when
325
- hook activation is part of the requested setup.
323
+ check; also check that command claims match their cited source. Setup does not
324
+ change credentials, install dependencies, or replace the user's workflow.
325
+ When `.joycraft/installation.json` lists the `claude` host, offer the [gates](gates.md) once, in one line; turn them on only on the user's yes.
326
326
 
327
327
  ## Upgrade and agent onboarding
328
328
 
329
329
  Updates go through the Joycraft CLI; follow [update guidance](update.md). The
330
330
  installation manifest `.joycraft/installation.json` records the installed bytes;
331
- it is dispatch input, not proof that hooks ran or that a review was independent.
331
+ it is dispatch input, not proof that a review was independent.
332
332
 
333
333
  A new worker reads `.joycraft/preferences.json` before work, reuses explicit
334
334
  model, effort, role, concurrency, verification and question-style choices, and inspects the
@@ -128,7 +128,7 @@ guidance](https://code.claude.com/docs/en/hooks#reference-scripts-by-path).
128
128
 
129
129
  On hosts without that native capability, create an equivalent manual Git linked
130
130
  worktree at an explicit, verified ref. Build each packet from its actual root:
131
- `workerRoot`, manifest path, source paths, hook binding context, commands,
131
+ `workerRoot`, manifest path, source paths, commands,
132
132
  receipts, and report paths must resolve there. A coordinator may not substitute
133
133
  the shared checkout merely because its sources look equivalent.
134
134
 
@@ -2,10 +2,50 @@ import { execFileSync } from 'node:child_process';
2
2
  import { existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import { assertReviewAllowed, visibleReports } from './completion.mjs';
5
6
  import { readLease } from './coordinator.mjs';
6
7
  import { prepareDispatch } from './dispatch-preflight.mjs';
7
8
  import { traceSpec } from './trace.mjs';
8
- import { localPath, readQueue, relativePath, requireValue, validateNativeActor } from './identity.mjs';
9
+ import { canonical, isObject, localPath, readLocal, readQueue, relativePath, requireValue, sha256, snapshot, validateNativeActor } from './identity.mjs';
10
+
11
+ export const reviewLimit = 3;
12
+
13
+ /** A review round is one distinct set of reviewed inputs: each bound input's
14
+ * path and normalized sha256. HEAD is left out (implementationRevision, and so
15
+ * subject.identity), so a commit that changes no input keeps the round. Status
16
+ * is already outside the normalized queue and spec hashes. Returns null for a
17
+ * report with no bound inputs. */
18
+ export function reviewRoundKey(subject) {
19
+ const inputs = subject?.inputs;
20
+ if (!Array.isArray(inputs) || inputs.length === 0
21
+ || !inputs.every(input => isObject(input) && typeof input.path === 'string' && typeof input.sha256 === 'string')) return null;
22
+ const bound = inputs.map(input => ({ path: input.path, sha256: input.sha256 }))
23
+ .sort((left, right) => left.path.localeCompare(right.path, 'en'));
24
+ return `inputs:${sha256(canonical(bound))}`;
25
+ }
26
+
27
+ /** Earlier reviews of one spec, keyed by reviewRoundKey: repeat reviews of one
28
+ * set of inputs are one round. A report with no bound inputs is its own round,
29
+ * keyed by its path. The spec's own accepted PASS report is not a round. Reports
30
+ * are read from the worker root and the coordinator root, where visibleReports
31
+ * looks for them. */
32
+ function earlierReviews({ roots, queuePath, spec }) {
33
+ const rounds = new Map();
34
+ for (const root of roots) {
35
+ for (const { path: file, report } of visibleReports({ root, queuePath, specId: spec.id })) {
36
+ const accepted = spec.acceptedReport;
37
+ if (report.verdict === 'PASS' && accepted?.path === file && sha256(readLocal(root, file)) === accepted.sha256) continue;
38
+ const shown = root === roots[0] ? file : path.join(root, file);
39
+ const key = reviewRoundKey(report.subject) ?? `path:${file}`;
40
+ rounds.set(key, [...(rounds.get(key) ?? []), shown]);
41
+ }
42
+ }
43
+ return rounds;
44
+ }
45
+
46
+ class ReviewLimitError extends Error {
47
+ constructor(message) { super(message); this.exitCode = 2; }
48
+ }
9
49
 
10
50
  // The native hook runtime is optional; without it, startup takes the manual path.
11
51
  async function hookRuntime() {
@@ -40,7 +80,7 @@ export async function startDispatch(options, nativeEvent) {
40
80
  const rel = path.relative(root, parent);
41
81
  requireValue(rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel), 'Packet output parent must stay inside the worker root');
42
82
  requireValue(gitIgnored(root, outPath), `Packet output must be git-ignored so it never becomes a scope path: ${outPath}; use .joycraft/local/packets/`);
43
- const { queue } = readQueue({ root, queuePath: options.queuePath, specId: options.specId });
83
+ const { queue, queuePath, spec, specPath } = readQueue({ root, queuePath: options.queuePath, specId: options.specId });
44
84
  requireValue(options.role === 'implementer' || options.role === 'reviewer', 'Task startup role must be implementer or reviewer');
45
85
  // A claimed queue takes work only from its coordinator, so a second session's
46
86
  // instructions cannot reach this worker. An unclaimed queue keeps 1.0.0 behavior.
@@ -48,9 +88,26 @@ export async function startDispatch(options, nativeEvent) {
48
88
  requireValue(!lease || options.coordinatorSession === lease.sessionId,
49
89
  lease && `Queue ${queue.feature} is coordinated by session ${lease.sessionId}${lease.host ? ` on ${lease.host}` : ''}; pass --coordinator-session ${lease.sessionId} only when that session dispatched this task`);
50
90
  const coordinator = lease ? { sessionId: lease.sessionId, ...(lease.host ? { host: lease.host } : {}) } : null;
91
+ // A spec gets at most three reviews. A done spec keeps its earlier behavior, and
92
+ // a no-review waiver keeps its own refusal, so both are checked first.
93
+ let rounds;
94
+ if (options.role === 'reviewer' && spec.status !== 'done') {
95
+ const roots = [root];
96
+ if (options.coordinatorRoot !== undefined && existsSync(options.coordinatorRoot)) {
97
+ const coordinatorRoot = realpathSync(options.coordinatorRoot);
98
+ if (coordinatorRoot !== root) roots.push(coordinatorRoot);
99
+ }
100
+ for (const each of roots) assertReviewAllowed({ root: each, queuePath });
101
+ rounds = earlierReviews({ roots, queuePath, spec });
102
+ if (rounds.size > reviewLimit || (rounds.size === reviewLimit && !rounds.has(reviewRoundKey(snapshot({ root, queuePath, specId: spec.id }))))) {
103
+ throw new ReviewLimitError(`Review limit reached: ${queue.feature} spec ${spec.id} (${specPath}) has had ${rounds.size} reviews of different reviewed inputs (${[...rounds.values()].flat().join(', ')}); the limit is ${reviewLimit}. Do not start another review. Record the open findings under "## Decision needed" in ${specPath}, leave the spec in-review, and continue with independent ready work.`);
104
+ }
105
+ }
51
106
  // Change scope is opt-in per spec: startup never writes it, and a reviewer
52
107
  // without one reviews against the verification inputs alone.
53
108
  const packet = prepareDispatch({ ...options, outPath: output });
109
+ const review = rounds === undefined ? {}
110
+ : { reviewRound: rounds.size + (rounds.has(reviewRoundKey(packet.subject)) ? 0 : 1), reviewLimit };
54
111
  const runtime = await hookRuntime();
55
112
  const config = runtime ? await runtime.readConfig(root) : { enabled: false };
56
113
  const hooks = config.enabled
@@ -62,7 +119,7 @@ export async function startDispatch(options, nativeEvent) {
62
119
  try { const { criteria, untraced, unknownTags, missingFiles, note } = traceSpec({ root, queuePath: options.queuePath, specId: options.specId }); trace = { criteria, untraced, unknownTags, missingFiles, ...(note ? { note } : {}) }; }
63
120
  catch (error) { trace = { error: error.message }; }
64
121
  }
65
- return { schemaVersion: 1, packetPath: outPath, packet, hooks, coordinator, ...(trace ? { trace } : {}),
122
+ return { schemaVersion: 1, packetPath: outPath, packet, hooks, coordinator, ...review, ...(trace ? { trace } : {}),
66
123
  ready: !config.enabled || hooks.eligible === true };
67
124
  }
68
125
 
@@ -109,5 +166,5 @@ export async function main(argv = process.argv.slice(2)) {
109
166
  }
110
167
 
111
168
  if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
112
- main().catch(error => { process.stderr.write(`Task startup stopped: ${error.message}\n`); process.exitCode = 1; });
169
+ main().catch(error => { process.stderr.write(`Task startup stopped: ${error.message}\n`); process.exitCode = error instanceof ReviewLimitError ? 2 : 1; });
113
170
  }
@@ -0,0 +1,308 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { isObject, localPath, parseJson, readLocal } from './identity.mjs';
5
+ import { accepted, projectStatus } from './status.mjs';
6
+
7
+ // The gate answers one question for a hook, CI or a person: does every done
8
+ // spec carry an acceptance, and do queue and spec frontmatter agree? A held
9
+ // in-review spec is never a failure. Queues written before schemaVersion 1 are
10
+ // skipped, so an old project does not block.
11
+
12
+ function legacySchema(queue) {
13
+ if (!isObject(queue)) return false;
14
+ const version = queue.schemaVersion;
15
+ if (version === undefined || version === null) return true;
16
+ if (typeof version === 'number') return version < 1;
17
+ return typeof version === 'string' && version.trim() !== '' && Number(version) < 1;
18
+ }
19
+
20
+ // A file that does not parse has one next step: repair it and tell the user.
21
+ const repair = (file, problem) => `Joycraft gate: ${file} does not parse: ${String(problem).replace(/\.$/, '')}. Repair ${file} and tell the user.`;
22
+
23
+ // Each drift kind in status.mjs has its own next step. status.mjs --fix repairs
24
+ // only an accepted spec without a pending journal; a pending journal needs
25
+ // completion.mjs recover and stops there; any other drift is set by hand to the queue's status,
26
+ // which is the status authority. An unaccepted done goes back to in-review first.
27
+ const setByHand = "set the spec frontmatter to the queue's status by hand and tell the user.";
28
+ function driftStep(item, { queuePath, pendingJournal }) {
29
+ if (pendingJournal) return `A completion journal is pending. Run node .joycraft/runtime/completion.mjs recover --queue ${queuePath}. If recovery reports a conflict or an invalid journal, stop and tell the user; do not edit a status.`;
30
+ if (item.fixable) return 'The queue records an accepted completion. Run node .joycraft/runtime/status.mjs --fix';
31
+ if (item.queue === 'done') return `The queue's done has no acceptance. First set the queue back to in-review, as the done line for this spec says. Then ${setByHand}`;
32
+ return setByHand[0].toUpperCase() + setByHand.slice(1);
33
+ }
34
+
35
+ function readRaw(root, queuePath) {
36
+ try { return parseJson(readLocal(root, queuePath), queuePath); } catch { return undefined; }
37
+ }
38
+
39
+ /** Gate findings for a project: unaccepted done specs, drift, and current-schema queues that do not parse. */
40
+ export function checkGates(root = process.cwd()) {
41
+ const status = projectStatus({ root });
42
+ const failures = [];
43
+ const skipped = [];
44
+ for (const problem of status.problems) {
45
+ if (problem.queuePath !== undefined) {
46
+ const raw = readRaw(root, problem.queuePath);
47
+ if (legacySchema(raw)) {
48
+ skipped.push({ queuePath: problem.queuePath, schemaVersion: raw.schemaVersion ?? null,
49
+ message: `Joycraft gate: skipped ${problem.queuePath}; ${raw.schemaVersion == null ? 'it has no schemaVersion' : `its schemaVersion ${JSON.stringify(raw.schemaVersion)} predates 1`}.` });
50
+ continue;
51
+ }
52
+ failures.push({ kind: 'queue', queuePath: problem.queuePath, message: repair(problem.queuePath, problem.problem) });
53
+ } else {
54
+ failures.push({ kind: 'spec', file: problem.specPath, message: repair(problem.specPath, problem.problem) });
55
+ }
56
+ }
57
+ for (const feature of status.features) {
58
+ const queue = parseJson(readLocal(root, feature.queuePath), feature.queuePath);
59
+ for (const spec of queue.specs) {
60
+ if (spec.status !== 'done' || accepted(spec)) continue;
61
+ const file = path.posix.join(path.posix.dirname(feature.queuePath), spec.file);
62
+ failures.push({ kind: 'unaccepted-done', feature: feature.feature, specId: spec.id, file, queuePath: feature.queuePath,
63
+ message: `Joycraft gate: ${feature.feature} spec ${spec.id} (${file}) is done with no accepted report, owner acceptance or waiver. `
64
+ + 'Set it back to in-review in the queue and the spec, get an independent review, then complete it with '
65
+ + `node .joycraft/runtime/completion.mjs finalize-review --queue ${feature.queuePath} --spec ${spec.id} --report <report.json>` });
66
+ }
67
+ }
68
+ const owner = new Map(status.features.flatMap(feature => feature.specs.map(row => [row.file, feature])));
69
+ for (const item of status.drift) {
70
+ const step = driftStep(item, owner.get(item.file));
71
+ failures.push({ kind: 'drift', feature: item.feature, specId: item.specId, file: item.file,
72
+ message: `Joycraft gate: ${item.feature} spec ${item.specId} (${item.file}) drifted: queue says ${item.queue}, spec frontmatter says ${item.frontmatter}. ${step}` });
73
+ }
74
+ return { failures, skipped };
75
+ }
76
+
77
+ // The Claude Code Stop hook. `.claude/settings.json` is the user's file: the
78
+ // hook subcommand edits its text in place, so every byte it does not own keeps
79
+ // its value. Joycraft's hook is the one whose command is exactly hookCommand.
80
+ // Claude Code sends the agent back only when a Stop hook exits 2, with the
81
+ // reason on stderr; `check` does that and reads nothing from stdin, so the
82
+ // result is the same when the event says stop_hook_active.
83
+ export const settingsFile = '.claude/settings.json';
84
+ export const hookCommand = 'node "$CLAUDE_PROJECT_DIR"/.joycraft/runtime/gate.mjs check --root "$CLAUDE_PROJECT_DIR"';
85
+ const hookGroup = { hooks: [{ type: 'command', command: hookCommand }] };
86
+ // What `--on` changed, so `--off` restores the earlier bytes when nobody edited the file since.
87
+ const stateFile = '.joycraft/local/gate-hook.json';
88
+
89
+ function claudeHost(root) {
90
+ try {
91
+ const manifest = JSON.parse(readFileSync(path.join(root, '.joycraft/installation.json'), 'utf8'));
92
+ return (Array.isArray(manifest?.hosts) ? manifest.hosts : [manifest?.harness]).includes('claude');
93
+ } catch { return false; }
94
+ }
95
+
96
+ // Offsets of every value in valid JSON text: objects and arrays keep their
97
+ // entries ({ key, start, end, value }) so one entry can be cut or added.
98
+ function locate(text) {
99
+ let index = 0;
100
+ const space = () => { while (index < text.length && /\s/.test(text[index])) index += 1; };
101
+ const string = () => {
102
+ const start = index;
103
+ for (index += 1; text[index] !== '"'; index += text[index] === '\\' ? 2 : 1);
104
+ index += 1;
105
+ return JSON.parse(text.slice(start, index));
106
+ };
107
+ const value = () => {
108
+ space();
109
+ const start = index;
110
+ const open = text[index];
111
+ if (open === '{' || open === '[') {
112
+ const entries = [];
113
+ index += 1;
114
+ space();
115
+ while (text[index] !== (open === '{' ? '}' : ']')) {
116
+ space();
117
+ const entryStart = index;
118
+ let key;
119
+ if (open === '{') { key = string(); space(); index += 1; }
120
+ const item = value();
121
+ entries.push({ key, start: entryStart, end: item.end, value: item });
122
+ space();
123
+ if (text[index] === ',') index += 1;
124
+ space();
125
+ }
126
+ index += 1;
127
+ return { type: open === '{' ? 'object' : 'array', start, end: index, entries };
128
+ }
129
+ if (open === '"') { string(); return { type: 'string', start, end: index }; }
130
+ while (index < text.length && !/[\s,\]}]/.test(text[index])) index += 1;
131
+ return { type: 'literal', start, end: index };
132
+ };
133
+ return value();
134
+ }
135
+
136
+ const member = (node, key) => node.entries.findLast(entry => entry.key === key);
137
+ const isOurs = (text, entry) => {
138
+ const hook = JSON.parse(text.slice(entry.value.start, entry.value.end));
139
+ return isObject(hook) && hook.type === 'command' && hook.command === hookCommand;
140
+ };
141
+
142
+ /** Insert one entry at the end of a container, indented like the file. */
143
+ function insert(text, container, value, key) {
144
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
145
+ const unit = /\n([ \t]+)\S/.exec(text)?.[1] ?? ' ';
146
+ const lineStart = text.lastIndexOf('\n', container.start) + 1;
147
+ const outer = /^[ \t]*/.exec(text.slice(lineStart))[0];
148
+ const inner = outer + unit;
149
+ const entry = `${key === undefined ? '' : `${JSON.stringify(key)}: `}${JSON.stringify(value, null, unit).split('\n').join(eol + inner)}`;
150
+ const last = container.entries.at(-1);
151
+ if (last) return text.slice(0, last.end) + `,${eol}${inner}${entry}` + text.slice(last.end);
152
+ const at = container.start + 1;
153
+ const closing = text.slice(at, container.end - 1).includes('\n') ? '' : eol + outer;
154
+ return text.slice(0, at) + eol + inner + entry + closing + text.slice(at);
155
+ }
156
+
157
+ /** Cut one entry and its separator out of a container. */
158
+ function cut(text, container, index) {
159
+ const { entries } = container;
160
+ if (index > 0) return text.slice(0, entries[index - 1].end) + text.slice(entries[index].end);
161
+ if (entries.length > 1) return text.slice(0, entries[0].start) + text.slice(entries[1].start);
162
+ return text.slice(0, container.start + 1) + text.slice(container.end - 1);
163
+ }
164
+
165
+ function readSettings(root) {
166
+ const file = localPath(root, settingsFile, true);
167
+ const before = existsSync(file) ? readFileSync(file, 'utf8') : null;
168
+ const text = before ?? '{}\n';
169
+ let data;
170
+ try { data = JSON.parse(text.replace(/^/, '')); } catch (error) { throw new Error(`${settingsFile} is not valid JSON (${error.message}); nothing was written`); }
171
+ if (!isObject(data)) throw new Error(`${settingsFile} is not a JSON object; nothing was written`);
172
+ return { file, before, text, data };
173
+ }
174
+
175
+ const hookOn = data => isObject(data.hooks) && Array.isArray(data.hooks.Stop)
176
+ && data.hooks.Stop.some(group => Array.isArray(group?.hooks) && group.hooks.some(hook => hook?.type === 'command' && hook.command === hookCommand));
177
+
178
+ /** The settings text with Joycraft's Stop hook added; change is 'none' when it is already there. */
179
+ export function planHook(root = process.cwd()) {
180
+ const { file, before, text, data } = readSettings(root);
181
+ if (hookOn(data)) return { file, before, after: before, change: 'none' };
182
+ const tree = locate(text);
183
+ const hooks = member(tree, 'hooks');
184
+ let after;
185
+ if (!hooks) after = insert(text, tree, { Stop: [hookGroup] }, 'hooks');
186
+ else if (hooks.value.type !== 'object') throw new Error(`"hooks" in ${settingsFile} is not an object; nothing was written`);
187
+ else {
188
+ const stop = member(hooks.value, 'Stop');
189
+ if (!stop) after = insert(text, hooks.value, [hookGroup], 'Stop');
190
+ else if (stop.value.type !== 'array') throw new Error(`"hooks.Stop" in ${settingsFile} is not an array; nothing was written`);
191
+ else after = insert(text, stop.value, hookGroup);
192
+ }
193
+ return { file, before, after, change: 'add' };
194
+ }
195
+
196
+ /** The settings text with every Joycraft Stop hook removed, and the containers it leaves empty, which `removed` names. */
197
+ function withoutHook(text) {
198
+ const removed = new Set();
199
+ for (;;) {
200
+ const tree = locate(text);
201
+ const hooks = member(tree, 'hooks');
202
+ const stop = hooks?.value.type === 'object' ? member(hooks.value, 'Stop') : undefined;
203
+ if (stop?.value.type !== 'array') return { text, removed: [...removed] };
204
+ const groups = stop.value.entries;
205
+ const groupIndex = groups.findIndex(group => group.value.type === 'object' && member(group.value, 'hooks')?.value.type === 'array'
206
+ && member(group.value, 'hooks').value.entries.some(entry => isOurs(text, entry)));
207
+ if (groupIndex === -1) return { text, removed: [...removed] };
208
+ const list = member(groups[groupIndex].value, 'hooks').value;
209
+ const ours = list.entries.findIndex(entry => isOurs(text, entry));
210
+ if (list.entries.length > 1) text = cut(text, list, ours);
211
+ else if (groups.length > 1) text = cut(text, stop.value, groupIndex);
212
+ else if (hooks.value.entries.length > 1) { text = cut(text, hooks.value, hooks.value.entries.indexOf(stop)); removed.add('the "hooks.Stop" list'); }
213
+ else { text = cut(text, tree, tree.entries.indexOf(hooks)); removed.add('the "hooks.Stop" list').add('the "hooks" object'); }
214
+ }
215
+ }
216
+
217
+ function writeState(root, value) {
218
+ const local = path.join(root, '.joycraft/local');
219
+ mkdirSync(local, { recursive: true });
220
+ if (!existsSync(path.join(local, '.gitignore'))) writeFileSync(path.join(local, '.gitignore'), '*\n');
221
+ writeFileSync(localPath(root, stateFile, true), `${JSON.stringify(value, null, 2)}\n`);
222
+ }
223
+
224
+ function readState(root) {
225
+ try { return JSON.parse(readFileSync(localPath(root, stateFile), 'utf8')); } catch { return null; }
226
+ }
227
+
228
+ const byHand = 'Run the check by hand: node .joycraft/runtime/gate.mjs check';
229
+
230
+ /** `hook --plan|--on|--off`: show, add or remove Joycraft's Stop hook in `.claude/settings.json`. */
231
+ export function hook(root, action) {
232
+ if (action !== 'off' && !claudeHost(root)) {
233
+ return { change: 'none', claude: false,
234
+ message: `The gate hook is for Claude Code only for now, and .joycraft/installation.json lists no claude host. Nothing was written. ${byHand}` };
235
+ }
236
+ if (action === 'off') {
237
+ const { file, before, data } = readSettings(root);
238
+ const state = readState(root);
239
+ if (before === null || !hookOn(data)) {
240
+ if (state) rmSync(localPath(root, stateFile));
241
+ return { file: settingsFile, change: 'none', message: `Joycraft's Stop hook is not in ${settingsFile}. Nothing was changed.` };
242
+ }
243
+ if (state?.after === before) {
244
+ if (state.before === null) rmSync(file); else writeFileSync(file, state.before);
245
+ rmSync(localPath(root, stateFile));
246
+ return { file: settingsFile, change: 'removed', message: `Removed Joycraft's Stop hook from ${settingsFile}. Every other line is as it was.` };
247
+ }
248
+ // No usable record: say what was cut, and claim nothing about the bytes before --on.
249
+ const { text: after, removed } = withoutHook(before);
250
+ writeFileSync(file, after);
251
+ if (state) rmSync(localPath(root, stateFile));
252
+ const empty = removed.length ? ` Without the hook, ${removed.join(' and ')} ${removed.length > 1 ? 'were' : 'was'} empty, so the command removed ${removed.length > 1 ? 'them' : 'it'} too.` : '';
253
+ return { file: settingsFile, change: 'removed', message: `Removed Joycraft's Stop hook from ${settingsFile}.${empty} No other setting was removed.` };
254
+ }
255
+ const plan = planHook(root);
256
+ if (plan.change === 'none') return { file: settingsFile, change: 'none', message: `Joycraft's Stop hook is already in ${settingsFile}. Nothing was changed.` };
257
+ if (action === 'plan') {
258
+ return { file: settingsFile, change: 'add', command: hookCommand, before: plan.before, after: plan.after,
259
+ message: `Plan only; nothing was written. Show this change to the user and run gate.mjs hook --on on their yes.` };
260
+ }
261
+ mkdirSync(path.dirname(plan.file), { recursive: true });
262
+ writeFileSync(localPath(root, settingsFile, true), plan.after);
263
+ writeState(root, { file: settingsFile, before: plan.before, after: plan.after });
264
+ return { file: settingsFile, change: 'added',
265
+ message: `Added Joycraft's Stop hook to ${settingsFile}. Claude Code now runs the gate check each time it ends a reply. Turn it off with: node .joycraft/runtime/gate.mjs hook --off` };
266
+ }
267
+
268
+ export function main(argv = process.argv.slice(2)) {
269
+ const usage = 'Usage: gate.mjs check [--root <project>] [--verbose] | gate.mjs hook --plan|--on|--off [--root <project>]';
270
+ if (argv[0] === 'hook') {
271
+ const actions = { '--plan': 'plan', '--on': 'on', '--off': 'off' };
272
+ let action;
273
+ let root;
274
+ for (let index = 1; index < argv.length; index += 1) {
275
+ if (actions[argv[index]] && action === undefined) { action = actions[argv[index]]; continue; }
276
+ if (argv[index] === '--root' && root === undefined && typeof argv[index + 1] === 'string' && !argv[index + 1].startsWith('--')) {
277
+ root = argv[index + 1]; index += 1; continue;
278
+ }
279
+ throw new Error(usage);
280
+ }
281
+ if (action === undefined) throw new Error(usage);
282
+ const result = hook(path.resolve(root ?? '.'), action);
283
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
284
+ process.exitCode = 0;
285
+ return result;
286
+ }
287
+ if (argv[0] !== 'check') throw new Error(usage);
288
+ const flags = {};
289
+ for (let index = 1; index < argv.length; index += 1) {
290
+ if (argv[index] === '--verbose' && !flags.verbose) { flags.verbose = true; continue; }
291
+ if (argv[index] === '--root' && flags.root === undefined && typeof argv[index + 1] === 'string' && !argv[index + 1].startsWith('--')) {
292
+ flags.root = argv[index + 1]; index += 1; continue;
293
+ }
294
+ throw new Error(usage);
295
+ }
296
+ const result = checkGates(path.resolve(flags.root ?? '.'));
297
+ const lines = [...(flags.verbose ? result.skipped.map(item => item.message) : []), ...result.failures.map(item => item.message)];
298
+ if (lines.length) process.stderr.write(`${lines.join('\n')}\n`);
299
+ process.exitCode = result.failures.length ? 2 : 0;
300
+ return result;
301
+ }
302
+
303
+ // Node runs the main module from its real path; a hook may name it through a symlinked project path.
304
+ const invoked = (() => { try { return realpathSync(process.argv[1]); } catch { return null; } })();
305
+ if (invoked && import.meta.url === pathToFileURL(invoked).href) {
306
+ const prefix = process.argv[2] === 'hook' ? 'Gate hook stopped' : 'Gate check stopped';
307
+ try { main(); } catch (error) { process.stderr.write(`${prefix}: ${error.message}\n`); process.exitCode = 1; }
308
+ }
@@ -20,7 +20,7 @@ function queuePaths(root) {
20
20
  .map(entry => `${featuresHome}/${entry.name}/${queueName}`).sort();
21
21
  }
22
22
 
23
- const accepted = spec => spec.status === 'done' && (isObject(spec.acceptedReport) || isObject(spec.ownerAcceptance) || isObject(spec.waiver));
23
+ export const accepted = spec => spec.status === 'done' && (isObject(spec.acceptedReport) || isObject(spec.ownerAcceptance) || isObject(spec.waiver));
24
24
 
25
25
  function openDecisions(root, folder) {
26
26
  const brief = `${folder}/brief.md`;
package/payload/PIN CHANGED
@@ -1,45 +1,46 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "source": "joycraft-prototype",
4
- "tag": "field-18",
5
- "commit": "880583a33d5c4562b4da02c5897f9ff81cb1edb6",
4
+ "tag": "field-20",
5
+ "commit": "bc63e17a87ae0be86a87a44ac37c685eb72ead0a",
6
6
  "files": {
7
7
  ".agents/skills/joycraft-cleanup/SKILL.md": "99ce785e551be33412ac7a99ce44585a9b2be4440617caac273680383b4f7057",
8
- ".agents/skills/joycraft-context/SKILL.md": "e2f85baa47058fd61811fdb60d0cb41fb3f505f3957812d929db95bb99124f1b",
8
+ ".agents/skills/joycraft-context/SKILL.md": "8eb9374846b8f0d99280217b3fc73cfddac97d72f3ff6f3aca4a86af58dd8b85",
9
9
  ".agents/skills/joycraft-decompose/SKILL.md": "71b518d4fa8aeda5d1c0e72f34b3f7f846b3bba055adf509344b40bea35f070e",
10
- ".agents/skills/joycraft-entry/SKILL.md": "390b0a0b3d4fcbc8c962259abfc490764871266028e49be3479224c8768b9904",
11
- ".agents/skills/joycraft-implement/SKILL.md": "65909a6e3a320d8c0591e10ea1fc26469facadc27dafd3060dd0eabaf06890d9",
10
+ ".agents/skills/joycraft-entry/SKILL.md": "2d9c665416715fb9adb389f57c9d2da97d3d59f577ca4caae9539c6b98cff83b",
11
+ ".agents/skills/joycraft-implement/SKILL.md": "7c7ed88f23103a973f1f275528b8011229d5dec0180910dd98498cff4f6f52c1",
12
12
  ".agents/skills/joycraft-retro/SKILL.md": "156f36cb047604c734bf273bd02822d964b6af86619ed6c2a30fa6d79eb9a986",
13
13
  ".agents/skills/joycraft-retro/agents/openai.yaml": "f0eb4732261635f41e08f0bbe9a931d62fd8ac645149d3406e6fc7e16a81750b",
14
- ".agents/skills/joycraft-session-end/SKILL.md": "e2661af991a72d51036d266b3ebeabcee44d5e602f7b35ea0e40c9c95c171a66",
15
- ".agents/skills/joycraft-testing/SKILL.md": "8c89f3aa996e7de0a0c05d00081a8f24077311c180638abff7aaac9b87f6f89e",
14
+ ".agents/skills/joycraft-session-end/SKILL.md": "e3ef930c1c528f7e6dd6a44a9cb1b352bc8a69d99832ffb1c954a532e036271f",
15
+ ".agents/skills/joycraft-testing/SKILL.md": "aa3b59c380a35a2199646009ccf9be7381edf290d1f07e56994d50b303a6ee12",
16
16
  ".agents/skills/joycraft-ui-slice/SKILL.md": "baf394edc4a31e582cb936c525d8ad28bea42a713ec3114f5921fa7e2bff833f",
17
17
  ".agents/skills/joycraft-ui-slice/scripts/serve.mjs": "c16858800b6fbe6f7a3a21b21e785ad70c9a89a3fe970bc08701fefeac5042fa",
18
- ".agents/skills/joycraft-verify/SKILL.md": "219f08d5f66d6c63338c7d4cc75e81fe7d2d993723728876136ab8ca5ed6f8c5",
18
+ ".agents/skills/joycraft-verify/SKILL.md": "6b3823751765636bae90b253fd8938dfacf96705296212856fe1ff22289e3176",
19
19
  ".claude/agents/joycraft-implementer.md": "30b26779bd49d2d66758bcb26442e78755b018a3830ac52ff634ebf057ce1cc5",
20
20
  ".claude/agents/joycraft-reviewer.md": "d671eb39827d5139d9d458d4cb7f5ce624bd40ec8cc5479f9d285bb787b5e5c6",
21
21
  ".joycraft/assets/artifacts/kit.css": "9c19cc52f16eb1d1beb6222ec4e206c567daf9952ff1f5597ea4d6050b72125a",
22
22
  ".joycraft/assets/artifacts/kit.js": "c60ae4441fb20146677313b27f949598889f40e8b90167b70db04f997854966d",
23
23
  ".joycraft/assets/artifacts/transports.js": "318e97895468b47f07febc913d3a6e100b0ad19b78b3a4fc51bebc488e67c25d",
24
24
  ".joycraft/contracts/types.d.ts": "e91f6a4199c0219cda3630a27ee0281ef94d4284221910840961061ee3b30d4f",
25
- ".joycraft/references/architecture.md": "52eaaa4b88053481c9f8cad2418ea0f1db880184c3a50c95901f30f24be75852",
25
+ ".joycraft/references/architecture.md": "4e225ba23ed72d3d7b1af9bfceeb708583eede79978c294724b917ad94674be9",
26
26
  ".joycraft/references/archive.md": "e9e662096f9e95d132c29e07d1a2624ca0826b5e9c1042f411e4ea2bf3805b67",
27
27
  ".joycraft/references/artifacts.md": "7fab219f6d6d8b23ef3b44a509f637b085b551b34f28622d6dc1167a7f484c6a",
28
28
  ".joycraft/references/cleanup.md": "aa784c63442a289c67de359d82c78abca3aa8cab5b5e2d91fcd731b45c209003",
29
29
  ".joycraft/references/completion.md": "7e6b1fe95aab6d97e514995a35f0f6cc67bdea18e4570565e2eef4900e0da01b",
30
- ".joycraft/references/context.md": "df72d3b59d55f0d9741234d4a3d7b56532f560d787c88d5d8630d954472bc430",
30
+ ".joycraft/references/context.md": "b94dd48a427aaafe826116bac100375cbae565b1ba3239fd7812c56eac724577",
31
31
  ".joycraft/references/delivery.md": "1afc417ee3922ebf5e84c0ae87796d6cb6305679c0257ed38a35f396949de5e8",
32
- ".joycraft/references/dispatch.md": "a1c03473f98b44e88de0d60829b5abc2a11537f53abd1d9c7f84a5a50a140a21",
32
+ ".joycraft/references/dispatch.md": "62e8ad3abf4700f63963fb21a17d03569b78b5100538c10bc37d559679db39b8",
33
33
  ".joycraft/references/doc-cleanup-LICENSE.md": "a9e210590e2d0ebf719fe3801f1c0fda8f940af28656ff36e908c4315d94f886",
34
+ ".joycraft/references/gates.md": "8061e2ecc74b494e21ab77c734d2ae591964af3211c76147bea9f915969c5932",
34
35
  ".joycraft/references/knowledge.md": "a08a117a5d0ae65a45dfd8ab3f3da92dd3c7aeedaa09ae1d71ddf3d6528c7f95",
35
36
  ".joycraft/references/recurring-failures.md": "7080f6c55492bc19c2897f4f0b128a830a71cdb516678c79ff6e97ffa1dc6b86",
36
- ".joycraft/references/retro.md": "f359eae19747777fb4687c1bc7eb280f0319ae629ee62913346e60fc56551562",
37
- ".joycraft/references/settings.md": "7c3e383634ff68522c45460056fd5ef120a5565a62c01f14aac7b060a41804cf",
38
- ".joycraft/references/setup.md": "a9bd9072adc9f021b46287ff0422281ddb2285ac34738b6e29ad11cc60e8a6e5",
37
+ ".joycraft/references/retro.md": "5f24b942f1faf308308caf5d0c543320fedbb69c59c2c240ef979cab50bae211",
38
+ ".joycraft/references/settings.md": "efaa8ea977d7dab9ec011dc0f83f652eb0e7f0098994a89d2d0ee07027b137d6",
39
+ ".joycraft/references/setup.md": "993ae51a753f5d55e13452787fc3f4bfd3df930e0c29730331639007e2ac4812",
39
40
  ".joycraft/references/testing.md": "ddbc0e69212f4bf29f32f65e139c016b12eb40c29f621a99510129bedf292950",
40
41
  ".joycraft/references/update.md": "36af36ab3d47b5ea46a8f71090333771e5e1deaa6ca19739a75c9fd4aea14eba",
41
42
  ".joycraft/references/workflow.md": "5b330debc6759b8f7975b159632f51074802067291fe4f4bebfb344f5b60cc52",
42
- ".joycraft/references/worktrees.md": "fb18af0cd76d4e3c5d5b892a7ae10946f21f189e642243235c188b571635f735",
43
+ ".joycraft/references/worktrees.md": "ad5645d2811e59da682c03f1cbdd1fb15abcc094fba74542c848548033890dba",
43
44
  ".joycraft/runtime/archive.mjs": "82b4d9567942a4abd21594ea299c4d323a8306ec7545cb0030431c87bd37f8b2",
44
45
  ".joycraft/runtime/artifacts/cli.mjs": "b3472857b6f8f680dc0d8a7be6495c502a430f5d0c47c88d44b42217e541b528",
45
46
  ".joycraft/runtime/artifacts/decisions.mjs": "e54fe173ca9050d495fd20b05aaedee8c918f3074553b6b7292cb40f500cbcb2",
@@ -56,8 +57,9 @@
56
57
  ".joycraft/runtime/coordinator.mjs": "9252a40ee3a82808a780158427b02129d8075679ed329bce2dd74168c7eb42ab",
57
58
  ".joycraft/runtime/delivery.mjs": "4fe897714eec33b24003f0d69abe1522a5199193ab7333fa6421776ee048df1c",
58
59
  ".joycraft/runtime/dispatch-preflight.mjs": "a86736e013dcca9f1f8a2ab1abd42cb81e614373b2140b272ca6ac91a0525d34",
59
- ".joycraft/runtime/dispatch-start.mjs": "b8d27b53566062c79cb95bf3f89bcb3e4abc9dd9dc15612cfced8685cf3a1c41",
60
+ ".joycraft/runtime/dispatch-start.mjs": "fd3654e78cd5db9ada013ed95ea9259d53725e41bcee399ce2cb1a7d9e54a579",
60
61
  ".joycraft/runtime/evidence.mjs": "ee5bec5c9e5f1372a994a899b8161ff88d96a1d0ccf552d75de87a61c1c04bd3",
62
+ ".joycraft/runtime/gate.mjs": "c714f50f9c228cf45455976ac1e8a1d91fe3f478f4f9743b9e24d87ced232da2",
61
63
  ".joycraft/runtime/identity.mjs": "9854974dfb24f4469668e4db0dd6d2279bb2298157ff6262bb7864ef8e9ad174",
62
64
  ".joycraft/runtime/kickoff.mjs": "9d96998bff94662863182b9a922f26732c649b7a0b0130b6da7d63ec73eb3590",
63
65
  ".joycraft/runtime/redact.mjs": "cc8c0fe5e8d8fe78116ef126f6eee757a247739084e19c342bcf09a2b06524bc",
@@ -65,7 +67,7 @@
65
67
  ".joycraft/runtime/review-tools.json": "e0b0f5625654bba5f02d49710356aa1740fd42dd282eef6a29af361396915763",
66
68
  ".joycraft/runtime/review-tools.mjs": "15d426558a3884628147debb29136a20f746c3f184c52d6474ad59c222e5d8d5",
67
69
  ".joycraft/runtime/scope.mjs": "e2cdd929596246bf24e18850698db440119badc7068a3c5beab03ded45abbd65",
68
- ".joycraft/runtime/status.mjs": "3c5bc62c2c0b440da37af950c28f9278c1f743ff4566d3b6c5685465075239af",
70
+ ".joycraft/runtime/status.mjs": "916cd7e839a90878e0ffa4dd2e7367575ec541808293b5b377bf39331f727585",
69
71
  ".joycraft/runtime/trace.mjs": "b7924f759b07991f4135698df9c32654631a325957f0f8de5c2ca1262c0a836a",
70
72
  ".joycraft/runtime/update-check.mjs": "987b65605a26ea71b6417fda7b48753980e0d8afa20eadbd527143850a93319e",
71
73
  ".joycraft/runtime/wiring.mjs": "e08bcc604d40560f260edbc3499a4481a1efa7c7d2fa80545caa858827404667",
@@ -79,7 +81,7 @@
79
81
  ".joycraft/templates/queue.json": "88f922b6cc47b80befc27df86a143d6bae0b30869c46d712958b64291e5ebcc2",
80
82
  ".joycraft/templates/spec.md": "5f4b1490c2ba2e47ced1ef5b369fe3e41386eb61386c42c7a561b1e8af02ea5e",
81
83
  ".joycraft/templates/ui-slice.html": "0c3cf45709ff37815f8f0550b4b9431cb935589b282d40e8688b310a91de2274",
82
- "scripts/export.mjs": "016d675b19ba3122468ce34817b8a9c444be919aa4ec583842cd9bc16d299243",
84
+ "scripts/export.mjs": "085433a46d9bba37685d52611c881a1c4891c38d607453c6cbd47acb629054f8",
83
85
  "scripts/hook-paths.mjs": "fed8a147a9bf6501bfda1e4c7f015b41947277920dc2bf49c23ad826cfb0c724",
84
86
  "scripts/legacy-hooks.mjs": "d44f841e28d10b0a6aacf999bdd3e8bcec0feb742fa18c7459d6265d1d4776ba",
85
87
  "scripts/legacy-inventory.json": "92455cceac13cc8bd27a0cbd5c16df71a44a82bf7a18280f5ba05b5dde2908ba"
@@ -191,8 +191,11 @@ export async function exportBundle({ sourceRoot, targetRoot, check = false, hook
191
191
  const bytes = await readFile(join(source, path));
192
192
  return harness === 'claude' && path.endsWith('.md') ? Buffer.from(bytes.toString('utf8').replaceAll('.agents/skills/', '.claude/skills/')) : bytes;
193
193
  };
194
- // Native hooks are optional; their installer loads only when hooks are requested.
195
- const hookInstaller = hooks ? await import('./install-hooks.mjs') : null;
194
+ // Native hooks are optional and not part of every bundle. Their installer
195
+ // loads only when hooks are requested and it is present beside this script.
196
+ const hookInstallerUrl = new URL('./install-hooks.mjs', import.meta.url);
197
+ if (hooks && !(await statOrNull(fileURLToPath(hookInstallerUrl)))) throw new Error('Native hooks are not part of this bundle; export with --without-hooks');
198
+ const hookInstaller = hooks ? await import(hookInstallerUrl) : null;
196
199
  if (hooks && !files.includes(hookInstaller.hookRuntimePath)) throw new Error('The source bundle has no hook runtime');
197
200
  const installed = await readInstallationManifest(target);
198
201
  const legacy = upgrade ? await legacyPlan(target, installed, new Set(files.map(destinationPath))) : { archive: [], conflicts: [] };