joycraft 1.1.1 → 1.2.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 (49) 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-decompose/SKILL.md +5 -1
  9. package/payload/.agents/skills/joycraft-entry/SKILL.md +35 -8
  10. package/payload/.agents/skills/joycraft-implement/SKILL.md +16 -0
  11. package/payload/.agents/skills/joycraft-session-end/SKILL.md +9 -4
  12. package/payload/.agents/skills/joycraft-testing/SKILL.md +7 -5
  13. package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +4 -3
  14. package/payload/.agents/skills/joycraft-verify/SKILL.md +1 -1
  15. package/payload/.claude/agents/joycraft-reviewer.md +7 -2
  16. package/payload/.joycraft/assets/artifacts/kit.css +8 -0
  17. package/payload/.joycraft/assets/artifacts/kit.js +163 -21
  18. package/payload/.joycraft/assets/artifacts/transports.js +14 -3
  19. package/payload/.joycraft/contracts/types.d.ts +22 -0
  20. package/payload/.joycraft/references/archive.md +4 -2
  21. package/payload/.joycraft/references/artifacts.md +21 -2
  22. package/payload/.joycraft/references/cleanup.md +109 -3
  23. package/payload/.joycraft/references/completion.md +55 -2
  24. package/payload/.joycraft/references/context.md +64 -2
  25. package/payload/.joycraft/references/dispatch.md +12 -0
  26. package/payload/.joycraft/references/doc-cleanup-LICENSE.md +23 -0
  27. package/payload/.joycraft/references/knowledge.md +58 -0
  28. package/payload/.joycraft/references/setup.md +165 -151
  29. package/payload/.joycraft/references/testing.md +14 -7
  30. package/payload/.joycraft/references/update.md +13 -3
  31. package/payload/.joycraft/references/workflow.md +3 -2
  32. package/payload/.joycraft/runtime/archive.mjs +19 -4
  33. package/payload/.joycraft/runtime/artifacts/decisions.mjs +16 -5
  34. package/payload/.joycraft/runtime/artifacts/server.mjs +14 -1
  35. package/payload/.joycraft/runtime/cleanup.mjs +95 -8
  36. package/payload/.joycraft/runtime/completion.mjs +210 -10
  37. package/payload/.joycraft/runtime/config.mjs +5 -3
  38. package/payload/.joycraft/runtime/dispatch-preflight.mjs +16 -3
  39. package/payload/.joycraft/runtime/evidence.mjs +4 -0
  40. package/payload/.joycraft/runtime/identity.mjs +11 -0
  41. package/payload/.joycraft/runtime/review-tools.json +110 -30
  42. package/payload/.joycraft/runtime/review-tools.mjs +702 -131
  43. package/payload/.joycraft/runtime/status.mjs +1 -1
  44. package/payload/.joycraft/runtime/update-check.mjs +38 -8
  45. package/payload/.joycraft/runtime/wiring.mjs +156 -0
  46. package/payload/.joycraft/runtime/worktrees.mjs +1 -1
  47. package/payload/.joycraft/templates/joycraft.yaml +2 -0
  48. package/payload/.joycraft/templates/project-context.md +6 -1
  49. package/payload/PIN +45 -42
@@ -41,6 +41,39 @@
41
41
  });
42
42
  }
43
43
 
44
+ // What a person decides from: the question, its options, and its recorded state.
45
+ function questionSignature(question) {
46
+ return JSON.stringify({
47
+ question: question.question || '',
48
+ options: (question.options || []).map(function (option) {
49
+ return { value: option.value, label: option.label || '', description: option.description || '', requiresNote: Boolean(option.requiresNote) };
50
+ }),
51
+ status: question.status || '',
52
+ answer: question.answer == null ? null : question.answer,
53
+ note: question.note == null ? '' : question.note
54
+ });
55
+ }
56
+
57
+ // Questions that differ between two models: changed, added or removed, in display order.
58
+ function changedQuestions(before, after) {
59
+ var oldQuestions = (before && before.questions) || [];
60
+ var newQuestions = (after && after.questions) || [];
61
+ var oldById = Object.create(null);
62
+ oldQuestions.forEach(function (question) { oldById[question.id] = question; });
63
+ var newIds = Object.create(null);
64
+ var changes = [];
65
+ newQuestions.forEach(function (question) {
66
+ newIds[question.id] = true;
67
+ var previous = oldById[question.id];
68
+ if (!previous) changes.push({ id: question.id, question: question.question || question.id, change: 'added' });
69
+ else if (questionSignature(previous) !== questionSignature(question)) changes.push({ id: question.id, question: question.question || question.id, change: 'changed' });
70
+ });
71
+ oldQuestions.forEach(function (question) {
72
+ if (!newIds[question.id]) changes.push({ id: question.id, question: question.question || question.id, change: 'removed' });
73
+ });
74
+ return changes;
75
+ }
76
+
44
77
  function mount(config) {
45
78
  if (!config || !config.element) throw new Error('JoycraftArtifacts.mount requires an element.');
46
79
  var root = config.element;
@@ -56,13 +89,21 @@
56
89
  var saving = false;
57
90
  var destroyed = false;
58
91
  var copyFallback = '';
59
- var sourceChanged = false;
92
+ // Persistent notice after the brief changed under this page. It stays until dismissed,
93
+ // so selecting options (which updates the status line) never hides it.
94
+ var sourceNotice = null;
95
+ // The notice element is created once and reused, so a re-render does not re-announce it.
96
+ var noticeElement = null, noticeKey = '';
60
97
  var message = transport ? 'Loading saved responses…' : 'Read-only preview. A response transport is not available.';
61
98
  var messageKind = transport ? 'quiet' : 'notice';
62
99
 
63
100
  function isReadOnly(question) {
64
101
  return !writable || ['clarified', 'settled', 'backlogged', 'discarded'].indexOf(question.status) !== -1;
65
102
  }
103
+ // A saved answer keeps its note open: the note can be added or changed and saved again.
104
+ function canEditNote(question) {
105
+ return writable && (!isReadOnly(question) || question.status === 'clarified');
106
+ }
66
107
  function dirty() { return !sameResponses(draft, saved); }
67
108
  function setMessage(kind, value) { messageKind = kind; message = value; }
68
109
  function statusLabel(status) {
@@ -87,11 +128,11 @@
87
128
 
88
129
  function unsavedAnswers() { return copiedResponses(draft).filter(function (item) {
89
130
  var q = model.questions.find(function (candidate) { return candidate.id === item.id; });
90
- return q && !isReadOnly(q) && !sameResponses({ value: item }, { value: saved[item.id] || {} });
131
+ return q && canEditNote(q) && !sameResponses({ value: item }, { value: saved[item.id] || {} });
91
132
  }); }
92
133
 
93
134
  async function save(question) {
94
- if (!transport || !writable || saving || loading || sourceChanged) return;
135
+ if (!transport || !writable || saving || loading) return;
95
136
  var pendingAnswers = unsavedAnswers();
96
137
  var problem = question ? validation(question) : pendingAnswers.map(function (item) {
97
138
  var q = (model.questions || []).filter(function (candidate) { return candidate.id === item.id; })[0];
@@ -105,15 +146,46 @@
105
146
  var result = await transport.save({ revision: revision, answers: answers });
106
147
  if (destroyed) return;
107
148
  applyLoaded(result, Boolean(question), answers.map(function (answer) { return answer.id; }));
149
+ if (sourceNotice && sourceNotice.conflict) sourceNotice.saved = true;
108
150
  setMessage('success', (result && result.message) || 'Saved in artifact — awaiting brief sync.');
109
151
  } catch (error) {
110
- setMessage('error', 'Could not save. Your edits are still here. ' + (error && error.message ? error.message : 'Try refreshing before saving again.'));
152
+ if (error && error.conflict) await reloadAfterConflict(error);
153
+ else setMessage('error', 'Could not save. Your edits are still here. ' + (error && error.message ? error.message : 'Try refreshing before saving again.'));
111
154
  } finally { saving = false; render(); }
112
155
  }
156
+ // The source changed after this page loaded: reload it, keep drafts for unchanged
157
+ // questions, and name the questions that changed in the persistent notice.
158
+ async function reloadAfterConflict(error) {
159
+ var reason = error && error.message ? error.message : 'The source changed after this page loaded.';
160
+ if (typeof transport.load !== 'function') { setMessage('error', 'Not saved. ' + reason + ' Reload the page to continue.'); return; }
161
+ try {
162
+ var latest = await transport.load();
163
+ if (destroyed) return;
164
+ applyLoaded(latest, true);
165
+ } catch (loadError) {
166
+ setMessage('error', 'Not saved. ' + reason + ' Reloading the source also failed: ' + (loadError && loadError.message ? loadError.message : 'unknown error') + '. Your edits are still here.');
167
+ return;
168
+ }
169
+ sourceNotice = sourceNotice || { changes: [], viewChanged: false };
170
+ sourceNotice.conflict = reason;
171
+ sourceNotice.saved = false;
172
+ setMessage('error', 'Not saved: ' + reason + ' The page now shows the current source. Your other answers are kept; save again.');
173
+ }
174
+ function mergeNotice(changes, viewChanged) {
175
+ var current = sourceNotice || { changes: [], viewChanged: false, conflict: '' };
176
+ changes.forEach(function (change) {
177
+ var existing = current.changes.filter(function (item) { return item.id === change.id; })[0];
178
+ if (existing) { existing.question = change.question; if (change.change === 'removed' || existing.change !== 'added') existing.change = change.change; }
179
+ else current.changes.push(change);
180
+ });
181
+ current.viewChanged = current.viewChanged || viewChanged;
182
+ sourceNotice = current;
183
+ }
184
+ function changedIds() { return sourceNotice ? sourceNotice.changes.map(function (change) { return change.id; }) : []; }
113
185
  function applyLoaded(result, preserveDraft, confirmedIds) {
114
186
  confirmedIds = confirmedIds || [];
115
187
  if (!result) throw new Error('The response transport returned no state.');
116
- var oldRevision = revision;
188
+ var oldModel = model;
117
189
  var oldViewRevision = viewRevision;
118
190
  var pending = Object.assign(Object.create(null), draft);
119
191
  var previouslySaved = Object.assign(Object.create(null), saved);
@@ -123,24 +195,31 @@
123
195
  writable = Boolean(result.writable);
124
196
  storage = result.storage || storage;
125
197
  saved = responseMap(result.responses);
198
+ // Portable pages store only their own answers; start a recorded answer from the brief so its note can change.
199
+ (model.questions || []).forEach(function (q) {
200
+ if (q.status === 'clarified' && q.answer && !saved[q.id]) saved[q.id] = { answer: q.answer, note: q.note || '' };
201
+ });
126
202
  draft = Object.assign(Object.create(null), saved);
127
- var changedSource = oldViewRevision !== viewRevision || (!confirmedIds.length && oldRevision && revision && oldRevision !== revision);
203
+ // Our own save changes the saved questions; any other difference came from elsewhere.
204
+ var changes = changedQuestions(oldModel, model).filter(function (change) { return confirmedIds.indexOf(change.id) === -1; });
205
+ var viewChanged = Boolean(oldViewRevision && viewRevision && oldViewRevision !== viewRevision);
206
+ if (changes.length || viewChanged) mergeNotice(changes, viewChanged);
207
+ // Only questions that changed in this load lose a pending choice; earlier ones were already re-chosen.
208
+ var changed = changes.map(function (change) { return change.id; });
128
209
  if (preserveDraft && !sameResponses(pending, previouslySaved)) {
129
210
  Object.keys(pending).forEach(function (id) {
130
- if (confirmedIds.indexOf(id) !== -1 || !model.questions.some(function (q) { return q.id === id && !isReadOnly(q); })) return;
211
+ if (confirmedIds.indexOf(id) !== -1) return;
212
+ var question = (model.questions || []).filter(function (q) { return q.id === id; })[0];
213
+ if (!question || !canEditNote(question)) return;
131
214
  var before = previouslySaved[id] || { answer: '', note: '' };
132
215
  var after = pending[id] || { answer: '', note: '' };
133
- if (before.answer !== after.answer || (before.note || '') !== (after.note || '')) {
134
- if (changedSource) draft[id] = { answer: '', note: after.note || '' };
135
- else draft[id] = after;
136
- }
216
+ if (before.answer === after.answer && (before.note || '') === (after.note || '')) return;
217
+ // A changed question needs a fresh choice; its note text is kept. Unchanged questions keep the draft.
218
+ if (changed.indexOf(id) !== -1) draft[id] = { answer: isReadOnly(question) ? ((saved[id] || {}).answer || '') : '', note: after.note || '' };
219
+ else draft[id] = after;
137
220
  });
138
- if (changedSource) {
139
- sourceChanged = true;
140
- setMessage('notice', 'The source changed. Your unsaved note text remains, but choose responses again before saving.');
141
- }
142
221
  }
143
- if (result.message && !sourceChanged) setMessage('notice', result.message);
222
+ if (result.message) setMessage('notice', result.message);
144
223
  }
145
224
  async function refresh() {
146
225
  if (!transport || typeof transport.load !== 'function' || loading) return;
@@ -186,13 +265,74 @@
186
265
  if (messageNode) { messageNode.className = 'jca-message jca-message-' + messageKind; messageNode.textContent = message; }
187
266
  var footer = root.querySelector('.jca-footer');
188
267
  if (footer) footer.textContent = writable ? (dirty() ? 'Unsaved response edits are on this page.' : countText() + '.') : 'Responses are read-only in this artifact.';
189
- root.querySelectorAll('[data-jca-save-all]').forEach(function (button) { button.disabled = !writable || saving || sourceChanged || !unsavedAnswers().length; });
268
+ root.querySelectorAll('[data-jca-save-all]').forEach(function (button) { describeDisabled(button, saveAllBlocked()); });
269
+ }
270
+ function saveAllBlocked() {
271
+ if (!writable) return 'Responses are read-only in this artifact.';
272
+ if (saving) return 'A save is in progress.';
273
+ if (loading) return 'Saved responses are still loading.';
274
+ if (!unsavedAnswers().length) return 'Nothing to save: choose a response first.';
275
+ return '';
276
+ }
277
+ function saveOneBlocked() {
278
+ if (saving) return 'A save is in progress.';
279
+ if (loading) return 'Saved responses are still loading.';
280
+ return '';
281
+ }
282
+ // A disabled button says why: as its tooltip and as its accessible description.
283
+ function describeDisabled(button, reason) {
284
+ button.disabled = Boolean(reason);
285
+ var reasonNode = button.jcaReason;
286
+ if (reasonNode) reasonNode.textContent = reason || '';
287
+ if (reason) {
288
+ button.setAttribute('title', reason);
289
+ if (reasonNode) button.setAttribute('aria-describedby', reasonNode.id);
290
+ } else {
291
+ button.removeAttribute('title');
292
+ button.removeAttribute('aria-describedby');
293
+ }
294
+ }
295
+ // Returns [button, hidden reason element]; both go into the page.
296
+ function saveButton(attributes, reason, reasonId) {
297
+ var button = node('button', Object.assign({ type: 'button' }, attributes));
298
+ button.jcaReason = node('span', { id: reasonId, class: 'jca-visually-hidden' });
299
+ describeDisabled(button, reason);
300
+ return [button, button.jcaReason];
301
+ }
302
+ function renderSourceNotice() {
303
+ if (!sourceNotice) { noticeElement = null; noticeKey = ''; return null; }
304
+ var key = JSON.stringify(sourceNotice);
305
+ if (noticeElement && key === noticeKey) return noticeElement;
306
+ var blocked = sourceNotice.conflict && !sourceNotice.saved;
307
+ if (!noticeElement) noticeElement = node('section', { role: 'alert', 'aria-labelledby': 'jca-source-notice-title' });
308
+ noticeElement.className = 'jca-source-notice' + (blocked ? ' jca-source-notice-error' : '');
309
+ noticeElement.replaceChildren();
310
+ noticeKey = key;
311
+ var banner = noticeElement;
312
+ banner.append(node('h2', { id: 'jca-source-notice-title', text: blocked ? 'Not saved: the source changed after this page loaded'
313
+ : sourceNotice.conflict ? 'The source changed after this page loaded; your later save went through' : 'The source changed after this page loaded' }));
314
+ if (blocked) banner.append(node('p', { text: sourceNotice.conflict }));
315
+ if (sourceNotice.changes.length) {
316
+ banner.append(node('p', { text: sourceNotice.changes.length === 1 ? 'This question changed:' : 'These questions changed:' }));
317
+ var list = node('ul');
318
+ sourceNotice.changes.forEach(function (change) {
319
+ var label = change.change === 'removed' ? ' (removed)' : change.change === 'added' ? ' (new)' : '';
320
+ list.append(node('li', {}, [change.change === 'removed' ? text(change.question + label) : node('a', { href: '#jca-question-' + change.id, text: change.question + label })]));
321
+ });
322
+ banner.append(list);
323
+ banner.append(node('p', { text: 'Choose again where a changed question needs it. Answers to other questions are kept and can be saved now.' }));
324
+ } else {
325
+ banner.append(node('p', { text: sourceNotice.viewChanged ? 'The screenshots or review on this page changed. No question changed; your answers are kept and can be saved now.' : 'No question on this page changed. Your answers are kept and can be saved now.' }));
326
+ }
327
+ banner.append(node('button', { type: 'button', text: 'Dismiss', onclick: function () { sourceNotice = null; setMessage('quiet', dirty() ? 'Unsaved changes.' : 'Source changes reviewed.'); render(); } }));
328
+ return banner;
190
329
  }
191
330
  function renderQuestion(question, index) {
192
331
  var current = draft[question.id] || { answer: '', note: '' };
193
332
  var readOnly = isReadOnly(question);
194
333
  var body = node('section', { class: 'jca-question', id: 'jca-question-' + question.id });
195
334
  body.append(node('div', { class: 'jca-question-kicker', text: 'Decision ' + (index + 1) }), node('h2', { text: question.question }));
335
+ if (changedIds().indexOf(question.id) !== -1) body.append(node('p', { class: 'jca-changed', text: 'Changed in the source since this page loaded. Check it and choose again if needed.' }));
196
336
  body.append(node('p', { class: 'jca-status jca-status-' + (question.status || 'open'), text: statusLabel(question.status) }));
197
337
  if (question.answer) body.append(node('p', { class: 'jca-recorded', text: 'Brief record: ' + question.answer }));
198
338
  (model.comparisons || []).filter(function (comparison) { return comparison.decisionId === question.id; }).forEach(function (comparison) { body.append(renderComparison(comparison)); });
@@ -213,7 +353,7 @@
213
353
  fieldset.append(label);
214
354
  });
215
355
  body.append(fieldset);
216
- var note = node('textarea', { class: 'jca-note', id: 'jca-note-' + question.id, rows: 3, disabled: readOnly, placeholder: 'Optional note' });
356
+ var note = node('textarea', { class: 'jca-note', id: 'jca-note-' + question.id, rows: 3, disabled: !canEditNote(question), placeholder: 'Optional note' });
217
357
  note.value = current.note || '';
218
358
  function syncNoteRequirement() {
219
359
  var selected = (question.options || []).find(function (option) { return option.value === (draft[question.id] || {}).answer; });
@@ -227,7 +367,7 @@
227
367
  note.addEventListener('input', function () { draft[question.id] = { answer: (draft[question.id] || {}).answer || '', note: note.value }; setMessage('quiet', 'Unsaved changes.'); syncLiveUi(); });
228
368
  body.append(noteLabel, note);
229
369
  if (question.answer && question.note) body.append(node('p', { class: 'jca-recorded', text: 'Brief note: ' + question.note }));
230
- if (!readOnly) body.append(node('button', { class: 'jca-save-one', type: 'button', text: 'Save this response', disabled: saving || loading || sourceChanged, onclick: function () { save(question); } }));
370
+ if (canEditNote(question)) body.append.apply(body, saveButton({ class: 'jca-save-one', text: readOnly ? 'Save note' : 'Save this response', onclick: function () { save(question); } }, saveOneBlocked(), 'jca-save-reason-' + question.id));
231
371
  return body;
232
372
  }
233
373
  function renderComparison(comparison) {
@@ -267,11 +407,12 @@
267
407
  header.append(provenance);
268
408
  }
269
409
  page.append(header);
410
+ var notice = renderSourceNotice();
411
+ if (notice) page.append(notice);
270
412
  page.append(node('p', { class: 'jca-message jca-message-' + messageKind, role: messageKind === 'error' ? 'alert' : 'status', text: message }));
271
413
  var actions = node('div', { class: 'jca-actions' });
272
414
  if (transport) actions.append(node('button', { type: 'button', text: loading ? 'Refreshing…' : 'Refresh', disabled: loading || saving, onclick: refresh }));
273
- actions.append(node('button', { type: 'button', 'data-jca-save-all': '', text: 'Save selected answers', disabled: !writable || saving || sourceChanged || !unsavedAnswers().length, onclick: function () { save(); } }));
274
- if (sourceChanged) actions.append(node('button', { type: 'button', text: 'I reviewed the updated source', onclick: function () { sourceChanged = false; setMessage('notice', 'Review acknowledged. Select a response where needed, then save.'); render(); } }));
415
+ actions.append.apply(actions, saveButton({ 'data-jca-save-all': '', text: 'Save selected answers', onclick: function () { save(); } }, saveAllBlocked(), 'jca-save-all-reason'));
275
416
  actions.append(node('button', { type: 'button', text: 'Copy saved', onclick: copySaved }), node('button', { type: 'button', text: 'Download saved', onclick: downloadSaved }));
276
417
  page.append(actions);
277
418
  (model.questions || []).forEach(function (question, index) { page.append(renderQuestion(question, index)); });
@@ -298,4 +439,5 @@
298
439
 
299
440
  global.JoycraftArtifacts = global.JoycraftArtifacts || {};
300
441
  global.JoycraftArtifacts.mount = mount;
442
+ global.JoycraftArtifacts.changedQuestions = changedQuestions;
301
443
  })(window);
@@ -7,6 +7,13 @@
7
7
  var QUESTION_STATES = new Set(['open', 'assigned', 'clarified', 'settled', 'backlogged', 'discarded']);
8
8
 
9
9
  function fail(message) { throw new Error(message); }
10
+ // A stale-source rejection: the page should reload the source and keep the person's drafts.
11
+ function conflict(message, details) {
12
+ var error = new Error(message);
13
+ error.conflict = true;
14
+ Object.keys(details || {}).forEach(function (key) { error[key] = details[key]; });
15
+ throw error;
16
+ }
10
17
  function nonempty(value) { return typeof value === 'string' && value.trim().length > 0; }
11
18
  function own(object, key) { return Object.prototype.hasOwnProperty.call(object, key); }
12
19
 
@@ -49,7 +56,7 @@
49
56
  if (note !== undefined && typeof note !== 'string') fail('Answer notes must be strings.');
50
57
  if (note !== undefined && note.length > MAX_NOTE_LENGTH) fail('Answer notes cannot exceed 4000 characters.');
51
58
  if (option.requiresNote && !nonempty(note)) fail('This answer requires a note.');
52
- if (mutation && question.status === 'clarified' && (question.answer !== response.answer || (question.note || '') !== (note || ''))) fail('Clarified responses can only be replayed exactly.');
59
+ if (mutation && question.status === 'clarified' && question.answer !== response.answer) fail('Reopen this decision to change its answer. Its note can change at any time.');
53
60
  seen.add(response.id);
54
61
  var answer = { id: response.id, answer: response.answer };
55
62
  if (note !== undefined && note !== '') answer.note = note;
@@ -90,7 +97,7 @@
90
97
  }
91
98
 
92
99
  function responseRevision(model, revision) {
93
- if (revision !== model.source.revision) fail('Source changed. Refresh before saving responses.');
100
+ if (revision !== model.source.revision) conflict('Source changed after this page loaded. Reload it before saving responses.', { revision: model.source.revision });
94
101
  }
95
102
 
96
103
  function requestedAnswers(model, request) {
@@ -128,7 +135,11 @@
128
135
  try { payload = await response.json(); } catch (_) { fail('Local response service returned invalid JSON.'); }
129
136
  if (!response || !response.ok) {
130
137
  var detail = payload && (payload.error || payload.message);
131
- fail(typeof detail === 'string' && detail ? detail : 'Local response service rejected the request' + (response && response.status ? ' (' + response.status + ')' : '') + '.');
138
+ var text = typeof detail === 'string' && detail ? detail : 'Local response service rejected the request' + (response && response.status ? ' (' + response.status + ')' : '') + '.';
139
+ if (payload && payload.conflict) conflict(text, { status: response.status, revision: payload.revision, viewRevision: payload.viewRevision });
140
+ var error = new Error(text);
141
+ if (response && response.status) error.status = response.status;
142
+ throw error;
132
143
  }
133
144
  return payload;
134
145
  }
@@ -68,6 +68,8 @@ export interface QueueSpec {
68
68
  acceptedReport?: { path: string; sha256: string };
69
69
  /** Explicit owner exception, mutually exclusive with acceptedReport; not a PASS. */
70
70
  ownerAcceptance?: Receipt;
71
+ /** The feature's FeatureWaiver file, plus the UNVERIFIED report a tool-break waiver completed on; mutually exclusive with acceptedReport and ownerAcceptance. */
72
+ waiver?: Receipt & { review?: Receipt };
71
73
  }
72
74
  export interface SpecQueue { schemaVersion: 1; feature: string; specs: QueueSpec[] }
73
75
  export interface BoundInput extends VerificationInput {
@@ -103,6 +105,8 @@ export interface Observation {
103
105
  result: Result;
104
106
  actual: string;
105
107
  receipts: Receipt[];
108
+ /** Set only on an UNVERIFIED observation whose recorded tool did not work during the run. */
109
+ cause?: 'tool-break';
106
110
  /** Mandatory for test/command observations; null means unavailable. */
107
111
  command?: { argv: string[]; exitCode: number | null };
108
112
  /** Mandatory for visual observations. Interactions name actual outcomes. */
@@ -156,6 +160,24 @@ export interface OwnerAcceptance {
156
160
  limitations: string[];
157
161
  createdAt: string;
158
162
  }
163
+ /**
164
+ * The user's own words, from one feature's interview, loosening that feature's queue only. Never covers a FAIL.
165
+ * Lives at `<feature folder>/waiver.json`. While it covers no-review, reviewer dispatch for the queue is refused.
166
+ */
167
+ export interface FeatureWaiver {
168
+ schemaVersion: 1;
169
+ kind: 'feature-waiver';
170
+ queuePath: string;
171
+ /** Nonempty subset: complete without a review report, or with an UNVERIFIED report whose gaps are all tool breaks. */
172
+ covers: Array<'no-review' | 'tool-break'>;
173
+ /** The user's exact words: whole words of the named decision's note or answer, at least three. */
174
+ instruction: string;
175
+ /** Id of the clarified or assigned brief decision whose note holds the instruction. */
176
+ decision: string;
177
+ /** Receipt of the feature brief that holds the decision. */
178
+ source: Receipt;
179
+ createdAt: string;
180
+ }
159
181
  export interface ValidationResult { ok: boolean; errors: string[] }
160
182
  export type Need = 'repair' | 'feature' | 'context' | 'decision' | 'ui-exploration' | 'implementation' | 'verification' | 'unknown';
161
183
  export type NextInteraction = 'continue' | 'inspect' | 'render-slice' | 'ask-focused' | 'verify' | 'abstain';
@@ -33,8 +33,10 @@ another decision or approval authority.
33
33
 
34
34
  The preview validates the complete queue before any write: the canonical queue
35
35
  must be the only queue anywhere in the feature tree, all specs must be
36
- `done`, and each spec must have exactly one of an accepted PASS report or an
37
- explicit `ownerAcceptance` receipt. A normal accepted report must retain its
36
+ `done`, and each spec must have exactly one of an accepted PASS report, an
37
+ explicit `ownerAcceptance` receipt, or a feature `waiver` receipt. A waiver
38
+ keeps its record bytes, the user's quoted instruction as its limitation, and
39
+ for a tool-break completion its UNVERIFIED `waiver.review` report and receipts. A normal accepted report must retain its
38
40
  PASS evidence. An owner-acceptance record is historical exception metadata:
39
41
  it binds the queue/spec/subject identity to a hashed independent review whose
40
42
  verdict remains `FAIL` or `UNVERIFIED`, carries nonempty limitations, and is
@@ -14,13 +14,32 @@ artifact CSS, JavaScript, or a second copy of the brief. Keep questions useful:
14
14
  one material choice can be enough. Use the existing product UI slice for a
15
15
  choice that depends on trying the actual product behavior.
16
16
 
17
+ ## Showing a page
18
+
19
+ Every page a person must read or answer (a decision artifact, a setup diff, a
20
+ review) is shown where they are working, and you always say its path:
21
+
22
+ 1. **The host has a viewer.** When your tools include one (the Claude Code
23
+ desktop app's browser pane or artifact tool, an editor preview), open the
24
+ page there. Do not hand it to the system browser.
25
+ 2. **A person at a terminal, no viewer.** Open it in the system browser (`open`,
26
+ `xdg-open` or `start`).
27
+ 3. **No person watching.** In a non-interactive run (`claude -p`, `codex exec`,
28
+ CI), open nothing; print the path. Signals: `CLAUDE_CODE_SESSION_ATTENDED=0`,
29
+ `CODEX_CI=1`, `CI` set, or no terminal. These beat `CLAUDE_CODE_ENTRYPOINT`,
30
+ which a nested run inherits from the app that started it.
31
+
17
32
  ## Decisions and view data
18
33
 
19
34
  A brief decision keeps its existing `id`, `status`, `question`, `answer`,
20
35
  `options`, and `affected` fields. Artifact views also support an optional
21
36
  `description` on an option and `requiresNote: true` when that option needs a
22
- short explanation. The canonical answer remains the declared option `value`,
23
- including a `custom` value. Store the human's exact words separately as that
37
+ short explanation. Every question also offers "Something else" (value `custom`,
38
+ note required), so the person can always answer in their own words; do not
39
+ declare it unless you want different wording. The canonical answer remains an
40
+ option `value`, including `custom`. A saved answer keeps its note box: the
41
+ person can add or change the note and save again without reopening. Changing
42
+ the chosen answer still needs a reopen. Store the human's exact words separately as that
24
43
  decision's note; never replace the canonical answer with free-form text.
25
44
 
26
45
  The view data has this shape:
@@ -10,6 +10,9 @@
10
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
11
  | `broken-link` | A Markdown link to a file that does not exist | Fix or remove the link |
12
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
+ | `missing-path` | A backticked project path in `AGENTS.md`, `CLAUDE.md` or a context page that does not exist | Point it at the current path, or drop the line |
14
+ | `unmapped` | A context page that only other context pages mention; no entry file links or names it | Add a context-map row with a "read when", or merge the page |
15
+ | `entry-size` | `AGENTS.md` or `CLAUDE.md` over `cleanup.entryWords` words (default 1000) | Move detail into context pages; leave a map row for each |
13
16
  | `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
17
  | `stale-after` | An OKF `stale_after` date that has passed | Recheck, then move the date or mark the page `deprecated` |
15
18
  | `deprecated-link` | A link to a page marked `status: deprecated` | Link the current page |
@@ -18,7 +21,16 @@
18
21
 
19
22
  Fenced code blocks are ignored. Inline, reference-style and `<angle>` links count.
20
23
  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.
24
+ `orphan`, `unmapped` and `working-link`. `broken-link` checks Markdown links;
25
+ `missing-path` checks backticked spans that read as project paths: they contain a
26
+ `/` and end in `/`, have a file extension, or start with an existing top-level
27
+ folder. It skips spans with spaces, globs (`*`), placeholders (`<slug>`, `[slug]`,
28
+ `{x}`, `$VAR`, `...`), URLs and other `:` forms, and absolute, `~` or `../` paths.
29
+ A path in a context page may be relative to the project root or to the page.
30
+ History pages are exempt from `missing-path`, because they rightly name paths that
31
+ were later removed: a page whose frontmatter has `type: log` or `type: history`,
32
+ and any file named `decision-log.md` or `shipped*.md`. Their links are still
33
+ checked.
22
34
 
23
35
  The impact map lives in `joycraft.yaml`:
24
36
 
@@ -31,5 +43,99 @@ cleanup:
31
43
 
32
44
  `*` matches within a folder and `**` across folders. A page with no commit yet is
33
45
  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`.
46
+ `verified`); cleanup reads `status` and `stale_after` when present, and `type`
47
+ for the history exemption above.
48
+
49
+ ## Doc roles
50
+
51
+ Inventory gives every in-scope doc one role:
52
+
53
+ - **entry**: `AGENTS.md` and `CLAUDE.md`, loaded every session.
54
+ - **required**: an entry doc says to read it.
55
+ - **reference**: read when a task needs it; it gets a context-map row.
56
+ - **historical**: kept for lookup, not guidance; it gets no map row.
57
+
58
+ ## The six rot patterns
59
+
60
+ From doc-cleanup. Test every in-scope doc for each; a doc claim is a hypothesis
61
+ and the code is the evidence.
62
+
63
+ 1. **Completed-work logs.** Finished checklists, phase logs, implementation
64
+ narratives, post-mortems and verification transcripts presented as guidance.
65
+ 2. **Executed plans.** A shipped plan still written as intent, with its
66
+ superseded analysis and rejected options.
67
+ 3. **Internal contradictions.** One fact with two values, a stale table corrected
68
+ by a note below it, dated addenda that reverse earlier text.
69
+ 4. **Stale claims.** Renamed symbols, changed constants, wrong line numbers, work
70
+ called unmerged after it landed.
71
+ 5. **Dead paths.** Missing files, old machine paths, moved repositories, removed
72
+ tools.
73
+ 6. **Authority drift.** A "source of truth" that no longer matches the code or a
74
+ later decision.
75
+
76
+ Each phase has an end:
77
+ - **Inventory** ends when every in-scope Markdown file has a role and every entry
78
+ pointer is resolved, dead or external.
79
+ - **Diagnose** ends when every inventoried file has an evidence-backed finding or
80
+ is marked clean. Files `cleanup.mjs` did not flag still get read.
81
+ - **Report** ends when the user can approve, reject or amend each change without
82
+ more investigation.
83
+ - **Execute** ends when each approved finding has a diff or a stated reason for
84
+ none, and each retained claim was re-checked.
85
+
86
+ ## Trimming an entry file
87
+
88
+ `AGENTS.md` and `CLAUDE.md` load into every session. They keep the project's
89
+ identity (a line or two on what it is), its rules, the Joycraft lines and the
90
+ context map. Propose moving the rest into context pages, each with a map row:
91
+
92
+ | In the entry file | Move to |
93
+ |---|---|
94
+ | Key-files or module tables | A codebase reference page, e.g. `docs/context/codebase.md` |
95
+ | Folder trees and architecture maps | The same page, or `docs/context/architecture.md` |
96
+ | Data-flow and code walkthroughs | The same page, beside the files they walk through |
97
+ | Setup, build, test and release workflows | `docs/context/workflow.md`; keep one test-command line in the entry if the rules need it |
98
+ | Gotchas and traps that are not rules | The project's traps page (see knowledge guidance), each as a short imperative |
99
+
100
+ Reuse a page the map already has before creating one, and create a page only
101
+ with the content it receives. Rules never move and are never reworded,
102
+ reordered or reformatted: ALWAYS / ASK FIRST / NEVER lists and any other section
103
+ that says what an agent must or must not do (release rules, holdout or
104
+ confidentiality rules). If a rule is also stale, report it as a finding for the
105
+ user to decide; do not fix it as part of the trim. After a move, the entry file
106
+ names each new page in the map, and `cleanup.mjs` reports no `unmapped` or
107
+ `orphan` page for it.
108
+
109
+ ## Execution playbook
110
+
111
+ Re-check each factual claim against the code immediately before writing it.
112
+
113
+ - **Archive history worth finding again.** Put a verbatim copy, or a clearly
114
+ bounded extract, under `paths.archive` with a source-and-date name, and record
115
+ the source path and Git blob hash in the report. Git history alone is enough
116
+ when nobody will look for it. A finished feature folder is archived only
117
+ through the session-end path (`archive.md`), after its durable facts reach the
118
+ context home.
119
+ - **Rewrite live guidance as current facts**, following
120
+ [knowledge guidance](knowledge.md): rewrite in place, reason to the decision
121
+ log, no addenda. Live pages never link the archive (`working-link`); record
122
+ each archive mapping in the cleanup report and the commit message instead.
123
+ - **Point to authorities.** Name the owning schema, config or source file instead
124
+ of copying values that change.
125
+ - **Condense completed work.** Replace a finished checklist with its outcome;
126
+ keep open items in their original words.
127
+ - **Preserve traps.** Keep each recurring gotcha as a short imperative before
128
+ moving the story of how it was found.
129
+ - **Banner unresolved drift.** When the code and a contract-like doc disagree and
130
+ the repository does not show which governs, add a short banner naming the
131
+ mismatch and the authority in force; do not rewrite the contract.
132
+ - **Repair entry docs.** Fix dead reading pointers and stale claims, apply the
133
+ approved trim, and keep the required-reading set small.
134
+
135
+ ## Verify
136
+
137
+ Every relative link in touched files resolves; archives match their sources
138
+ byte for byte (extracts match their recorded bounds); load-bearing content found
139
+ in diagnosis survives in live guidance, with rules byte-identical; the diff holds
140
+ only approved Markdown changes; no new contradiction appears across touched docs;
141
+ `cleanup.mjs` reports nothing new.
@@ -11,10 +11,11 @@ node .joycraft/runtime/completion.mjs scope --queue <queue-path> --spec <id>
11
11
  node .joycraft/runtime/completion.mjs snapshot --queue <queue-path> --spec <id> --out <subject.json>
12
12
  node .joycraft/runtime/completion.mjs finalize-review --queue <queue-path> --spec <id> --report <report.json>
13
13
  node .joycraft/runtime/completion.mjs accept-owner --queue <queue-path> --spec <id> --decision <owner-acceptance.json>
14
+ node .joycraft/runtime/completion.mjs accept-waiver --queue <queue-path> --spec <id> --waiver <feature-waiver.json> [--report <report.json>]
14
15
  node .joycraft/runtime/completion.mjs recover --queue <queue-path>
15
16
  ```
16
17
 
17
- `scope` checks a queue's declared change scope without writing a subject. `snapshot` does the same check first, then exclusively creates a new `--out` subject file without changing a status. It binds the implementation revision, queue/spec identity, criteria, and SHA-256 values for exact relevant inputs. The shared record shapes are defined in [.joycraft/contracts/types.d.ts](../contracts/types.d.ts). New subjects carry `binding.version: 1`: their queue projection contains the reviewed spec and its transitive dependencies, with completion metadata (`status`, `acceptedReport`, and `ownerAcceptance`) removed from those records. An unrelated queue record can change without staling that subject; a selected spec's other metadata and dependency edges remain bound. A spec binding preserves raw bytes except for its top-level `status:` value.
18
+ `scope` checks a queue's declared change scope without writing a subject. `snapshot` does the same check first, then exclusively creates a new `--out` subject file without changing a status. It binds the implementation revision, queue/spec identity, criteria, and SHA-256 values for exact relevant inputs. The shared record shapes are defined in [.joycraft/contracts/types.d.ts](../contracts/types.d.ts). New subjects carry `binding.version: 1`: their queue projection contains the reviewed spec and its transitive dependencies, with completion metadata (`status`, `acceptedReport`, `ownerAcceptance`, and `waiver`) removed from those records. An unrelated queue record can change without staling that subject; a selected spec's other metadata and dependency edges remain bound. A spec binding preserves raw bytes except for its top-level `status:` value.
18
19
 
19
20
  An optional `verification.changeScope` records an explicit full Git commit SHA in `baseRevision`; a branch name, `origin/main`, or inferred base is rejected. Changed verification inputs are captured from NUL-delimited Git status records, including staged, unstaged, rename, and deletion topology. Any changed path outside the verification inputs must be named exactly in `exclusions` with its reason. Store temporary packets and subjects in the project's ignored local-artifact home when it has one; otherwise add each exact untracked snapshot packet output to `exclusions`. `complete` filters only its exact report, receipt, owner-decision, and pending-journal paths while rechecking scope. A deliberate deletion needs a non-requirement verification input with `state: "absent"`; requirement inputs cannot be absent. A rename needs the new present input and the old non-requirement input declared absent.
20
21
 
@@ -86,9 +87,61 @@ verified, and the original failed or unverified report remains historical
86
87
  evidence. Archive may preserve this paired history only at session end; it does
87
88
  not rewrite the report or create a fresh acceptance.
88
89
 
90
+ ## Feature waiver
91
+
92
+ Review defaults are strict for every feature. A `FeatureWaiver` loosens them for
93
+ one feature's queue, only in the user's own words from that feature's
94
+ interview. The agent never proposes or asks about one, and the next feature
95
+ starts from the defaults. Record the user's words in the note of a settled brief
96
+ decision, then write the feature's one waiver file, `waiver.json` beside
97
+ `brief.md` (never a verification input), before any review runs:
98
+
99
+ ```json
100
+ {
101
+ "schemaVersion": 1,
102
+ "kind": "feature-waiver",
103
+ "queuePath": "docs/features/example/specs/.joycraft-spec-queue.json",
104
+ "covers": ["no-review"],
105
+ "instruction": "quick janky prototype, skip review on this",
106
+ "decision": "skip-review",
107
+ "source": { "path": "docs/features/example/brief.md", "sha256": "<SHA-256 of the brief>" },
108
+ "createdAt": "2026-11-02T12:00:00.000Z"
109
+ }
110
+ ```
111
+
112
+ `covers` is a nonempty subset of `no-review` and `tool-break`. `decision` is the
113
+ id of the brief decision that holds the user's words. `accept-waiver` refuses a
114
+ waiver for another queue, at another path, with unknown fields or covers, an
115
+ empty instruction, a `source` that is not this feature's `brief.md`, a brief hash
116
+ that differs, or a `decision` that is missing, not `clarified`/`assigned` with an
117
+ answer, or whose `note` or `answer` does not contain the instruction as whole
118
+ words (at least three; whitespace and line wraps are normalized).
119
+
120
+ - **Skip means review never runs** (decision `block-review-dispatch`).
121
+ `dispatch-preflight.mjs` refuses a reviewer for a queue whose `waiver.json`
122
+ covers `no-review`, in the worker tree or the coordinator tree, and refuses
123
+ while that file is unreadable. So no review, and no `FAIL`, exists for a spec
124
+ that `no-review` completes. Without `--report`, `no-review` completes an
125
+ `in-review` spec. As an extra guard it still refuses when a review report for
126
+ the spec is visible in the feature folder or `.joycraft/local/packets/`.
127
+ - With `--report`, the report must be current and independent (validated as for
128
+ `accept-owner`), `UNVERIFIED`, and every non-`PASS` observation must carry
129
+ `cause: "tool-break"`; the waiver must cover `tool-break`. The report keeps
130
+ its verdict; evidence errors are returned as diagnostics. A tool-break-only
131
+ waiver does not block reviewer dispatch.
132
+ - A `FAIL` verdict or any `FAIL` observation never completes, whatever `covers`
133
+ says. A `PASS` report uses `finalize-review`.
134
+
135
+ Limit: a review that ran before `waiver.json` existed is caught only by the
136
+ folder guard. The waiver comes from the interview, so it exists before dispatch.
137
+ On success the queue entry records `waiver: { path, sha256 }`, plus
138
+ `review: { path, sha256 }` for a report-backed completion, mutually exclusive
139
+ with `acceptedReport` and `ownerAcceptance`. A waived spec counts as `done` for
140
+ dependents. Report it as `done, waived by the user: "<instruction>"`.
141
+
89
142
  ## Evidence and reporting
90
143
 
91
- Evidence records observations rather than promises. Command and test observations retain their actual argv, exit code, and unfiltered output receipt. Source review supports structural claims only. A required visual claim needs an inspected render, route, state, viewport, interactions, and observed outcomes. Record unavailable work as `UNVERIFIED`, failures as `FAIL`, and limits explicitly.
144
+ Evidence records observations rather than promises. Command and test observations retain their actual argv, exit code, and unfiltered output receipt. Source review supports structural claims only. A required visual claim needs an inspected render, route, state, viewport, interactions, and observed outcomes. Record a check that should have run and did not (a tool break, an app that did not start) as `UNVERIFIED`, failures as `FAIL`, and limits explicitly. A claim that needs evidence beyond the recorded tool's `canShow`, or a package the user skipped, is an agreed limit, not `UNVERIFIED`; a check within `canShow` that could not run because the tool broke is `UNVERIFIED` with `cause: 'tool-break'`.
92
145
 
93
146
  Report the command result, reviewer identity, receipt paths, actual observations, and limitations. A green suite or an implementation commit alone is not accepted completion.
94
147