joycraft 1.0.1 → 1.1.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.
package/README.md CHANGED
@@ -90,6 +90,26 @@ agent both views: the whole project and the detail of the current step.
90
90
  Joycraft does not ship a wiki. If you keep one, link it from the context map, and
91
91
  treat `docs/features/` and `docs/archive/` as non-authoritative in your doc audits.
92
92
 
93
+ ### Settings: `joycraft.yaml`
94
+
95
+ Joycraft works with no settings. To change its folders, run a command after a
96
+ feature is archived, or tell cleanup which code each context page describes, add a
97
+ `joycraft.yaml` at the project root (template: `.joycraft/templates/joycraft.yaml`):
98
+
99
+ ```yaml
100
+ paths:
101
+ features: working/features # default docs/features
102
+ archive: working/archive # default docs/archive
103
+ hooks:
104
+ afterArchive: node scripts/wiki-sync.mjs
105
+ cleanup:
106
+ impact:
107
+ - source: src/auction/**
108
+ docs: [docs/context/auction-rules.md]
109
+ ```
110
+
111
+ The file is yours: Joycraft reads it and never rewrites it.
112
+
93
113
  ### Keeping the workspace clean
94
114
 
95
115
  At the end of a session the agent runs three checks for you:
@@ -101,6 +121,13 @@ At the end of a session the agent runs three checks for you:
101
121
  made by Joycraft, and says why. `worktrees.mjs list` shows what is left and its size.
102
122
  - `node .joycraft/runtime/coordinator.mjs` keeps one coordinating session per queue,
103
123
  so a second session's instructions do not reach the first session's workers.
124
+ - `node .joycraft/runtime/cleanup.mjs` reports stale or unreachable project
125
+ knowledge: finished features not archived, context pages that link to working
126
+ material, broken or orphaned pages, and pages whose code changed. Ask your agent
127
+ to "clean up the docs" and it shows the fixes for your approval.
128
+
129
+ Tests name the acceptance criterion they check, `[AC:<criterion-id>]`, so the
130
+ reviewing agent can see which criteria have a test.
104
131
 
105
132
  ## Answering questions: the decision page
106
133
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "releaseVersion": "1.0.1",
3
+ "releaseVersion": "1.1.1",
4
4
  "manifestSchemas": [
5
5
  1
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joycraft",
3
- "version": "1.0.1",
3
+ "version": "1.1.1",
4
4
  "description": "Install and update Joycraft, a skill bundle and runtime for agent-led software work, in any project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,8 +13,8 @@
13
13
  "payload"
14
14
  ],
15
15
  "joycraft": {
16
- "release": "1.0.1",
17
- "summary": "Cleans up worker worktrees, keeps one coordinating session per queue, reports status drift, and shows documents as rendered pages.",
16
+ "release": "1.1.1",
17
+ "summary": "Fixes from the 1.0.1 and 1.1 re-reviews: cleanup reads code fences correctly, trace reads folders like tests/[slug], prune skips the tree it runs from, and stale locks are taken over safely.",
18
18
  "autoSafeEligible": false
19
19
  },
20
20
  "scripts": {
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: joycraft-cleanup
3
+ description: Find stale or unreachable project knowledge (finished features left in the working folder, context pages that link to working material, broken or orphaned pages, pages whose code changed, leftover worktrees) and fix what the user approves.
4
+ compatibility: Requires Node.js 22+ and the installed .joycraft runtime. Git improves the code-drift and worktree checks.
5
+ ---
6
+
7
+ # Joycraft Cleanup
8
+
9
+ Use when the user asks to clean up docs, remove stale material or check that
10
+ project knowledge is current, and at session end when `status.mjs` or the
11
+ archive step leaves loose ends. It keeps the context home trustworthy; it does
12
+ not change product decisions.
13
+
14
+ Run the report from the project root:
15
+
16
+ ```sh
17
+ node .joycraft/runtime/cleanup.mjs
18
+ ```
19
+
20
+ Exit 0 means no findings; exit 2 means findings. The script reads
21
+ `joycraft.yaml` for `paths` and the `cleanup.impact` map (code globs → context
22
+ pages) and never edits a file. Read `.joycraft/references/cleanup.md` for each
23
+ check and its usual fix.
24
+
25
+ Then, for each finding:
26
+
27
+ 1. Read the files it names before proposing anything. For `impact-drift`,
28
+ read the listed commits' changes and the page; the page may still be true.
29
+ 2. Propose one concrete fix per finding: the exact link, page, section or
30
+ command. Group findings by fix, not by check.
31
+ 3. Show the proposals to the user as a rendered page (the decision artifact for
32
+ choices, or an HTML page), never only as Markdown in chat. Ask once.
33
+ 4. Apply only what the user approves. Move durable facts into the context home
34
+ before an archive. Archive only through the session-end archive path. Remove
35
+ an unknown worktree only after checking it for unmerged work and with the
36
+ user's approval.
37
+ 5. Run the report again and give the remaining findings with their reasons.
38
+
39
+ Never delete a context page to clear a finding; merge or redirect it. Do not
40
+ invent facts to refresh a stale page: when the code does not settle it, record
41
+ the question in the owning brief.
@@ -68,6 +68,10 @@ options, and saves the answers to the brief. Plain chat is only for one quick
68
68
  yes/no or an open question with no options. If you already asked option
69
69
  questions in chat and they are unanswered, move them to an artifact now.
70
70
 
71
+ **Use the project's folders.** If `joycraft.yaml` exists, run
72
+ `node .joycraft/runtime/config.mjs` and use its `paths` wherever Joycraft guidance
73
+ says `docs/features`, `docs/archive` or `docs/context`.
74
+
71
75
  **Show documents as pages.** A brief, plan, spec set or review that the user must
72
76
  read or approve is also rendered, never left as Markdown in chat: the decision
73
77
  artifact for a brief, an HTML page for anything else. Open it and say where it is.
@@ -58,7 +58,7 @@ isolation cannot be obtained, replan the affected wave and set the current
58
58
  queue entry's `execution.parallel` to `false` before dispatch, recording why;
59
59
  then run it serially. Otherwise leave it unstarted.
60
60
 
61
- Implement the spec and run meaningful checks and any relevant rendered inspection during implementation. Do not defer ordinary checks to the batch boundary. Run each test command once in single-run mode with `CI=1` and a 300000 ms timeout; follow [running tests](../../../.joycraft/references/testing.md#running-tests) when one times out. Write one focused test per acceptance `Check:`, from the spec rather than the code; if a criterion or test looks wrong, report a spec gap instead of editing it to pass. When the implementation is finished, update both the queue entry and the spec's top-level frontmatter `status:` to `in-review` together. A passing test suite, commit, or empty ready set does not accept the work.
61
+ Implement the spec and run meaningful checks and any relevant rendered inspection during implementation. Do not defer ordinary checks to the batch boundary. Run each test command once in single-run mode with `CI=1` and a 300000 ms timeout; follow [running tests](../../../.joycraft/references/testing.md#running-tests) when one times out. Write one focused test per acceptance `Check:`, from the spec rather than the code, and tag it with its queue criterion ID as `[AC:<criterion-id>]` in the test name or a comment; if a criterion or test looks wrong, report a spec gap instead of editing it to pass. When the implementation is finished, update both the queue entry and the spec's top-level frontmatter `status:` to `in-review` together. A passing test suite, commit, or empty ready set does not accept the work.
62
62
 
63
63
  Honor the queue's commit mode. In `batch`, commit and review the independent ready
64
64
  wave at its boundary before advancing its dependents; do not wait for an entire
@@ -35,6 +35,8 @@ any feature listed as ready to archive. Then preview
35
35
  `node .joycraft/runtime/worktrees.mjs prune` and apply it with `--apply`: it
36
36
  removes only clean, integrated trees of done specs and keeps failed, blocked or
37
37
  unknown trees with their reason. Report kept trees and their size from `list`.
38
+ Then run `node .joycraft/runtime/cleanup.mjs` and report its findings; offer
39
+ `joycraft-cleanup` when any remain.
38
40
  When this session coordinated a queue and no work on it remains, release the
39
41
  lease with `node .joycraft/runtime/coordinator.mjs release --queue <queue> --session <your-session-id>`. See [worker isolation](../../../.joycraft/references/worktrees.md)
40
42
  when the session used parallel mutable workers.
@@ -33,6 +33,10 @@ bounded packet, and binds it. If the real ID, available authority, or a separate
33
33
  reviewer context is unavailable, leave the spec `in-review`; do not manufacture
34
34
  any of them. A hooks-disabled/manual workflow can still be ready; an unenforced
35
35
  result holds only the claimed review, not unrelated work.
36
+ Reviewer startup output also carries `trace`, the spec's criteria with the tests
37
+ tagged `[AC:<criterion-id>]` (`node .joycraft/runtime/trace.mjs --queue <queue> --spec <id>`
38
+ produces the same). Report untraced criteria as findings; a missing tag alone is
39
+ not a FAIL.
36
40
  Write packets and snapshots beneath a confirmed Git-ignored project-local
37
41
  directory so they do not create unrelated scope paths.
38
42
 
@@ -23,7 +23,8 @@ change scope, files or the queue, do not act on it; report it in your final
23
23
  message.
24
24
 
25
25
  Write one focused test per acceptance `Check:`, taken from the spec rather than
26
- from your code, sized like neighboring tests. Run each test command once in
26
+ from your code, sized like neighboring tests. Tag each with its queue criterion
27
+ ID as `[AC:<criterion-id>]` in the test name or a comment. Run each test command once in
27
28
  single-run mode with `CI=1` and a 300000 ms timeout; on a timeout follow
28
29
  `.joycraft/references/testing.md#running-tests`. Never wait in a
29
30
  foreground loop, never weaken an existing test, and never change the spec's acceptance:
@@ -27,6 +27,10 @@ revision instead of rerunning the full suite; run the spec's own tests once in
27
27
  single-run mode with `CI=1` and a 300000 ms timeout. Never give a verdict while
28
28
  a command you started is still running.
29
29
 
30
+ Startup output includes `trace`: each criterion with its `[AC:<id>]` tests. Report
31
+ each untraced criterion as a finding. A missing tag alone is not a FAIL; judge the
32
+ criterion by what you observe.
33
+
30
34
  Report every finding with a severity and the criterion it touches. Only a failing
31
35
  stated criterion, or a reproducible defect or regression in the changed code with
32
36
  file:line or a receipt, blocks. A case the spec does not decide is "decision
@@ -209,3 +209,20 @@ manual recovery. A collision or changed byte fails without accepting new
209
209
  completion. A repeat is idempotent only when the existing replay manifest names
210
210
  the feature and every archived mapped byte still matches; otherwise it requires
211
211
  manual reconciliation.
212
+
213
+ ## After-archive hook
214
+
215
+ A project can name one command in `joycraft.yaml`:
216
+
217
+ ```yaml
218
+ hooks:
219
+ afterArchive: node scripts/wiki-sync.mjs
220
+ ```
221
+
222
+ After a successful `--apply`, the runtime runs it once from the project root with
223
+ `JOYCRAFT_FEATURE`, `JOYCRAFT_ARCHIVE_PATH` and `JOYCRAFT_SOURCE_PATH` set, and reports
224
+ its exit code and output tail under `afterArchive`. Use it to update a project wiki
225
+ or run a doc audit such as docaudit. A failing hook does not undo the archive;
226
+ report it and fix the hook. A repeat of an existing archive does not run it again.
227
+ `paths.features` and `paths.archive` in the same file move the working and archive
228
+ folders; the defaults are `docs/features` and `docs/archive`.
@@ -0,0 +1,35 @@
1
+ # Cleanup checks
2
+
3
+ `cleanup.mjs` reports; it never edits. Each finding has `check`, `path`, often
4
+ `line`, a `detail` and a suggested `fix`. `skipped` lists checks it could not run.
5
+
6
+ | Check | Finds | Usual fix |
7
+ |---|---|---|
8
+ | `unarchived` | A feature whose specs are all `done` but is still in `paths.features` | Carry durable facts into the context home, then archive at session end |
9
+ | `status-drift` | Spec frontmatter that disagrees with the queue | `status.mjs --fix` for accepted done specs; otherwise reconcile by hand |
10
+ | `working-link` | `AGENTS.md`, `CLAUDE.md` or a context page linking into `paths.features` or `paths.archive` | Move the fact into the context home and link that |
11
+ | `broken-link` | A Markdown link to a file that does not exist | Fix or remove the link |
12
+ | `orphan` | A context page that nothing in `AGENTS.md`, `CLAUDE.md` or the context home mentions | Add a context-map row with a "read when", or merge the page |
13
+ | `impact-drift` | A page mapped in `cleanup.impact` whose code changed in commits after the page last changed | Read the change; update the page, or commit it unchanged when still true |
14
+ | `stale-after` | An OKF `stale_after` date that has passed | Recheck, then move the date or mark the page `deprecated` |
15
+ | `deprecated-link` | A link to a page marked `status: deprecated` | Link the current page |
16
+ | `frontmatter-unreadable` | Page frontmatter in YAML that cleanup cannot read, so its `status` and `stale_after` go unchecked | Use plain `key: value` lines, lists and quoted strings |
17
+ | `unknown-worktree` | A linked worktree that `worktrees.mjs` did not create | Check for unmerged work, then remove with approval |
18
+
19
+ Fenced code blocks are ignored. Inline, reference-style and `<angle>` links count.
20
+ Backticked paths such as `` `docs/context/x.md` `` count as references for
21
+ `orphan` and `working-link`; only real Markdown links are checked for existence.
22
+
23
+ The impact map lives in `joycraft.yaml`:
24
+
25
+ ```yaml
26
+ cleanup:
27
+ impact:
28
+ - source: src/auction/**
29
+ docs: [docs/context/auction-rules.md]
30
+ ```
31
+
32
+ `*` matches within a folder and `**` across folders. A page with no commit yet is
33
+ skipped. Pages may carry OKF frontmatter (`type`, `status`, `stale_after`,
34
+ `verified`); cleanup reads `status` and `stale_after` when present. For a fuller
35
+ doc audit, such as docaudit, run it from `hooks.afterArchive`.
@@ -178,6 +178,13 @@ its UI claims stay `UNVERIFIED`. With no network, the probes still run; offer
178
178
  the install later. For a CI-only project, record the CI job as the evidence
179
179
  source when the user picks it.
180
180
 
181
+ `review-tools.json` also lists `optIn` tools that detection never plans. Offer
182
+ one only when it fits the project. Example: Doc Detective, for docs that are
183
+ step-by-step procedures. Say what it does not cover and that it is AGPL-3.0 with a
184
+ large browser download, and install nothing without the user's yes. Record an
185
+ accepted opt-in tool in the `## Review loop` section by hand, with its evidence
186
+ command.
187
+
181
188
  ## Project-owned worktrees
182
189
 
183
190
  For an observed Git project with a parallel-worker preference, keep bootstrap
@@ -241,6 +248,12 @@ Create additional homes only when they have content:
241
248
  | Current feature or mixed change | `docs/features/<slug>/brief.md` |
242
249
  | Authorized implementation queue | `docs/features/<slug>/specs/` |
243
250
 
251
+ A project can move these folders, add an after-archive hook and map code to
252
+ context pages in an optional root `joycraft.yaml`. It is project-owned: create it
253
+ from `.joycraft/templates/joycraft.yaml` only when the user wants one of those
254
+ settings, and never overwrite it. `node .joycraft/runtime/config.mjs` prints the
255
+ settings in effect.
256
+
244
257
  Only the context homes are current project knowledge. `docs/features/` is working
245
258
  material: a brief or spec there can be out of date until the feature is archived,
246
259
  and `docs/archive/` is history. Context retrieval and any project wiki or doc audit
@@ -118,3 +118,13 @@ does not automatically belong in CI. Diagnose an environment-only UNVERIFIED
118
118
  result as an environment limitation, repair that setup, and rerun the affected
119
119
  review; do not send unchanged code through a speculative fix round. A genuine
120
120
  test race still needs a code/test diagnosis, not just a longer timeout.
121
+
122
+ ## Criterion tags
123
+
124
+ Tag each acceptance test with its queue criterion ID, `[AC:<criterion-id>]`, in the
125
+ test name or a comment, in any language. `trace.mjs --queue <queue> --spec <id>`
126
+ lists each criterion with its tagged tests from the spec's `check` inputs (add
127
+ `--tests <glob>` for undeclared files) and exits 2 while a criterion is untraced.
128
+ Reviewer startup includes the same trace. A tag shows that a test claims the
129
+ criterion; it does not show that the test is right. Write the test from the spec
130
+ text before reading the implementation.
@@ -74,6 +74,11 @@ another route.
74
74
 
75
75
  ## Commitment and queue
76
76
 
77
+ Folder names in this guidance are defaults. A project's `joycraft.yaml` can move
78
+ `paths.features`, `paths.archive` and `paths.context`; run
79
+ `node .joycraft/runtime/config.mjs` once per session and use the folders it prints
80
+ wherever a skill or reference says `docs/features`, `docs/archive` or `docs/context`.
81
+
77
82
  Use `docs/features/<slug>/specs/.joycraft-spec-queue.json` and the exact shapes in
78
83
  `.joycraft/contracts/types.d.ts`. Only `todo`, `in-review`, `done` are
79
84
  spec statuses, mirrored in spec frontmatter. Open or unknown decision state blocks
@@ -1,17 +1,19 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { boundQueueForSubject, briefDecisionRecords, canonical, isObject, isSha256, localPath, nonempty, normalizedQueueForSubject, parseJson, readLocal, readQueue, relativePath, requireValue, scopedRequirementForSubject, sha256, specStatus, subjectIdentity, validateIndependentReview } from './identity.mjs';
6
6
  import { validateEvidence } from './evidence.mjs';
7
7
  import { validateOwnerAcceptance } from './completion.mjs';
8
+ import { readConfig, workPaths } from './config.mjs';
8
9
 
9
10
  const featureName = value => {
10
11
  requireValue(typeof value === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(value), 'Feature must be a lowercase slug');
11
12
  return value;
12
13
  };
13
- const archivePath = feature => `docs/archive/${feature}`;
14
- const featurePath = feature => `docs/features/${feature}`;
14
+ // Folders come from joycraft.yaml (paths.features / paths.archive); defaults are docs/features and docs/archive.
15
+ const archivePath = (root, feature) => `${workPaths(root).archive}/${feature}`;
16
+ const featurePath = (root, feature) => `${workPaths(root).features}/${feature}`;
15
17
 
16
18
  function localDirectory(root, relative) {
17
19
  relative = relativePath(relative);
@@ -56,7 +58,8 @@ function parseAttestation(root, input) {
56
58
  const references = attestation.durableContext.references.map(relativePath);
57
59
  for (const reference of references) {
58
60
  requireValue(reference.endsWith('.md'), 'Durable context references must be current Markdown documentation');
59
- requireValue(!reference.startsWith('docs/features/') && !reference.startsWith('docs/archive/'), 'Durable context cannot rely on the feature being archived');
61
+ const { features, archive } = workPaths(root);
62
+ requireValue(!reference.startsWith(`${features}/`) && !reference.startsWith(`${archive}/`), 'Durable context cannot rely on the feature being archived');
60
63
  readLocal(root, reference);
61
64
  }
62
65
  return { schemaVersion: 1, phase: 'session-end', host: { sessionId: attestation.host.sessionId, quiescent: true, activeWorkers: [], dependentWork: [] }, durableContext: { carried: true, references } };
@@ -80,7 +83,7 @@ const isDecisionAnswered = decision => ['clarified', 'assigned'].includes(decisi
80
83
  * and after hashes must equal that commit's parent and own brief bytes.
81
84
  */
82
85
  function briefAmendments(root, feature, briefPath, later) {
83
- const recordPath = `${featurePath(feature)}/brief-amendments.json`;
86
+ const recordPath = `${featurePath(root, feature)}/brief-amendments.json`;
84
87
  const changed = `Original requirement changed after acceptance: ${briefPath}`;
85
88
  requireValue(existsSync(localPath(root, recordPath, true)), `${changed} (no ${recordPath} records its amendments)`);
86
89
  const record = parseJson(readLocal(root, recordPath), recordPath);
@@ -118,7 +121,7 @@ function validateReconciliation(record, feature) {
118
121
 
119
122
  function readReconciliation(root, feature, file) {
120
123
  if (file === undefined) return undefined;
121
- requireValue(file === `${featurePath(feature)}/archive-reconciliation.json`, 'Use the feature archive-reconciliation.json for the explicit override');
124
+ requireValue(file === `${featurePath(root, feature)}/archive-reconciliation.json`, 'Use the feature archive-reconciliation.json for the explicit override');
122
125
  const bytes = readLocal(root, file), record = parseJson(bytes, file);
123
126
  validateReconciliation(record, feature);
124
127
  return { path: file, sha256: sha256(bytes), record, used: new Set() };
@@ -160,7 +163,7 @@ function historicalRequirement(root, feature, input, project, normalizations = [
160
163
  const later = gitIn(root, ['log', '--full-history', '--topo-order', '--format=%H', '--reverse', `${accepted}..HEAD`, '--', input.path]).split('\n').filter(Boolean);
161
164
  const raw = committedBytes(root, accepted, input.path);
162
165
  const record = { path: input.path, normalization: input.normalization ?? 'none', ...(input.scope !== undefined ? { scope: input.scope } : {}), acceptedSha256: input.sha256, acceptedCommit: accepted, restoredSha256: sha256(raw), laterCommits: later };
163
- if (input.path === `${featurePath(feature)}/brief.md`) record.amendments = briefAmendments(root, feature, input.path, later);
166
+ if (input.path === `${featurePath(root, feature)}/brief.md`) record.amendments = briefAmendments(root, feature, input.path, later);
164
167
  return record;
165
168
  }
166
169
 
@@ -199,7 +202,7 @@ function historicalReport(root, queuePath, state, review, { ownerAccepted = fals
199
202
  const reviewedSpec = reviewedQueue.specs.find(spec => spec.id === state.spec.id);
200
203
  requireValue(reviewedSpec && reviewedSpec.file === state.spec.file && canonical(report.subject.criteria) === canonical(reviewedSpec.verification.criteria), `Accepted report criteria differ from the archived spec: ${reportPath}`);
201
204
  const declaredSpecPaths = new Set([...state.queue.specs, ...reviewedQueue.specs].map(spec => path.posix.join(path.posix.dirname(queuePath), spec.file)));
202
- for (const required of [state.specPath, `docs/features/${state.queue.feature}/brief.md`, ...report.subject.criteria.map(item => relativePath(item.requirement.path))]) {
205
+ for (const required of [state.specPath, `${featurePath(root, state.queue.feature)}/brief.md`, ...report.subject.criteria.map(item => relativePath(item.requirement.path))]) {
203
206
  requireValue(inputs.some(input => isObject(input) && input.path === required && input.kind === 'requirement' && isSha256(input.sha256)), `Accepted report omits original requirement ${required}: ${reportPath}`);
204
207
  }
205
208
  const requirement = (input, project) => {
@@ -213,7 +216,7 @@ function historicalReport(root, queuePath, state, review, { ownerAccepted = fals
213
216
  const explicit = reconciliation?.record.entries.some(entry => entry.report.path === review.path && entry.path === input.path && entry.normalization === input.normalization);
214
217
  if (!history.has(key)) history.set(key, explicit ? reconciledRequirement(root, state, review, input, project, reconciliation) : historicalRequirement(root, state.queue.feature, input, project));
215
218
  };
216
- for (const input of inputs.filter(input => isObject(input) && input.kind === 'requirement' && (bound !== undefined || input.path.startsWith(`docs/features/${state.queue.feature}/`)))) {
219
+ for (const input of inputs.filter(input => isObject(input) && input.kind === 'requirement' && (bound !== undefined || input.path.startsWith(`${featurePath(root, state.queue.feature)}/`)))) {
217
220
  // The queue was checked above. Only an explicit, hash-bound reconciliation can
218
221
  // preserve a changed acceptance record; normal requirement fallback cannot.
219
222
  if (input.path === queuePath) {
@@ -278,13 +281,13 @@ function historicalDecision(root, queuePath, state, reconciliation) {
278
281
  function fileDigest(root, relative) { return { path: relative, sha256: sha256(readLocal(root, relative)) }; }
279
282
 
280
283
  function existingArchive(root, feature) {
281
- const destination = archivePath(feature);
284
+ const destination = archivePath(root, feature);
282
285
  const manifestPath = `${destination}/archive-replay.json`;
283
286
  const manifest = parseJson(readLocal(root, manifestPath), manifestPath);
284
- requireValue(isObject(manifest) && manifest.schemaVersion === 1 && manifest.kind === 'joycraft-archive-replay' && manifest.feature === feature && manifest.source === featurePath(feature) && Array.isArray(manifest.files), `Archive destination is not a valid archive for ${feature}: ${destination}`);
287
+ requireValue(isObject(manifest) && manifest.schemaVersion === 1 && manifest.kind === 'joycraft-archive-replay' && manifest.feature === feature && manifest.source === featurePath(root, feature) && Array.isArray(manifest.files), `Archive destination is not a valid archive for ${feature}: ${destination}`);
285
288
  if (manifest.reconciliation !== undefined) {
286
289
  const proof = manifest.reconciliation;
287
- requireValue(isObject(proof) && proof.path === `${featurePath(feature)}/archive-reconciliation.json` && isSha256(proof.sha256), 'Archived reconciliation metadata is malformed');
290
+ requireValue(isObject(proof) && proof.path === `${featurePath(root, feature)}/archive-reconciliation.json` && isSha256(proof.sha256), 'Archived reconciliation metadata is malformed');
288
291
  validateReconciliation(proof.record, feature);
289
292
  const ledger = manifest.files.find(file => file.operation === 'moved' && file.originalPath === proof.path && file.sha256 === proof.sha256);
290
293
  requireValue(ledger && sha256(readLocal(root, ledger.archivedPath)) === proof.sha256 && canonical(parseJson(readLocal(root, ledger.archivedPath), proof.path)) === canonical(proof.record), 'Archived reconciliation paper trail is missing or changed');
@@ -318,7 +321,7 @@ function existingArchive(root, feature) {
318
321
  export function previewArchiveFeature({ root = process.cwd(), feature, phase, attestation, reconciliation: reconciliationPath }) {
319
322
  feature = featureName(feature);
320
323
  requireValue(phase === 'session-end', 'Archive is allowed only during phase=session-end');
321
- const source = featurePath(feature), destination = archivePath(feature);
324
+ const source = featurePath(root, feature), destination = archivePath(root, feature);
322
325
  const parsedAttestation = parseAttestation(root, attestation);
323
326
  if (existsSync(projectTarget(root, destination))) {
324
327
  requireValue(!existsSync(projectTarget(root, source)), `Archive destination already exists while live source remains: ${destination}`);
@@ -401,7 +404,7 @@ export function archiveFeature(options) {
401
404
  // Revalidate every input immediately before changing paths, so a preview cannot race a writer.
402
405
  const fresh = previewArchiveFeature({ ...options, root, apply: false });
403
406
  requireValue(canonical({ ...plan, attestation: undefined }) === canonical({ ...fresh, attestation: undefined }), 'Archive inputs changed after preview; rerun the session-end preflight');
404
- const stage = `docs/archive/.${plan.feature}.staging-${process.pid}-${Date.now()}`;
407
+ const stage = `${workPaths(root).archive}/.${plan.feature}.staging-${process.pid}-${Date.now()}`;
405
408
  const stageLocal = projectTarget(root, stage), destinationLocal = projectTarget(root, plan.destination), sourceLocal = localDirectory(root, plan.source);
406
409
  requireValue(!existsSync(stageLocal) && !existsSync(destinationLocal), 'Archive collision detected before move');
407
410
  mkdirSync(stageLocal, { recursive: true, mode: 0o700 });
@@ -435,7 +438,22 @@ export function archiveFeature(options) {
435
438
  const recovery = restored ? 'The live feature path was preserved.' : `The staged feature remains at ${stage}; restore it manually before retrying.`;
436
439
  throw new Error(`Archive stopped without accepting new completion: ${error.message}. ${recovery}`);
437
440
  }
438
- return { status: 'archived', destination: plan.destination, manifest: `${plan.destination}/archive-replay.json`, historical: plan.historical };
441
+ const afterArchive = runAfterArchive(root, plan);
442
+ return { status: 'archived', destination: plan.destination, manifest: `${plan.destination}/archive-replay.json`, historical: plan.historical, ...(afterArchive ? { afterArchive } : {}) };
443
+ }
444
+
445
+ /** Run the project's hooks.afterArchive once. Its failure is reported; the archive stands. */
446
+ function runAfterArchive(root, plan) {
447
+ let command;
448
+ try { command = readConfig(root).hooks.afterArchive; } catch (error) { return { ran: false, error: error.message }; }
449
+ if (!command) return null;
450
+ const result = spawnSync(command, {
451
+ cwd: root, shell: true, encoding: 'utf8', timeout: 600_000, maxBuffer: 16 * 1024 * 1024,
452
+ env: { ...process.env, JOYCRAFT_FEATURE: plan.feature, JOYCRAFT_ARCHIVE_PATH: plan.destination, JOYCRAFT_SOURCE_PATH: plan.source },
453
+ });
454
+ const tail = text => (text ?? '').split('\n').slice(-20).join('\n').trim();
455
+ return { ran: true, command, exitCode: result.status, ok: result.status === 0 && !result.error,
456
+ ...(result.error ? { error: result.error.message } : {}), stdout: tail(result.stdout), stderr: tail(result.stderr) };
439
457
  }
440
458
 
441
459
  function argumentsFor(argv) {
@@ -455,6 +473,8 @@ export function main(argv = process.argv.slice(2)) {
455
473
  const flags = argumentsFor(argv);
456
474
  const result = archiveFeature({ feature: flags['--feature'], phase: flags['--phase'], attestation: flags['--attestation'], reconciliation: flags['--reconciliation'], apply: flags['--apply'] === true });
457
475
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
476
+ // The archive stands; exit 3 tells a caller that only the after-archive hook failed.
477
+ if (result.afterArchive && !result.afterArchive.ok) process.exitCode = 3;
458
478
  return result;
459
479
  }
460
480
 
@@ -0,0 +1,167 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { parseYaml, readConfig } from './config.mjs';
6
+ import { requireValue } from './identity.mjs';
7
+ import { projectStatus } from './status.mjs';
8
+ import { listWorktrees } from './worktrees.mjs';
9
+
10
+ // A report-only sweep for stale project knowledge. Every check is deterministic:
11
+ // files, links, frontmatter and Git history. It never edits a file; the
12
+ // joycraft-cleanup skill proposes fixes and applies only the approved ones.
13
+ const entryFiles = ['AGENTS.md', 'CLAUDE.md'];
14
+
15
+ function markdownFiles(root, folder, skip = []) {
16
+ const out = [];
17
+ const walk = relative => {
18
+ if (skip.includes(relative)) return;
19
+ let entries;
20
+ try { entries = readdirSync(path.join(root, relative), { withFileTypes: true }); } catch { return; }
21
+ for (const entry of entries) {
22
+ const child = `${relative}/${entry.name}`;
23
+ if (entry.isDirectory()) walk(child);
24
+ else if (entry.isFile() && entry.name.endsWith('.md')) out.push(child);
25
+ }
26
+ };
27
+ walk(folder);
28
+ return out.sort();
29
+ }
30
+
31
+ const read = (root, file) => { try { return readFileSync(path.join(root, file), 'utf8'); } catch { return null; } };
32
+
33
+ // A fence opens with three or more backticks or tildes at any indent (list items
34
+ // indent theirs) and closes on a line of the same character, at least as long.
35
+ // An unclosed fence runs to the end of the file, as in CommonMark.
36
+ function blankFences(text) {
37
+ let fence = null;
38
+ return text.split('\n').map(line => {
39
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
40
+ if (!fence) {
41
+ // A backtick fence's info string has no backtick; ```npm test``` is inline code.
42
+ if (!marker || (marker[0] === '`' && line.trimStart().slice(marker.length).includes('`'))) return line;
43
+ fence = marker;
44
+ } else if (marker && marker[0] === fence[0] && marker.length >= fence.length && /^\s*[`~]+\s*$/.test(line)) {
45
+ fence = null;
46
+ }
47
+ return ' '.repeat(line.length);
48
+ }).join('\n');
49
+ }
50
+
51
+ /** Markdown links (checked for existence) and backticked project paths (references only). */
52
+ export function references(file, text) {
53
+ const dir = path.posix.dirname(file);
54
+ const links = [], mentions = [];
55
+ // Blank out fenced code so examples are not read as links; keep line numbers.
56
+ text = blankFences(text);
57
+ const lineOf = index => text.slice(0, index).split('\n').length;
58
+ const add = (raw, index) => {
59
+ const target = raw.split('#')[0];
60
+ if (!target || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('/')) return;
61
+ let decoded = target;
62
+ try { decoded = decodeURI(target); } catch { /* keep the raw text when an escape is malformed */ }
63
+ links.push({ target: path.posix.normalize(path.posix.join(dir, decoded)), line: lineOf(index) });
64
+ };
65
+ for (const match of text.matchAll(/\[[^\]]*\]\((?:<([^>]+)>|([^)\s]+))(?:\s+"[^"]*")?\)/g)) add(match[1] ?? match[2], match.index);
66
+ for (const match of text.matchAll(/^ {0,3}\[[^\]]+\]:\s+(?:<([^>]+)>|(\S+))/gm)) add(match[1] ?? match[2], match.index);
67
+ 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 });
69
+ }
70
+ return { links, mentions };
71
+ }
72
+
73
+ function frontmatter(text) {
74
+ const block = /^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
75
+ if (!block) return null;
76
+ try { return parseYaml(block[1]); } catch (error) { return { unreadable: error.message.replace(/^joycraft\.yaml /, '') }; }
77
+ }
78
+
79
+ const inside = (file, folder) => file === folder || file.startsWith(`${folder}/`);
80
+
81
+ function git(root, args) {
82
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
83
+ }
84
+
85
+ /** Context pages whose mapped code changed in commits after the page last changed. */
86
+ function impactDrift(root, impact, findings, skipped) {
87
+ if (impact.length === 0) return;
88
+ try { git(root, ['rev-parse', '--verify', 'HEAD']); } catch { skipped.push({ check: 'impact-drift', reason: 'Not a Git repository with commits.' }); return; }
89
+ for (const entry of impact) {
90
+ for (const doc of entry.docs) {
91
+ if (!existsSync(path.join(root, doc))) { findings.push({ check: 'impact-drift', path: doc, detail: `Mapped to ${entry.source} in joycraft.yaml, but the page does not exist.`, fix: 'Create the page or remove it from cleanup.impact.' }); continue; }
92
+ const last = git(root, ['log', '-1', '--format=%H', '--', doc]);
93
+ if (!last) { skipped.push({ check: 'impact-drift', path: doc, reason: 'The page has no commit yet.' }); continue; }
94
+ const commits = git(root, ['log', '--format=%h', `${last}..HEAD`, '--', `:(glob)${entry.source}`]).split('\n').filter(Boolean);
95
+ if (commits.length) {
96
+ const files = [...new Set(git(root, ['diff', '--name-only', last, 'HEAD', '--', `:(glob)${entry.source}`]).split('\n').filter(Boolean))];
97
+ findings.push({ check: 'impact-drift', path: doc, detail: `${commits.length} commit(s) changed ${entry.source} after this page last changed: ${files.slice(0, 8).join(', ')}${files.length > 8 ? ', …' : ''}.`, fix: 'Read the changed code and update the page, or commit the page unchanged if it is still true.', commits });
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ /** Report stale working material, link problems, unmapped pages and code drift. */
104
+ export function cleanupReport({ root = process.cwd(), now = Date.now() } = {}) {
105
+ const config = readConfig(root);
106
+ const { features, archive, context } = config.paths;
107
+ const findings = [], skipped = [];
108
+
109
+ const status = projectStatus({ root });
110
+ for (const item of status.readyToArchive) {
111
+ findings.push({ check: 'unarchived', path: item.folder, detail: `Every spec is done, but the feature is still in ${features}.${item.openDecisions.length ? ` Open decisions: ${item.openDecisions.join(', ')}.` : ''}`, fix: 'Archive it at session end (archive.mjs), after carrying durable facts into the context home.' });
112
+ }
113
+ for (const item of status.drift) findings.push({ check: 'status-drift', path: item.file, detail: `Queue says ${item.queue}, frontmatter says ${item.frontmatter}.`, fix: item.fixable ? 'Run status.mjs --fix.' : item.reason });
114
+
115
+ const pages = markdownFiles(root, context, [features, archive]);
116
+ const authorities = [...entryFiles.filter(file => existsSync(path.join(root, file))), ...pages];
117
+ const referenced = new Set();
118
+ const deprecated = new Set();
119
+ for (const page of pages) {
120
+ const meta = frontmatter(read(root, page) ?? '');
121
+ if (meta?.unreadable) { findings.push({ check: 'frontmatter-unreadable', path: page, detail: `Frontmatter uses YAML that cleanup cannot read (${meta.unreadable}), so its status and stale_after are not checked.`, fix: 'Use plain key: value lines, lists and quoted strings in the frontmatter.' }); continue; }
122
+ if (meta?.status === 'deprecated') deprecated.add(page);
123
+ const staleAfter = meta?.stale_after == null ? NaN : Date.parse(String(meta.stale_after));
124
+ 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
+ }
126
+ for (const file of authorities) {
127
+ const text = read(root, file) ?? '';
128
+ const { links, mentions } = references(file, text);
129
+ for (const ref of [...links, ...mentions]) {
130
+ if (ref.target !== file) referenced.add(ref.target);
131
+ if (inside(ref.target, features) || inside(ref.target, archive)) {
132
+ 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.` });
133
+ }
134
+ if (deprecated.has(ref.target)) findings.push({ check: 'deprecated-link', path: file, line: ref.line, detail: `Links to ${ref.target}, which is marked status: deprecated.`, fix: 'Link the current page instead, or drop the link.' });
135
+ }
136
+ for (const ref of links) {
137
+ 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
+ }
139
+ }
140
+ for (const page of pages) {
141
+ 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
+ }
143
+
144
+ impactDrift(root, config.cleanup.impact, findings, skipped);
145
+
146
+ try {
147
+ for (const tree of listWorktrees({ root, sizes: false }).trees.filter(tree => tree.owner !== 'joycraft')) {
148
+ findings.push({ check: 'unknown-worktree', path: tree.path, detail: `A linked worktree${tree.branch ? ` on ${tree.branch}` : ''} that worktrees.mjs did not create.`, fix: 'Check it for unmerged work, then remove it with git worktree remove.' });
149
+ }
150
+ } catch { skipped.push({ check: 'unknown-worktree', reason: 'Not a Git repository.' }); }
151
+
152
+ const counts = Object.fromEntries([...new Set(findings.map(item => item.check))].map(check => [check, findings.filter(item => item.check === check).length]));
153
+ return { config: config.source ?? 'defaults', paths: config.paths, counts, findings, skipped };
154
+ }
155
+
156
+ export async function main(argv = process.argv.slice(2)) {
157
+ const index = argv.indexOf('--root');
158
+ requireValue(argv.length === 0 || (argv.length === 2 && index === 0), 'Usage: cleanup.mjs [--root <project>]');
159
+ const result = cleanupReport({ root: path.resolve(index === 0 ? argv[1] : '.') });
160
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
161
+ if (result.findings.length) process.exitCode = 2;
162
+ return result;
163
+ }
164
+
165
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
166
+ main().catch(error => { process.stderr.write(`Cleanup stopped: ${error.message}\n`); process.exitCode = 1; });
167
+ }