joycraft 1.1.1 → 1.1.2

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 (29) hide show
  1. package/README.md +57 -16
  2. package/dist/cli.js +50 -9
  3. package/dist/cli.js.map +1 -1
  4. package/dist/joycraft-release.json +1 -1
  5. package/package.json +3 -3
  6. package/payload/.agents/skills/joycraft-cleanup/SKILL.md +81 -34
  7. package/payload/.agents/skills/joycraft-context/SKILL.md +30 -4
  8. package/payload/.agents/skills/joycraft-entry/SKILL.md +19 -8
  9. package/payload/.agents/skills/joycraft-session-end/SKILL.md +8 -3
  10. package/payload/.joycraft/assets/artifacts/kit.css +8 -0
  11. package/payload/.joycraft/assets/artifacts/kit.js +163 -21
  12. package/payload/.joycraft/assets/artifacts/transports.js +14 -3
  13. package/payload/.joycraft/references/artifacts.md +21 -2
  14. package/payload/.joycraft/references/cleanup.md +109 -3
  15. package/payload/.joycraft/references/context.md +64 -2
  16. package/payload/.joycraft/references/doc-cleanup-LICENSE.md +23 -0
  17. package/payload/.joycraft/references/knowledge.md +58 -0
  18. package/payload/.joycraft/references/setup.md +128 -138
  19. package/payload/.joycraft/references/update.md +5 -3
  20. package/payload/.joycraft/runtime/artifacts/decisions.mjs +16 -5
  21. package/payload/.joycraft/runtime/artifacts/server.mjs +14 -1
  22. package/payload/.joycraft/runtime/cleanup.mjs +95 -8
  23. package/payload/.joycraft/runtime/config.mjs +5 -3
  24. package/payload/.joycraft/runtime/review-tools.mjs +55 -8
  25. package/payload/.joycraft/runtime/update-check.mjs +38 -8
  26. package/payload/.joycraft/runtime/wiring.mjs +156 -0
  27. package/payload/.joycraft/templates/joycraft.yaml +2 -0
  28. package/payload/.joycraft/templates/project-context.md +6 -1
  29. package/payload/PIN +25 -22
@@ -1,21 +1,17 @@
1
1
  # First-use project setup
2
2
 
3
- Use this on first entry, an explicit setup/init request, or a missing context
4
- home. It is an agent-guided part of `joycraft-entry`, not an installer side
5
- effect or a separate interview; the one exception is the opt-in
6
- [kickoff for a new project](#kickoff-for-a-new-project). Work inside the current project. Read-only
7
- requests do not authorize setup writes.
8
-
9
- For a reviewed clone, `node scripts/setup.mjs --target <project>` previews the
10
- smallest missing knowledge homes. Add `--write` only after reviewing the preview.
11
- It reads only plain target-local repository facts; it never reads `.env.local`,
12
- Keychain, sibling projects, or private directories. Its `ready` and `partial`
13
- status describes context discovery, never hook trust or a successful command.
3
+ Run this after every install from the prompt, when the user asks ("set up
4
+ Joycraft", "check the context map"), and whenever
5
+ `node .joycraft/runtime/wiring.mjs --root .` exits 2. The CLI knows nothing
6
+ about the project, so it writes nothing to `AGENTS.md` or `CLAUDE.md`; you build
7
+ the context map from the repository and a short interview with the user. Many
8
+ installs land in existing, sometimes large, projects, so the interview is part
9
+ of every setup, not only a new project's. Work inside the current project. A
10
+ read-only request gets the findings reported, not written.
14
11
 
15
12
  ## Contents
16
13
 
17
- - [Discover before writing](#discover-before-writing)
18
- - [Small shared entry point](#small-shared-entry-point)
14
+ - [Set up the context map](#set-up-the-context-map)
19
15
  - [Kickoff for a new project](#kickoff-for-a-new-project)
20
16
  - [Review loop tools](#review-loop-tools)
21
17
  - [Project-owned worktrees](#project-owned-worktrees)
@@ -23,87 +19,99 @@ status describes context discovery, never hook trust or a successful command.
23
19
  - [Finish setup and continue](#finish-setup-and-continue)
24
20
  - [Upgrade and agent onboarding](#upgrade-and-agent-onboarding)
25
21
 
26
- ## Discover before writing
27
-
28
- Read applicable instructions, root `AGENTS.md` and `CLAUDE.md` if present, README,
29
- and the relevant existing context links. Inspect manifests, lockfiles, task
30
- scripts and CI only as needed to establish the stack and actual commands. Follow
31
- the project's documentation conventions instead of migrating them into ours.
32
- Do not scan neighboring projects or credential files. Do not run installs,
33
- deployments, destructive commands, or application setup just to populate a table.
34
-
35
- Use the current conversation for intended users, purpose, stakeholders and
36
- constraints. Separate user-stated intent from repository observations and your
37
- assumptions. A declared command is not a verified successful command: cite its
38
- manifest/script source and mark it unrun until actually executed. On a bare
39
- project, say the stack and commands are not established; do not choose them for
40
- the sake of setup. Offer the kickoff below instead.
41
-
42
- When the current authorized work exposes an unclear state, data, or
43
- responsibility boundary, inspect the relevant owner and its actual counterparts
44
- before recording guidance. Preserve source-backed navigation in the existing
45
- context map or reference home; keep product behavior in the current brief. Read
46
- `architecture.md` for this focused, conditional discovery. Do not create an
47
- architecture phase, architecture-complete marker, or empty map during setup.
48
-
49
- ## Small shared entry point
50
-
51
- If `AGENTS.md` is missing, create a concise project-specific file with:
52
-
53
- - Project purpose supported by the request or repository; if unknown, say so.
54
- - Existing commands, their source and execution status, when available.
55
- - Only established project constraints, preserving their scope.
56
- - A context map with project-relative links and a short “read when” for each.
57
- - This line: “First action in each session: run
58
- `node .joycraft/runtime/update-check.mjs check`. If it prints JSON, follow
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”.
68
-
69
- Do not copy prototype-maintainer rules or fill it with generic coding advice.
70
- Link detail rather than duplicating it. Do not encode a tentative product idea
71
- as a permanent boundary. Keep current feature intent in its brief.
72
-
73
- If `AGENTS.md` already exists, preserve its content and add only missing facts,
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
76
- rather than adding another. Read linked content before deciding it is missing.
77
- When its map names a project-context home, use that exact project-relative home;
78
- use `docs/context/project.md` only when no context home exists. Do not link a
79
- context document that setup did not create or find. This keeps a bare project
80
- free of dangling links.
81
- Do not reformat, delete, or replace user instructions. Surface consequential
82
- contradictions rather than silently resolving them. Respect symlinks and managed
83
- files; do not replace them or write outside the project through them.
84
-
85
- For a missing `CLAUDE.md`, create a thin pointer after `AGENTS.md` exists:
86
-
87
- ```md
88
- @AGENTS.md
89
- ```
90
-
91
- For an existing `CLAUDE.md`, preserve all guidance. Add the import only if there
92
- is no equivalent link and it would not create a reference cycle. If CLAUDE.md is
93
- already the shared authority, keep it there and let the new AGENTS.md point to
94
- it; do not create reciprocal imports or duplicate its rules. This shared context
95
- pointer does not itself install skills or hooks; the exporter must use
96
- `--harness claude` to place those in Claude discovery paths.
97
-
98
- Before assigning workers, read an existing `.joycraft/preferences.json`. Reuse
99
- explicit model, effort, role, concurrency, and verification choices. Then inspect
100
- the active host for the actual planner, implementer, reviewer, testing, UI, and
101
- fixture capabilities. Generated defaults and an `unknown` fixture status do not
102
- prove capability. Until actual isolation is established, use at most four workers
103
- and one UI worker. Relevant acceptance requires both an inspected rendered UI
104
- and independent review; if one is unavailable, hold only the claim it would
105
- support. Ask one short combined question only when a consequential choice remains
106
- after that inspection.
22
+ ## Set up the context map
23
+
24
+ The context map in `AGENTS.md` is the project's memory index. Each row points to
25
+ one home for one kind of knowledge and says when to read it, so an agent loads
26
+ only what its work needs; the map then grows with every decision, trap and
27
+ feature ([knowledge.md](knowledge.md)). A project without a real map gets
28
+ nothing from Joycraft, so build it from the project, never from a template.
29
+
30
+ **Nothing new, nothing done.** When `wiring.mjs` exits 0, every doc worth
31
+ reading already has a row, and nothing the user told you or the audit found is
32
+ unrecorded, say in one line that Joycraft is already set up. Write nothing,
33
+ render nothing, ask nothing: a repeated setup must leave the project unchanged.
34
+
35
+ 1. **Read and audit.** Read `AGENTS.md`, `CLAUDE.md`, the README and every doc
36
+ they point to, then the other Markdown docs (skip dependencies, generated
37
+ files, `.joycraft/` and installed skills). Run `joycraft-cleanup` steps 1–2
38
+ (inventory and diagnose) on what you read: it gives each doc a
39
+ [role](cleanup.md#doc-roles) and hands its findings back to you, with no
40
+ report page and no stop of its own. Check claims in entry and required docs
41
+ against the code; in reference docs, check only the claims the interview or
42
+ an audit finding touches. Inspect manifests, scripts and CI only to
43
+ establish the stack and real commands; a declared command is unrun until
44
+ executed. In a large repo, read the entry docs and their pointers first,
45
+ then one area at a time; propose each area you did not read as an item of
46
+ a `## Not yet mapped` list in `docs/context/project.md` (current areas
47
+ only, no history), so a later session maps it when work reaches it. Do
48
+ not scan neighboring projects or credential files, and do not run
49
+ installs, deployments or destructive commands.
50
+ 2. **Interview.** Ask only what the repository cannot tell you: purpose, users,
51
+ who owns what, constraints, decisions already made and why, which docs are
52
+ trusted, and each audit finding that needs a human. Ask in short rounds of
53
+ at most three questions, each one that changes what you will write. Write
54
+ each choice with options as a decision in a setup brief at
55
+ `.joycraft/local/setup/brief.md` (format of `.joycraft/templates/brief.md`,
56
+ `feature: setup`; give `.joycraft/local/` a `.gitignore` of `*` when it has
57
+ none, so nothing there becomes a project change) and serve the decision
58
+ artifact on it ([artifacts.md](artifacts.md)); plain chat is only for one
59
+ quick yes/no or an open question with no options. The brief is scratch:
60
+ each answer then goes to its home in step 3. Stop when the user says enough. Never ask again
61
+ what the user answered or a home already states. Keep the user's words apart
62
+ from your observations and assumptions. On a bare project, offer the
63
+ [kickoff](#kickoff-for-a-new-project) instead.
64
+ 3. **Propose.** Draft every change:
65
+ - **Joycraft lines** in `AGENTS.md`, each only when missing:
66
+ “First action in each session: run
67
+ `node .joycraft/runtime/update-check.mjs check`. If it prints JSON, follow
68
+ `.joycraft/references/update.md`.” and “Show every document a person must
69
+ read, review or answer (a brief, plan, spec set, review or set of
70
+ questions) as a rendered page, never only as Markdown in chat: use the
71
+ decision artifact (`node .joycraft/runtime/artifacts/cli.mjs`, see
72
+ `.joycraft/references/artifacts.md`) for a brief or questions, or an HTML
73
+ page for any other document. Show it where the person works (see
74
+ `.joycraft/references/artifacts.md#showing-a-page`) and say where it is.”
75
+ - **The map**: one `## Context Map` table (`| Document | Read when |`). One
76
+ row per real home: each required or reference doc, and each home you
77
+ create. A read-when names the work that needs the doc ("Changing how counts
78
+ are stored"), not its topic. Add a row for
79
+ `.joycraft/references/artifacts.md`, read when "showing a document or
80
+ questions to a person". Historical docs get no row. In an existing map,
81
+ append rows below the user's rows; never edit, reorder or reformat theirs.
82
+ Every row targets a file that exists after the write.
83
+ - **Homes**, only with content, routed by [knowledge.md](knowledge.md).
84
+ - **`CLAUDE.md`**, only when `.joycraft/installation.json` lists the
85
+ `claude` host: missing → create it as `@AGENTS.md` followed by an empty
86
+ `## Claude Code` section; present without an `@AGENTS.md` line → add
87
+ `@AGENTS.md` as line 1; present with it → leave it alone. When `AGENTS.md`
88
+ already imports or defers to `CLAUDE.md`, add no reciprocal import.
89
+ - **Audit fixes** for the findings the user agreed to in the interview, made
90
+ as joycraft-cleanup step 4 says.
91
+
92
+ Add lines, rows and pages. Do not reword, reformat, reorder or delete user
93
+ content: every existing line of `AGENTS.md` and `CLAUDE.md` survives. With
94
+ no `AGENTS.md`, create one with the purpose (or "unknown"), established
95
+ constraints, commands with their source, the Joycraft lines and the map. Keep
96
+ generic coding advice and tentative product ideas out; feature intent stays
97
+ in its brief. Respect symlinks and managed files.
98
+ 4. **Show, then write.** Render the diff of every file you would change or
99
+ create, audit fixes included, as one HTML page under
100
+ `.joycraft/local/setup/`. Show it as [showing a page](artifacts.md#showing-a-page)
101
+ says, give its path, and write only on the
102
+ user's yes; this page is setup's only approval stop. A request that
103
+ already approves the files you propose counts as the yes.
104
+ 5. **Check.** `wiring.mjs` exits 0. `node .joycraft/runtime/cleanup.mjs`
105
+ reports no `missing-path`, `unmapped`, `orphan` or `broken-link` for the
106
+ files you touched. Every original line of `AGENTS.md` and `CLAUDE.md` is
107
+ still there. Fix what fails, then tell the user in a few lines which docs the
108
+ map now reaches, which homes you created and what you have not read or do
109
+ not know yet. Continue the original request.
110
+
111
+ When the work exposes an unclear state, data, or responsibility boundary,
112
+ inspect the owner and its actual counterparts before recording guidance; read
113
+ `architecture.md` for that focused check. Do not create an architecture phase,
114
+ architecture-complete marker, or empty map during setup.
107
115
 
108
116
  ## Kickoff for a new project
109
117
 
@@ -158,7 +166,11 @@ Pass `--host-tools browser`, `simulator` or `computer-use` only for tools the
158
166
  active host actually reports; they can stand in for a missing install. The plan
159
167
  detects each package from its manifests, probes versions read-only, and prints
160
168
  one table and at most one question. It never installs. When it prints
161
- `Review loop unchanged.`, ask nothing.
169
+ `Review loop unchanged.`, ask nothing. Packages come from declared workspaces;
170
+ with none and no root manifest, from the manifests below the root that git does
171
+ not ignore. When it prints `No packages found`, ask the user which folders hold
172
+ the apps and pass them as `--packages <dir,dir>` to `plan`, `install` and
173
+ `record`.
162
174
 
163
175
  Show the table and ask its one question. Only after the user's yes in this
164
176
  conversation, run `review-tools.mjs install --root . --yes` (add
@@ -230,23 +242,9 @@ explicit manual Git-worktree workflow.
230
242
 
231
243
  ## Knowledge grows with the work
232
244
 
233
- Reuse existing documents for project facts. If none exists and there are durable
234
- facts worth retaining, create `docs/context/project.md` with the known purpose,
235
- users/stakeholders and constraints, their source, and any consequential unknowns.
236
- Create its parent directory and link it from the context map. Omit empty sections
237
- and private contact details that are unnecessary for the work. If nothing is
238
- known yet, create only the instruction files; gather the first useful fact before
239
- creating a context document. Do not manufacture a directory tree of empty files.
240
-
241
- Create additional homes only when they have content:
242
-
243
- | Content | Default home when no existing convention applies |
244
- |---|---|
245
- | Durable project knowledge | `docs/context/project.md` or a focused reference linked by the map |
246
- | Source-backed cross-boundary navigation | The existing context map or a focused reference linked by it |
247
- | Reusable decision rationale | `docs/context/decision-log.md`, linking to the owning decision |
248
- | Current feature or mixed change | `docs/features/<slug>/brief.md` |
249
- | Authorized implementation queue | `docs/features/<slug>/specs/` |
245
+ Which home holds which kind of fact, and when to create one, is in
246
+ [knowledge guidance](knowledge.md). A current feature lives in
247
+ `docs/features/<slug>/brief.md` and its queue in `docs/features/<slug>/specs/`.
250
248
 
251
249
  A project can move these folders, add an after-archive hook and map code to
252
250
  context pages in an optional root `joycraft.yaml`. It is project-owned: create it
@@ -263,16 +261,16 @@ and links it from the context map.
263
261
 
264
262
  The brief retains decision authority under `workflow.md`; the context document
265
263
  and decision log must not become competing answer stores. Later accepted facts
266
- update their existing home. Repeating entry with no new knowledge should make
264
+ update their existing home; [knowledge.md](knowledge.md) owns how each fact is
265
+ routed, changed in place and kept current. Repeating entry with no new knowledge should make
267
266
  no setup edits, create no duplicate links, and ask no repeated questions. There
268
267
  is no setup-complete sentinel: useful source content, not a flag, determines
269
268
  whether context is available.
270
269
 
271
- Ask only for missing human knowledge that materially changes the next action.
272
- Prefer one short contextual question and continue independent work while it is
273
- pending. An explicit setup-only request with no product context may end with that
274
- question or the kickoff offer; do not generate a questionnaire or start building
275
- an imagined app.
270
+ Outside setup's interview, ask only for missing human knowledge that materially
271
+ changes the next action. Prefer one short contextual question and continue
272
+ independent work while it is pending. Do not generate a questionnaire or start
273
+ building an imagined app.
276
274
 
277
275
  Use the project’s existing interaction home for a choice. A question with
278
276
  options goes in the decision artifact; only one quick yes/no or an open question
@@ -281,28 +279,20 @@ owning brief and do not ask it again.
281
279
 
282
280
  ## Finish setup and continue
283
281
 
284
- Check that newly added links resolve, command claims match their cited source,
285
- and existing guidance survived the diff. Briefly tell the user which knowledge
286
- homes were created or extended and any important unknown; then continue the
287
- original request. Setup does not approve hooks, change credentials, install
282
+ Step 5 of [Set up the context map](#set-up-the-context-map) is the finish
283
+ check; also check that command claims match their cited source. Setup does not approve hooks, change credentials, install
288
284
  dependencies, or replace the user's workflow. Read `hooks-install.md` only when
289
285
  hook activation is part of the requested setup.
290
286
 
291
287
  ## Upgrade and agent onboarding
292
288
 
293
- Use `node scripts/export.mjs --target <project> --check --upgrade` to preview an
294
- upgrade. It names only recognized old Joycraft files that would be replaced.
295
- Applying without `--check` copies those replaced bytes to `.joycraft-backups/`
296
- first and writes `.joycraft/installation.json`, whose hashes attest to
297
- the actual installed skill, reference, and runtime bytes. A changed file absent
298
- from the prior installation manifest remains a conflict; there is no blanket
299
- force flag. The manifest is dispatch input, not proof that hooks ran or that a
300
- review was independent.
301
-
302
- For a new worker, copy the onboarding prompt from the setup preview. It directs
303
- the worker to read existing project preferences before work, reuse explicit
304
- model/effort/role/concurrency/verification choices, and inspect the host's
305
- currently available planner, implementer, reviewer, testing, UI, and fixture
306
- capabilities rather than claiming a hardcoded model is available. State
307
- unavailable roles and native-hook checks plainly. Do not alter accepted queues,
308
- decision state, user guidance, or credentials during setup or upgrade.
289
+ Updates go through the Joycraft CLI; follow [update guidance](update.md). The
290
+ installation manifest `.joycraft/installation.json` records the installed bytes;
291
+ it is dispatch input, not proof that hooks ran or that a review was independent.
292
+
293
+ A new worker reads `.joycraft/preferences.json` before work, reuses explicit
294
+ model, effort, role, concurrency and verification choices, and inspects the
295
+ host's available planner, implementer, reviewer, testing, UI and fixture
296
+ capabilities instead of assuming a model. It states unavailable roles plainly.
297
+ Setup and upgrade never change accepted queues, decision state, user guidance or
298
+ credentials.
@@ -8,8 +8,10 @@ If it prints JSON, read `action`. Put the line below in your next reply to the u
8
8
  even when the request is about something else and even when your reply is short:
9
9
 
10
10
  - `note`: tell the user `message` in one line. Do not ask anything.
11
- - `ask`: tell the user `message` in one line and ask once: update now, not now, or
12
- turn off. Do not ask again in this session.
11
+ - `ask`: tell the user `message` and ask once: update now, not now, or turn off.
12
+ Do not ask again in this session. `message` names each release since the
13
+ installed one (newest five, then how many more) and ends with the changelog link.
14
+ - `kind` is `patch` (same minor), `minor` (newer minor), or `migration` (newer major).
13
15
  - `apply`: the user chose automatic updates. Follow "Update" below without asking.
14
16
  If the plan would back up an edited file, stop and ask instead.
15
17
 
@@ -37,7 +39,7 @@ that the files are back as they were, and continue your work.
37
39
  that version for seven days.
38
40
  - Turn off: `node .joycraft/runtime/update-check.mjs policy off`.
39
41
  - Automatic updates: `node .joycraft/runtime/update-check.mjs policy auto-safe`. Only
40
- a release marked safe applies by itself. A new major version always asks.
42
+ a `patch` release marked safe applies by itself. A `minor` or `migration` always asks.
41
43
  - Stay on this version: `node .joycraft/runtime/update-check.mjs pin`, and `unpin` to
42
44
  undo it.
43
45
 
@@ -86,6 +86,15 @@ function validateOptionalString(value, name) {
86
86
  if (value !== undefined && typeof value !== 'string') throw new Error(`${name} must be a string`);
87
87
  }
88
88
 
89
+ // Every displayed question offers a custom answer, so a person is never forced
90
+ // to pick an option they disagree with. A declared `custom` option keeps its text.
91
+ const CUSTOM_OPTION = Object.freeze({ value: 'custom', label: 'Something else', description: 'Describe what you want instead.', requiresNote: true });
92
+
93
+ function withCustomOption(options) {
94
+ if (!options.some(option => option.value === CUSTOM_OPTION.value)) return [...options, CUSTOM_OPTION];
95
+ return options.map(option => option.value === CUSTOM_OPTION.value ? { ...option, requiresNote: true } : option);
96
+ }
97
+
89
98
  function displayedDecision(brief, id) {
90
99
  const index = brief.decisions.findIndex(item => item.id === id);
91
100
  const decision = brief.decisions[index];
@@ -103,6 +112,7 @@ function displayedDecision(brief, id) {
103
112
  if (option.requiresNote !== undefined && typeof option.requiresNote !== 'boolean') throw new Error('Option requiresNote must be boolean');
104
113
  values.add(option.value);
105
114
  }
115
+ values.add(CUSTOM_OPTION.value);
106
116
  if (!(decision.answer === null || values.has(decision.answer)) || (decision.status === 'clarified' && decision.answer === null)) {
107
117
  throw new Error('Invalid decision answer');
108
118
  }
@@ -115,7 +125,7 @@ function publicQuestion(decision) {
115
125
  const question = {
116
126
  id: decision.id,
117
127
  question: decision.question,
118
- options: decision.options.map(option => {
128
+ options: withCustomOption(decision.options).map(option => {
119
129
  const result = { value: option.value, label: option.label };
120
130
  if (option.description !== undefined) result.description = option.description;
121
131
  if (option.requiresNote !== undefined) result.requiresNote = option.requiresNote;
@@ -157,7 +167,7 @@ function responseNote(response) {
157
167
  }
158
168
 
159
169
  function sameAnswer(decision, answer, note) {
160
- return decision.answer === answer && decision.note === note;
170
+ return decision.answer === answer && (decision.note || undefined) === (note || undefined);
161
171
  }
162
172
 
163
173
  /**
@@ -177,14 +187,15 @@ export function saveAnswers(text, request) {
177
187
  }
178
188
  ids.add(response.id);
179
189
  const { decision, index } = displayedDecision(brief, response.id);
180
- const option = decision.options.find(item => item.value === response.answer);
190
+ const option = withCustomOption(decision.options).find(item => item.value === response.answer);
181
191
  if (!option) throw new Error('Unknown choice');
182
192
  const note = responseNote(response);
183
193
  if (option.requiresNote && !nonempty(note)) throw new Error('This choice requires a note');
184
194
  if (sameAnswer(decision, response.answer, note)) continue;
185
- if (!['open', 'assigned'].includes(decision.status)) throw new Error('Reopen the decision explicitly before changing its answer.');
195
+ const noteOnly = decision.status === 'clarified' && decision.answer === response.answer;
196
+ if (!noteOnly && !['open', 'assigned'].includes(decision.status)) throw new Error('Reopen the decision explicitly before changing its answer.');
186
197
  const updated = { ...decision, answer: response.answer, status: 'clarified' };
187
- if (note === undefined) delete updated.note;
198
+ if (note === undefined || note === '') delete updated.note;
188
199
  else updated.note = note;
189
200
  changes.push({ index, updated });
190
201
  }
@@ -8,6 +8,17 @@ export async function startArtifact({ root = process.cwd(), brief, view, theme,
8
8
  await loadArtifact(args);
9
9
  const token = randomBytes(24).toString('hex');
10
10
  let url;
11
+ // A save against an older brief or view is a source conflict: say so, with the
12
+ // current revisions, so the page reloads and keeps answers to unchanged questions.
13
+ const conflictBody = async (error, request) => {
14
+ try {
15
+ const { source } = (await loadArtifact(args)).model;
16
+ if (request?.revision !== source.revision || request?.viewRevision !== source.viewRevision) {
17
+ return { error: error.message, conflict: true, revision: source.revision, viewRevision: source.viewRevision };
18
+ }
19
+ } catch { /* the original error is the useful one */ }
20
+ return { error: error.message };
21
+ };
11
22
  const server = createServer(async (request, response) => {
12
23
  const send = (status, data, type = 'application/json') => {
13
24
  response.writeHead(status, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
@@ -29,7 +40,9 @@ export async function startArtifact({ root = process.cwd(), brief, view, theme,
29
40
  body += part;
30
41
  if (Buffer.byteLength(body) > 500_000) return send(413, { error: 'Answer request too large' });
31
42
  }
32
- return send(200, await saveLocal({ ...args, request: JSON.parse(body) }));
43
+ const answerRequest = JSON.parse(body);
44
+ try { return send(200, await saveLocal({ ...args, request: answerRequest })); }
45
+ catch (error) { return send(409, await conflictBody(error, answerRequest)); }
33
46
  }
34
47
  return send(404, { error: 'Not found' });
35
48
  } catch (error) { return send(409, { error: error.message }); }
@@ -48,13 +48,47 @@ function blankFences(text) {
48
48
  }).join('\n');
49
49
  }
50
50
 
51
- /** Markdown links (checked for existence) and backticked project paths (references only). */
51
+ // File types a backticked name with a slash is read as a path for; a name with a
52
+ // slash and no extension counts only when it ends in / or its first folder exists.
53
+ const pathExtensions = new Set(['md', 'mdx', 'txt', 'json', 'jsonl', 'yaml', 'yml', 'toml', 'js', 'mjs', 'cjs', 'ts', 'mts', 'cts', 'tsx', 'jsx',
54
+ 'py', 'rb', 'go', 'rs', 'java', 'kt', 'swift', 'c', 'h', 'cpp', 'cs', 'php', 'sh', 'sql', 'html', 'css', 'scss', 'svg', 'png', 'lock', 'env', 'xml', 'csv']);
55
+
56
+ /**
57
+ * A backticked span that names a project path, normalized, or null. Skipped:
58
+ * anything with spaces, globs, placeholders (<slug>, [slug], {x}, $VAR, ...),
59
+ * URLs and other colon forms, absolute, home, parent and flag-like spans, and
60
+ * names without a slash (a bare file name could live in any folder).
61
+ */
62
+ export function projectPath(span, exists = () => true) {
63
+ let value = span.trim().replace(/#.*$/, '').replace(/:\d+(?::\d+)?$/, '');
64
+ if (!value || /\s/.test(value) || /[*?<>[\]{}$%:@`'"|\\]/.test(value) || value.includes('...')) return null;
65
+ if (/^[-/~.]/.test(value) && !value.startsWith('./') && !/^\.[A-Za-z0-9_]/.test(value)) return null;
66
+ if (!value.includes('/')) return null;
67
+ value = path.posix.normalize(value);
68
+ if (value.startsWith('../') || value === '..' || value === '.') return null;
69
+ const extension = /\.([A-Za-z0-9]+)$/.exec(value.replace(/\/$/, ''))?.[1]?.toLowerCase();
70
+ if (span.trim().endsWith('/') || pathExtensions.has(extension) || exists(value.split('/')[0])) return value;
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * Markdown links (checked for existence), backticked project paths and
76
+ * `@path` import lines (references only). Imports resolve from the file's folder,
77
+ * as Claude Code reads them.
78
+ */
52
79
  export function references(file, text) {
53
80
  const dir = path.posix.dirname(file);
54
- const links = [], mentions = [];
81
+ const links = [], mentions = [], imports = [];
55
82
  // Blank out fenced code so examples are not read as links; keep line numbers.
56
83
  text = blankFences(text);
57
- const lineOf = index => text.slice(0, index).split('\n').length;
84
+ // Offsets where each line starts, built once; a lookup is a binary search.
85
+ const starts = [0];
86
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', index + 1)) starts.push(index + 1);
87
+ const lineOf = index => {
88
+ let low = 0, high = starts.length - 1;
89
+ while (low < high) { const mid = (low + high + 1) >> 1; if (starts[mid] <= index) low = mid; else high = mid - 1; }
90
+ return low + 1;
91
+ };
58
92
  const add = (raw, index) => {
59
93
  const target = raw.split('#')[0];
60
94
  if (!target || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('/')) return;
@@ -65,9 +99,17 @@ export function references(file, text) {
65
99
  for (const match of text.matchAll(/\[[^\]]*\]\((?:<([^>]+)>|([^)\s]+))(?:\s+"[^"]*")?\)/g)) add(match[1] ?? match[2], match.index);
66
100
  for (const match of text.matchAll(/^ {0,3}\[[^\]]+\]:\s+(?:<([^>]+)>|(\S+))/gm)) add(match[1] ?? match[2], match.index);
67
101
  for (const match of text.matchAll(/`([A-Za-z0-9_.\/-]+\.md)`/g)) {
68
- if (match[1].includes('/')) mentions.push({ target: path.posix.normalize(match[1]), line: text.slice(0, match.index).split('\n').length });
102
+ if (match[1].includes('/')) mentions.push({ target: path.posix.normalize(match[1]), line: lineOf(match.index) });
103
+ }
104
+ for (const match of text.matchAll(/^[ \t]*@(\S+)[ \t]*$/gm)) {
105
+ const target = match[1];
106
+ if (/^[~/]/.test(target) || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
107
+ imports.push({ target: path.posix.normalize(path.posix.join(dir, target)), line: lineOf(match.index) });
69
108
  }
70
- return { links, mentions };
109
+ // Single-backtick spans on one line; fenced blocks are already blank.
110
+ const spans = [];
111
+ for (const match of text.matchAll(/(?<!`)`([^`\n]+)`(?!`)/g)) spans.push({ span: match[1], line: lineOf(match.index) });
112
+ return { links, mentions, imports, spans };
71
113
  }
72
114
 
73
115
  function frontmatter(text) {
@@ -76,6 +118,14 @@ function frontmatter(text) {
76
118
  try { return parseYaml(block[1]); } catch (error) { return { unreadable: error.message.replace(/^joycraft\.yaml /, '') }; }
77
119
  }
78
120
 
121
+ /** A page that records the past: `type: log|history` frontmatter, a decision log or a shipped ledger. */
122
+ function historyPage(file, text) {
123
+ const name = path.posix.basename(file);
124
+ if (name === 'decision-log.md' || /^shipped.*\.md$/.test(name)) return true;
125
+ const type = frontmatter(text)?.type;
126
+ return type === 'log' || type === 'history';
127
+ }
128
+
79
129
  const inside = (file, folder) => file === folder || file.startsWith(`${folder}/`);
80
130
 
81
131
  function git(root, args) {
@@ -123,10 +173,14 @@ export function cleanupReport({ root = process.cwd(), now = Date.now() } = {}) {
123
173
  const staleAfter = meta?.stale_after == null ? NaN : Date.parse(String(meta.stale_after));
124
174
  if (Number.isFinite(staleAfter) && staleAfter <= now) findings.push({ check: 'stale-after', path: page, detail: `stale_after ${meta.stale_after} has passed.`, fix: 'Recheck the page against its sources, then move stale_after forward or mark it deprecated.' });
125
175
  }
126
- for (const file of authorities) {
176
+ // Read and parse each file once; the checks below share the result.
177
+ const parsed = new Map(authorities.map(file => {
127
178
  const text = read(root, file) ?? '';
128
- const { links, mentions } = references(file, text);
129
- for (const ref of [...links, ...mentions]) {
179
+ return [file, { text, ...references(file, text) }];
180
+ }));
181
+ for (const file of authorities) {
182
+ const { links, mentions, imports } = parsed.get(file);
183
+ for (const ref of [...links, ...mentions, ...imports]) {
130
184
  if (ref.target !== file) referenced.add(ref.target);
131
185
  if (inside(ref.target, features) || inside(ref.target, archive)) {
132
186
  findings.push({ check: 'working-link', path: file, line: ref.line, detail: `Links to ${ref.target}, which is ${inside(ref.target, archive) ? 'history' : 'working material'}, not current knowledge.`, fix: `Move the fact it relies on into ${context}/ and link that instead.` });
@@ -137,6 +191,39 @@ export function cleanupReport({ root = process.cwd(), now = Date.now() } = {}) {
137
191
  if (!existsSync(path.join(root, ref.target))) findings.push({ check: 'broken-link', path: file, line: ref.line, detail: `Links to ${ref.target}, which does not exist.`, fix: 'Fix the link or remove it.' });
138
192
  }
139
193
  }
194
+ // missing-path: a backticked project path that names nothing in the project,
195
+ // read from the root or, in a context page, from the page's own folder.
196
+ // History pages (a decision log, a shipped ledger) rightly name removed paths.
197
+ const exists = relative => existsSync(path.join(root, relative));
198
+ for (const file of authorities) {
199
+ const { text, spans } = parsed.get(file);
200
+ if (historyPage(file, text)) continue;
201
+ const seen = new Set();
202
+ for (const { span, line } of spans) {
203
+ const target = projectPath(span, exists);
204
+ if (!target || seen.has(target)) continue;
205
+ seen.add(target);
206
+ const local = path.posix.normalize(path.posix.join(path.posix.dirname(file), target));
207
+ if (exists(target) || exists(local)) continue;
208
+ findings.push({ check: 'missing-path', path: file, line, detail: `Names ${target}, which does not exist.`, fix: 'Point it at the current path, or remove the line if the thing is gone.' });
209
+ }
210
+ }
211
+ // unmapped: a context page that only other context pages reference. An entry
212
+ // file must link, name or @-import it, or agents reach it only by chance. Pages nothing
213
+ // references at all are reported once, as orphan.
214
+ const mapped = new Set();
215
+ for (const file of authorities.filter(file => entryFiles.includes(file))) {
216
+ const { links, mentions, imports } = parsed.get(file);
217
+ for (const ref of [...links, ...mentions, ...imports]) mapped.add(ref.target);
218
+ }
219
+ for (const page of pages) {
220
+ if (referenced.has(page) && !mapped.has(page)) findings.push({ check: 'unmapped', path: page, detail: `Only other ${context}/ pages mention this page; ${entryFiles.join(' and ')} do not, so agents may not know when to read it.`, fix: 'Add a context-map row with a "read when", or merge it into a mapped page.' });
221
+ }
222
+ // entry-size: entry files load into every session; keep them within budget.
223
+ for (const file of authorities.filter(file => entryFiles.includes(file))) {
224
+ const words = parsed.get(file).text.split(/\s+/).filter(Boolean).length;
225
+ if (words > config.cleanup.entryWords) findings.push({ check: 'entry-size', path: file, detail: `${words} words; the budget is ${config.cleanup.entryWords} (cleanup.entryWords).`, fix: 'Move reference detail into context pages and leave a map row that says when to read each.', words });
226
+ }
140
227
  for (const page of pages) {
141
228
  if (!referenced.has(page)) findings.push({ check: 'orphan', path: page, detail: `Nothing in ${entryFiles.join(', ')} or ${context}/ links to this page, so agents may never read it.`, fix: 'Add it to the context map with a "read when", or merge it into a linked page.' });
142
229
  }