@ulysses-ai/create-workspace 0.19.0-beta.0 → 0.21.0-beta.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 (28) hide show
  1. package/README.md +1 -1
  2. package/lib/upgrade.mjs +20 -0
  3. package/lib/upgrade.test.mjs +119 -0
  4. package/package.json +3 -3
  5. package/template/CLAUDE.md.tmpl +5 -2
  6. package/template/_claude/hooks/workspace-update-check.mjs +4 -4
  7. package/template/_claude/lib/freshness.mjs +20 -7
  8. package/template/_claude/lib/registry-check.mjs +80 -14
  9. package/template/_claude/scripts/build-workspace-context.mjs +2 -0
  10. package/template/_claude/scripts/chat-record.mjs +27 -19
  11. package/template/_claude/scripts/classify-update.mjs +212 -0
  12. package/template/_claude/scripts/cleanup-work-session.mjs +4 -2
  13. package/template/_claude/scripts/maintenance-audit.mjs +0 -0
  14. package/template/_claude/scripts/merge-mode.mjs +61 -0
  15. package/template/_claude/scripts/migrate-canonical-priority.mjs +7 -1
  16. package/template/_claude/scripts/migrate-claude-md-freshness-include.mjs +35 -10
  17. package/template/_claude/scripts/migrate-session-layout.mjs +19 -8
  18. package/template/_claude/scripts/migrate-sessions.mjs +444 -121
  19. package/template/_claude/scripts/task-pr.mjs +213 -105
  20. package/template/_claude/scripts/task-worktree.mjs +26 -16
  21. package/template/_claude/skills/complete-work/SKILL.md +16 -12
  22. package/template/_claude/skills/maintenance/SKILL.md +48 -108
  23. package/template/_claude/skills/migrate-sessions/SKILL.md +17 -5
  24. package/template/_claude/skills/start-work/SKILL.md +4 -4
  25. package/template/_claude/skills/workspace-init/SKILL.md +20 -14
  26. package/template/_claude/skills/workspace-update/SKILL.md +93 -40
  27. package/template/_gitignore +3 -0
  28. package/template/workspace.json.tmpl +0 -1
@@ -368,16 +368,17 @@ Ask: "These changes weren't part of a formal work session. What do you want to d
368
368
  Reached from Step 1 when detection says `model: task`. The state is the branch, the chat record's task entries, and the linked issue — there is no session folder and no `session.md`. This chat normally runs at the workspace root (the launcher) but may be running inside one of the worktrees; either way, every input comes from the detect result, never from cwd. Run `cd "{launcher-root}"` first — steps 2–5 and every relative path in them are anchored there:
369
369
 
370
370
  - `{chat}` — the `Chat record:` line injected by the SessionStart hook (the same value Step 1 passed as `--chat`)
371
- - `{tasks}` — the detect result's task entries from the chat record, each carrying `{workItem}`, `{branch}`, `{repo}`; `repo: "."` is the workspace repo itself. When detection came from cwd alone (`source: 'worktree'`, no chat record entry — e.g. a no-tracker task) there are no task entries: take `{repo}` and `{branch}` from the detect result itself and treat `{workItem}` as absent
371
+ - `{tasks}` — the detect result's task entries from the chat record, each carrying `{workItem}` (null without a tracker), `{branch}`, `{repo}`; `repo: "."` is the workspace repo itself. When detection came from cwd alone (`source: 'worktree'`, no chat record entry — e.g. a chat whose record was never written) there are no task entries: take `{repo}` and `{branch}` from the detect result itself and treat `{workItem}` as absent
372
372
  - `{worktree}` — `{launcher-root}/repos/{repo}/.claude/worktrees/{slug}` for a project repo, or `{launcher-root}/.claude/worktrees/{slug}` for the workspace repo (`.`), where `{slug}` is the branch with `/` replaced by `-`
373
373
  - `{workspace-worktree}` — `{launcher-root}/.claude/worktrees/{slug}`: the workspace repo's own task worktree, created in step 2 only when drawer items are promoted (Claude Code's native worktree location — the two converge on it)
374
- - `{defaultBranch}` — `workspace.json` → `repos.{repo}.branch`, default `main`; for `.` it is the workspace origin's HEAD with `main` as the fallback — exactly what `task-worktree.mjs`'s `defaultBranchFor` resolves
374
+ - `{defaultBranch}` — `workspace.json` → `repos.{repo}.branch`, default `main`; for `.` it is the workspace origin's HEAD with `main` as the fallback — or, when the launcher has no origin, the branch it sits on when that is `main`/`master` — exactly what `task-worktree.mjs`'s `defaultBranchFor` resolves
375
+ - `{mode}` per repo — `forge` or `local`, resolved exactly as `task-pr.mjs` resolves it: `local` when the repo has no origin remote or its override says so (`repos.{repo}.merge`, or `workspace.merge` for `.`) — the override for a clone whose origin is a third-party upstream nobody here may push to; `forge` when its origin is a forge remote. A local repo is never pushed: it merges into its source clone in step 4.
375
376
 
376
377
  If several tasks are open, ask the user which one to complete — group by branch; a multi-repo task is several entries sharing a branch — and complete one branch at a time.
377
378
 
378
379
  0. **Pre-flight: the worktrees must be clean.** For each `{worktree}` of the chosen task, `git -C "{worktree}" status --porcelain` must be empty. If it is not, stop here — before the rebase — and ask the user to commit or discard: rebasing over uncommitted work silently invalidates it.
379
380
 
380
- 1. **Rebase each task worktree onto `origin/{defaultBranch}`** (`git -C "{worktree}" fetch origin`, then `git -C "{worktree}" rebase "origin/{defaultBranch}"`). Freshness first: the PR in step 3 must describe the branch as it will merge. If conflicts arise, STOP and present them — do not auto-resolve.
381
+ 1. **Rebase each task worktree onto its base** — `origin/{defaultBranch}` for a `forge` repo (`git -C "{worktree}" fetch origin`, then `git -C "{worktree}" rebase "origin/{defaultBranch}"`), the local `{defaultBranch}` for a `local` repo (`git -C "{worktree}" rebase "{defaultBranch}"`; no fetch — there is no remote to fetch from). Freshness first: the PR in step 3 must describe the branch as it will merge. If conflicts arise, STOP and present them — do not auto-resolve.
381
382
 
382
383
  2. **Route durable thinking.** List the chat drawer `{launcher-root}/workspace-scratchpad/chats/{chat}/` and ask which items should graduate into `workspace-context/`. The offer is filtered by task: an item whose frontmatter carries a `workItem:` is listed only when it names this task's `{workItem}`, an item with no `workItem:` is always listed, and an item tagged for another open task is not this completion's to promote — it belongs to that task's completion. Leftovers of an earlier completion attempt are never offered: the `pr-{slug}-*.md` bodies and the `prs-{slug}.json` state file are step 3–4 machinery, not thinking. Drafting skills (`/braindump`, `/handoff`, designs and plans) tag their drawer writes with `workItem:` while a task is active so this filter has something to filter on. If nothing is chosen, skip this step — no `.` worktree is needed yet. Do NOT invoke `/promote`: it writes relative to cwd and commits per item, which at the launcher lands on the default branch — exactly the hole this flow closes, and it does not know about drawer items. For the chosen items, first create the workspace worktree on the task's branch and record it alongside the project entries:
383
384
 
@@ -386,7 +387,7 @@ If several tasks are open, ask the user which one to complete — group by branc
386
387
  node "{launcher-root}/.claude/scripts/chat-record.mjs" --root "{launcher-root}" --add-task --chat "{chat}" --work-item "{workItem}" --branch "{branch}" --repo "."
387
388
  ```
388
389
 
389
- Skip the record line when there is no `{workItem}`. Then copy each chosen item to `{workspace-worktree}/workspace-context/shared/{item}` or `{workspace-worktree}/workspace-context/team-member/{user}/{item}` — ask which level; `shared/locked/` only if explicitly requested — keeping the filename and making sure the file carries a `description:` frontmatter (add one if the drawer item has none). Never write under `{launcher-root}/workspace-context/` at the launcher. Rebuild the indexes and commit once, and only when something is staged:
390
+ Omit `--work-item` from the record line when the task has none — without a work item the entry is keyed by repo + branch. Then copy each chosen item to `{workspace-worktree}/workspace-context/shared/{item}` or `{workspace-worktree}/workspace-context/team-member/{user}/{item}` — ask which level; `shared/locked/` only if explicitly requested — keeping the filename and making sure the file carries a `description:` frontmatter (add one if the drawer item has none). Never write under `{launcher-root}/workspace-context/` at the launcher. Rebuild the indexes and commit once, and only when something is staged:
390
391
 
391
392
  ```bash
392
393
  node "{launcher-root}/.claude/scripts/build-workspace-context.mjs" --write --root "{workspace-worktree}"
@@ -396,7 +397,7 @@ If several tasks are open, ask the user which one to complete — group by branc
396
397
 
397
398
  The drawer is per-chat, so it survives task teardown — but it is machine-local and backed up nowhere, and this review, with the work fresh in mind, is the moment to decide what graduates. Items left behind are not lost, only unreviewed.
398
399
 
399
- 3. **Write one PR body per repo into the drawer, then create every PR with `task-pr.mjs --create`** — never `gh pr` directly. For each repo of the task, `{worktree}` included when it exists, write `{launcher-root}/workspace-scratchpad/chats/{chat}/pr-{slug}-{repo}.md` (with `{repo}` rendered as `workspace` for `.`). Each body carries a short summary of what changed and why, then a `## Verification` section stating how the change was checked — the commands run and their results. The drawer is machine-local and gitignored, so these files never touch a branch, and `--create` requires one for every repo whose branch has commits. Then one command does the rest:
400
+ 3. **Write one PR body per forge repo into the drawer, then create every PR with `task-pr.mjs --create`** — never `gh pr` directly. For each **forge**-mode repo of the task, `{workspace-worktree}` included when it exists, write `{launcher-root}/workspace-scratchpad/chats/{chat}/pr-{slug}-{repo}.md` (with `{repo}` rendered as `workspace` for `.`). Each body carries a short summary of what changed and why, then a `## Verification` section stating how the change was checked — the commands run and their results. The drawer is machine-local and gitignored, so these files never touch a branch; `--create` requires one for every forge repo whose branch has commits, and a local repo needs none (one given for it is accepted and ignored). Then one command does the rest:
400
401
 
401
402
  ```bash
402
403
  node "{launcher-root}/.claude/scripts/task-pr.mjs" --create --root "{launcher-root}" --branch "{branch}" \
@@ -405,9 +406,9 @@ If several tasks are open, ask the user which one to complete — group by branc
405
406
  --out "{launcher-root}/workspace-scratchpad/chats/{chat}/prs-{slug}.json"
406
407
  ```
407
408
 
408
- Omit `--work-item` when the task has none, and repeat `--body-file` once per repo. `--chat` resolves the task's repos from this chat's record entries for the branch; when detection came from cwd alone, pass `--repo "{repo}"` once per repo instead. The script skips repos whose branch has no commits over `origin/{defaultBranch}` (reporting them as `empty` — no push, no PR, no body file needed, torn down in step 5 like any other; a workspace branch that collected no promotions gets no PR), parses each worktree's own origin into `{owner}/{name}` and stops **before pushing anything** if any origin is not forge-hosted — such a repo is completed under the session model — then pushes `-u origin {branch}` and opens one PR per remaining repo through a per-repo forge aimed at that worktree's own remote, never the launcher's. The workspace repo (`.`) is handled exactly like a project repo. The PR title is the linked issue's title, or the branch's first commit subject without a `{workItem}`; the body is the drawer file with `Closes <ref>` appended, where `<ref>` is `#N` when the PR's repo is the tracker's repo and `{tracker-repo}#N` otherwise — only the first form closes an issue in the PR's own repo. If the push is rejected as non-fast-forward — the branch already existed on origin and step 1's rebase rewrote it — the script stops and says so; ask the user, and only on explicit confirmation re-run the same command with `--force-with-lease` (the script never forces on its own). If `workspace.forge` is `false` in `workspace.json`, the script refuses before pushing anything: forge operations are disabled in this workspace and the PR is opened by hand. `--out` writes the run's JSON to `prs-{slug}.json` for step 4 — `{ prs: [{ repo, owner, name, number, id, url, isWorkspace }], empty: [repo…], pushed: [repo…] }`, printed to stdout as well — instead of shell redirection, so the command is identical on every shell. The run is idempotent: a repo whose branch already has an open PR against `{defaultBranch}` gets that PR reused, never duplicated, and if the run fails partway the file still records what was pushed and opened so far — fix the cause and re-run the same command; it completes the set.
409
+ Omit `--work-item` when the task has none, and repeat `--body-file` once per forge repo. `--chat` resolves the task's repos from this chat's record entries for the branch; when detection came from cwd alone, pass `--repo "{repo}"` once per repo instead. The script resolves each repo's merge mode before doing anything else: a forge repo is pushed `-u origin {branch}` and gets one PR through a per-repo forge aimed at that worktree's own origin, never the launcher's; a local repo (no origin, or `merge: "local"`) is neither pushed nor PR'd — it is recorded as a local entry for step 4. The workspace repo (`.`) is handled exactly like a project repo. It skips repos whose branch has no commits over the base (reporting them as `empty` — no push, no PR, no body file needed, torn down in step 5 like any other; a workspace branch that collected no promotions gets no PR), and stops **before pushing anything** when a repo's origin exists but is not forge-hosted and has no `"local"` override — the error names the `workspace.json` setting (`repos.{repo}.merge`, or `workspace.merge` for `.`) that opts the repo into local mode. The PR title is the linked issue's title, or the branch's first commit subject without a `{workItem}`; the body is the drawer file with `Closes <ref>` appended, where `<ref>` is `#N` when the PR's repo is the tracker's repo and `{tracker-repo}#N` otherwise — only the first form closes an issue in the PR's own repo. If the push is rejected as non-fast-forward — the branch already existed on origin and step 1's rebase rewrote it — the script stops and says so; ask the user, and only on explicit confirmation re-run the same command with `--force-with-lease` (the script never forces on its own). If `workspace.forge` is `false` in `workspace.json` and any repo resolved to forge, the script refuses before pushing anything: forge operations are disabled in this workspace and the PR is opened by hand. `--out` writes the run's JSON to `prs-{slug}.json` for step 4 — `{ prs: [{ repo, mode, … }], empty: [repo…], pushed: [repo…] }`, printed to stdout as well — instead of shell redirection, so the command is identical on every shell. Every entry carries `commits`; a forge entry also carries `owner`, `name`, `number`, `id`, `url`, `isWorkspace`, and a local entry `branch`, `base`, `worktree`. The run is idempotent: a repo whose branch already has an open PR against `{defaultBranch}` gets that PR reused, never duplicated, and if the run fails partway the file still records what was pushed and opened so far — fix the cause and re-run the same command; it completes the set.
409
410
 
410
- 4. **Ask before merging, then run `task-pr.mjs --merge`, which also closes the linked issue.** When step 3 reported `prs: []` — every repo was empty — there is nothing to merge: skip this step, say so, and leave the linked issue open for the user to decide (close it by hand, or keep the task going); `--merge` itself refuses an empty PRs file for exactly that reason. Otherwise present a summary per repo that got a PR — the workspace repo included — built from `--create`'s output, and ask once:
411
+ 4. **Ask before merging, then run `task-pr.mjs --merge`, which also closes the linked issue.** When step 3 reported `prs: []` — every repo was empty — there is nothing to merge: skip this step, say so, and leave the linked issue open for the user to decide (close it by hand, or keep the task going); `--merge` itself refuses an empty PRs file for exactly that reason. Otherwise present a summary per repo that got an entry — forge and local alike, the workspace repo included — built from `--create`'s output, and ask once. A local repo shows `(local merge)` in place of a PR line; a mixed task asks `Merge all?`, an all-local task `Merge all locally?`:
411
412
 
412
413
  ```
413
414
  Task complete:
@@ -415,9 +416,12 @@ If several tasks are open, ask the user which one to complete — group by branc
415
416
  PROJECT: {owner}/{name}
416
417
  PR: {pr.url}
417
418
  Branch: {branch} → {defaultBranch}
418
- Commits: {n} # git -C "{worktree}" rev-list --count "origin/{defaultBranch}..{branch}"
419
+ Commits: {n} # from the entry's `commits` count
419
420
 
420
- WORKSPACE: {ws-owner}/{ws-name} # from the workspace worktree's origin
421
+ PROJECT: {repo} (local merge)
422
+ Branch: {branch} → {defaultBranch} # merged in repos/{repo}
423
+
424
+ WORKSPACE: {ws-owner}/{ws-name} # from the workspace worktree's origin, or "(local merge)"
421
425
  PR: {ws-pr.url}
422
426
  Branch: {branch} → {defaultBranch}
423
427
 
@@ -433,16 +437,16 @@ If several tasks are open, ask the user which one to complete — group by branc
433
437
  --prs "{launcher-root}/workspace-scratchpad/chats/{chat}/prs-{slug}.json" --work-item "{workItem}"
434
438
  ```
435
439
 
436
- The script checks each PR's state first, then merges the project PRs (squash, delete branch), then the workspace PR only when every project merge succeeded — the workspace branch's promoted context describes the project merges and must never merge ahead of them. A PR the forge already reports as merged counts as done and is never merged twice, which is what makes a re-run safe: the run that finally gets every PR merged also does the pull and the close. The launcher is pulled `--ff-only` only when it sits on the workspace default branch — it waited there on the workspace merge, and a project-only task pulls after the project merges; when it sits on some other branch the JSON reports `pullSkipped: "launcher on <branch>"`, and a failed pull is reported as `pullFailed: true` rather than an error, because the merges stand and the issue still closes — in both cases tell the user to pull the launcher by hand before step 5. The close comes last, with a one-line comment naming the merged PR URL(s): merge precedes close because an issue closed before its PR merges points at work that never landed; without a `{workItem}` (no tracker, or the task was never recorded) the close is skipped and the script says so. On any merge failure the script stops, names the PRs still open, and exits non-zero — nothing is torn down, and re-running `--merge` once the failure is fixed is safe. After a successful merge, delete the drawer's `pr-{slug}-*.md` body files and the spent `prs-{slug}.json`.
440
+ The script checks each entry's state first, then finishes the project entries — forge PRs (squash, delete branch) and local branches as `git merge --ff-only {branch}` in the repo's source clone (`repos/{repo}`, or the launcher for `.`), which must sit clean on its default branch — then the workspace entry only when every project merge succeeded: the workspace branch's promoted context describes the project merges and must never merge ahead of them. A PR the forge already reports as merged and a local branch already contained in the default branch both count as done, which is what makes a re-run safe: the run that finally gets every entry merged also does the pull and the close. A local branch that will not fast-forward stops the run and says to rebase the task branch onto the local `{defaultBranch}` and re-run. The launcher is pulled `--ff-only` only when it sits on the workspace default branch, `.` was not itself merged locally (that merge ran in the launcher — `pullSkipped: "workspace merged locally"`), the workspace repo is not local (no forge merge of `.` happened that a pull could fetch — `pullSkipped: "workspace repo is local"`), and the launcher branch has an upstream to pull from (`pullSkipped: "launcher has no upstream"`); a launcher on some other branch reports `pullSkipped: "launcher on <branch>"`, and a failed pull is reported as `pullFailed: true` rather than an error, because the merges stand and the issue still closes — a failed pull is the one case that needs the launcher pulled by hand before step 5. The close comes last, with a one-line comment naming each merged PR URL or local `{repo} {branch}->{base}`: merge precedes close because an issue closed before its PR merges points at work that never landed. It happens only when `{workItem}` is given AND a tracker is configured — without a work item or without a tracker, `closed` is `null` and the JSON says why (`closeSkipped`) — say so to the user. On any merge failure the script stops, names what is still open, and exits non-zero — nothing is torn down, and re-running `--merge` once the failure is fixed is safe. After a successful merge, delete the drawer's `pr-{slug}-*.md` body files and the spent `prs-{slug}.json`.
437
441
 
438
- 5. **Tear down only what finished — worktree first, then the record entry**, and only for a repo whose PR merged in step 4, or whose branch was empty and never pushed in step 3; the workspace repo included (`--repo "."`). If a repo's push, PR, or merge failed, or the user declined the merge, leave that repo's worktree, branch, and record entry exactly in place and say so: `--delete-branch` would otherwise `branch -D` commits that exist nowhere but the local worktree. For `.` the script never deletes the branch checked out at the launcher root.
442
+ 5. **Tear down only what finished — worktree first, then the record entry**, and only for a repo whose PR merged or whose local merge succeeded in step 4, or whose branch was empty and never pushed in step 3; the workspace repo included (`--repo "."`). If a repo's push, PR, or merge failed, or the user declined the merge, leave that repo's worktree, branch, and record entry exactly in place and say so: `--delete-branch` would otherwise `branch -D` commits that exist nowhere but the local worktree. For `.` the script never deletes the branch checked out at the launcher root.
439
443
 
440
444
  ```bash
441
445
  node "{launcher-root}/.claude/scripts/task-worktree.mjs" --root "{launcher-root}" --remove --repo "{repo}" --branch "{branch}" --delete-branch
442
446
  node "{launcher-root}/.claude/scripts/chat-record.mjs" --root "{launcher-root}" --remove-task --chat "{chat}" --work-item "{workItem}" --repo "{repo}"
443
447
  ```
444
448
 
445
- Skip the `--remove-task` line when there is no record entry (no `{workItem}`). Worktree first because a refusal (dirty worktree, slug collision) then leaves both the worktree and its record entry in place — nothing orphaned, safe to retry. `--delete-branch` also removes the local branch: the forge's `deleteBranch` removed only the remote one, so post-merge teardown passes it to clean the local clone; this is the only step that ever passes it. Never pass `--force` without asking the user.
449
+ When the task has no `{workItem}`, drop `--work-item` and pass `--branch "{branch}"` instead — the record entry is keyed by repo + branch. Worktree first because a refusal (dirty worktree, slug collision) then leaves both the worktree and its record entry in place — nothing orphaned, safe to retry. `--delete-branch` also removes the local branch: the forge's `deleteBranch` removed only the remote one, so post-merge teardown passes it to clean the local clone; this is the only step that ever passes it. Never pass `--force` without asking the user.
446
450
 
447
451
  ## Notes
448
452
  - The session tracker's body is the primary source for PR-body synthesis — it captures the full session history alongside specs and plans
@@ -16,33 +16,41 @@ Keep the workspace healthy. Combines integrity auditing with active cleanup reco
16
16
 
17
17
  Read-only integrity checks. Reports problems but never modifies files.
18
18
 
19
+ The mechanical checks are scripted (gh:180) — run the audit and present its report:
20
+
21
+ ```bash
22
+ node .claude/scripts/maintenance-audit.mjs --root .
23
+ ```
24
+
25
+ The report prints one block per section — ✓ ok lines, ✗ issues, ⚠ warnings, ℹ infos — then a result summary. Severity drives the exit code: any issue-severity finding → exit `1`, otherwise `0` (a non-zero exit is the report above it, not a crash). `--offline` skips section 7, the only network user; `--json` emits `{issues, summary}` instead of the human report when another step needs the machine-readable numbers.
26
+
27
+ Sections 1–7 below explain what the script checks, so its findings can be interpreted. Each also names what it does not carry — those residual checks Claude performs alongside the script run.
28
+
19
29
  ### 1. Cross-reference consistency
20
- Scan all workspace-context files against each other:
21
- - **Stale references** — file A mentions "2 mandatory rules" but there are now 4
22
- - **Path references** — file A mentions a file that was moved or deleted
23
- - **Contradictions** — file A says "user-scoped is default" but file B says "root is default"
30
+ The script checks the CLAUDE.md skill list against `.claude/skills/` in both directions, and walks CLAUDE.md's `@`-import graph for dangling imports. A missing `local-only-*` file or the optional `CODEBASE.md` stub is info, not an issue — expected states on machines that never generated them.
31
+
32
+ Semantic drift between context files — one saying "2 mandatory rules" when there are now 4, or two files contradicting each other — is not mechanically decidable; cleanup step 10's reconciliation covers it.
24
33
 
25
34
  ### 2. Frontmatter integrity
26
- For each workspace-context `.md` file and each `work-sessions/*/workspace/session.md`:
27
- - Valid frontmatter? (state, lifecycle, type, topic, author, updated; plus name/status/branch/repos for session trackers)
28
- - `branch` field references a branch that still exists?
29
- - `repo`/`repos` field references repos that exist in workspace.json?
30
- - `lifecycle: active` on a file not updated in 7+ days? (stale candidate)
31
- - `lifecycle: resolved` files that should have been processed by /complete-work?
32
- - Session tracker `status: active` but the workspace worktree at `work-sessions/{name}/workspace/` is missing? (orphaned)
33
- - `confidence` field present? Must be one of `high`, `medium`, `low` if set.
35
+ For each non-gitignored workspace-context `.md` and each `work-sessions/*/workspace/session.md`, the script checks:
36
+ - Frontmatter parses
37
+ - Session trackers carry `name`, `status`, `branch`
38
+ - `branch` references a branch that still exists
39
+ - `repo`/`repos` reference repos in workspace.json
40
+ - `lifecycle: active` untouched in 7+ days (stale candidate)
41
+ - `lifecycle: resolved` (info — confirm /complete-work has processed it)
42
+ - `confidence`, when set, is one of `high`, `medium`, `low`
34
43
 
35
44
  ### 3. Workspace structure
36
- - Actual directory layout matches what workspace-structure rule describes?
37
- - CLAUDE.md references skills and rules that actually exist?
38
- - Orphaned rules or skills not referenced anywhere?
39
- - workspace.json repos all present in `repos/`?
45
+ The script checks that workspace.json and CLAUDE.md are present and parseable, that `workspace-context/` and `.claude/rules`, `skills`, `scripts` directories exist, and that every manifest repo is cloned under `repos/`.
40
46
 
41
47
  ### 4. Git state
48
+ The script covers the launcher itself: on its default branch, tracked tree clean. Untracked paths are info — gitignored content is not counted.
49
+
50
+ The worktree-level checks are not carried by the script; perform them alongside it:
42
51
  - Worktrees with no recent commits? (orphaned)
43
52
  - Local branches with no remote tracking? (unpushed work)
44
53
  - Worktrees whose branch has already been merged? (cleanup candidates)
45
- - Workspace repo on expected branch?
46
54
  - Orphan worktree records in project repos — run `git -C repos/{repo} worktree list` for each repo and flag any `prunable` markers. These usually come from a workspace-first teardown (the unsafe order) leaving stale admin records behind. Suggest `git worktree prune` on the affected repo.
47
55
  - Task-model state (gh:146), three checks:
48
56
  - **Unrecorded task worktrees** — list `repos/*/.claude/worktrees/*` and `.claude/worktrees/*`, read each candidate's branch (`git -C "{path}" rev-parse --abbrev-ref HEAD`), and keep only those on a task-prefixed branch (`feature/`, `bugfix/`, `chore/`) — Claude Code's own worktrees carry other branch names, so the prefix filter skips them without guessing a name convention. Cross-reference the chat records (`node .claude/scripts/chat-record.mjs --root . --list`): a task-prefixed worktree no record entry claims is *unrecorded* — it may be a legitimate no-tracker task (those are never recorded), so present it and ask before suggesting `node .claude/scripts/task-worktree.mjs --root . --remove --repo "{repo}" --branch "{branch}"`.
@@ -50,92 +58,29 @@ For each workspace-context `.md` file and each `work-sessions/*/workspace/sessio
50
58
  - **Merged but never completed** — a recorded task branch that already merged. Judge merged-ness by the forge's merged PRs for that repo, matching on head branch — never `git branch --merged`, which a squash merge (never an ancestor) silently misses. `/complete-work` never ran. Suggest running `/complete-work` for that branch (detection from the chat record finds it).
51
59
 
52
60
  ### 5. Workspace-context auto-file integrity
61
+ The script regenerates `workspace-context/index.md`, `canonical.md`, and each `workspace-context/team-member/{user}/index.md` in memory and compares fingerprints — the same semantics as `build-workspace-context.mjs --check`:
62
+ - Missing or stale artifact → issue; regenerate with `node .claude/scripts/build-workspace-context.mjs --write --root .`
63
+ - A missing gitignored per-user index → info (regenerated per machine, the normal fresh-checkout state)
64
+ - Canonical body over budget after trim and stub → warning, deferred to cleanup triage
65
+ - Trimmed or stubbed but within budget → info
53
66
 
54
- `workspace-context/index.md`, `workspace-context/canonical.md`, and each `workspace-context/team-member/{user}/index.md` are auto-generated from frontmatter and locked content. Run the check:
67
+ The canonical budget is opt-in: `workspace.canonicalBudgetBytes` off (absent or `null`) means canonical ships every locked file in full and over-budget cannot occur. When set, selection walks `ok` → `trimmed` → `stubbed` → `over-budget` as the generator gives up progressively more reference content to fit: `trimmedFiles` are reference files whose `<!-- canonical:trim --> ... <!-- canonical:end-trim -->` spans were dropped, `stubbedFiles` are reference files reduced to a one-line breadcrumb. `over-budget` means the budget is still exceeded after stubbing — regeneration cannot fix it; the locked content itself needs triage via `/maintenance cleanup` (step 11). Stale wins over over-budget: a stale canonical is reported as stale, hiding any over-budget condition until it is regenerated.
55
68
 
56
- ```bash
57
- node .claude/scripts/build-workspace-context.mjs --check --root .
58
- ```
59
-
60
- The script reports per-artifact status as JSON and uses three exit codes to distinguish what's wrong:
61
-
62
- - `0` — all artifacts current and, when a canonical budget is set, the rendered canonical fits inside `workspace.canonicalBudgetBytes`.
63
- - `1` — at least one artifact is `missing` or `stale`. Run `--write` to regenerate. `missing` means the artifact does not exist yet; `stale` means it exists but no longer matches its sources (a file was added or deleted, a `description:` changed, a `shared/locked/` file was edited, an `.indexignore` rule was added).
64
- - `2` — artifacts are current but canonical body bytes exceed the budget after the trim and stub stages have already run. Only reachable when a budget is set. Regeneration cannot fix this; the locked content itself needs triage. Stale wins over over-budget when both apply, so a `1` can hide an over-budget condition until you regen.
65
-
66
- The JSON payload always includes a `canonical` block summarizing the budget outcome:
67
-
68
- ```json
69
- {
70
- "status": "current",
71
- "missing": [],
72
- "stale": [],
73
- "canonical": {
74
- "budget": 40960,
75
- "current": 47802,
76
- "overBy": 6842,
77
- "selectionStatus": "stubbed",
78
- "trimmedFiles": ["post-release-discipline"],
79
- "stubbedFiles": ["project-status", "release-flow-recipes"]
80
- }
81
- }
82
- ```
83
-
84
- `selectionStatus` walks `ok` → `trimmed` → `stubbed` → `over-budget` as the script gives up progressively more reference content trying to fit the budget. `trimmedFiles` lists reference files whose `<!-- canonical:trim --> ... <!-- canonical:end-trim -->` spans were dropped; `stubbedFiles` lists reference files whose entire body was replaced with a one-line breadcrumb. `overBy` is present only when `selectionStatus === 'over-budget'` and reports the bytes still over after stubbing.
85
-
86
- The canonical budget is opt-in. `workspace.canonicalBudgetBytes` is off unless workspace.json sets it — absent or `null` means no budget. When off, `canonical.md` ships every locked file in full, the `canonical` block reports `"budget": null` with `selectionStatus: "ok"`, exit `2` cannot occur, and the audit reports one informational line in place of the budget OK/warning line:
87
-
88
- ```
89
- • Canonical budget: off (alwaysLoadedBudgetBytes covers the total)
90
- ```
91
-
92
- No warning accompanies it. To turn the budget back on, set a byte count in workspace.json (e.g. `"canonicalBudgetBytes": 40960`) and regenerate.
93
-
94
- Audit mode reports the status verbatim. When a budget is set and `selectionStatus` is `over-budget`, audit emits the budget violation and recommends `/maintenance cleanup` to triage — regeneration will not resolve it. Cleanup mode runs `--write` when `missing` or `stale`, re-checks, and then enters the budget triage flow described in cleanup step 11 if the post-regen check still reports `over-budget`.
95
-
96
- While the indexes are being read, also flag entries with weak fallbacks: filename-slug-only descriptions (e.g., "project status" with no period) usually indicate the underlying file is missing a `description:` or has no usable opening sentence. Suggest adding `description:` to those source files — the index will pick it up on the next regeneration.
69
+ Residual, not in the script: while reading the indexes, flag filename-slug-only descriptions (e.g., "project status" with no period) — usually the source file is missing a `description:` or has no usable opening sentence. Suggest adding `description:`; the index picks it up on the next regeneration.
97
70
 
98
71
  ### 6. Always-loaded context budget
72
+ The script measures everything Claude reads at launch — CLAUDE.md, its @-imports, and the active rules — against `workspace.alwaysLoadedBudgetBytes`. Rules with `paths:` frontmatter are conditional (they load only when a matching file is touched) and count separately; with no budget in workspace.json the check passes trivially.
99
73
 
100
- Everything Claude reads at launch — CLAUDE.md, its @-imports, and the active rules — is measured against `workspace.alwaysLoadedBudgetBytes`:
101
-
102
- ```bash
103
- node .claude/scripts/context-footprint.mjs --root .
104
- ```
105
-
106
- Rules carrying `paths:` frontmatter are conditional (they load only when a matching file is touched); the script lists them in a separate conditional section and excludes them from the total. With no `alwaysLoadedBudgetBytes` in workspace.json there is no budget and this check passes trivially.
107
-
108
- Within budget → an OK line: `✓ Always-loaded context: 43 KB / 64 KB`. Over budget → a Warning (the workspace still functions; this is drift, not breakage) naming the top contributors and the fixes:
109
-
110
- ```
111
- ⚠ Always-loaded context exceeds budget: 78 KB / 64 KB. Top contributors:
112
- .claude/rules/git-conventions.md (12 KB), CLAUDE.md (9 KB),
113
- .claude/rules/workspace-structure.md (8 KB). Scope situational rules with
114
- paths: frontmatter, or move reference content to shared/.
115
- ```
116
-
117
- The script itself exits `1` when over budget; `/maintenance` reports that as the warning above, not as a failed run.
74
+ Within budget → an OK line (`✓ Always-loaded context: 43 KB / 64 KB`). Over → a warning — the workspace still functions; this is drift, not breakage — naming the top contributors. Fixes: scope situational rules with `paths:` frontmatter, or move reference content to `shared/`.
118
75
 
119
76
  ### 7. Template freshness
77
+ The script invokes `refreshIfStale` with a 24h TTL regardless of `workspace.versionCheck.ambient` — the user explicitly ran `/maintenance` — and reports:
78
+ - `outdated` → warning: `Template v{current} → v{latest} available. Run npx @ulysses-ai/create-workspace --upgrade.`
79
+ - `current` → ✓ Template is up to date (v{latest})
80
+ - `unknown` → warning: could not reach the npm registry
81
+ - `skipped: 'uninitialized'` → info: workspace not initialized, freshness check unavailable
120
82
 
121
- Compare the workspace's pinned template version against the latest published on npm.
122
-
123
- Always invoke `refreshIfStale` from the audit (regardless of `workspace.versionCheck.ambient` — the user explicitly ran `/maintenance`):
124
-
125
- ```javascript
126
- import { refreshIfStale } from './.claude/lib/freshness.mjs';
127
- const result = await refreshIfStale({
128
- workspaceRoot: process.cwd(),
129
- ttlMs: 24 * 60 * 60 * 1000,
130
- });
131
- ```
132
-
133
- Report one of:
134
- - `outdated` → `✗ Template v{current} → v{latest} available. Run npx @ulysses-ai/create-workspace --upgrade.`
135
- - `current` → `✓ Template is up to date (v{latest}).`
136
- - `unknown` (with cache) → `⚠ Could not reach npm registry; last cached latest was v{latest} as of {checkedAt}.`
137
- - `unknown` (no cache) → `⚠ Could not reach npm registry; no cached version on file. Try again when online.`
138
- - `skipped: 'uninitialized'` → `⚠ Workspace not initialized; freshness check unavailable.`
83
+ An `outdated` result also rewrites the `local-only-template-freshness.md` banner and the version cache, as this check always has.
139
84
 
140
85
  ## Cleanup
141
86
 
@@ -173,7 +118,7 @@ When stale candidates are found, surface them as warnings in the output format a
173
118
 
174
119
  ### 11. Canonical budget triage
175
120
 
176
- This step runs only when a canonical budget is set (`workspace.canonicalBudgetBytes` holds a number) and the post-regen `--check` from the cleanup regen pass (Flow step 9) still reports `selectionStatus: 'over-budget'`. With the budget off — absent or `null` in workspace.json — `--check` can never report over-budget, so this step is unreachable. Skip it too if the regular regen pass cleared the budget, or if `--check` was already `ok`, `trimmed`, or `stubbed` after that pass.
121
+ This step runs only when a canonical budget is set (`workspace.canonicalBudgetBytes` holds a number) and the post-regen `--check` from the cleanup regen pass (Flow step 4) still reports `selectionStatus: 'over-budget'`. With the budget off — absent or `null` in workspace.json — `--check` can never report over-budget, so this step is unreachable. Skip it too if the regular regen pass cleared the budget, or if `--check` was already `ok`, `trimmed`, or `stubbed` after that pass.
177
122
 
178
123
  The rest of cleanup is suggestion-list-with-confirmation: surface a candidate, ask before applying, move on. Triage is the one meaningfully more interactive surface in `/maintenance`. It runs as a small REPL: present the budget state and a triage menu, take one action, re-run `--check`, present the menu again with the new state. No suggestion is auto-applied; every action is the user's choice.
179
124
 
@@ -231,8 +176,8 @@ Read `workspace.json`. If `workspace.tracker?.type === 'github-issues'` and `wor
231
176
  This is migration guidance for workspaces created before the `forge` field landed — the field is back-compat with a sensible default, so the unset case is not a bug, just an opportunity to make the implicit explicit. If `workspace.forge.type` is set to a value with no adapter at `.claude/scripts/forges/{type}.mjs`, that IS an error and goes in the Issues section.
232
177
 
233
178
  ### 13. Health metrics
234
- - Canonical budget — read from the same `--check` invocation as step 5. When a budget is set, reported as `current / budget` bytes with the selection status (e.g., `full`, `2 reference files trimmed`); over-budget cases are deferred to the cleanup triage flow rather than re-reported here. When off, report the step 5 one-liner: `• Canonical budget: off (alwaysLoadedBudgetBytes covers the total)`.
235
- - Always-loaded context — read from the same `context-footprint.mjs` invocation as audit step 6, reported the same way (`current / budget` bytes); over-budget is already surfaced as a warning there.
179
+ - Canonical budget — read from the audit script's section 5 outcome (the same regenerate-and-compare it already ran). When a budget is set, reported as `current / budget` bytes with the selection status (e.g., `full`, `2 reference files trimmed`); over-budget cases are deferred to the cleanup triage flow rather than re-reported here. When off, report the step 5 one-liner: `• Canonical budget: off (alwaysLoadedBudgetBytes covers the total)`.
180
+ - Always-loaded context — read from the audit script's section 6 outcome, reported the same way (`current / budget` bytes); over-budget is already surfaced as a warning there.
236
181
  - Number of ephemeral files — flag if accumulating without resolution
237
182
  - Session log stats (if `workspace-scratchpad/session-log.jsonl` exists):
238
183
  - Sessions without capture
@@ -272,16 +217,11 @@ OK (6):
272
217
 
273
218
  ## Flow
274
219
 
275
- 1. Scan workspace-context/ recursively — read all `.md` files and their frontmatter
276
- 2. Read CLAUDE.md — extract skill and rule references
277
- 3. Read workspace.json — extract repo manifest
278
- 4. Check `.claude/rules/`, `.claude/skills/`, `.claude/agents/` against references
279
- 5. Check git state (worktrees, branches, remotes)
280
- 6. Run `node .claude/scripts/build-workspace-context.mjs --check --root .` — capture status. Exit `0` = clean (and within budget when one is set), `1` = artifact missing or stale, `2` = artifacts current but canonical body over budget — only possible with a budget set. The `canonical` block in the JSON output drives both the audit budget line and the cleanup triage decision; `"budget": null` means the canonical budget is off.
281
- 7. Run `node .claude/scripts/context-footprint.mjs --root .` — capture the total and the `BUDGET` line. Exit `0` = within budget or no budget set; exit `1` = over budget, reported as a warning with the top contributors (audit step 6).
282
- 8. Read session-log.jsonl if it exists
283
- 9. If cleanup mode: regenerate the workspace-context auto-files if stale (index.md, canonical.md, per-user team-member indexes); compare files pairwise for overlap; scan for stale cross-references. If post-regen `--check` reports `over-budget`, enter the canonical-budget triage flow described in cleanup step 11.
284
- 10. Compile and present findings grouped by severity
220
+ 1. Run `node .claude/scripts/maintenance-audit.mjs --root .` and present its report — it carries audit sections 1–7. Add `--offline` when there is no network (section 7 is the only network user), or `--json` when step 13's health metrics want the machine-readable `summary.canonical` / `summary.alwaysLoaded` numbers.
221
+ 2. Perform the residual checks the script does not carry — the worktree-level git checks from audit section 4 (orphaned worktrees, unpushed branches, merged worktrees, prunable worktree records, the task-model checks against `chat-record.mjs --list`).
222
+ 3. Read session-log.jsonl if it exists (feeds step 13's session log stats)
223
+ 4. If cleanup mode: run `node .claude/scripts/build-workspace-context.mjs --check --root .` — exit `0` = clean (and within budget when one is set), `1` = artifact missing or stale → regenerate with `--write`, `2` = artifacts current but canonical body over budget (only possible with a budget set). The `canonical` block in the JSON drives the triage decision; `"budget": null` means the canonical budget is off. Then compare context files pairwise for overlap and scan for stale cross-references; if the post-regen `--check` reports `over-budget`, enter the canonical-budget triage flow described in cleanup step 11.
224
+ 5. Compile and present findings grouped by severity (Output Format above): the script's findings plus the residual checks, with cleanup suggestions from steps 3–4 folded in.
285
225
 
286
226
  ## Notes
287
227
  - Audit mode is always read-only — never modifies files
@@ -17,16 +17,21 @@ Drain a workspace's accumulated session entries and switch new work to the task
17
17
  node .claude/scripts/migrate-sessions.mjs --inventory
18
18
  ```
19
19
 
20
- Read-only. Present the stderr table plus each session's proposal with its reasons and warnings. Say plainly that the proposals are proposals — evidence and a starting point, not decisions. Pay particular attention to the per-remote state shown per worktree (`same`, `ahead +N`, `behind -N`, `diverged +N/-M`, `not-fetched`, `unknown`) and to `unbacked` warnings: they change what Finish and Archive mean for that session. Entries shown as `foreign` (symlinked) are never acted on — surface them for manual reconciliation.
20
+ Read-only. Present the stderr table plus each session's proposal with its reasons and warnings. Say plainly that the proposals are proposals — evidence and a starting point, not decisions. Pay particular attention to the per-remote state shown per worktree (`same`, `ahead +N`, `behind -N`, `diverged +N/-M`, `not-fetched`, `unknown`) and to `unbacked` warnings: they change what Finish and Archive mean for that session. Each worktree also lists every configured remote with its exact URL — read those before any backup decision: `origin:none` means only that the remote holds no copy of this branch, never that the repo has no remote, and an `origin` that is really a third-party upstream shows its URL right there. Entries shown as `foreign` (symlinked) are never acted on — surface them for manual reconciliation.
21
21
 
22
22
  ## 2. Decide per session, with the operator — one at a time
23
23
 
24
24
  For each session, lay out its evidence and ask the operator which way to go. Never infer the decision from the proposal. The options:
25
25
 
26
26
  - **Finish** (typical for MERGEABLE) — resume the session with `/start-work`, then run `/complete-work`; its own merge confirmation applies there. But if the inventory shows a **diverged** remote for that session, say so *before* the operator chooses Finish: `/complete-work`'s plain push will be rejected, and pushing the rewritten history needs `--force-with-lease` — which you run only on the operator's explicit yes naming the branch. Never force silently.
27
- - **Archive** (typical for ABANDONED, a broken shell, or a MERGEABLE the operator gives up on) — take it out of the active lifecycle without destroying anything. Two steps, each its own decision:
28
- 1. **Offer a backup.** Archiving keeps everything on this machine; a backup adds an off-machine copy of the session's commits, and it is what makes a later deletion safe. It creates `drain/{session}/…` tags and pushes them to the resolved remote(s) — tags may land in a public repository, so show the plan first: `node .claude/scripts/migrate-sessions.mjs --backup --session {name} --dry-run` (add `--remote <name>` to aim somewhere other than the resolved default). It lists, per tip, the tag, the remote, and which tips a remote branch or tag already holds exactly, with no side effects. On the operator's yes, run it without `--dry-run` and show the tags it created. Declining is fine — the archive still keeps everything locally. A repo with no remote at all is refused by backup; say so.
29
- 2. **Archive after an explicit yes naming the session:** `node .claude/scripts/migrate-sessions.mjs --archive --session {name}`. The whole session folder moves to `{sessions}/.archived/{name}--{timestamp}/` and git's worktree links are repaired to follow it — every commit, uncommitted edit, untracked or ignored file, and embedded repository comes along. If the move or the repair fails, the session is put back and the result says whether every link was verified. The session's branches stay checked out in the archived worktrees, so a new task cannot reuse those branch names until the archive is deleted. The archive refuses, touching nothing, when a directory in the folder cannot be read, when the folder holds a worktree of a repository outside this workspace, or when it holds a submodule checkout (its link cannot be repaired) — surface the reason; for a submodule the options are Finish or Keep. Relay any `warnings` (relative symlinks that pointed outside the session no longer resolve after the move).
27
+ - **Archive** (typical for ABANDONED, a broken shell, or a MERGEABLE the operator gives up on) — take it out of the active lifecycle without destroying anything. Three steps, in this order, each its own decision:
28
+ 1. **Clear uncommitted work.** `--archive` refuses when any of the session's worktrees has uncommitted or untracked changes — an edited `session.md` counts — and names them, because edits buried uncommitted in an archive are invisible to every later merge or PR. Offer the operator: commit them to the session branch first (`git -C {worktree} add -A`, then `git -C {worktree} commit -m "…"` — per dirty worktree), discard them explicitly (`git -C {worktree} restore …` / `git -C {worktree} clean …`), or, on an explicit yes, re-run with `--allow-uncommitted` to archive them mid-edit. Do this before the backup: the backup tags committed tips only, so committing first brings those edits under the backup, while anything archived with `--allow-uncommitted` is NOT in it.
29
+ 2. **Offer a backup.** Archiving keeps everything on this machine; a backup adds an off-machine copy of the session's commits, and it is what makes a later deletion safe. It covers the committed tips as they stand after step 1. Plain `--backup` creates `drain/{session}/…` tags locally and pushes nothing — for a repo whose only remote is one the operator does not own, that local tag IS the backup. Pushing is a separate, explicitly allowed step:
30
+ ```bash
31
+ node .claude/scripts/migrate-sessions.mjs --backup --session {name} --remote
32
+ ```
33
+ With no allow flag this pushes nothing and exits non-zero, listing per repo the tag and the exact URL(s) it would push to. Approve against the push URL, not the fetch URL: a remote whose push URL differs from its fetch URL shows both, and the script refuses to push there on `--remote-allow-all` — only an explicit `--remote-allow {repo}={remote}` naming it proceeds. Walk the operator through every URL and ask per repo. **Never push backup tags to a remote the operator does not own — a third-party upstream, a read-only mirror, an unfamiliar push URL; pushing `drain/*` tags there publishes the session's commits somewhere foreign.** On yes for repos they do own, re-run adding `--remote-allow {repo}={remote}` per repo (`.` is the workspace repo; `--remote-allow-all` only when every listed URL is their own) and show what was pushed. Declining is fine — the archive still keeps everything locally.
34
+ 3. **Archive after an explicit yes naming the session:** `node .claude/scripts/migrate-sessions.mjs --archive --session {name}`. The whole session folder moves to `{sessions}/.archived/{name}--{timestamp}/` and git's worktree links are repaired to follow it — every commit, uncommitted edit, untracked or ignored file, and embedded repository comes along. If the move or the repair fails, the session is put back and the result says whether every link was verified. The session's branches stay checked out in the archived worktrees, so a new task cannot reuse those branch names until the archive is deleted. The archive refuses, touching nothing, when a directory in the folder cannot be read, when the folder holds a worktree of a repository outside this workspace, or when it holds a submodule checkout (its link cannot be repaired) — surface the reason; for a submodule the options are Finish or Keep. Relay any `warnings` (relative symlinks that pointed outside the session no longer resolve after the move).
30
35
  - **Keep** (typical for ACTIVE, and the only sane answer for UNKNOWN) — leave it; it completes later under the session lifecycle.
31
36
 
32
37
  Unbacked commits (present on no remote) are safe in an archive — they are only ever at risk when someone deletes one. Say so when you archive such a session, and offer the backup.
@@ -43,7 +48,14 @@ The switch procedure:
43
48
  ```bash
44
49
  node .claude/scripts/migrate-sessions.mjs --enable-task-model --root .claude/worktrees/chore-enable-task-model
45
50
  ```
46
- 3. Commit there, open a PR through the workspace's normal flow, and pull the launcher after merge. The launcher root never commits to its default branch.
51
+ 3. Land the change. With a forge-hosted remote, commit there, open a PR through the workspace's normal flow, and pull the launcher after merge. Without one (`git -C . remote -v` shows no remote this workspace can open PRs against), land it locally — commit in the worktree, fast-forward the launcher's default branch, remove the worktree:
52
+ ```bash
53
+ git -C .claude/worktrees/chore-enable-task-model add workspace.json
54
+ git -C .claude/worktrees/chore-enable-task-model commit -m "chore: switch to the task lifecycle"
55
+ git -C . merge --ff-only chore/enable-task-model
56
+ node .claude/scripts/task-worktree.mjs --root . --remove --repo . --branch chore/enable-task-model --delete-branch
57
+ ```
58
+ Either way the launcher root never commits to its default branch directly. A workspace with neither a remote nor a tracker can use the task model's local mode (gh:173); until that ships, recommend such workspaces stay on sessions.
47
59
 
48
60
  The switch output reports `remainingSessions: null` when run from the worktree — the real remaining-sessions list comes from a separate `--inventory` at the launcher root. Remaining sessions are fine either way: they keep resuming and completing under the session lifecycle after the switch.
49
61
 
@@ -19,7 +19,7 @@ Begin or resume a persistent work session. Each session lives in its own `work-s
19
19
 
20
20
  New work as a task: one tracker issue, one branch, one worktree per repo the work touches. This flow creates no `work-sessions/` folder, no `session.md`, and seeds no task list — the issue, the branch, and the chat record are the entire state. The chat stays at the workspace root — `{launcher-root}`, the absolute path on the `Workspace root:` line the SessionStart hook injects (at /start-work time you are normally already there); the worktrees are reached by path.
21
21
 
22
- If `workspace.tracker` is absent, say tracking is off and skip step 1 — but still ask for the type (`bug` / `feat` / `chore`) and a one-line description, because the type picks the branch prefix — then continue with steps 2–6. Tell the user plainly what that costs: without a tracker there is no `workItem`, the task is not recorded on the chat record, and `/complete-work` cannot find it from the launcher. It is completed either by running `/complete-work` from inside the worktree (cwd detection) or by opening the PR by hand.
22
+ If `workspace.tracker` is absent, say tracking is off and skip step 1 — but still ask for the type (`bug` / `feat` / `chore`) and a one-line description, because the type picks the branch prefix — then continue with steps 2–6. What that costs: without a tracker there is no `workItem` and no issue to close at completion — the task is still recorded on the chat record (with no work item, keyed by repo + branch), so `/complete-work` finds it from the launcher like any other task.
23
23
 
24
24
  1. **Identify or create the tracker issue and claim it.** If the invocation's arguments already name an issue — `gh:N`, `#N`, or an issue URL — normalize it to the adapter's id (`#42` and a `.../issues/42` URL both mean `gh:42`), fetch it with `tracker.getIssue(id)`, claim it when it is not yet assigned to you (with the same `ALREADY_ASSIGNED` handling as the fallback pick below), and skip the candidate list entirely. Otherwise, list the candidates — the same adapter calls as Flow: Blank steps 3–6:
25
25
 
@@ -54,13 +54,13 @@ If `workspace.tracker` is absent, say tracking is off and skip step 1 — but st
54
54
  ```bash
55
55
  node .claude/scripts/task-worktree.mjs --root . --create --repo "{repo}" --branch "{branch}"
56
56
  ```
57
- The script fetches origin best-effort (offline is fine) before choosing the base. A project repo's worktree lands at `repos/{repo}/.claude/worktrees/{slug}/` — Claude Code's native worktree location — based on `origin/{defaultBranch}` when that ref exists, and never tracking it. For `.` the worktree lands at `.claude/worktrees/{slug}/` — the same native location, one level up — based on the workspace origin's HEAD (falling back to `main`); the workspace's own `.gitignore` already covers the path.
57
+ The script fetches origin best-effort (offline is fine) before choosing the base. A project repo's worktree lands at `repos/{repo}/.claude/worktrees/{slug}/` — Claude Code's native worktree location — based on `origin/{defaultBranch}` when that ref exists and the local `{defaultBranch}` otherwise — a local-mode repo (`merge: "local"`) bases on the local `{defaultBranch}` itself, since its merges land there and its origin ref never advances — and never tracking it. For `.` the worktree lands at `.claude/worktrees/{slug}/` — the same native location, one level up — based on the workspace origin's HEAD (falling back to `main`); the workspace's own `.gitignore` already covers the path. A repo without a forge remote — no origin at all, or `merge: "local"` in `workspace.json` — runs the task in local mode: nothing is pushed for it, and `/complete-work` merges it into its source clone instead.
58
58
 
59
- 5. **Record the task on this chat's record** (only when a `workItem` exists — see the no-tracker note above):
59
+ 5. **Record the task on this chat's record:**
60
60
  ```bash
61
61
  node .claude/scripts/chat-record.mjs --root . --add-task --chat "{chat}" --work-item "{workItem}" --branch "{branch}" --repo "{repo}"
62
62
  ```
63
- `{chat}` is the name from the `Chat record:` line the SessionStart hook injected into this conversation. If there is no such line, run `node .claude/scripts/chat-record.mjs --whoami --root .` first — compaction can drop the hook line, and this recovers the name by matching the chat's session id. When that too prints nothing, say so and skip recording rather than guessing a name.
63
+ Omit `--work-item` when the task has none — the entry is recorded with a null work item, keyed by repo + branch. `{chat}` is the name from the `Chat record:` line the SessionStart hook injected into this conversation. If there is no such line, run `node .claude/scripts/chat-record.mjs --whoami --root .` first — compaction can drop the hook line, and this recovers the name by matching the chat's session id. When that too prints nothing, say so and skip recording rather than guessing a name.
64
64
 
65
65
  6. **Tell the user where the work happens:** the worktree path(s) above — edits belong there, not in the source clones at `repos/{repo}/`. Work continues from this chat by path. A chat started inside a **project** worktree would not load the workspace's conventions or hooks (a worktree is a context boundary), so staying here is the default. A `.` worktree does load a copy of the workspace's `CLAUDE.md`/`.claude/` — but with the worktree as root, so its chat records land in the worktree's own scratchpad rather than the launcher's; the task still belongs to this chat.
66
66
 
@@ -26,11 +26,11 @@ If `workspace.json` has `"initialized": true` and no `.workspace-update/` payloa
26
26
 
27
27
  ## Branching
28
28
 
29
- Workspace-init creates a branch for all its work:
29
+ Workspace-init creates a branch for all its work. Record the default branch first (`git branch --show-current` before switching — usually `main`), then:
30
30
  ```bash
31
31
  git checkout -b chore/workspace-init
32
32
  ```
33
- All commits go on this branch. After completion, the user reviews and squash-merges to main.
33
+ All commits go on this branch. Step 18 merges the branch back into the default branch at the end — init must finish with every commit on the default branch, never stranded on the init branch (an unmerged init branch leaves `workspace.json` without `initialized: true` on the default branch, which blocks later `/workspace-update` runs). The granular per-step history stays on `chore/workspace-init` for review.
34
34
 
35
35
  ## Flow
36
36
 
@@ -373,9 +373,9 @@ git remote -v
373
373
  - Detect the org from project repo remotes in workspace.json
374
374
  - Ask: "Create workspace repo as `{org}/workspace-{project}`? Or provide a different name/URL."
375
375
  - Create via `gh repo create {org}/{name} --private` and add as remote
376
- - Do NOT push yet — user merges the branch first
376
+ - Do NOT push yet — Step 18 merges the init branch and pushes the default branch after the merge
377
377
 
378
- ### Step 18: Mark initialized and report
378
+ ### Step 18: Mark initialized, merge to the default branch, report
379
379
 
380
380
  Update workspace.json:
381
381
  - Set `initialized: true`
@@ -383,12 +383,20 @@ Update workspace.json:
383
383
 
384
384
  **Commit:** `git commit -m "chore: mark workspace as initialized"`
385
385
 
386
+ **Merge to the default branch.** Init is not finished while its commits live only on `chore/workspace-init` — an unmerged init branch leaves the default branch without `initialized: true`, which blocks later `/workspace-update` runs. Ask: "Merge chore/workspace-init into {default-branch} now? [Y/n]" and on yes:
387
+ ```bash
388
+ git checkout {default-branch}
389
+ git merge --squash chore/workspace-init
390
+ git commit -m "chore: workspace initialization"
391
+ ```
392
+ If a remote is configured, push the default branch (`git push origin {default-branch}`; use `--force-with-lease` only if the operator explicitly accepts rewritten history after a Step 17 rebase). Keep `chore/workspace-init` — it carries the granular per-step history — unless the user asks for it to be deleted. If the user declines the merge, the final report must tell them exactly how to finish it themselves.
393
+
386
394
  **Final report:**
387
395
 
388
396
  ```
389
397
  "Workspace initialized. Restart Claude Code for all rules and hooks to take effect. Then run /start-work to begin.
390
398
 
391
- Branch: chore/workspace-init
399
+ Branch: chore/workspace-init (merged to {default-branch} as "chore: workspace initialization")
392
400
 
393
401
  Summary:
394
402
  - {N} repos cloned
@@ -402,6 +410,7 @@ Summary:
402
410
  - {V} self-contradictions found and fixed
403
411
  - Template version: {version}
404
412
  - Remote: {status}
413
+ - All init commits are on {default-branch}
405
414
 
406
415
  Issues encountered:
407
416
  - {list every expected behavior that failed}
@@ -414,15 +423,12 @@ Active work sessions (formalized from existing worktrees):
414
423
  Items in workspace-scratchpad/unmigrated/:
415
424
  - {list each item with a one-line description}
416
425
 
417
- Review the branch:
418
- git log --oneline chore/workspace-init
419
- git diff main..chore/workspace-init
420
-
421
- Then merge:
422
- git checkout main
423
- git merge --squash chore/workspace-init
424
- git commit -m 'chore: workspace initialization'
425
- git push origin main
426
+ If the merge was declined, replace the branch line with:
427
+ Not merged yet — finish with:
428
+ git checkout {default-branch}
429
+ git merge --squash chore/workspace-init
430
+ git commit -m 'chore: workspace initialization'
431
+ git push origin {default-branch}
426
432
 
427
433
  This session is done. Start a fresh Claude Code session and run /start-work to begin."
428
434
  ```