joycraft 1.0.0 → 1.1.0

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 (30) hide show
  1. package/README.md +54 -0
  2. package/dist/joycraft-release.json +1 -1
  3. package/package.json +3 -3
  4. package/payload/.agents/skills/joycraft-cleanup/SKILL.md +41 -0
  5. package/payload/.agents/skills/joycraft-entry/SKILL.md +10 -0
  6. package/payload/.agents/skills/joycraft-implement/SKILL.md +14 -2
  7. package/payload/.agents/skills/joycraft-session-end/SKILL.md +10 -4
  8. package/payload/.agents/skills/joycraft-verify/SKILL.md +4 -0
  9. package/payload/.claude/agents/joycraft-implementer.md +7 -1
  10. package/payload/.claude/agents/joycraft-reviewer.md +9 -0
  11. package/payload/.joycraft/references/archive.md +17 -0
  12. package/payload/.joycraft/references/cleanup.md +35 -0
  13. package/payload/.joycraft/references/context.md +5 -0
  14. package/payload/.joycraft/references/dispatch.md +6 -1
  15. package/payload/.joycraft/references/setup.md +30 -1
  16. package/payload/.joycraft/references/testing.md +10 -0
  17. package/payload/.joycraft/references/workflow.md +5 -0
  18. package/payload/.joycraft/references/worktrees.md +26 -0
  19. package/payload/.joycraft/runtime/archive.mjs +35 -15
  20. package/payload/.joycraft/runtime/cleanup.mjs +149 -0
  21. package/payload/.joycraft/runtime/config.mjs +191 -0
  22. package/payload/.joycraft/runtime/context/search.mjs +5 -3
  23. package/payload/.joycraft/runtime/coordinator.mjs +169 -0
  24. package/payload/.joycraft/runtime/dispatch-start.mjs +18 -3
  25. package/payload/.joycraft/runtime/review-tools.json +7 -0
  26. package/payload/.joycraft/runtime/status.mjs +97 -0
  27. package/payload/.joycraft/runtime/trace.mjs +79 -0
  28. package/payload/.joycraft/runtime/worktrees.mjs +201 -0
  29. package/payload/.joycraft/templates/joycraft.yaml +19 -0
  30. package/payload/PIN +28 -19
package/README.md CHANGED
@@ -49,6 +49,9 @@ bigger than one quick change:
49
49
  installed those tools in step 4 of the install.
50
50
  5. **The agent wraps up.** It records what it learned for the next session.
51
51
 
52
+ You do not need to call the Joycraft skills by name. Describe the work and the agent
53
+ picks the right step.
54
+
52
55
  On a new, empty project, the agent first asks what you want to build. It writes your
53
56
  answers to `docs/context/project.md`. It does not choose a stack or write app code at
54
57
  this step.
@@ -75,6 +78,57 @@ You can feed it too. Give your agent meeting notes, a photo of a whiteboard or a
75
78
  screenshot, and ask it to add what matters to the project context. This gives the
76
79
  agent both views: the whole project and the detail of the current step.
77
80
 
81
+ ### What in `docs/` is current
82
+
83
+ - **`docs/context/` is current.** It holds what the project is and the decisions you
84
+ made. The agent keeps it up to date.
85
+ - **`docs/features/` is working material.** Briefs and specs record the plan for one
86
+ piece of work. They can be out of date while the work runs. The spec queue
87
+ (`.joycraft-spec-queue.json`) is the status of record, not the text.
88
+ - **`docs/archive/` is history.** Finished features move there.
89
+
90
+ Joycraft does not ship a wiki. If you keep one, link it from the context map, and
91
+ treat `docs/features/` and `docs/archive/` as non-authoritative in your doc audits.
92
+
93
+ ### Settings: `joycraft.yaml`
94
+
95
+ Joycraft works with no settings. To change its folders, run a command after a
96
+ feature is archived, or tell cleanup which code each context page describes, add a
97
+ `joycraft.yaml` at the project root (template: `.joycraft/templates/joycraft.yaml`):
98
+
99
+ ```yaml
100
+ paths:
101
+ features: working/features # default docs/features
102
+ archive: working/archive # default docs/archive
103
+ hooks:
104
+ afterArchive: node scripts/wiki-sync.mjs
105
+ cleanup:
106
+ impact:
107
+ - source: src/auction/**
108
+ docs: [docs/context/auction-rules.md]
109
+ ```
110
+
111
+ The file is yours: Joycraft reads it and never rewrites it.
112
+
113
+ ### Keeping the workspace clean
114
+
115
+ At the end of a session the agent runs three checks for you:
116
+
117
+ - `node .joycraft/runtime/status.mjs` finds specs whose text disagrees with the queue,
118
+ and features that are finished but not archived.
119
+ - `node .joycraft/runtime/worktrees.mjs prune` removes the agent's worker worktrees
120
+ once their spec is done and merged. It keeps anything unfinished, unmerged or not
121
+ made by Joycraft, and says why. `worktrees.mjs list` shows what is left and its size.
122
+ - `node .joycraft/runtime/coordinator.mjs` keeps one coordinating session per queue,
123
+ so a second session's instructions do not reach the first session's workers.
124
+ - `node .joycraft/runtime/cleanup.mjs` reports stale or unreachable project
125
+ knowledge: finished features not archived, context pages that link to working
126
+ material, broken or orphaned pages, and pages whose code changed. Ask your agent
127
+ to "clean up the docs" and it shows the fixes for your approval.
128
+
129
+ Tests name the acceptance criterion they check, `[AC:<criterion-id>]`, so the
130
+ reviewing agent can see which criteria have a test.
131
+
78
132
  ## Answering questions: the decision page
79
133
 
80
134
  When the agent needs you to choose between options, it shows the questions on a
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "releaseVersion": "1.0.0",
3
+ "releaseVersion": "1.1.0",
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.0.0",
3
+ "version": "1.1.0",
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.0.0",
17
- "summary": "A new one-loop workflow with independent review. Moving from 0.7 is a migration you choose and can undo.",
16
+ "release": "1.1.0",
17
+ "summary": "Adds joycraft.yaml (folders, an after-archive hook, a code-to-docs map), joycraft-cleanup for stale docs, and [AC:id] test tags the reviewer traces.",
18
18
  "autoSafeEligible": false
19
19
  },
20
20
  "scripts": {
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: joycraft-cleanup
3
+ description: Find stale or unreachable project knowledge (finished features left in the working folder, context pages that link to working material, broken or orphaned pages, pages whose code changed, leftover worktrees) and fix what the user approves.
4
+ compatibility: Requires Node.js 22+ and the installed .joycraft runtime. Git improves the code-drift and worktree checks.
5
+ ---
6
+
7
+ # Joycraft Cleanup
8
+
9
+ Use when the user asks to clean up docs, remove stale material or check that
10
+ project knowledge is current, and at session end when `status.mjs` or the
11
+ archive step leaves loose ends. It keeps the context home trustworthy; it does
12
+ not change product decisions.
13
+
14
+ Run the report from the project root:
15
+
16
+ ```sh
17
+ node .joycraft/runtime/cleanup.mjs
18
+ ```
19
+
20
+ Exit 0 means no findings; exit 2 means findings. The script reads
21
+ `joycraft.yaml` for `paths` and the `cleanup.impact` map (code globs → context
22
+ pages) and never edits a file. Read `.joycraft/references/cleanup.md` for each
23
+ check and its usual fix.
24
+
25
+ Then, for each finding:
26
+
27
+ 1. Read the files it names before proposing anything. For `impact-drift`,
28
+ read the listed commits' changes and the page; the page may still be true.
29
+ 2. Propose one concrete fix per finding: the exact link, page, section or
30
+ command. Group findings by fix, not by check.
31
+ 3. Show the proposals to the user as a rendered page (the decision artifact for
32
+ choices, or an HTML page), never only as Markdown in chat. Ask once.
33
+ 4. Apply only what the user approves. Move durable facts into the context home
34
+ before an archive. Archive only through the session-end archive path. Remove
35
+ an unknown worktree only after checking it for unmerged work and with the
36
+ user's approval.
37
+ 5. Run the report again and give the remaining findings with their reasons.
38
+
39
+ Never delete a context page to clear a finding; merge or redirect it. Do not
40
+ invent facts to refresh a stale page: when the code does not settle it, record
41
+ the question in the owning brief.
@@ -68,6 +68,16 @@ options, and saves the answers to the brief. Plain chat is only for one quick
68
68
  yes/no or an open question with no options. If you already asked option
69
69
  questions in chat and they are unanswered, move them to an artifact now.
70
70
 
71
+ **Use the project's folders.** If `joycraft.yaml` exists, run
72
+ `node .joycraft/runtime/config.mjs` and use its `paths` wherever Joycraft guidance
73
+ says `docs/features`, `docs/archive` or `docs/context`.
74
+
75
+ **Show documents as pages.** A brief, plan, spec set or review that the user must
76
+ read or approve is also rendered, never left as Markdown in chat: the decision
77
+ artifact for a brief, an HTML page for anything else. Open it and say where it is.
78
+ If the project's `AGENTS.md` lacks this rule or its context-map row for
79
+ `.joycraft/references/artifacts.md`, add them as `setup.md` describes.
80
+
71
81
  For a request to keep an artifact theme or colors from now on, record
72
82
  `artifacts.theme` or `artifacts.colors` in that project's
73
83
  `.joycraft/preferences.json` with the artifact CLI and add one link to the
@@ -37,8 +37,20 @@ report why, and continue unrelated authorized or manual/disabled workflow.
37
37
 
38
38
  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
39
 
40
+ Before the first dispatch, claim the queue as its coordinator with your actual
41
+ host session ID, and pass that ID as `--coordinator-session` to every startup:
42
+
43
+ ```sh
44
+ node .joycraft/runtime/coordinator.mjs claim --queue <queue> --session <your-session-id> --host <host>
45
+ ```
46
+
47
+ If another session holds the queue, stop and report the holder; take it over
48
+ with `--take-over` only when the user says that session has ended.
49
+
40
50
  For a spec marked `execution.parallel: true`, use a separate linked worktree for
41
- each concurrent mutator, including its build/cache state. Its first action is
51
+ each concurrent mutator, including its build/cache state. Create it with
52
+ `node .joycraft/runtime/worktrees.mjs create --queue <queue> --spec <id> --session <your-session-id>`
53
+ when the host has no native worktree isolation; never invent another folder. Its first action is
42
54
  the documented project bootstrap, before edits, stateful runtime work, or packet
43
55
  preparation. Dispatch from its actual root. Read [worker isolation](../../../.joycraft/references/worktrees.md)
44
56
  when parallel work, integration, cleanup, or resource capacity is in play. If
@@ -46,7 +58,7 @@ isolation cannot be obtained, replan the affected wave and set the current
46
58
  queue entry's `execution.parallel` to `false` before dispatch, recording why;
47
59
  then run it serially. Otherwise leave it unstarted.
48
60
 
49
- Implement the spec and run meaningful checks and any relevant rendered inspection during implementation. Do not defer ordinary checks to the batch boundary. Run each test command once in single-run mode with `CI=1` and a 300000 ms timeout; follow [running tests](../../../.joycraft/references/testing.md#running-tests) when one times out. Write one focused test per acceptance `Check:`, from the spec rather than the code; if a criterion or test looks wrong, report a spec gap instead of editing it to pass. When the implementation is finished, update both the queue entry and the spec's top-level frontmatter `status:` to `in-review` together. A passing test suite, commit, or empty ready set does not accept the work.
61
+ Implement the spec and run meaningful checks and any relevant rendered inspection during implementation. Do not defer ordinary checks to the batch boundary. Run each test command once in single-run mode with `CI=1` and a 300000 ms timeout; follow [running tests](../../../.joycraft/references/testing.md#running-tests) when one times out. Write one focused test per acceptance `Check:`, from the spec rather than the code, and tag it with its queue criterion ID as `[AC:<criterion-id>]` in the test name or a comment; if a criterion or test looks wrong, report a spec gap instead of editing it to pass. When the implementation is finished, update both the queue entry and the spec's top-level frontmatter `status:` to `in-review` together. A passing test suite, commit, or empty ready set does not accept the work.
50
62
 
51
63
  Honor the queue's commit mode. In `batch`, commit and review the independent ready
52
64
  wave at its boundary before advancing its dependents; do not wait for an entire
@@ -29,10 +29,16 @@ If a completion operation failed or was interrupted, do not declare success or h
29
29
 
30
30
  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
31
 
32
- Before ending the session, retain failed or blocked worker trees and their
33
- diagnostic state. Release worker trees and project-owned resource leases only
34
- after their changes are integrated and accepted through the required review and
35
- completion path. See [worker isolation](../../../.joycraft/references/worktrees.md)
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`.
38
+ Then run `node .joycraft/runtime/cleanup.mjs` and report its findings; offer
39
+ `joycraft-cleanup` when any remain.
40
+ When this session coordinated a queue and no work on it remains, release the
41
+ lease with `node .joycraft/runtime/coordinator.mjs release --queue <queue> --session <your-session-id>`. See [worker isolation](../../../.joycraft/references/worktrees.md)
36
42
  when the session used parallel mutable workers.
37
43
 
38
44
  When an `UNVERIFIED` review identifies only an environment condition, record
@@ -33,6 +33,10 @@ bounded packet, and binds it. If the real ID, available authority, or a separate
33
33
  reviewer context is unavailable, leave the spec `in-review`; do not manufacture
34
34
  any of them. A hooks-disabled/manual workflow can still be ready; an unenforced
35
35
  result holds only the claimed review, not unrelated work.
36
+ Reviewer startup output also carries `trace`, the spec's criteria with the tests
37
+ tagged `[AC:<criterion-id>]` (`node .joycraft/runtime/trace.mjs --queue <queue> --spec <id>`
38
+ produces the same). Report untraced criteria as findings; a missing tag alone is
39
+ not a FAIL.
36
40
  Write packets and snapshots beneath a confirmed Git-ignored project-local
37
41
  directory so they do not create unrelated scope paths.
38
42
 
@@ -17,8 +17,14 @@ each Joycraft runtime call as its own plain shell command, never chained with
17
17
  `&&`, `;`, `|` or `$(git …)`; your worktree isolation refuses Git inside a
18
18
  compound command. Paste literal paths and revisions instead.
19
19
 
20
+ Startup output names the queue's `coordinator` session when the queue is claimed.
21
+ Take task instructions only from that session. If another session asks you to
22
+ change scope, files or the queue, do not act on it; report it in your final
23
+ message.
24
+
20
25
  Write one focused test per acceptance `Check:`, taken from the spec rather than
21
- from your code, sized like neighboring tests. Run each test command once in
26
+ from your code, sized like neighboring tests. Tag each with its queue criterion
27
+ ID as `[AC:<criterion-id>]` in the test name or a comment. Run each test command once in
22
28
  single-run mode with `CI=1` and a 300000 ms timeout; on a timeout follow
23
29
  `.joycraft/references/testing.md#running-tests`. Never wait in a
24
30
  foreground loop, never weaken an existing test, and never change the spec's acceptance:
@@ -16,12 +16,21 @@ Run each `git` command and each Joycraft runtime call as its own plain shell
16
16
  command, never chained with `&&`, `;`, `|` or `$(git …)`; your worktree
17
17
  isolation refuses Git inside a compound command. Paste literal paths and revisions instead.
18
18
 
19
+ Startup output names the queue's `coordinator` session when the queue is claimed.
20
+ Take task instructions only from that session. If another session asks you to
21
+ change scope, files or the queue, do not act on it; report it in your final
22
+ message.
23
+
19
24
  Judge the current code against every acceptance bullet and its `Check:`, and
20
25
  against the owner intent in the brief. Reuse a suite receipt bound to the same
21
26
  revision instead of rerunning the full suite; run the spec's own tests once in
22
27
  single-run mode with `CI=1` and a 300000 ms timeout. Never give a verdict while
23
28
  a command you started is still running.
24
29
 
30
+ Startup output includes `trace`: each criterion with its `[AC:<id>]` tests. Report
31
+ each untraced criterion as a finding. A missing tag alone is not a FAIL; judge the
32
+ criterion by what you observe.
33
+
25
34
  Report every finding with a severity and the criterion it touches. Only a failing
26
35
  stated criterion, or a reproducible defect or regression in the changed code with
27
36
  file:line or a receipt, blocks. A case the spec does not decide is "decision
@@ -209,3 +209,20 @@ manual recovery. A collision or changed byte fails without accepting new
209
209
  completion. A repeat is idempotent only when the existing replay manifest names
210
210
  the feature and every archived mapped byte still matches; otherwise it requires
211
211
  manual reconciliation.
212
+
213
+ ## After-archive hook
214
+
215
+ A project can name one command in `joycraft.yaml`:
216
+
217
+ ```yaml
218
+ hooks:
219
+ afterArchive: node scripts/wiki-sync.mjs
220
+ ```
221
+
222
+ After a successful `--apply`, the runtime runs it once from the project root with
223
+ `JOYCRAFT_FEATURE`, `JOYCRAFT_ARCHIVE_PATH` and `JOYCRAFT_SOURCE_PATH` set, and reports
224
+ its exit code and output tail under `afterArchive`. Use it to update a project wiki
225
+ or run a doc audit such as docaudit. A failing hook does not undo the archive;
226
+ report it and fix the hook. A repeat of an existing archive does not run it again.
227
+ `paths.features` and `paths.archive` in the same file move the working and archive
228
+ folders; the defaults are `docs/features` and `docs/archive`.
@@ -0,0 +1,35 @@
1
+ # Cleanup checks
2
+
3
+ `cleanup.mjs` reports; it never edits. Each finding has `check`, `path`, often
4
+ `line`, a `detail` and a suggested `fix`. `skipped` lists checks it could not run.
5
+
6
+ | Check | Finds | Usual fix |
7
+ |---|---|---|
8
+ | `unarchived` | A feature whose specs are all `done` but is still in `paths.features` | Carry durable facts into the context home, then archive at session end |
9
+ | `status-drift` | Spec frontmatter that disagrees with the queue | `status.mjs --fix` for accepted done specs; otherwise reconcile by hand |
10
+ | `working-link` | `AGENTS.md`, `CLAUDE.md` or a context page linking into `paths.features` or `paths.archive` | Move the fact into the context home and link that |
11
+ | `broken-link` | A Markdown link to a file that does not exist | Fix or remove the link |
12
+ | `orphan` | A context page that nothing in `AGENTS.md`, `CLAUDE.md` or the context home mentions | Add a context-map row with a "read when", or merge the page |
13
+ | `impact-drift` | A page mapped in `cleanup.impact` whose code changed in commits after the page last changed | Read the change; update the page, or commit it unchanged when still true |
14
+ | `stale-after` | An OKF `stale_after` date that has passed | Recheck, then move the date or mark the page `deprecated` |
15
+ | `deprecated-link` | A link to a page marked `status: deprecated` | Link the current page |
16
+ | `frontmatter-unreadable` | Page frontmatter in YAML that cleanup cannot read, so its `status` and `stale_after` go unchecked | Use plain `key: value` lines, lists and quoted strings |
17
+ | `unknown-worktree` | A linked worktree that `worktrees.mjs` did not create | Check for unmerged work, then remove with approval |
18
+
19
+ Fenced code blocks are ignored. Inline, reference-style and `<angle>` links count.
20
+ Backticked paths such as `` `docs/context/x.md` `` count as references for
21
+ `orphan` and `working-link`; only real Markdown links are checked for existence.
22
+
23
+ The impact map lives in `joycraft.yaml`:
24
+
25
+ ```yaml
26
+ cleanup:
27
+ impact:
28
+ - source: src/auction/**
29
+ docs: [docs/context/auction-rules.md]
30
+ ```
31
+
32
+ `*` matches within a folder and `**` across folders. A page with no commit yet is
33
+ skipped. Pages may carry OKF frontmatter (`type`, `status`, `stale_after`,
34
+ `verified`); cleanup reads `status` and `stale_after` when present. For a fuller
35
+ doc audit, such as docaudit, run it from `hooks.afterArchive`.
@@ -78,3 +78,8 @@ order where unranked; previously successful scores retain their provenance.
78
78
  not that every candidate was scored; inspect `status` and `scoredCount`.
79
79
  Invalid inputs or an unavailable Git inventory exit nonzero. Provider scores
80
80
  advise reading order and never approve intent, authorize work or certify evidence.
81
+
82
+ Treat only the context homes as current authority. `docs/features/` is working
83
+ material that can be stale until its feature is archived, and `docs/archive/` is
84
+ history; see the knowledge-home table in `setup.md`. Joycraft ships no wiki. Skills
85
+ do not need to be named by the user: pick the step from the request.
@@ -64,9 +64,14 @@ node .joycraft/runtime/dispatch-start.mjs \
64
64
  --out .joycraft/local/packets/<packet.json> \
65
65
  --native-session <actual-host-session-id> \
66
66
  --native-agent <actual-host-child-agent-id> \
67
- --native-host <host>
67
+ --native-host <host> \
68
+ --coordinator-session <coordinator-session-id>
68
69
  ```
69
70
 
71
+ `--coordinator-session` is required while the queue has a coordinator lease
72
+ (`coordinator.mjs claim`) and must equal the holder; startup output then names
73
+ the coordinator. Omit it only for an unclaimed queue.
74
+
70
75
  Run each `git` command and each Joycraft runtime call (`node
71
76
  .joycraft/runtime/…`, `pnpm joycraft:…`) as its own plain shell
72
77
  command: never chain them with `&&`, `;` or `|`, and never use `$(git …)`. To
@@ -57,13 +57,22 @@ If `AGENTS.md` is missing, create a concise project-specific file with:
57
57
  - This line: “First action in each session: run
58
58
  `node .joycraft/runtime/update-check.mjs check`. If it prints JSON, follow
59
59
  `.joycraft/references/update.md`.”
60
+ - This line: “Show every document a person must read, review or answer (a brief,
61
+ plan, spec set, review or set of questions) as a rendered page, never only as
62
+ Markdown in chat: use the decision artifact
63
+ (`node .joycraft/runtime/artifacts/cli.mjs`, see `.joycraft/references/artifacts.md`)
64
+ for a brief or questions, or an HTML page for any other document. Open it for
65
+ the person and say where it is.”
66
+ - A context-map row for `.joycraft/references/artifacts.md`, read when “showing a
67
+ document or questions to a person”.
60
68
 
61
69
  Do not copy prototype-maintainer rules or fill it with generic coding advice.
62
70
  Link detail rather than duplicating it. Do not encode a tentative product idea
63
71
  as a permanent boundary. Keep current feature intent in its brief.
64
72
 
65
73
  If `AGENTS.md` already exists, preserve its content and add only missing facts,
66
- useful context pointers and the update-check line above with a targeted edit. Reuse an existing context map
74
+ useful context pointers, the update-check line, the rendered-documents line and its
75
+ context-map row above with a targeted edit. Reuse an existing context map
67
76
  rather than adding another. Read linked content before deciding it is missing.
68
77
  When its map names a project-context home, use that exact project-relative home;
69
78
  use `docs/context/project.md` only when no context home exists. Do not link a
@@ -169,6 +178,13 @@ its UI claims stay `UNVERIFIED`. With no network, the probes still run; offer
169
178
  the install later. For a CI-only project, record the CI job as the evidence
170
179
  source when the user picks it.
171
180
 
181
+ `review-tools.json` also lists `optIn` tools that detection never plans. Offer
182
+ one only when it fits the project. Example: Doc Detective, for docs that are
183
+ step-by-step procedures. Say what it does not cover and that it is AGPL-3.0 with a
184
+ large browser download, and install nothing without the user's yes. Record an
185
+ accepted opt-in tool in the `## Review loop` section by hand, with its evidence
186
+ command.
187
+
172
188
  ## Project-owned worktrees
173
189
 
174
190
  For an observed Git project with a parallel-worker preference, keep bootstrap
@@ -232,6 +248,19 @@ Create additional homes only when they have content:
232
248
  | Current feature or mixed change | `docs/features/<slug>/brief.md` |
233
249
  | Authorized implementation queue | `docs/features/<slug>/specs/` |
234
250
 
251
+ A project can move these folders, add an after-archive hook and map code to
252
+ context pages in an optional root `joycraft.yaml`. It is project-owned: create it
253
+ from `.joycraft/templates/joycraft.yaml` only when the user wants one of those
254
+ settings, and never overwrite it. `node .joycraft/runtime/config.mjs` prints the
255
+ settings in effect.
256
+
257
+ Only the context homes are current project knowledge. `docs/features/` is working
258
+ material: a brief or spec there can be out of date until the feature is archived,
259
+ and `docs/archive/` is history. Context retrieval and any project wiki or doc audit
260
+ should treat both as non-authoritative and must not link to them as current
261
+ truth. Joycraft ships no wiki; a project that keeps one keeps it in its own home
262
+ and links it from the context map.
263
+
235
264
  The brief retains decision authority under `workflow.md`; the context document
236
265
  and decision log must not become competing answer stores. Later accepted facts
237
266
  update their existing home. Repeating entry with no new knowledge should make
@@ -118,3 +118,13 @@ does not automatically belong in CI. Diagnose an environment-only UNVERIFIED
118
118
  result as an environment limitation, repair that setup, and rerun the affected
119
119
  review; do not send unchanged code through a speculative fix round. A genuine
120
120
  test race still needs a code/test diagnosis, not just a longer timeout.
121
+
122
+ ## Criterion tags
123
+
124
+ Tag each acceptance test with its queue criterion ID, `[AC:<criterion-id>]`, in the
125
+ test name or a comment, in any language. `trace.mjs --queue <queue> --spec <id>`
126
+ lists each criterion with its tagged tests from the spec's `check` inputs (add
127
+ `--tests <glob>` for undeclared files) and exits 2 while a criterion is untraced.
128
+ Reviewer startup includes the same trace. A tag shows that a test claims the
129
+ criterion; it does not show that the test is right. Write the test from the spec
130
+ text before reading the implementation.
@@ -74,6 +74,11 @@ another route.
74
74
 
75
75
  ## Commitment and queue
76
76
 
77
+ Folder names in this guidance are defaults. A project's `joycraft.yaml` can move
78
+ `paths.features`, `paths.archive` and `paths.context`; run
79
+ `node .joycraft/runtime/config.mjs` once per session and use the folders it prints
80
+ wherever a skill or reference says `docs/features`, `docs/archive` or `docs/context`.
81
+
77
82
  Use `docs/features/<slug>/specs/.joycraft-spec-queue.json` and the exact shapes in
78
83
  `.joycraft/contracts/types.d.ts`. Only `todo`, `in-review`, `done` are
79
84
  spec statuses, mirrored in spec frontmatter. Open or unknown decision state blocks
@@ -45,6 +45,32 @@ integration boundary make that safe. Record durable coordinator ownership and
45
45
  the captured refs before dispatch or restart, so recovery can distinguish this
46
46
  run's resources from another session's.
47
47
 
48
+ ## Commands
49
+
50
+ `worktrees.mjs` is the one home for worker trees on hosts without native
51
+ worktree isolation:
52
+
53
+ ```sh
54
+ node .joycraft/runtime/worktrees.mjs create --queue <queue> --spec <id> --session <coordinator-session>
55
+ node .joycraft/runtime/worktrees.mjs list
56
+ node .joycraft/runtime/worktrees.mjs prune # preview
57
+ node .joycraft/runtime/worktrees.mjs prune --apply
58
+ ```
59
+
60
+ `create` adds `.joycraft/local/worktrees/<feature>-<spec>` on branch
61
+ `joycraft/<feature>-<spec>` from the current or `--base` revision and records the
62
+ owner in `.joycraft/local/worktrees.json`. `list` shows every linked tree with
63
+ its spec status, merged and clean state and size; a tree not in the ledger is
64
+ `unknown-owner`. `prune --apply` removes a tree only when it is recorded, its spec
65
+ is `done`, it is clean and its branch is contained in `--into` (default `HEAD`).
66
+ It never forces a removal. If the project's test runner discovers files under
67
+ dot folders, exclude `.joycraft/` from discovery.
68
+
69
+ `coordinator.mjs claim|heartbeat|release|show` keeps one coordinator lease per
70
+ queue in the main checkout's `.joycraft/local/coordinators/`. Every worker tree
71
+ reads the same lease. While a lease exists, `dispatch-start.mjs` starts a task only
72
+ with a matching `--coordinator-session` and names the coordinator in its output.
73
+
48
74
  ## Workspace input and project setup
49
75
 
50
76
  Dispatch accepts an optional runtime workspace input:
@@ -1,17 +1,19 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { boundQueueForSubject, briefDecisionRecords, canonical, isObject, isSha256, localPath, nonempty, normalizedQueueForSubject, parseJson, readLocal, readQueue, relativePath, requireValue, scopedRequirementForSubject, sha256, specStatus, subjectIdentity, validateIndependentReview } from './identity.mjs';
6
6
  import { validateEvidence } from './evidence.mjs';
7
7
  import { validateOwnerAcceptance } from './completion.mjs';
8
+ import { readConfig, workPaths } from './config.mjs';
8
9
 
9
10
  const featureName = value => {
10
11
  requireValue(typeof value === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(value), 'Feature must be a lowercase slug');
11
12
  return value;
12
13
  };
13
- const archivePath = feature => `docs/archive/${feature}`;
14
- const featurePath = feature => `docs/features/${feature}`;
14
+ // Folders come from joycraft.yaml (paths.features / paths.archive); defaults are docs/features and docs/archive.
15
+ const archivePath = (root, feature) => `${workPaths(root).archive}/${feature}`;
16
+ const featurePath = (root, feature) => `${workPaths(root).features}/${feature}`;
15
17
 
16
18
  function localDirectory(root, relative) {
17
19
  relative = relativePath(relative);
@@ -56,7 +58,8 @@ function parseAttestation(root, input) {
56
58
  const references = attestation.durableContext.references.map(relativePath);
57
59
  for (const reference of references) {
58
60
  requireValue(reference.endsWith('.md'), 'Durable context references must be current Markdown documentation');
59
- requireValue(!reference.startsWith('docs/features/') && !reference.startsWith('docs/archive/'), 'Durable context cannot rely on the feature being archived');
61
+ const { features, archive } = workPaths(root);
62
+ requireValue(!reference.startsWith(`${features}/`) && !reference.startsWith(`${archive}/`), 'Durable context cannot rely on the feature being archived');
60
63
  readLocal(root, reference);
61
64
  }
62
65
  return { schemaVersion: 1, phase: 'session-end', host: { sessionId: attestation.host.sessionId, quiescent: true, activeWorkers: [], dependentWork: [] }, durableContext: { carried: true, references } };
@@ -80,7 +83,7 @@ const isDecisionAnswered = decision => ['clarified', 'assigned'].includes(decisi
80
83
  * and after hashes must equal that commit's parent and own brief bytes.
81
84
  */
82
85
  function briefAmendments(root, feature, briefPath, later) {
83
- const recordPath = `${featurePath(feature)}/brief-amendments.json`;
86
+ const recordPath = `${featurePath(root, feature)}/brief-amendments.json`;
84
87
  const changed = `Original requirement changed after acceptance: ${briefPath}`;
85
88
  requireValue(existsSync(localPath(root, recordPath, true)), `${changed} (no ${recordPath} records its amendments)`);
86
89
  const record = parseJson(readLocal(root, recordPath), recordPath);
@@ -118,7 +121,7 @@ function validateReconciliation(record, feature) {
118
121
 
119
122
  function readReconciliation(root, feature, file) {
120
123
  if (file === undefined) return undefined;
121
- requireValue(file === `${featurePath(feature)}/archive-reconciliation.json`, 'Use the feature archive-reconciliation.json for the explicit override');
124
+ requireValue(file === `${featurePath(root, feature)}/archive-reconciliation.json`, 'Use the feature archive-reconciliation.json for the explicit override');
122
125
  const bytes = readLocal(root, file), record = parseJson(bytes, file);
123
126
  validateReconciliation(record, feature);
124
127
  return { path: file, sha256: sha256(bytes), record, used: new Set() };
@@ -160,7 +163,7 @@ function historicalRequirement(root, feature, input, project, normalizations = [
160
163
  const later = gitIn(root, ['log', '--full-history', '--topo-order', '--format=%H', '--reverse', `${accepted}..HEAD`, '--', input.path]).split('\n').filter(Boolean);
161
164
  const raw = committedBytes(root, accepted, input.path);
162
165
  const record = { path: input.path, normalization: input.normalization ?? 'none', ...(input.scope !== undefined ? { scope: input.scope } : {}), acceptedSha256: input.sha256, acceptedCommit: accepted, restoredSha256: sha256(raw), laterCommits: later };
163
- if (input.path === `${featurePath(feature)}/brief.md`) record.amendments = briefAmendments(root, feature, input.path, later);
166
+ if (input.path === `${featurePath(root, feature)}/brief.md`) record.amendments = briefAmendments(root, feature, input.path, later);
164
167
  return record;
165
168
  }
166
169
 
@@ -199,7 +202,7 @@ function historicalReport(root, queuePath, state, review, { ownerAccepted = fals
199
202
  const reviewedSpec = reviewedQueue.specs.find(spec => spec.id === state.spec.id);
200
203
  requireValue(reviewedSpec && reviewedSpec.file === state.spec.file && canonical(report.subject.criteria) === canonical(reviewedSpec.verification.criteria), `Accepted report criteria differ from the archived spec: ${reportPath}`);
201
204
  const declaredSpecPaths = new Set([...state.queue.specs, ...reviewedQueue.specs].map(spec => path.posix.join(path.posix.dirname(queuePath), spec.file)));
202
- for (const required of [state.specPath, `docs/features/${state.queue.feature}/brief.md`, ...report.subject.criteria.map(item => relativePath(item.requirement.path))]) {
205
+ for (const required of [state.specPath, `${featurePath(root, state.queue.feature)}/brief.md`, ...report.subject.criteria.map(item => relativePath(item.requirement.path))]) {
203
206
  requireValue(inputs.some(input => isObject(input) && input.path === required && input.kind === 'requirement' && isSha256(input.sha256)), `Accepted report omits original requirement ${required}: ${reportPath}`);
204
207
  }
205
208
  const requirement = (input, project) => {
@@ -213,7 +216,7 @@ function historicalReport(root, queuePath, state, review, { ownerAccepted = fals
213
216
  const explicit = reconciliation?.record.entries.some(entry => entry.report.path === review.path && entry.path === input.path && entry.normalization === input.normalization);
214
217
  if (!history.has(key)) history.set(key, explicit ? reconciledRequirement(root, state, review, input, project, reconciliation) : historicalRequirement(root, state.queue.feature, input, project));
215
218
  };
216
- for (const input of inputs.filter(input => isObject(input) && input.kind === 'requirement' && (bound !== undefined || input.path.startsWith(`docs/features/${state.queue.feature}/`)))) {
219
+ for (const input of inputs.filter(input => isObject(input) && input.kind === 'requirement' && (bound !== undefined || input.path.startsWith(`${featurePath(root, state.queue.feature)}/`)))) {
217
220
  // The queue was checked above. Only an explicit, hash-bound reconciliation can
218
221
  // preserve a changed acceptance record; normal requirement fallback cannot.
219
222
  if (input.path === queuePath) {
@@ -278,13 +281,13 @@ function historicalDecision(root, queuePath, state, reconciliation) {
278
281
  function fileDigest(root, relative) { return { path: relative, sha256: sha256(readLocal(root, relative)) }; }
279
282
 
280
283
  function existingArchive(root, feature) {
281
- const destination = archivePath(feature);
284
+ const destination = archivePath(root, feature);
282
285
  const manifestPath = `${destination}/archive-replay.json`;
283
286
  const manifest = parseJson(readLocal(root, manifestPath), manifestPath);
284
- requireValue(isObject(manifest) && manifest.schemaVersion === 1 && manifest.kind === 'joycraft-archive-replay' && manifest.feature === feature && manifest.source === featurePath(feature) && Array.isArray(manifest.files), `Archive destination is not a valid archive for ${feature}: ${destination}`);
287
+ requireValue(isObject(manifest) && manifest.schemaVersion === 1 && manifest.kind === 'joycraft-archive-replay' && manifest.feature === feature && manifest.source === featurePath(root, feature) && Array.isArray(manifest.files), `Archive destination is not a valid archive for ${feature}: ${destination}`);
285
288
  if (manifest.reconciliation !== undefined) {
286
289
  const proof = manifest.reconciliation;
287
- requireValue(isObject(proof) && proof.path === `${featurePath(feature)}/archive-reconciliation.json` && isSha256(proof.sha256), 'Archived reconciliation metadata is malformed');
290
+ requireValue(isObject(proof) && proof.path === `${featurePath(root, feature)}/archive-reconciliation.json` && isSha256(proof.sha256), 'Archived reconciliation metadata is malformed');
288
291
  validateReconciliation(proof.record, feature);
289
292
  const ledger = manifest.files.find(file => file.operation === 'moved' && file.originalPath === proof.path && file.sha256 === proof.sha256);
290
293
  requireValue(ledger && sha256(readLocal(root, ledger.archivedPath)) === proof.sha256 && canonical(parseJson(readLocal(root, ledger.archivedPath), proof.path)) === canonical(proof.record), 'Archived reconciliation paper trail is missing or changed');
@@ -318,7 +321,7 @@ function existingArchive(root, feature) {
318
321
  export function previewArchiveFeature({ root = process.cwd(), feature, phase, attestation, reconciliation: reconciliationPath }) {
319
322
  feature = featureName(feature);
320
323
  requireValue(phase === 'session-end', 'Archive is allowed only during phase=session-end');
321
- const source = featurePath(feature), destination = archivePath(feature);
324
+ const source = featurePath(root, feature), destination = archivePath(root, feature);
322
325
  const parsedAttestation = parseAttestation(root, attestation);
323
326
  if (existsSync(projectTarget(root, destination))) {
324
327
  requireValue(!existsSync(projectTarget(root, source)), `Archive destination already exists while live source remains: ${destination}`);
@@ -401,7 +404,7 @@ export function archiveFeature(options) {
401
404
  // Revalidate every input immediately before changing paths, so a preview cannot race a writer.
402
405
  const fresh = previewArchiveFeature({ ...options, root, apply: false });
403
406
  requireValue(canonical({ ...plan, attestation: undefined }) === canonical({ ...fresh, attestation: undefined }), 'Archive inputs changed after preview; rerun the session-end preflight');
404
- const stage = `docs/archive/.${plan.feature}.staging-${process.pid}-${Date.now()}`;
407
+ const stage = `${workPaths(root).archive}/.${plan.feature}.staging-${process.pid}-${Date.now()}`;
405
408
  const stageLocal = projectTarget(root, stage), destinationLocal = projectTarget(root, plan.destination), sourceLocal = localDirectory(root, plan.source);
406
409
  requireValue(!existsSync(stageLocal) && !existsSync(destinationLocal), 'Archive collision detected before move');
407
410
  mkdirSync(stageLocal, { recursive: true, mode: 0o700 });
@@ -435,7 +438,22 @@ export function archiveFeature(options) {
435
438
  const recovery = restored ? 'The live feature path was preserved.' : `The staged feature remains at ${stage}; restore it manually before retrying.`;
436
439
  throw new Error(`Archive stopped without accepting new completion: ${error.message}. ${recovery}`);
437
440
  }
438
- return { status: 'archived', destination: plan.destination, manifest: `${plan.destination}/archive-replay.json`, historical: plan.historical };
441
+ const afterArchive = runAfterArchive(root, plan);
442
+ return { status: 'archived', destination: plan.destination, manifest: `${plan.destination}/archive-replay.json`, historical: plan.historical, ...(afterArchive ? { afterArchive } : {}) };
443
+ }
444
+
445
+ /** Run the project's hooks.afterArchive once. Its failure is reported; the archive stands. */
446
+ function runAfterArchive(root, plan) {
447
+ let command;
448
+ try { command = readConfig(root).hooks.afterArchive; } catch (error) { return { ran: false, error: error.message }; }
449
+ if (!command) return null;
450
+ const result = spawnSync(command, {
451
+ cwd: root, shell: true, encoding: 'utf8', timeout: 600_000, maxBuffer: 16 * 1024 * 1024,
452
+ env: { ...process.env, JOYCRAFT_FEATURE: plan.feature, JOYCRAFT_ARCHIVE_PATH: plan.destination, JOYCRAFT_SOURCE_PATH: plan.source },
453
+ });
454
+ const tail = text => (text ?? '').split('\n').slice(-20).join('\n').trim();
455
+ return { ran: true, command, exitCode: result.status, ok: result.status === 0 && !result.error,
456
+ ...(result.error ? { error: result.error.message } : {}), stdout: tail(result.stdout), stderr: tail(result.stderr) };
439
457
  }
440
458
 
441
459
  function argumentsFor(argv) {
@@ -455,6 +473,8 @@ export function main(argv = process.argv.slice(2)) {
455
473
  const flags = argumentsFor(argv);
456
474
  const result = archiveFeature({ feature: flags['--feature'], phase: flags['--phase'], attestation: flags['--attestation'], reconciliation: flags['--reconciliation'], apply: flags['--apply'] === true });
457
475
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
476
+ // The archive stands; exit 3 tells a caller that only the after-archive hook failed.
477
+ if (result.afterArchive && !result.afterArchive.ok) process.exitCode = 3;
458
478
  return result;
459
479
  }
460
480