joycraft 1.1.2 → 1.2.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.
Files changed (37) hide show
  1. package/README.md +15 -10
  2. package/dist/joycraft-release.json +1 -1
  3. package/package.json +3 -3
  4. package/payload/.agents/skills/joycraft-decompose/SKILL.md +5 -1
  5. package/payload/.agents/skills/joycraft-entry/SKILL.md +28 -7
  6. package/payload/.agents/skills/joycraft-implement/SKILL.md +16 -0
  7. package/payload/.agents/skills/joycraft-session-end/SKILL.md +1 -1
  8. package/payload/.agents/skills/joycraft-testing/SKILL.md +7 -5
  9. package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +4 -3
  10. package/payload/.agents/skills/joycraft-verify/SKILL.md +1 -1
  11. package/payload/.claude/agents/joycraft-reviewer.md +7 -2
  12. package/payload/.joycraft/assets/artifacts/kit.css +7 -0
  13. package/payload/.joycraft/assets/artifacts/kit.js +23 -7
  14. package/payload/.joycraft/contracts/types.d.ts +22 -0
  15. package/payload/.joycraft/references/archive.md +4 -2
  16. package/payload/.joycraft/references/artifacts.md +66 -9
  17. package/payload/.joycraft/references/completion.md +55 -2
  18. package/payload/.joycraft/references/dispatch.md +12 -0
  19. package/payload/.joycraft/references/setup.md +70 -30
  20. package/payload/.joycraft/references/testing.md +14 -7
  21. package/payload/.joycraft/references/update.md +8 -0
  22. package/payload/.joycraft/references/workflow.md +10 -5
  23. package/payload/.joycraft/runtime/archive.mjs +19 -4
  24. package/payload/.joycraft/runtime/artifacts/cli.mjs +29 -5
  25. package/payload/.joycraft/runtime/artifacts/decisions.mjs +13 -5
  26. package/payload/.joycraft/runtime/artifacts/model.mjs +1 -1
  27. package/payload/.joycraft/runtime/artifacts/preferences.mjs +95 -2
  28. package/payload/.joycraft/runtime/completion.mjs +210 -10
  29. package/payload/.joycraft/runtime/dispatch-preflight.mjs +16 -3
  30. package/payload/.joycraft/runtime/evidence.mjs +4 -0
  31. package/payload/.joycraft/runtime/identity.mjs +11 -0
  32. package/payload/.joycraft/runtime/review-tools.json +110 -30
  33. package/payload/.joycraft/runtime/review-tools.mjs +658 -129
  34. package/payload/.joycraft/runtime/status.mjs +1 -1
  35. package/payload/.joycraft/runtime/worktrees.mjs +1 -1
  36. package/payload/.joycraft/templates/brief.md +1 -1
  37. package/payload/PIN +35 -35
@@ -54,9 +54,18 @@ render nothing, ask nothing: a repeated setup must leave the project unchanged.
54
54
  each choice with options as a decision in a setup brief at
55
55
  `.joycraft/local/setup/brief.md` (format of `.joycraft/templates/brief.md`,
56
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:
57
+ none, so nothing there becomes a project change). First, when
58
+ `node .joycraft/runtime/artifacts/cli.mjs questions` prints `unset: true`,
59
+ ask how the user wants questions, as two decisions: pacing (one decision at
60
+ a time with a short discussion after each answer, or a page of decisions)
61
+ and surface (the decision page, or numbered prose in chat). Give an example
62
+ of each. Ask only these two, in today's style (a page), and wait for the
63
+ answer before you ask any other setup question. Record it with
64
+ `questions --set pacing=...,surface=...` and say that the user can change it
65
+ for one feature later. Never ask again when a style is recorded. Then ask the
66
+ other setup decisions in that style ([asking questions](artifacts.md#asking-questions));
67
+ plain chat with no decision is only for one quick yes/no or an open question
68
+ with no options. The brief is scratch:
60
69
  each answer then goes to its home in step 3. Stop when the user says enough. Never ask again
61
70
  what the user answered or a home already states. Keep the user's words apart
62
71
  from your observations and assumptions. On a bare project, offer the
@@ -66,12 +75,16 @@ render nothing, ask nothing: a repeated setup must leave the project unchanged.
66
75
  “First action in each session: run
67
76
  `node .joycraft/runtime/update-check.mjs check`. If it prints JSON, follow
68
77
  `.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.”
78
+ read or review (a brief, plan, spec set or review) as a rendered page,
79
+ never only as Markdown in chat: use the decision artifact
80
+ (`node .joycraft/runtime/artifacts/cli.mjs`, see
81
+ `.joycraft/references/artifacts.md`) for a brief, or an HTML page for any
82
+ other document. Show it where the person works (see
83
+ `.joycraft/references/artifacts.md#showing-a-page`) and say where it is.
84
+ Ask questions in the project's question style
85
+ (`.joycraft/references/artifacts.md#asking-questions`).” Replace an older
86
+ version of this line that lists a "set of questions", so it does not
87
+ override a chat question style.
75
88
  - **The map**: one `## Context Map` table (`| Document | Read when |`). One
76
89
  row per real home: each required or reference doc, and each home you
77
90
  create. A read-when names the work that needs the doc ("Changing how counts
@@ -168,28 +181,54 @@ detects each package from its manifests, probes versions read-only, and prints
168
181
  one table and at most one question. It never installs. When it prints
169
182
  `Review loop unchanged.`, ask nothing. Packages come from declared workspaces;
170
183
  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`.
174
-
175
- Show the table and ask its one question. Only after the user's yes in this
176
- conversation, run `review-tools.mjs install --root . --yes` (add
177
- `--tools <ids>` for a per-tool choice); it adds project-local tools with the
178
- project's own package manager and lockfile. Never run a system install, `sudo`,
179
- a license acceptance or a sign-in: give the user the printed steps. Then record
180
- the choice, with `--skip <ids>` for declined tools:
184
+ not ignore. When it prints `No packages found`, ask the user once which folders
185
+ hold the apps and pass them as `--packages <dir,dir>` to `plan`, `install` and
186
+ `record`. When the user says there is no app to review (for example one script
187
+ with no manifest), record their words with `record --none "<reason>"`; a
188
+ repeated setup then prints `Review loop unchanged.` and asks nothing.
189
+
190
+ Show the table: what the plan found per package. Ask the user to confirm it or
191
+ name a tool the plan missed, together with its one question. For a gap, say
192
+ plainly that automated review of that package needs a tool that can show the
193
+ work. Recommend one from the hint list (`review-tools.json`), with its
194
+ trade-offs: size, what it can show, cost and licence. Say you are happy to
195
+ research other options. Explain what the install runs and where, then wait for
196
+ the user's yes in this conversation before you run
197
+ `review-tools.mjs install --root . --yes` (add `--tools <ids>` for a per-tool
198
+ choice or a hint the user picked). It adds project-local tools with the
199
+ project's own package manager and lockfile. It also runs a user-scope CLI
200
+ install (`npm install -g`, `brew install`) when the hint marks no `sudo`,
201
+ licence or sign-in. Never run `sudo`, a licence acceptance or a sign-in: give
202
+ the user the printed `steps`. Then record the choice:
181
203
 
182
204
  ```sh
183
- node .joycraft/runtime/review-tools.mjs record --root . --skip <ids>
205
+ node .joycraft/runtime/review-tools.mjs record --root . [--choose <package>=<tool>] [--command <package>=<command>] [--skip <tool>|<package>:<tool>|<package>] [--host <name> --host-tools <observed host tools>]
184
206
  ```
185
207
 
186
- This writes or replaces only the `## Review loop` section of `AGENTS.md`: each
187
- tool, the command that starts the app and the command that takes the evidence.
188
- Worker packets carry that section. For a skipped UI tool, say in one line that
189
- its UI claims stay `UNVERIFIED`. With no network, the probes still run; offer
190
- the install later. For a CI-only project, record the CI job as the evidence
208
+ `--choose` records the tool the user picked for a package (a hint id, or a
209
+ found script with its `--command`); `'apps/*'=<tool>` records one shared harness
210
+ for those packages. `--skip <tool>` skips that missing tool in every package;
211
+ `--skip apps/lab:<tool>` or `--skip apps/lab` skips only that package. Repeat
212
+ `--command` per value. This writes or replaces only the `## Review loop` section
213
+ of `AGENTS.md`: one row per package with its tool, what it can show, the command
214
+ that starts the app and the command that takes the evidence. Recording again
215
+ keeps earlier choices and skips for packages the call does not name. Host tools
216
+ go to the git-ignored `.joycraft/local/review-loop.json`, never `AGENTS.md`.
217
+ Worker packets carry both. A skipped package's row says it is not reviewed
218
+ (user skipped). With no network, the probes still run; offer the install later. For a CI-only project, record the CI job as the evidence
191
219
  source when the user picks it.
192
220
 
221
+ **Change a tool.** Talk about the review loop only here: at install, at
222
+ setup and upgrade when the plan reports a change, and when the user asks to
223
+ try, switch, add or remove a tool ("try Maestro for the iOS app"). For a
224
+ request, confirm or research the tool, install it as above, and re-record only
225
+ that package with `--choose <package>=<tool>` (or `--skip` to remove one);
226
+ other rows stay. When the plan's `Changed since the recorded Review loop` names
227
+ a newly detected tool, offer to switch that package to it. When it reports
228
+ `recorded with v1; re-record to keep it`, confirm the table with the user and run
229
+ record again, repeating any `--choose` or `--skip` the table shows; a v1 record
230
+ does not carry them over. An unchanged project asks nothing.
231
+
193
232
  `review-tools.json` also lists `optIn` tools that detection never plans. Offer
194
233
  one only when it fits the project. Example: Doc Detective, for docs that are
195
234
  step-by-step procedures. Say what it does not cover and that it is AGPL-3.0 with a
@@ -272,10 +311,11 @@ changes the next action. Prefer one short contextual question and continue
272
311
  independent work while it is pending. Do not generate a questionnaire or start
273
312
  building an imagined app.
274
313
 
275
- Use the project’s existing interaction home for a choice. A question with
276
- options goes in the decision artifact; only one quick yes/no or an open question
277
- with no options stays in native chat. Retain a chat answer in the
278
- owning brief and do not ask it again.
314
+ Use the project’s existing interaction home for a choice. Ask a question with
315
+ options in the user's question style ([asking questions](artifacts.md#asking-questions)),
316
+ in the decision artifact or in chat; only one quick yes/no or an open question
317
+ with no options stays in native chat without a decision. Retain a chat answer in
318
+ the owning brief and do not ask it again.
279
319
 
280
320
  ## Finish setup and continue
281
321
 
@@ -291,7 +331,7 @@ installation manifest `.joycraft/installation.json` records the installed bytes;
291
331
  it is dispatch input, not proof that hooks ran or that a review was independent.
292
332
 
293
333
  A new worker reads `.joycraft/preferences.json` before work, reuses explicit
294
- model, effort, role, concurrency and verification choices, and inspects the
334
+ model, effort, role, concurrency, verification and question-style choices, and inspects the
295
335
  host's available planner, implementer, reviewer, testing, UI and fixture
296
336
  capabilities instead of assuming a model. It states unavailable roles plainly.
297
337
  Setup and upgrade never change accepted queues, decision state, user guidance or
@@ -94,20 +94,27 @@ an accepted reference only when that reference is part of the requirement or is
94
94
  available and relevant to the comparison. This does not create a universal
95
95
  before/after gate.
96
96
 
97
+ Take visual evidence with the package's recorded tool from the packet's
98
+ `reviewLoop` (shared `section` plus `local` host tools), within its `canShow`.
97
99
  An empty `visual.interactions` list is appropriate for a static appearance-only
98
- claim. For an interactive requirement, the reviewer must require the relevant
99
- actions and outcomes; the validator cannot infer them from a criterion id. A
100
+ claim or a tool whose `canShow` has no `interact`. A limit the user agreed to is
101
+ not UNVERIFIED: the reviewer reports how it checked and the parent agent judges
102
+ what is left. For an interactive requirement whose tool can interact, the
103
+ reviewer must require the relevant actions and outcomes; the validator cannot
104
+ infer them from a criterion id. A
100
105
  disabled control or error state can itself be an observed result; explain it.
101
106
 
102
107
  When an inspection finds a scoped defect: retain the observation, fix it, render
103
108
  again, repeat affected interactions and inspect the result. If the fix changes a
104
109
  bound input, obtain a new subject and fresh affected observations before seeking
105
110
  completion. Keep the final flow concise and link prior diagnostics rather than
106
- copying a transcript. An unavailable browser, inaccessible route or blocked tool
107
- is a limit and UNVERIFIED check, not permission to bypass access controls or
108
- declare visual PASS. Do not wrap, relay, or otherwise route around a denied
109
- command; ask the host for the legitimate correction. Continue independent work
110
- that remains possible.
111
+ copying a transcript. A recorded tool that stopped working (a browser that
112
+ will not launch) is a tool break: an UNVERIFIED check with `cause: 'tool-break'`,
113
+ not an agreed limit. A route the app does not serve can be an app defect and a
114
+ FAIL. A command the host denies is not a tool break. None of these permits
115
+ bypassing access controls or declaring visual PASS.
116
+ Do not wrap, relay, or otherwise route around a denied command; ask the host for
117
+ the legitimate correction. Continue independent work that remains possible.
111
118
 
112
119
  ## Where checks run
113
120
 
@@ -29,6 +29,14 @@ Use the version from `latest`:
29
29
  apply a migration without the user's yes.
30
30
  3. Run `npx joycraft@<latest> doctor .`.
31
31
  4. Tell the user in plain words what is different now.
32
+ 5. Run the review-loop plan
33
+ ([review loop tools](setup.md#review-loop-tools)). When it prints
34
+ `Review loop unchanged.`, say nothing about it. When it reports a newly
35
+ detected tool, offer to switch that package to it and re-record only that
36
+ package with `--choose`.
37
+ When it reports `recorded with v1; re-record to keep it`, confirm the table with the
38
+ user and run record again, repeating any `--choose` or `--skip` the table shows; a
39
+ v1 record does not carry them over.
32
40
 
33
41
  If the update fails, run `npx joycraft@<latest> update . --recover`, tell the user
34
42
  that the files are back as they were, and continue your work.
@@ -24,8 +24,10 @@ Routine refinements within the answer do not require another approval.
24
24
 
25
25
  ## Decision artifacts
26
26
 
27
- Ask the user to choose between options through the artifact workflow in
28
- [artifacts.md](artifacts.md), not as a list in chat. Plain chat is only for one
27
+ Record each choice between options as a brief decision and ask it in the
28
+ user's question style ([asking questions](artifacts.md#asking-questions)): one
29
+ at a time or as a page, in the artifact or in chat. Save every answer to the
30
+ brief, whatever the surface. Plain chat with no decision record is only for one
29
31
  quick yes/no or an open question with no options.
30
32
  The brief remains authoritative; artifact data selects what to show and does not
31
33
  copy the brief or hold independent answers.
@@ -36,7 +38,9 @@ The optional `joycraft-ui-slice/scripts/serve.mjs` helper supports a JSON flow
36
38
  array under top-level `decisions:` in YAML frontmatter, as in the brief template.
37
39
  Each displayed record has `id`, `status`, `question`, `answer` (null or an option
38
40
  value), `options` (two or more `{value,label}` records) and `affected` (paths/IDs).
39
- Options may additionally have a concise `description` and `requiresNote: true`.
41
+ Options may additionally have a concise `description`, `example`, `tradeoff`,
42
+ `recommended: true` and `requiresNote: true`; a decision may have `context`,
43
+ `why`, `details` and `recommendation` ([decisions](artifacts.md#decisions-and-view-data)).
40
44
  Other record fields and all text outside that array are preserved. Unsupported or
41
45
  malformed frontmatter is rejected; adapt the artifact to an existing project
42
46
  format instead of migrating it without cause. This is an authoring convention,
@@ -68,8 +72,9 @@ outcomes, viewport, route/state and limits. A screenshot or static render is
68
72
  enough for an appearance-only choice only when it is actually inspected; it cannot
69
73
  prove that the answer was saved. Ask concise visual-detail questions before making
70
74
  a pixel-sensitive choice when the available render leaves them material. Check
71
- both file state and reload. If tools are unavailable or denied, mark required
72
- visual work UNVERIFIED and continue disjoint work. Never bypass a denial with
75
+ both file state and reload. If a recorded tool breaks or is denied, mark required
76
+ visual work UNVERIFIED and continue disjoint work; a limit the user agreed to is
77
+ not UNVERIFIED. Never bypass a denial with
73
78
  another route.
74
79
 
75
80
  ## Commitment and queue
@@ -4,7 +4,7 @@ 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
- import { validateOwnerAcceptance } from './completion.mjs';
7
+ import { validateOwnerAcceptance, validateWaiver } from './completion.mjs';
8
8
  import { readConfig, workPaths } from './config.mjs';
9
9
 
10
10
  const featureName = value => {
@@ -262,7 +262,22 @@ const validTimestamp = value => typeof value === 'string' && nonempty(value) &&
262
262
  function historicalDecision(root, queuePath, state, reconciliation) {
263
263
  const accepted = state.spec.acceptedReport;
264
264
  const owner = state.spec.ownerAcceptance;
265
- requireValue(!(accepted !== undefined && owner !== undefined), `Spec ${state.spec.id} has both acceptedReport and ownerAcceptance`);
265
+ const waiver = state.spec.waiver;
266
+ requireValue([accepted, owner, waiver].filter(item => item !== undefined).length <= 1, `Spec ${state.spec.id} has more than one of acceptedReport, ownerAcceptance and waiver`);
267
+ if (waiver !== undefined) {
268
+ // The brief may evolve after completion; the waiver bytes and record stay bound.
269
+ requireValue(isObject(waiver) && isSha256(waiver.sha256), `Spec ${state.spec.id} has a malformed waiver`);
270
+ const waiverPath = relativePath(waiver.path);
271
+ const waiverBytes = readLocal(root, waiverPath);
272
+ requireValue(sha256(waiverBytes) === waiver.sha256, `Feature waiver is missing or changed: ${waiverPath}`);
273
+ const record = parseJson(waiverBytes, waiverPath);
274
+ validateWaiver({ root, waiver: record, waiverPath, state, checkSource: false });
275
+ const limitations = [`waived by the user: "${record.instruction}"`];
276
+ if (waiver.review === undefined) return { kind: 'feature-waiver', path: waiverPath, sha256: waiver.sha256, report: null, covers: record.covers, receipts: [], limitations };
277
+ const report = historicalReport(root, queuePath, state, waiver.review, { ownerAccepted: true, reconciliation });
278
+ requireValue(report.verdict === 'UNVERIFIED', `Waived report must stay UNVERIFIED: ${report.path}`);
279
+ return { kind: 'feature-waiver', path: waiverPath, sha256: waiver.sha256, report: { path: report.path, sha256: report.sha256, verdict: report.verdict }, covers: record.covers, receipts: report.receipts, limitations, ...(report.requirementHistory ? { requirementHistory: report.requirementHistory } : {}) };
280
+ }
266
281
  if (accepted !== undefined) {
267
282
  const report = historicalReport(root, queuePath, state, accepted, { reconciliation });
268
283
  return { kind: 'accepted-report', path: report.path, sha256: report.sha256, report: { path: report.path, sha256: report.sha256, verdict: report.verdict }, receipts: report.receipts, limitations: [], ...(report.requirementHistory ? { requirementHistory: report.requirementHistory } : {}) };
@@ -305,7 +320,7 @@ function existingArchive(root, feature) {
305
320
  if (['queue-scope', 'queue-status', 'spec-status'].includes(record.normalization) || record.reconciliationEntry !== undefined) {
306
321
  requireValue(manifest.reconciliation && record.reconciliationSha256 === manifest.reconciliation.sha256 && Number.isInteger(record.reconciliationEntry), `Reconciled replay has no matching paper trail: ${archivedPath}`);
307
322
  const entry = manifest.reconciliation.record.entries[record.reconciliationEntry];
308
- requireValue(entry && entry.path === record.path && entry.normalization === record.normalization && entry.acceptedSha256 === record.acceptedSha256 && (entry.acceptedCommit === undefined || entry.acceptedCommit === record.acceptedCommit) && manifest.evidence.some(decision => decision.report.path === entry.report.path && decision.report.sha256 === entry.report.sha256 && decision.requirementHistory?.some(item => canonical(item) === canonical(record))) && manifest.files.some(item => ['moved', 'copied'].includes(item.operation) && item.originalPath === entry.path && item.sha256 === entry.currentSha256), `Reconciled replay differs from its paper trail: ${archivedPath}`);
323
+ requireValue(entry && entry.path === record.path && entry.normalization === record.normalization && entry.acceptedSha256 === record.acceptedSha256 && (entry.acceptedCommit === undefined || entry.acceptedCommit === record.acceptedCommit) && manifest.evidence.some(decision => decision.report?.path === entry.report.path && decision.report?.sha256 === entry.report.sha256 && decision.requirementHistory?.some(item => canonical(item) === canonical(record))) && manifest.files.some(item => ['moved', 'copied'].includes(item.operation) && item.originalPath === entry.path && item.sha256 === entry.currentSha256), `Reconciled replay differs from its paper trail: ${archivedPath}`);
309
324
  }
310
325
  requireValue(archivedPath === restoredPath(destination, record) && sha256(requirementProjection(bytes, record)) === record.acceptedSha256, `Restored requirement does not match acceptance: ${archivedPath}`);
311
326
  }
@@ -354,7 +369,7 @@ export function previewArchiveFeature({ root = process.cwd(), feature, phase, at
354
369
  if (reconciliation) requireValue(reconciliation.used.size === reconciliation.record.entries.length, 'Archive reconciliation contains unused or stale entries');
355
370
  const copies = new Map();
356
371
  for (const decision of evidence) {
357
- for (const evidencePath of [decision.path, decision.report.path, ...decision.receipts.map(receipt => receipt.path)]) {
372
+ for (const evidencePath of [decision.path, decision.report?.path, ...decision.receipts.map(receipt => receipt.path)].filter(Boolean)) {
358
373
  if (!evidencePath.startsWith(`${source}/`)) copies.set(evidencePath, fileDigest(root, evidencePath));
359
374
  }
360
375
  }
@@ -1,19 +1,19 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { pathToFileURL } from 'node:url';
3
- import { loadArtifact, persistResponses, readProjectFile, writeArtifact } from './model.mjs';
3
+ import { loadArtifact, persistResponses, readProjectFile, replaceBrief, writeArtifact } from './model.mjs';
4
4
  import { renderArtifact } from './render.mjs';
5
5
  import { startArtifact } from './server.mjs';
6
- import { setArtifactColors, setArtifactTheme } from './preferences.mjs';
6
+ import { briefQuestionStyle, effectiveQuestionStyle, parseQuestionStyle, projectQuestionStyle, setArtifactColors, setArtifactTheme, setQuestionStyle, withBriefQuestionStyle } from './preferences.mjs';
7
7
 
8
8
  export async function main(argv, root = process.cwd()) {
9
9
  const [command, ...args] = argv;
10
- const flags = command === 'serve' ? ['--brief', '--view', '--theme'] : command === 'build' ? ['--brief', '--view', '--out', '--mode', '--theme'] : command === 'import' ? ['--brief', '--view', '--responses', '--apply'] : command === 'theme' ? ['--set'] : command === 'colors' ? ['--set', '--reset'] : [];
11
- if (!flags.length) throw new Error('Use serve --brief <path> [--view <path>] [--theme light|dark], build --brief <path> [--view <path>] --out <path> --mode claude|portable [--theme light|dark], import --brief <path> [--view <path>] --responses <path> [--apply], theme --set light|dark, or colors --set <colors.json> | --reset');
10
+ const flags = command === 'serve' ? ['--brief', '--view', '--theme'] : command === 'build' ? ['--brief', '--view', '--out', '--mode', '--theme'] : command === 'import' ? ['--brief', '--view', '--responses', '--apply'] : command === 'theme' ? ['--set'] : command === 'colors' ? ['--set', '--reset'] : command === 'questions' ? ['--brief', '--set', '--clear'] : [];
11
+ if (!flags.length) throw new Error('Use serve --brief <path> [--view <path>] [--theme light|dark], build --brief <path> [--view <path>] --out <path> --mode claude|portable [--theme light|dark], import --brief <path> [--view <path>] --responses <path> [--apply], theme --set light|dark, colors --set <colors.json> | --reset, or questions [--brief <path>] [--set pacing=one-at-a-time|page,surface=chat|artifact | --clear]');
12
12
  const values = {};
13
13
  for (let i = 0; i < args.length; i += 1) {
14
14
  const flag = args[i];
15
15
  if (!flags.includes(flag) || Object.hasOwn(values, flag)) throw new Error(`Unknown or repeated argument: ${flag}`);
16
- if (flag === '--apply' || flag === '--reset') values[flag] = true;
16
+ if (flag === '--apply' || flag === '--reset' || flag === '--clear') values[flag] = true;
17
17
  else { if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing value for ${flag}`); values[flag] = args[++i]; }
18
18
  }
19
19
  if (command === 'theme') {
@@ -22,6 +22,30 @@ export async function main(argv, root = process.cwd()) {
22
22
  console.log(JSON.stringify({ path: '.joycraft/preferences.json', theme: preferences.artifacts.theme }, null, 2));
23
23
  return preferences;
24
24
  }
25
+ if (command === 'questions') {
26
+ // With --brief, --set and --clear change only that feature; without it, --set changes the project default.
27
+ const briefPath = values['--brief'];
28
+ if (values['--set'] && values['--clear']) throw new Error('Use --set or --clear, not both');
29
+ if (values['--clear'] && !briefPath) throw new Error('--clear needs --brief: it removes a feature\'s own question style');
30
+ const change = values['--set'] ? parseQuestionStyle(values['--set']) : values['--clear'] ? null : undefined;
31
+ // Read the project default first: a bad stored preference must stop the command before any write.
32
+ const project = await projectQuestionStyle(root);
33
+ let brief;
34
+ if (briefPath) {
35
+ const text = (await readProjectFile(root, briefPath)).toString('utf8');
36
+ brief = briefQuestionStyle(text);
37
+ if (change !== undefined) {
38
+ const updated = withBriefQuestionStyle(text, change);
39
+ // Check the new text before the write: a failed command must leave the brief as it was.
40
+ brief = briefQuestionStyle(updated);
41
+ if (JSON.stringify(brief ?? null) !== JSON.stringify(change === null ? null : { ...(briefQuestionStyle(text) ?? {}), ...change })) throw new Error('Could not write question-style: safely; the brief is unchanged');
42
+ await replaceBrief(root, briefPath, text, updated);
43
+ }
44
+ } else if (change) await setQuestionStyle(root, change);
45
+ const style = effectiveQuestionStyle({ project: change && !briefPath ? await projectQuestionStyle(root) : project, brief });
46
+ console.log(JSON.stringify(style, null, 2));
47
+ return style;
48
+ }
25
49
  if (command === 'colors') {
26
50
  if (!values['--set'] === !values['--reset']) throw new Error('Colors needs --set <colors.json> or --reset');
27
51
  let colors = null;
@@ -102,16 +102,25 @@ function displayedDecision(brief, id) {
102
102
  !Array.isArray(decision.affected) || !decision.affected.every(nonempty)) {
103
103
  throw new Error('Displayed decision needs question, options and affected references');
104
104
  }
105
- for (const field of ['why', 'context', 'details']) validateOptionalString(decision[field], `Decision ${field}`);
105
+ for (const field of ['why', 'context', 'details', 'recommendation']) validateOptionalString(decision[field], `Decision ${field}`);
106
106
  const values = new Set();
107
+ let recommended = 0;
107
108
  for (const option of decision.options) {
108
109
  if (!option || typeof option !== 'object' || Array.isArray(option) || !nonempty(option.value) || !nonempty(option.label) || values.has(option.value)) {
109
110
  throw new Error('Invalid decision options');
110
111
  }
111
- validateOptionalString(option.description, 'Option description');
112
+ for (const field of ['description', 'example', 'tradeoff']) validateOptionalString(option[field], `Option ${field}`);
112
113
  if (option.requiresNote !== undefined && typeof option.requiresNote !== 'boolean') throw new Error('Option requiresNote must be boolean');
114
+ if (option.recommended !== undefined && typeof option.recommended !== 'boolean') throw new Error('Option recommended must be boolean');
115
+ if (option.recommended === true) {
116
+ if (option.value === CUSTOM_OPTION.value) throw new Error('"Something else" cannot be the recommended option');
117
+ recommended += 1;
118
+ }
113
119
  values.add(option.value);
114
120
  }
121
+ // One recommendation at most, and a stated reason needs the option it recommends.
122
+ if (recommended > 1) throw new Error('Only one option can be recommended');
123
+ if (decision.recommendation !== undefined && recommended === 0) throw new Error('A recommendation needs a recommended option');
115
124
  values.add(CUSTOM_OPTION.value);
116
125
  if (!(decision.answer === null || values.has(decision.answer)) || (decision.status === 'clarified' && decision.answer === null)) {
117
126
  throw new Error('Invalid decision answer');
@@ -127,15 +136,14 @@ function publicQuestion(decision) {
127
136
  question: decision.question,
128
137
  options: withCustomOption(decision.options).map(option => {
129
138
  const result = { value: option.value, label: option.label };
130
- if (option.description !== undefined) result.description = option.description;
131
- if (option.requiresNote !== undefined) result.requiresNote = option.requiresNote;
139
+ for (const field of ['description', 'example', 'tradeoff', 'requiresNote', 'recommended']) if (option[field] !== undefined) result[field] = option[field];
132
140
  return result;
133
141
  }),
134
142
  affected: [...decision.affected],
135
143
  status: decision.status,
136
144
  answer: decision.answer
137
145
  };
138
- for (const field of ['why', 'context', 'details']) if (decision[field] !== undefined) question[field] = decision[field];
146
+ for (const field of ['why', 'context', 'details', 'recommendation']) if (decision[field] !== undefined) question[field] = decision[field];
139
147
  if (decision.note !== undefined) question.note = decision.note;
140
148
  return question;
141
149
  }
@@ -111,7 +111,7 @@ export function validateEnvelope(envelope, model) {
111
111
  }
112
112
 
113
113
  /** Cooperative lock + compare before atomic replacement; no silent stale write. */
114
- async function replaceBrief(root, path, before, after) {
114
+ export async function replaceBrief(root, path, before, after) {
115
115
  if (before === after) return;
116
116
  const absolute = await checkedPath(root, path);
117
117
  const lock = `${absolute}.joycraft-answer-lock`;
@@ -76,6 +76,7 @@ function parsePreferences(bytes) {
76
76
  catch { throw new Error(`Invalid JSON: ${preferencePath}`); }
77
77
  if (!preferences || typeof preferences !== 'object' || Array.isArray(preferences)) throw new Error(`${preferencePath} must contain an object`);
78
78
  if (preferences.artifacts !== undefined && (!preferences.artifacts || typeof preferences.artifacts !== 'object' || Array.isArray(preferences.artifacts))) throw new Error(`${preferencePath} artifacts must be an object`);
79
+ if (preferences.questions !== undefined) checkedQuestionStyle(preferences.questions, `${preferencePath} questions`);
79
80
  return preferences;
80
81
  }
81
82
 
@@ -87,7 +88,7 @@ export async function artifactTheme(root) {
87
88
  return preferences.artifacts?.theme === undefined ? undefined : checkedTheme(preferences.artifacts.theme, 'Artifact preference theme');
88
89
  }
89
90
 
90
- async function updatePreferences(root, change) {
91
+ async function updatePreferences(root, change, section = 'artifacts') {
91
92
  const base = await realpath(root);
92
93
  const directory = join(base, '.joycraft');
93
94
  await mkdir(directory, { recursive: true });
@@ -97,7 +98,7 @@ async function updatePreferences(root, change) {
97
98
  let preferences;
98
99
  try { preferences = parsePreferences(await readFile(path)); }
99
100
  catch (error) { if (error.code !== 'ENOENT') throw error; preferences = { schemaVersion: 1 }; }
100
- const updated = { ...preferences, artifacts: change({ ...(preferences.artifacts ?? {}) }) };
101
+ const updated = { ...preferences, [section]: change({ ...(preferences[section] ?? {}) }) };
101
102
  const temporary = `${path}.prefs-${randomBytes(8).toString('hex')}`;
102
103
  const file = await open(temporary, 'wx', 0o600);
103
104
  try { await file.writeFile(`${JSON.stringify(updated, null, 2)}\n`); await file.sync(); }
@@ -125,3 +126,95 @@ export async function setArtifactColors(root, colors) {
125
126
  const checked = colors === null ? null : await checkedColors(colors);
126
127
  return updatePreferences(root, ({ colors: _colors, ...artifacts }) => checked && Object.keys(checked).length ? { ...artifacts, colors: checked } : artifacts);
127
128
  }
129
+
130
+ // How an agent asks the user: how many decisions at once, and where.
131
+ const questionValues = Object.freeze({ pacing: ['one-at-a-time', 'page'], surface: ['chat', 'artifact'] });
132
+ /** With no recorded style, Joycraft asks as it always has (decision `unset-default`). */
133
+ export const DEFAULT_QUESTION_STYLE = Object.freeze({ pacing: 'page', surface: 'artifact' });
134
+ const styleLine = /^question-style:[ \t]*([^\r\n]*)/gm;
135
+
136
+ export function checkedQuestionStyle(style, source = 'Question style') {
137
+ if (!style || typeof style !== 'object' || Array.isArray(style)) throw new Error(`${source} must be an object with pacing and/or surface`);
138
+ for (const [key, value] of Object.entries(style)) {
139
+ if (!Object.hasOwn(questionValues, key)) throw new Error(`${source} has an unknown key: ${key}. Use: ${Object.keys(questionValues).join(', ')}`);
140
+ if (!questionValues[key].includes(value)) throw new Error(`${source} ${key} must be ${questionValues[key].join(' or ')}`);
141
+ }
142
+ return style;
143
+ }
144
+
145
+ /** Parse `pacing=one-at-a-time,surface=chat` from the command line. */
146
+ export function parseQuestionStyle(value) {
147
+ const style = {};
148
+ for (const pair of String(value).split(',')) {
149
+ const [key, choice, extra] = pair.split('=').map(part => part.trim());
150
+ if (!key || choice === undefined || extra !== undefined || Object.hasOwn(style, key)) throw new Error('Use --set key=value[,key=value], for example pacing=one-at-a-time,surface=chat');
151
+ style[key] = choice;
152
+ }
153
+ return checkedQuestionStyle(style, 'Question style');
154
+ }
155
+
156
+ function frontmatterBounds(text) {
157
+ const match = /^(---\r?\n)([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
158
+ if (!match) throw new Error('Brief needs YAML frontmatter');
159
+ const start = match[1].length;
160
+ return { start, end: start + match[2].length };
161
+ }
162
+
163
+ function styleLines(text) {
164
+ const { start, end } = frontmatterBounds(text);
165
+ return [...text.slice(start, end).matchAll(styleLine)].map(match => ({ index: start + match.index, length: match[0].length, value: match[1] }));
166
+ }
167
+
168
+ /** The brief's own question style, or undefined when it keeps the project's. */
169
+ export function briefQuestionStyle(text) {
170
+ const lines = styleLines(text);
171
+ if (lines.length > 1) throw new Error('Expected at most one question-style: line');
172
+ if (!lines.length) return undefined;
173
+ let style;
174
+ try { style = JSON.parse(lines[0].value); }
175
+ catch { throw new Error('question-style: must be a JSON object, for example {"pacing":"one-at-a-time"}'); }
176
+ return checkedQuestionStyle(style, 'Brief question-style');
177
+ }
178
+
179
+ /** Replace, add or (with null) remove only the brief's question-style line. */
180
+ export function withBriefQuestionStyle(text, style) {
181
+ const current = briefQuestionStyle(text);
182
+ const [line] = styleLines(text);
183
+ if (style === null) {
184
+ if (!line) return text;
185
+ // Remove the line with its own ending, whatever the rest of the file uses.
186
+ const next = text.indexOf('\n', line.index + line.length);
187
+ return text.slice(0, line.index) + text.slice(next + 1);
188
+ }
189
+ const merged = checkedQuestionStyle({ ...(current ?? {}), ...style }, 'Brief question-style');
190
+ const replacement = `question-style: ${JSON.stringify(merged)}`;
191
+ if (line) return text.slice(0, line.index) + replacement + text.slice(line.index + line.length);
192
+ // The new line takes the ending of the last frontmatter line, so --clear gives the same bytes back.
193
+ const { end } = frontmatterBounds(text);
194
+ const newline = text.startsWith('\r\n', end) ? '\r\n' : '\n';
195
+ return text.slice(0, end) + newline + replacement + text.slice(end);
196
+ }
197
+
198
+ export async function projectQuestionStyle(root) {
199
+ let path;
200
+ try { path = await checkedPreferencePath(root); }
201
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
202
+ return parsePreferences(await readFile(path)).questions;
203
+ }
204
+
205
+ export async function setQuestionStyle(root, style) {
206
+ checkedQuestionStyle(style);
207
+ return updatePreferences(root, questions => ({ ...questions, ...style }), 'questions');
208
+ }
209
+
210
+ /** Each key from the brief first, then the project, then the default; `source` says which. */
211
+ export function effectiveQuestionStyle({ project, brief } = {}) {
212
+ const result = {};
213
+ const source = {};
214
+ for (const key of Object.keys(questionValues)) {
215
+ [result[key], source[key]] = brief?.[key] !== undefined ? [brief[key], 'brief'] : project?.[key] !== undefined ? [project[key], 'project'] : [DEFAULT_QUESTION_STYLE[key], 'default'];
216
+ }
217
+ result.source = source;
218
+ if (project === undefined || Object.keys(project).length === 0) result.unset = true;
219
+ return result;
220
+ }