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
@@ -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
 
@@ -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
 
@@ -27,6 +29,14 @@ Use the version from `latest`:
27
29
  apply a migration without the user's yes.
28
30
  3. Run `npx joycraft@<latest> doctor .`.
29
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.
30
40
 
31
41
  If the update fails, run `npx joycraft@<latest> update . --recover`, tell the user
32
42
  that the files are back as they were, and continue your work.
@@ -37,7 +47,7 @@ that the files are back as they were, and continue your work.
37
47
  that version for seven days.
38
48
  - Turn off: `node .joycraft/runtime/update-check.mjs policy off`.
39
49
  - 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.
50
+ a `patch` release marked safe applies by itself. A `minor` or `migration` always asks.
41
51
  - Stay on this version: `node .joycraft/runtime/update-check.mjs pin`, and `unpin` to
42
52
  undo it.
43
53
 
@@ -68,8 +68,9 @@ outcomes, viewport, route/state and limits. A screenshot or static render is
68
68
  enough for an appearance-only choice only when it is actually inspected; it cannot
69
69
  prove that the answer was saved. Ask concise visual-detail questions before making
70
70
  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
71
+ both file state and reload. If a recorded tool breaks or is denied, mark required
72
+ visual work UNVERIFIED and continue disjoint work; a limit the user agreed to is
73
+ not UNVERIFIED. Never bypass a denial with
73
74
  another route.
74
75
 
75
76
  ## 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
  }
@@ -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
  }