@skitterbyte/skitterspec-jira 2.18.1 → 3.0.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.
package/MIGRATION.md CHANGED
@@ -1,5 +1,131 @@
1
1
  # Migration guide
2
2
 
3
+ ## Providers drop the `skitterspec` bin: install the base alongside (action required)
4
+
5
+ Every provider used to answer to two names: its own (`skitterspec-github`)
6
+ and `skitterspec`. That alias kept a machine to **one** global provider, because
7
+ npm refuses a second package claiming a bin another already owns:
8
+
9
+ ```
10
+ npm error File exists: /usr/local/bin/skitterspec
11
+ npm error Remove the existing file and try again, or run npm
12
+ npm error with --force to overwrite files recklessly.
13
+ ```
14
+
15
+ Now `skitterspec` belongs to the base package, `@skitterbyte/skitterspec`, and
16
+ each provider exposes only its own name. The skills and commands still run
17
+ `skitterspec …`, so
18
+ **the base is installed alongside your provider, and the two are updated together**.
19
+ In exchange, every provider can be installed globally on one
20
+ machine, and `skitterspec update --all` updates every local install in one go.
21
+
22
+ `update` warns when it cannot find `skitterspec` beside a provider. The two
23
+ packages number their versions separately (the base is v23, GitHub v3), so
24
+ they never match by number. Install the latest of each at the same time.
25
+
26
+ Find your install below. You can check what you have with:
27
+
28
+ ```bash
29
+ npm ls -g --depth=0 | grep skitterbyte # global installs
30
+ grep skitterbyte package.json # a project dependency
31
+ ```
32
+
33
+ ### A global provider (the usual setup for `init --local`)
34
+
35
+ Upgrade the provider and install the base **in the same command**. The upgrade
36
+ removes the old `skitterspec` link, so the base can take it. List every
37
+ provider you use:
38
+
39
+ ```bash
40
+ npm i -g @skitterbyte/skitterspec@latest @skitterbyte/skitterspec-github@latest @skitterbyte/skitterspec-azure-boards@latest
41
+ skitterspec update --all
42
+ ```
43
+
44
+ Then check that both names answer:
45
+
46
+ ```bash
47
+ skitterspec --version
48
+ skitterspec-github --version
49
+ ```
50
+
51
+ **If you installed the base on its own first** and got the `File exists` error
52
+ above, the old provider still owns the name. Upgrade the provider
53
+ (`npm i -g @skitterbyte/skitterspec-<provider>@latest`), then install the base
54
+ again. Don't use `--force`: it overwrites the link and leaves the old
55
+ provider's files in place.
56
+
57
+ ### A solo project with a committed install or a `package.json` dependency
58
+
59
+ Move it to a local install with a global CLI, so that later releases never
60
+ touch a tracked file there:
61
+
62
+ 1. Do the global install above on this machine.
63
+ 2. In the project, start a branch (`/no-spec skitterspec-local`), because the
64
+ next steps change tracked files.
65
+ 3. `skitterspec init --local`. This stages the managed files for removal from
66
+ git, moves the hooks into `.claude/settings.local.json`, and moves the
67
+ CLAUDE block into `CLAUDE.local.md`. The files stay on disk.
68
+ 4. Remove the dependency, which updates `package.json` and the lockfile:
69
+ `npm uninstall @skitterbyte/skitterspec-<provider>` (or `pnpm remove …`).
70
+ 5. `skitterspec update`. The commands are rewritten to call `skitterspec`
71
+ from your PATH.
72
+ 6. Commit the staged removals together with `package.json` and the lockfile
73
+ (`/commit`), review the page and land.
74
+
75
+ From then on, `skitterspec update --all` covers this project.
76
+
77
+ ### A team project with a `package.json` dependency
78
+
79
+ The dependency stays, because that is how everyone runs one version. Add the
80
+ base beside it, taking the latest of both together:
81
+
82
+ ```bash
83
+ pnpm add -D @skitterbyte/skitterspec@latest @skitterbyte/skitterspec-<provider>@latest
84
+ skitterspec update
85
+ ```
86
+
87
+ Do this on a `/no-spec` branch, since it changes tracked files. On every
88
+ later bump, move the two together:
89
+ `pnpm up @skitterbyte/skitterspec @skitterbyte/skitterspec-<provider>`.
90
+ `update --all` lists a team project and never writes to it.
91
+
92
+ ### A Windows VM
93
+
94
+ Global installs belong to one machine, and the VM has its own. Inside the VM,
95
+ run the same `npm i -g …` line and then `skitterspec update --all`. That reads
96
+ the VM's own Claude Code project list. Where the Mac and the VM share one
97
+ checkout, update both machines at the same time. Otherwise each `update`
98
+ rewrites the other's files.
99
+
100
+ ### After every release, from now on
101
+
102
+ ```bash
103
+ npm i -g @skitterbyte/skitterspec@latest @skitterbyte/skitterspec-<provider>@latest # every provider you use
104
+ skitterspec update --all
105
+ ```
106
+
107
+ Repeat both lines inside the VM.
108
+
109
+ ## `@skitterbyte/skitterspec-github` v2 → v3 (the `skitterspec` bin moves to the base)
110
+
111
+ Install `@skitterbyte/skitterspec` alongside. See
112
+ [Providers drop the `skitterspec` bin](#providers-drop-the-skitterspec-bin-install-the-base-alongside-action-required).
113
+
114
+ ## `@skitterbyte/skitterspec-azure-boards` v2 → v3 (the `skitterspec` bin moves to the base)
115
+
116
+ Install `@skitterbyte/skitterspec` alongside. See
117
+ [Providers drop the `skitterspec` bin](#providers-drop-the-skitterspec-bin-install-the-base-alongside-action-required).
118
+
119
+ ## `@skitterbyte/skitterspec-jira` v2 → v3 (the `skitterspec` bin moves to the base)
120
+
121
+ Install `@skitterbyte/skitterspec` alongside. See
122
+ [Providers drop the `skitterspec` bin](#providers-drop-the-skitterspec-bin-install-the-base-alongside-action-required).
123
+
124
+ ## `@skitterbyte/skitterspec-linear` v19 → v20 (the `skitterspec` bin moves to the base)
125
+
126
+ Install `@skitterbyte/skitterspec` alongside. See
127
+ [Providers drop the `skitterspec` bin](#providers-drop-the-skitterspec-bin-install-the-base-alongside-action-required).
128
+
3
129
  ## A PR-mode finish runs the `afterLand` entries its land matched (nothing to edit)
4
130
 
5
131
  After the host merged a PR, `spec-env integrate` used to print `nothing to
package/README.md CHANGED
@@ -5,8 +5,17 @@ superset of [`@skitterbyte/skitterspec`](https://www.npmjs.com/package/@skitterb
5
5
  the base filesystem workflow plus `/spec-push` · `/spec-status` and the
6
6
  `spec-sync` CLI. The repo is canonical; Jira is a generated mirror.
7
7
 
8
- Install exactly one distribution — this, the base, or
9
- `@skitterbyte/skitterspec-linear` — never two:
8
+ Install this provider **and** the base, `@skitterbyte/skitterspec`, and
9
+ update the two together: the provider carries the sync, and the base answers the
10
+ `skitterspec` command the skills run. Use one provider per project; several
11
+ can be installed globally side by side — see `MIGRATION.md`,
12
+ *Providers drop the `skitterspec` bin*.
13
+
14
+ ```
15
+ npm i -g @skitterbyte/skitterspec @skitterbyte/skitterspec-jira
16
+ ```
17
+
18
+ Then, in the project:
10
19
 
11
20
  ```
12
21
  npx @skitterbyte/skitterspec-jira init
@@ -27,9 +27,10 @@ Two things about Jira Cloud shape everything below:
27
27
 
28
28
  ## 1. Install the package
29
29
 
30
- Install the Jira superset (or, if you already run the base or the Linear
31
- superset, switch — every distribution contains the entire base, so install
32
- exactly one):
30
+ Install the Jira provider, and the base, `@skitterbyte/skitterspec`, beside
31
+ it, updating the two together: the base answers the `skitterspec` command the
32
+ skills run. Every provider contains the whole base engine, so a project uses
33
+ one provider:
33
34
 
34
35
  ```sh
35
36
  npx @skitterbyte/skitterspec-jira init
@@ -18,7 +18,7 @@ and lifecycle stay consistent. Each sets a status on the spec header
18
18
  | `/spec-next` | Build the next phase of the spec this session is in (re-run per phase) | `In Progress` (unchanged) | (unchanged) |
19
19
  | `/spec-reviewed` | Pick up a review approved on the page — offered by its code, claimed on your word | (unchanged) | (unchanged) |
20
20
  | `/spec-epic-next` | Name the epic member that can start now, as the `/spec-start` to type in a new tab — a picker when several can; reads only | (unchanged) | (unchanged) |
21
- | `/spec-resume` | Go back into a spec already in flight, by name or `#N`. It rebuilds the worktree when this machine has none, shows what it is blocked on, and acts on the message given with it. It starts nothing | (unchanged) | (unchanged) |
21
+ | `/spec-resume` | Go back into a spec already in flight, by name or `#N`. It rebuilds the worktree when this machine has none, shows what it is blocked on, and acts on the message given with it. It starts nothing. A completed spec is offered a re-open: a fresh branch from the base, moved back to in-progress | (unchanged), or `In Progress` on a re-open | (unchanged), or `specs/in-progress/` on a re-open |
22
22
  | `/spec-park` | Park a spec in flight on something outside the repo: a `Blocked on:` line on the spec or a phase, committed on its branch. The worktree stays | (unchanged) | (unchanged) |
23
23
  | `/spec-to-main` | Land the branch on the base (rebase + ff) **without** finishing — for running the work in CI / a shared env mid-spec; repeatable | `In Progress` (unchanged) | (unchanged) |
24
24
  | `/spec-complete` | Verify all phases done + tests green; land + tear down | `Complete` | `specs/complete/` |
@@ -583,12 +583,15 @@ tracker-free: it knows nothing about any specific ticketing system. A
583
583
  ticketing provider is installed as its own distribution that plugs into named
584
584
  **seams** in the shared skills and fulfils a skill-name + CLI contract.
585
585
 
586
- Part of that contract is the **binary name**: the shipped `/spec-connect` and
587
- `/spec-live` commands invoke `skitterspec`, so a superset that replaces the base
588
- must expose that name too, alongside whatever it calls itself — one entry point
589
- under two names. A distribution shipping only its own name leaves those commands
590
- failing with `command not found`, which reads as a broken install rather than a
591
- missing alias.
586
+ Part of that contract is the **binary name**. `skitterspec` belongs to the base
587
+ package alone, and a provider exposes only its own name
588
+ (`skitterspec-<provider>`). The shipped commands and skills invoke
589
+ `skitterspec`, so a provider is installed **alongside the base**, globally or
590
+ as two dev dependencies, and the two are updated together. Providers used to alias
591
+ `skitterspec` to their own entry point. That kept a machine to one global
592
+ provider, because npm refuses a second package claiming a bin another already
593
+ owns (feat-global-install). `init` and `update` warn when `skitterspec` cannot
594
+ be found beside a provider.
592
595
  Sync is **one-way**: the repo is the source of truth and the tracker is a
593
596
  **generated mirror**. It ships `/spec-push` (repo→tracker; computes a create/update plan
594
597
  against a committed last-pushed snapshot and applies it) and `/spec-status`
@@ -31,13 +31,140 @@ each spec branch, local then remote-tracking, never fetched. That matters
31
31
  because the base branch reads `backlog` for the whole life of a spec, and under
32
32
  `land.specDocs: "branch"` an in-flight spec may exist only on its branch.
33
33
 
34
- - **`ok: false`.** Relay the `refused` text and stop with `⏸`. It covers a
35
- name or ticket that matches nothing (it never guesses the nearest), a spec in
36
- `backlog` (`Next` is `/spec-start <name>`), one already complete or
37
- cancelled, and one with no branch anywhere to resume from.
34
+ - **`ok: false` with an `offer`.** That is a completed spec, and the offer is
35
+ re-opening it. Relay the `refused` text, **then** put the offer's `label`
36
+ and Cancel to the operator as `.claude/rules/offered-unblocks.md`
37
+ describes: the label verbatim, nothing pre-selected, and no third option.
38
+ On the label, go to **1b**. On Cancel, stop with `⏸` and record nothing.
39
+ - **`ok: false` and no `offer`.** Relay the `refused` text and stop with
40
+ `⏸`. It covers a name or ticket that matches nothing (it never guesses the
41
+ nearest), a spec in `backlog` (`Next` is `/spec-start <name>`), a cancelled
42
+ spec, a completed hotfix or epic, and one with no branch anywhere to resume
43
+ from. **Never offer a re-open the engine did not declare**, however
44
+ obviously one seems to fit.
38
45
  - **`ok: true`.** Carry on. `blockers`, `progress` and `identifier` are read
39
46
  in step 3.
40
47
 
48
+ ## 1b. Re-open a completed spec (only on the offer's pick)
49
+
50
+ Sometimes a spec was completed to get its work onto the base branch, and more
51
+ phases turn out to be needed. Its branch went at teardown, and its work is on
52
+ the base, so re-opening is a fresh branch **at the base as it is now**. This
53
+ step does what `/spec-start` does for that branch, and nothing more.
54
+
55
+ 1. **Ask for the plan.** Run
56
+ `skitterspec spec-env resume <spec> --reopen --json`. A refusal here
57
+ (a worktree still standing, or a leftover branch holding commits the base
58
+ does not have) is relayed and ends `⏸`. It never resets work, and neither
59
+ do you.
60
+ 2. **Provision.** Bring the review server up as step 2 says. Run the plan's
61
+ `commands` in order from the primary checkout. The first creates the
62
+ branch at the base, and the second is `spec-env up`, a planner: run the
63
+ commands it prints, then its `then` line with the `cd` in front, exactly
64
+ as `/spec-start` step 3 does. Confirm with `skitterspec spec-env resolve`
65
+ (no argument) as step 2 below does.
66
+ 3. **Move it back, and say why.** Run the plan's `move` command. Add a dated
67
+ Changelog line, `Re-opened from complete: <reason>`. The reason comes from
68
+ the message, or is **asked once** when there is none.
69
+
70
+ **Who owns this spec's status.** Only when `specs/.core/jira.config.json` exists.
71
+ Run `skitterspec spec-sync ownership --json` once and read both values:
72
+
73
+ - **`workflowState: "pull"`** — Jira is the record of this spec's status, so
74
+ this skill **writes no `> **Status:**` header and appends no State log row**,
75
+ wherever its steps below say to. A spec this skill creates gets neither: its
76
+ header carries `> **Tracker:** <issue url>` instead, filled in once linking
77
+ has stamped the url, and its body has no `## State log` section. Readiness is
78
+ the spec's own content — a `Draft` is a spec whose **Open questions** is not
79
+ empty — so nothing is lost with the header.
80
+ - **`assignee: "pull"`** — Jira holds who is building it, so this skill
81
+ **writes no `> **Developer:**` line** either.
82
+ - **Anything else** — `push`, `none`, sync reported off, or the command failing
83
+ — is cannot-tell, and the steps below run exactly as written.
84
+
85
+ What `pull` leaves alone: the folder move (a bucket records what the repo did to
86
+ the code, not a planning status), the phase files and index, and the Changelog.
87
+ A reason a `Status:` header would have carried — a cancellation's, a knock-back
88
+ to Draft — goes in a dated Changelog line instead. A spec that already carries
89
+ any of these lines keeps them untouched: they are history, and nothing rewrites
90
+ them.
91
+
92
+ - Set the **Status** header: `> **Status:** In Progress — re-opened <YYYY-MM-DD>`.
93
+ - Append a **State log** row: `| <YYYY-MM-DD> | In Progress | in-progress | <git user.name> |`.
94
+
95
+ 4. **Put the ticket back in progress.** The bucket move is the same code fact
96
+ `/spec-start` reports, so it takes the same steps. On a re-open, the board
97
+ reporting the ticket Done or Cancelled is **expected rather than a warning**:
98
+ the push below is what moves it back. Do not relay it.
99
+
100
+ Assignment sync is **not yet supported by the Jira provider**: the issue's
101
+ assignee is never read or written, and there is no `/spec-claim`. The
102
+ `> **Developer:**` header is still set by the base skill's own step — that is
103
+ the repo's record and it needs nothing from the tracker. Nothing to run here.
104
+
105
+ **Only when `specs/.core/jira.config.json` exists** and the spec's overview
106
+ carries a `jira_identifier`. Either missing → **skip**, in one line
107
+ (`not linked to Jira — /spec-push to mirror it`), and carry on. Nothing else in
108
+ this step changes.
109
+
110
+ **Ask the board first.** Run `skitterspec spec-sync board <spec>`. It is silent
111
+ unless Jira already says Done or Cancelled for this issue; when it prints a
112
+ line, relay it once as a warning and **carry on** — you are the one about to hold
113
+ this branch, so the cleanup it names is yours to choose, and nothing here runs it
114
+ or refuses on it.
115
+
116
+ **Refresh the mirror now, without asking.** Run `/spec-push`. The spec has just
117
+ moved to `in-progress/` — a real state change, and the tracker is a generated
118
+ mirror of it. (The developer stamped beside it stays a repo-side record:
119
+ assignment sync is not yet supported by the Jira provider.) It costs one engine
120
+ call and no model tokens when Jira credentials are set (see `apply.transport`
121
+ in `jira.config.md`).
122
+
123
+ - **Never mint.** An unlinked spec is skipped, not created. A spec kept
124
+ deliberately local should stay that way — `/spec-push` is how someone opts in.
125
+ - **Never fatal.** If the push fails — offline, no credentials, a Jira error —
126
+ say so and **finish the operation anyway**. The spec is in flight in the repo
127
+ regardless; the mirror is disposable and the next push repairs it. Do not roll
128
+ the provisioning back, and do not stop to ask.
129
+ - **Say what happened** in the skill's report: mirror updated, skipped as
130
+ unlinked, or failed with the reason.
131
+
132
+ ### Why it sits here
133
+
134
+ Pinned **after the `git mv` and before the commit**, and both halves matter:
135
+
136
+ - **After the move**, because the projection reads a spec's workflow status from
137
+ its folder bucket. Push while the folder is still in `backlog/` and the issue
138
+ is set to the status the spec is *leaving*.
139
+ - **Before the commit**, because the push stamps keys into the spec and writes a
140
+ snapshot under `specs/.core/`. The `git add` that follows sweeps both up with
141
+ the status change; push after it instead and those files are left uncommitted —
142
+ which strands a dirty worktree on the hand-off, and makes `spec-env integrate`
143
+ refuse to land the branch.
144
+
145
+ ### Why this is not the refresh `/spec-next` already runs
146
+
147
+ It was once reasoned that a push here would send the same thing twice, one commit
148
+ apart, because `/spec-next` refreshes the moment it starts. That holds only in
149
+ `checkout` mode, where `/spec-next` follows immediately. In `worktree` mode the
150
+ spec is built elsewhere and the refresh can be hours away or never come — and
151
+ until it does, the issue sits in its old status while the repo reads
152
+ `in-progress`.
153
+
154
+ The two pushes are not duplicates either way. This one carries the issue's
155
+ workflow status; the one `/spec-next` runs carries phase 1 starting. Every other
156
+ lifecycle skill mirrors the state change it makes, and this is the seam that
157
+ stops `/spec-start` being the exception.
158
+
159
+ 5. **Commit it** before anything is built: `skitterspec spec-env stage <spec>`
160
+ and its `owned` paths, pathspec-bounded on both the `add` and the
161
+ `commit`, as `docs(spec): reopen <spec>` with the `Refs:` trailer when
162
+ there is a ticket.
163
+
164
+ Then carry on at **step 3**. Every phase reads `✅`, so step 4's rule for new
165
+ work applies: the message becomes a new phase file plus an index row. With no
166
+ message, **ask what the new phase is** rather than inventing one.
167
+
41
168
  ## 2. Get into its worktree
42
169
 
43
170
  **Only when the project has per-spec isolation** (`specs/.core/env.config.json`).
@@ -140,13 +267,15 @@ Otherwise, end with the block defined in `.claude/rules/spec-reports.md`.
140
267
  stands, or bootstrap failed a step that does not stop the reading.
141
268
  - `❌`: provisioning or the move failed part-way. Name what was left and
142
269
  where.
143
- - `⏸`: the engine refused. Nothing was provisioned and nothing moved.
270
+ - `⏸`: the engine refused, or a re-open offer was answered Cancel. Nothing
271
+ was provisioned and nothing moved.
144
272
 
145
273
  **Fields:** `Tracker` · `Spec` · `Built` · `Notes` · `Worktree` ·
146
274
  `Follow-ups` · `Next`
147
275
 
148
- `Spec` is the bucket and progress (`2 of 4 done, phase 3 in progress`).
149
- `Worktree` is the path, and says **entered** or **provisioned**. `Built` lists
276
+ `Spec` is the bucket and progress (`2 of 4 done, phase 3 in progress`), and
277
+ says **re-opened from complete** after 1b. `Worktree` is the path, and says
278
+ **entered**, **provisioned** or **re-opened**. `Built` lists
150
279
  what the message added to the spec (tasks, a cleared blocker), and is absent
151
280
  when nothing was written. `Notes` carries any blocker still standing, quoted.
152
281
  `Next` is `/spec-next` when the spec is ready to build, or the blocker when one
@@ -47,8 +47,9 @@ async function main(argv) {
47
47
  // A source package HAS a runnable bin and src, but its assets/ is
48
48
  // PRE-composition (seam markers still literal). Installing from it would
49
49
  // write those markers into the user's skills — refuse before any install
50
- // command runs.
51
- if (cmd === 'init' || cmd === 'update') {
50
+ // command runs. `update --all` installs nothing itself — it runs each
51
+ // project's own bin — so it is not asked.
52
+ if (cmd === 'init' || (cmd === 'update' && !rest.includes('--all'))) {
52
53
  require('../src/init.js').assertComposedAssets()
53
54
  }
54
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skitterbyte/skitterspec-jira",
3
- "version": "2.18.1",
3
+ "version": "3.0.0",
4
4
  "description": "Spec-driven development for Claude Code, with one-way Jira Cloud sync — a superset of @skitterbyte/skitterspec: the base filesystem workflow plus /spec-status · /spec-push and the spec-sync CLI. The repo is canonical; Jira is a generated mirror. Install this OR the base OR the Linear superset — exactly one.",
5
5
  "keywords": [
6
6
  "claude",
@@ -15,8 +15,7 @@
15
15
  "author": "Reuben Greaves",
16
16
  "type": "commonjs",
17
17
  "bin": {
18
- "skitterspec-jira": "bin/skitterspec-jira.js",
19
- "skitterspec": "bin/skitterspec-jira.js"
18
+ "skitterspec-jira": "bin/skitterspec-jira.js"
20
19
  },
21
20
  "files": [
22
21
  "bin",
package/src/cli.js CHANGED
@@ -4,7 +4,7 @@ const fs = require('fs')
4
4
  const path = require('path')
5
5
  const os = require('os')
6
6
  const { pathToFileURL } = require('url')
7
- const { execFileSync } = require('child_process')
7
+ const { execFileSync, spawnSync } = require('child_process')
8
8
  const { init, resync, reset, uninstall, disable, enable, checkSync, isExistingSetup, localSeedFiles } = require('./init.js')
9
9
  const {
10
10
  detectReleaseTooling,
@@ -197,7 +197,7 @@ const {
197
197
  const { planPrune, liveSlugsForSpecs, reconcileRegistry } = require('./env/prune.js')
198
198
  const { planIntegrate, planIntegrateCheckout, planIntegratePr, planIntegrateDocs } = require('./env/integrate.js')
199
199
  const { specBranchDocs, preferBranches } = require('./env/specbranches.js')
200
- const { findTarget, planResume, resumeLines, blockingNext } = require('./env/resume.js')
200
+ const { findTarget, planResume, planReopen, resumeLines, reopenLines, blockingNext } = require('./env/resume.js')
201
201
  const { parseRemote, prFor, prPlanCommand, prAbandonCommand, preferRemoteBase } = require('./env/host.js')
202
202
  const { collectDisposition } = require('./env/disposition.js')
203
203
  const { planHandoff } = require('./env/handoff.js')
@@ -286,7 +286,10 @@ Usage:
286
286
  skitterspec update [dir] Resync managed files to the latest, keeping your
287
287
  edits (--force to overwrite). Leaves specs/ + live
288
288
  .core config alone. --check reports what it would
289
- change and writes nothing.
289
+ change and writes nothing. --all updates every
290
+ local install this machine's Claude Code has run
291
+ in, each with its own provider; team installs are
292
+ listed, not written.
290
293
  skitterspec uninstall [dir] Take a local install (init --local) back off this
291
294
  machine: managed files, hooks, the CLAUDE.local.md
292
295
  block, the git excludes. Prints the plan; --yes
@@ -353,6 +356,8 @@ Usage:
353
356
  resume [spec|#N] an in-flight spec: its blockers, and the plan
354
357
  to rebuild its worktree from its branch
355
358
  (prints commands; creates nothing)
359
+ --reopen: a completed spec, re-opened on a
360
+ fresh branch from the base
356
361
  base fetch, list baseBranchPattern matches
357
362
  newest-first, mark the base, and name
358
363
  specs forked from an older match
@@ -486,6 +491,39 @@ function parse(argv) {
486
491
  return { opts, positional }
487
492
  }
488
493
 
494
+ // `update --all`: plan from Claude Code's project list, run each project's own
495
+ // distribution, one line per project. Exit 1 only when an update failed.
496
+ function updateAll() {
497
+ const { planUpdateAll, runUpdateAll } = require('./updateall.js')
498
+ const { readManifest, hasPathInstall } = require('./init.js')
499
+ const git = (dir, args) => {
500
+ try {
501
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
502
+ } catch {
503
+ return null
504
+ }
505
+ }
506
+ const rows = planUpdateAll({
507
+ dirs: knownDirs(defaultRoot()),
508
+ exists: fs.existsSync,
509
+ git,
510
+ readManifest,
511
+ onPath: (bin) => hasPathInstall(process.env, bin),
512
+ })
513
+ if (!rows.length) {
514
+ process.stdout.write("update --all — no skitterspec installs found in Claude Code's project list\n")
515
+ return 0
516
+ }
517
+ process.stdout.write(`update --all — ${rows.length} project${rows.length === 1 ? '' : 's'}\n`)
518
+ // The run is in the project folder with no dir argument, so no path is ever
519
+ // quoted for a shell — cmd.exe needs the shell to start a `.cmd` shim.
520
+ const run = (bin, _args, cwd) =>
521
+ spawnSync(bin, ['update'], { cwd, encoding: 'utf8', shell: process.platform === 'win32' })
522
+ const { lines, failed } = runUpdateAll(rows, run)
523
+ for (const l of lines) process.stdout.write(`${l}\n`)
524
+ return failed ? 1 : 0
525
+ }
526
+
489
527
  // After an `update`, clean up release tooling left by an older skitterspec (it
490
528
  // now lives in @skitterbyte/skittership). Deletes only on an explicit interactive
491
529
  // "yes" or --remove-release-tooling; a non-TTY/--yes run only prints the pointer,
@@ -4613,12 +4651,14 @@ function specEnvResolve(dir, config, specArg, flags = {}) {
4613
4651
  }
4614
4652
 
4615
4653
  /**
4616
- * `skitterspec spec-env resume <name|#N> [--json]` (feat-spec-resume)
4654
+ * `skitterspec spec-env resume <name|#N> [--reopen] [--json]` (feat-spec-resume)
4617
4655
  *
4618
4656
  * Which in-flight spec the argument means, what it is blocked on, and — where
4619
4657
  * this machine has no worktree for it — the commands that rebuild one from its
4620
4658
  * branch. Plans and prints; creates nothing, moves nothing, asks no tracker.
4621
- * A refusal exits 1.
4659
+ * A refusal exits 1. A completed spec's refusal carries an `offer` of
4660
+ * `--reopen` (feat-resume-reopen), which plans a fresh branch at the base and
4661
+ * the move back to in-progress.
4622
4662
  *
4623
4663
  * Every copy of the spec this clone can see is read — the checkout it runs
4624
4664
  * from, each live worktree, and each spec branch (local, then remote-tracking,
@@ -4695,6 +4735,28 @@ function specEnvResume(dir, config, arg, flags = {}) {
4695
4735
  }
4696
4736
  }
4697
4737
  const worktreePath = ownTree(target.folder)
4738
+ if (flags.reopen) {
4739
+ // Merged means an ancestor of the base: `merge-base --is-ancestor` exits 0
4740
+ // for yes and 1 for no, and the reader returns null for any non-zero exit,
4741
+ // so a git error reads as NOT merged, the side that resets nothing.
4742
+ const merged = (ref) => (base ? git(['merge-base', '--is-ancestor', ref, base]) !== null : null)
4743
+ const localBranch = git(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`]) !== null
4744
+ const remoteBranch = git(['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${branch}`]) !== null
4745
+ const rr = planReopen(target, {
4746
+ branch,
4747
+ base,
4748
+ remote,
4749
+ worktreePath,
4750
+ worktreeExists: fs.existsSync(worktreePath),
4751
+ localBranch,
4752
+ localMerged: localBranch ? merged(`refs/heads/${branch}`) : null,
4753
+ remoteBranch,
4754
+ remoteMerged: remoteBranch ? merged(`refs/remotes/${remote}/${branch}`) : null,
4755
+ })
4756
+ if (!rr.ok) process.exitCode = 1
4757
+ process.stdout.write(flags.json ? JSON.stringify(rr, null, 2) + '\n' : reopenLines(rr).join('\n') + '\n')
4758
+ return
4759
+ }
4698
4760
  const r = planResume(target, {
4699
4761
  branch,
4700
4762
  worktreePath,
@@ -8188,6 +8250,7 @@ async function specEnv(rest) {
8188
8250
  else if (args[i] === '--assert-primary-clean') flags.assertPrimaryClean = true
8189
8251
  else if (args[i] === '--use-fallback') flags.useFallback = true
8190
8252
  else if (args[i] === '--unpin') flags.unpin = true
8253
+ else if (args[i] === '--reopen') flags.reopen = true
8191
8254
  else positional.push(args[i])
8192
8255
  }
8193
8256
  dir = path.resolve(dir)
@@ -8550,6 +8613,10 @@ async function run(argv) {
8550
8613
  // `update` is a resync — refresh managed files, keep customized ones
8551
8614
  // (--force to overwrite). Leaves specs/ and live .core config alone.
8552
8615
  // `--check` reports what it WOULD change and writes nothing.
8616
+ if (opts.all) {
8617
+ process.exitCode = updateAll()
8618
+ break
8619
+ }
8553
8620
  if (opts.check) {
8554
8621
  checkSync(dir, { claudeMd: opts.claudeMd })
8555
8622
  break
package/src/env/resume.js CHANGED
@@ -177,8 +177,18 @@ function planResume(target, env) {
177
177
  const how =
178
178
  target.bucket === 'backlog'
179
179
  ? ' — it was never started; /spec-start puts it in flight'
180
- : ' — there is nothing left to resume'
181
- return { ok: false, ...base, refused: `${target.folder} is in ${target.bucket}${how}` }
180
+ : reopenable(target)
181
+ ? ' — re-opening it forks a fresh branch from the base branch as it is now'
182
+ : ' — there is nothing left to resume'
183
+ const r = { ok: false, ...base, refused: `${target.folder} is in ${target.bucket}${how}` }
184
+ if (reopenable(target)) {
185
+ r.offer = {
186
+ kind: 'satisfy',
187
+ label: `Re-open ${target.folder}`,
188
+ command: `skitterspec spec-env resume ${target.folder} --reopen`,
189
+ }
190
+ }
191
+ return r
182
192
  }
183
193
  if (env.worktreeExists) return { ok: true, ...base, commands: [], then: [] }
184
194
 
@@ -204,6 +214,95 @@ function planResume(target, env) {
204
214
  return { ok: true, ...base, commands, then: [`skitterspec spec-env bootstrap ${target.folder}`] }
205
215
  }
206
216
 
217
+ /**
218
+ * Whether a finished spec may be re-opened (feat-resume-reopen): only from
219
+ * `complete`, and never a hotfix (it lands by tag and cherry-pick, so a
220
+ * re-opened one has no landing path) or an epic (it holds no phases). A
221
+ * cancelled spec's code never landed, so "from the current state" would be a
222
+ * rebuild from the text alone — that is a new spec.
223
+ *
224
+ * The kind is read off the `Type:` header, falling back to the folder prefix
225
+ * for a spec written without one.
226
+ */
227
+ function reopenable(target) {
228
+ if (!target || target.bucket !== 'complete') return false
229
+ const type = (headerValue(target.overview, 'Type') || '').toLowerCase()
230
+ if (type === 'hotfix' || type === 'epic') return false
231
+ return !/^(hotfix|epic)-/.test(target.folder)
232
+ }
233
+
234
+ /**
235
+ * The plan for `spec-env resume <spec> --reopen`, or a refusal with no offer.
236
+ *
237
+ * The spec's branch was deleted when it completed, and its work is on the base
238
+ * branch, so re-opening is a fresh branch AT the base. The branch is created
239
+ * here (`git branch -f`) rather than left to `up`, so `up` takes its attach
240
+ * path: left alone, `up` would carry on from a leftover remote branch instead,
241
+ * which is an older state than the base it landed on.
242
+ *
243
+ * WHAT WOULD FOOL THIS: a leftover branch with commits the base does not hold
244
+ * — a teardown that was declined, or a squash merge, whose commits are never
245
+ * ancestors of the base. `-f` over that branch would destroy them, so an
246
+ * unmerged leftover, local or remote, refuses and names it. An answer the
247
+ * caller could not get (`null`) is read the same way: a branch nobody could
248
+ * prove safe is not reset (`.claude/rules/negative-checks.md` rule 4).
249
+ *
250
+ * @param {object} target the copy `findTarget` chose
251
+ * @param {object} env `{ branch, base, worktreePath, worktreeExists,
252
+ * localBranch, localMerged, remoteBranch, remoteMerged, remote }`
253
+ */
254
+ function planReopen(target, env) {
255
+ const spec = target.folder
256
+ const refuse = (refused) => ({ ok: false, spec, bucket: target.bucket, branch: env.branch, refused })
257
+ if (!reopenable(target)) {
258
+ if (target.bucket !== 'complete') return refuse(`${spec} is in ${target.bucket} — only a completed spec can be re-opened`)
259
+ const epic = /^epic-/.test(spec) || (headerValue(target.overview, 'Type') || '').toLowerCase() === 'epic'
260
+ return refuse(
261
+ epic
262
+ ? `${spec} is a completed epic, which holds no phases`
263
+ : `${spec} is a completed hotfix, which lands by tag and has no branch to re-open`,
264
+ )
265
+ }
266
+ if (!env.base) return refuse(`the base branch cannot be resolved, so there is nothing to fork ${spec} from`)
267
+ if (env.worktreeExists) {
268
+ return refuse(`a worktree for ${spec} still exists at ${env.worktreePath} — tear it down (spec-env down ${spec}) or work there`)
269
+ }
270
+ if (env.localBranch && env.localMerged !== true) {
271
+ return refuse(`${env.branch} still exists with commits not on ${env.base} — land or delete it before re-opening`)
272
+ }
273
+ if (env.remoteBranch && env.remoteMerged !== true) {
274
+ return refuse(
275
+ `${env.remote}/${env.branch} still exists with commits not on ${env.base} — ` +
276
+ `delete it (git push ${env.remote} --delete ${env.branch}) before re-opening`,
277
+ )
278
+ }
279
+ return {
280
+ ok: true,
281
+ spec,
282
+ bucket: target.bucket,
283
+ branch: env.branch,
284
+ base: env.base,
285
+ worktree: { path: env.worktreePath, present: false },
286
+ commands: [`git branch -f ${env.branch} ${env.base}`, `skitterspec spec-env up ${spec}`],
287
+ move: [`git -C ${shellPath(env.worktreePath)} mv specs/complete/${spec} specs/in-progress/${spec}`],
288
+ }
289
+ }
290
+
291
+ /** The text report for `--reopen`. */
292
+ function reopenLines(r) {
293
+ if (!r.ok) return [`spec-env resume --reopen: refused — ${r.refused}`]
294
+ return [
295
+ `spec-env resume --reopen: ${r.spec} (complete → in-progress, on ${r.branch} from ${r.base})`,
296
+ ` worktree: ${r.worktree.path}`,
297
+ '',
298
+ ' to provision, run (then run what `up` prints):',
299
+ ...r.commands.map((c) => ` ${c}`),
300
+ '',
301
+ ' then, move the spec:',
302
+ ...r.move.map((c) => ` ${c}`),
303
+ ]
304
+ }
305
+
207
306
  function blockerLine(b) {
208
307
  const where = b.where === 'spec' ? 'spec' : `phase ${b.where}`
209
308
  return `${where} — ${b.text}${b.until ? ` (until ${b.until})` : ''}`
@@ -221,6 +320,7 @@ function resumeLines(r) {
221
320
  for (const b of r.blockers) lines.push(` blocked: ${blockerLine(b)}${r.blocking && b.where === r.blocking.where ? ' ← holds the next build' : ''}`)
222
321
  if (!r.ok) {
223
322
  lines.push(` refused: ${r.refused}`)
323
+ if (r.offer) lines.push(` offer: ${r.offer.label} — ${r.offer.command}`)
224
324
  return lines
225
325
  }
226
326
  lines.push(` worktree: ${r.worktree.path}${r.worktree.present ? '' : ' (missing — provision below)'}`)
@@ -231,4 +331,17 @@ function resumeLines(r) {
231
331
  return lines
232
332
  }
233
333
 
234
- module.exports = { blockers, blockingNext, parseBlockedOn, findTarget, planResume, resumeLines, blockerLine, frontmatterField, sameRef }
334
+ module.exports = {
335
+ blockers,
336
+ blockingNext,
337
+ parseBlockedOn,
338
+ findTarget,
339
+ planResume,
340
+ planReopen,
341
+ reopenable,
342
+ resumeLines,
343
+ reopenLines,
344
+ blockerLine,
345
+ frontmatterField,
346
+ sameRef,
347
+ }
package/src/init.js CHANGED
@@ -130,19 +130,27 @@ function detectPackageManager(dir) {
130
130
  // name alongside `skitterspec`, and either proves the engine is reachable.
131
131
  const ENGINE_BINS = ['skitterspec', 'skitterspec-linear', 'skitterspec-jira', 'skitterspec-github', 'skitterspec-azure-boards']
132
132
 
133
- function binNames() {
134
- return process.platform === 'win32'
135
- ? ENGINE_BINS.flatMap((n) => [n, `${n}.cmd`, `${n}.exe`])
136
- : ENGINE_BINS
133
+ // `bin` narrows the look to one name. A provider no longer answers to
134
+ // `skitterspec` (feat-global-install), so a line that runs `skitterspec` is
135
+ // only served by the base being installed — any engine name proving "an
136
+ // install" would render a command for a bin that is not there.
137
+ function binNames(bin) {
138
+ const names = bin ? [bin] : ENGINE_BINS
139
+ return process.platform === 'win32' ? names.flatMap((n) => [n, `${n}.cmd`, `${n}.exe`]) : names
140
+ }
141
+
142
+ // The npm package a bin comes from: each distribution's bin carries its name.
143
+ function packageForBin(bin) {
144
+ return ENGINE_BINS.includes(bin) ? `@skitterbyte/${bin}` : distributionPackage()
137
145
  }
138
146
 
139
147
  // Rung 1 — a local install, found by walking up. Bounded at 6 levels, matching
140
148
  // the hooks' own `findEngine`: a git worktree's checkout has its own
141
149
  // `node_modules`, and a monorepo package hoists to the root.
142
- function hasLocalInstall(dir) {
150
+ function hasLocalInstall(dir, bin) {
143
151
  let at = path.resolve(dir)
144
152
  for (let i = 0; i < 6; i++) {
145
- for (const name of binNames()) {
153
+ for (const name of binNames(bin)) {
146
154
  if (fs.existsSync(path.join(at, 'node_modules', '.bin', name))) return true
147
155
  }
148
156
  const up = path.dirname(at)
@@ -165,12 +173,12 @@ const NPX_CACHE_RE = /[\\/]_npx[\\/]/
165
173
  // for it here would bake a bare `skitterspec …` into four COMMITTED files that
166
174
  // stop working the moment init exits. Excluding `_npx` entries is what makes
167
175
  // this rung evidence of an install rather than evidence of the install running.
168
- function hasPathInstall(env = process.env) {
176
+ function hasPathInstall(env = process.env, bin) {
169
177
  const raw = env.PATH || env.Path || ''
170
178
  if (!raw) return false
171
179
  for (const entry of raw.split(path.delimiter)) {
172
180
  if (!entry || NPX_CACHE_RE.test(entry)) continue
173
- for (const name of binNames()) {
181
+ for (const name of binNames(bin)) {
174
182
  if (fs.existsSync(path.join(entry, name))) return true
175
183
  }
176
184
  }
@@ -196,9 +204,9 @@ function hasPathInstall(env = process.env) {
196
204
  * between pristine and updatable as different people run `update`. A lockfile
197
205
  * is committed and answers the same everywhere; PATH is one machine's business.
198
206
  */
199
- function detectRunner(dir, env = process.env) {
200
- if (hasLocalInstall(dir)) return { runner: detectPackageManager(dir), rung: 'local' }
201
- if (hasPathInstall(env)) return { runner: '', rung: 'path' }
207
+ function detectRunner(dir, env = process.env, bin) {
208
+ if (hasLocalInstall(dir, bin)) return { runner: detectPackageManager(dir), rung: 'local' }
209
+ if (hasPathInstall(env, bin)) return { runner: '', rung: 'path' }
202
210
  return { runner: 'npx', rung: 'none' }
203
211
  }
204
212
 
@@ -234,11 +242,14 @@ function distributionPackage() {
234
242
  // `Bash(skitterspec …)` rather than `Bash( skitterspec …)`.
235
243
  const EXEC_RE = /\{\{exec\}\}( ?)([A-Za-z0-9._-]*)/g
236
244
 
245
+ // Each occurrence is detected for ITS bin: a provider skill's
246
+ // `skitterspec-github` and a command's `skitterspec` come from two packages
247
+ // that may be installed in two different places.
237
248
  function renderExec(content, dir, env = process.env) {
238
249
  if (!content.includes('{{exec}}')) return content
239
- const { runner, rung } = detectRunner(dir, env)
240
250
  return content.replace(EXEC_RE, (_m, sp, bin) => {
241
- if (rung === 'none') return bin ? `npx -p ${distributionPackage()} ${bin}` : 'npx'
251
+ const { runner, rung } = detectRunner(dir, env, bin || undefined)
252
+ if (rung === 'none') return bin ? `npx -p ${packageForBin(bin)} ${bin}` : 'npx'
242
253
  const prefix = runner === 'npx' ? 'npx --no-install' : runner
243
254
  if (!prefix) return bin
244
255
  return `${prefix}${sp}${bin}`
@@ -314,7 +325,7 @@ function launcherPrefix(dir) {
314
325
  }
315
326
 
316
327
  function launcherFor(bin, dir) {
317
- const script = LAUNCHER.replace('{{pkg}}', distributionPackage())
328
+ const script = LAUNCHER.replace('{{pkg}}', packageForBin(bin))
318
329
  .replace('{{bin}}', bin)
319
330
  .replace('{{prefix}}', launcherPrefix(dir))
320
331
  return `node -e "${script}" --`
@@ -324,8 +335,10 @@ function launcherFor(bin, dir) {
324
335
  // install and the `npx -p` fallback resolve the same from any directory.
325
336
  function renderCommand(content, dir, env = process.env) {
326
337
  if (!content.includes('{{exec}}')) return content
327
- if (detectRunner(dir, env).rung !== 'local') return renderExec(content, dir, env)
328
- return content.replace(EXEC_RE, (_m, _sp, bin) => (bin ? launcherFor(bin, dir) : 'node'))
338
+ return content.replace(EXEC_RE, (match, _sp, bin) => {
339
+ if (bin && detectRunner(dir, env, bin).rung === 'local') return launcherFor(bin, dir)
340
+ return renderExec(match, dir, env)
341
+ })
329
342
  }
330
343
 
331
344
  // Which managed files carry the token: markdown only. Hooks and JSON templates
@@ -507,12 +520,16 @@ function readManifest(dir) {
507
520
  scope: parsed.scope === 'local' ? 'local' : 'team',
508
521
  // Absent means enabled: only `disable` writes the field.
509
522
  enabled: parsed.enabled !== false,
523
+ // The package that wrote it — what `update --all` runs here. Absent on
524
+ // manifests written before feat-global-install: cannot tell, and the
525
+ // caller infers it rather than this guessing.
526
+ distribution: typeof parsed.distribution === 'string' ? parsed.distribution : null,
510
527
  }
511
528
  }
512
529
  } catch {
513
530
  /* missing or malformed → empty baseline */
514
531
  }
515
- return { version: MANIFEST_VERSION, files: {}, baselined: false, scope: 'team', enabled: true }
532
+ return { version: MANIFEST_VERSION, files: {}, baselined: false, scope: 'team', enabled: true, distribution: null }
516
533
  }
517
534
 
518
535
  function writeManifest(dir, files, { local = false, enabled = true } = {}) {
@@ -520,7 +537,7 @@ function writeManifest(dir, files, { local = false, enabled = true } = {}) {
520
537
  ensureDir(path.dirname(target))
521
538
  const sorted = {}
522
539
  for (const k of Object.keys(files).sort()) sorted[k] = files[k]
523
- const body = local ? { version: MANIFEST_VERSION, scope: 'local', files: sorted } : { version: MANIFEST_VERSION, files: sorted }
540
+ const body = { version: MANIFEST_VERSION, distribution: distributionPackage(), ...(local ? { scope: 'local' } : {}), files: sorted }
524
541
  // Written only when false, so an enabled install's manifest reads exactly as
525
542
  // every manifest written before `disable` existed.
526
543
  if (!enabled) body.enabled = false
@@ -687,11 +704,18 @@ function installCommands(dir, opts) {
687
704
  // real work to do either way — skills, rules, folders — and none of it needs
688
705
  // the CLI reachable later. Silence here is what let a project install cleanly
689
706
  // and hand back four commands that 404 on first use.
690
- if (COMMANDS.length && detectRunner(dir).rung === 'none') {
707
+ //
708
+ // It asks for `skitterspec` BY NAME: a provider no longer answers to it
709
+ // (feat-global-install), so a provider installed alone leaves every command
710
+ // and every skill's `skitterspec …` with nothing behind it — and the fix is
711
+ // the base installed alongside, which the warning names.
712
+ if (COMMANDS.length && detectRunner(dir, process.env, 'skitterspec').rung === 'none') {
713
+ const base = packageForBin('skitterspec')
714
+ const beside = distributionPackage() === base ? '' : ` alongside ${distributionPackage()}`
691
715
  report.warnings.push(
692
716
  `the skitterspec CLI could not be found here, so the ${COMMANDS.length} slash ` +
693
- `command(s) were written to fetch it on every run (\`npx -p ${distributionPackage()}\`) — ` +
694
- `install it (npm i -g ${distributionPackage()}, or add it as a dev ` +
717
+ `command(s) were written to fetch it on every run (\`npx -p ${base}\`) — ` +
718
+ `install ${base}${beside} (npm i -g, or as a dev ` +
695
719
  'dependency) and re-run `skitterspec update` to rewrite them',
696
720
  )
697
721
  }
@@ -2004,6 +2028,8 @@ module.exports = {
2004
2028
  detectPackageManager,
2005
2029
  detectRunner,
2006
2030
  renderCommand,
2031
+ hasPathInstall,
2032
+ packageForBin,
2007
2033
  renderExec,
2008
2034
  distributionPackage,
2009
2035
  localExcludes,
@@ -0,0 +1,152 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `skitterspec update --all` — every local-scope project on this machine,
5
+ * updated by its own distribution (feat-global-install, phase 2).
6
+ *
7
+ * Projects are the folders Claude Code has run sessions in (`knownDirs`, the
8
+ * list `tada` reads), kept only where a skitterspec manifest is found: that file
9
+ * is a positive signal an install was made there, where a folder merely named
10
+ * in a transcript is not. A linked worktree is folded into its primary
11
+ * checkout, because a local install seeds its worktrees from the primary — one
12
+ * update there reaches them all.
13
+ *
14
+ * WHAT WOULD FOOL THIS: a project that never ran a Claude Code session on this
15
+ * machine is not in the list, so it is not updated — and not mentioned either.
16
+ * A transcript root that was cleared forgets projects the same way. Both cost a
17
+ * project left on the old version, which `skitterspec update` there still
18
+ * fixes; neither can update the wrong thing.
19
+ *
20
+ * Every lookup that touches the machine is injected, so the planner is tested
21
+ * against fake folders and a fake transcript root.
22
+ */
23
+
24
+ const fs = require('node:fs')
25
+ const path = require('node:path')
26
+
27
+ const MANIFEST = path.join('specs', '.core', '.skitterspec-manifest.json')
28
+ const PROVIDERS = ['github', 'linear', 'jira', 'azure-boards']
29
+ const BASE = '@skitterbyte/skitterspec'
30
+
31
+ function real(p) {
32
+ try {
33
+ return fs.realpathSync.native(p)
34
+ } catch {
35
+ return path.resolve(p)
36
+ }
37
+ }
38
+
39
+ // The nearest folder at or above `dir` holding a manifest, bounded so a stray
40
+ // manifest far above the project is never reached.
41
+ function projectAt(dir, exists) {
42
+ let at = path.resolve(dir)
43
+ for (let i = 0; i < 6; i++) {
44
+ if (exists(path.join(at, MANIFEST))) return at
45
+ const up = path.dirname(at)
46
+ if (up === at) return null
47
+ at = up
48
+ }
49
+ return null
50
+ }
51
+
52
+ // The same project folder in the primary checkout, when `dir` is inside a
53
+ // linked worktree; else `dir`. A git that cannot answer leaves it unchanged.
54
+ function inPrimary(dir, git) {
55
+ const top = git(dir, ['rev-parse', '--show-toplevel'])
56
+ const common = git(dir, ['rev-parse', '--git-common-dir'])
57
+ if (!top || !common) return dir
58
+ const primary = path.dirname(path.resolve(dir, common))
59
+ if (real(primary) === real(top)) return dir
60
+ const rel = path.relative(real(top), real(dir))
61
+ return rel.startsWith('..') || path.isAbsolute(rel) ? dir : path.join(primary, rel)
62
+ }
63
+
64
+ /**
65
+ * The distribution that owns a project: what its manifest recorded, else the
66
+ * provider whose config is in `specs/.core/`, else the base. Inferred only for
67
+ * manifests written before the field existed.
68
+ */
69
+ function distributionOf(dir, manifest, exists) {
70
+ if (manifest.distribution) return manifest.distribution
71
+ for (const p of PROVIDERS) {
72
+ if (exists(path.join(dir, 'specs', '.core', `${p}.config.json`))) return `${BASE}-${p}`
73
+ }
74
+ return BASE
75
+ }
76
+
77
+ const binOf = (pkg) => pkg.replace(/^@skitterbyte\//, '')
78
+
79
+ /**
80
+ * One row per project: `{ dir, name, scope, distribution, action }`, where
81
+ * action is `update` · `team` · `disabled` · `missing`. Sorted by name so the
82
+ * report reads the same on every run.
83
+ */
84
+ function planUpdateAll({ dirs, exists, git, readManifest, onPath }) {
85
+ const seen = new Map()
86
+ for (const d of dirs) {
87
+ if (!exists(d)) continue
88
+ const found = projectAt(d, exists)
89
+ if (!found) continue
90
+ const dir = inPrimary(found, git)
91
+ if (!exists(path.join(dir, MANIFEST))) continue
92
+ const key = real(dir)
93
+ if (!seen.has(key)) seen.set(key, dir)
94
+ }
95
+ const rows = []
96
+ for (const dir of seen.values()) {
97
+ const manifest = readManifest(dir)
98
+ const distribution = distributionOf(dir, manifest, exists)
99
+ let action = 'update'
100
+ if (manifest.scope !== 'local') action = 'team'
101
+ else if (!manifest.enabled) action = 'disabled'
102
+ else if (!onPath(binOf(distribution))) action = 'missing'
103
+ rows.push({ dir, name: path.basename(dir), scope: manifest.scope, distribution, action })
104
+ }
105
+ return rows.sort((a, b) => a.name.localeCompare(b.name) || a.dir.localeCompare(b.dir))
106
+ }
107
+
108
+ // How many managed files an `update` run wrote, read from its own report: the
109
+ // lines under `created:`, `updated:` and `removed:`.
110
+ function countChanged(stdout) {
111
+ let n = 0
112
+ let counting = false
113
+ for (const line of String(stdout).split(/\r?\n/)) {
114
+ if (/^(created|updated|removed):$/.test(line)) counting = true
115
+ else if (/^\S/.test(line) || line === '') counting = false
116
+ else if (counting && /^ {2}\S/.test(line)) n++
117
+ }
118
+ return n
119
+ }
120
+
121
+ /**
122
+ * Run the plan. `run(bin, args, cwd)` returns `{ status, stdout, stderr }`.
123
+ * Returns `{ lines, failed }`: one line per project, and whether any update
124
+ * failed — listed and skipped projects are not failures.
125
+ */
126
+ function runUpdateAll(rows, run) {
127
+ const lines = []
128
+ let failed = false
129
+ const width = Math.max(0, ...rows.map((r) => r.name.length))
130
+ for (const r of rows) {
131
+ const head = `${r.name.padEnd(width)} ${r.scope.padEnd(5)} · ${binOf(r.distribution).replace(/^skitterspec-?/, '') || 'base'}`
132
+ let outcome
133
+ if (r.action === 'team') outcome = 'listed — team install, update it on a /no-spec branch'
134
+ else if (r.action === 'disabled') outcome = 'skipped — disabled (skitterspec enable turns it on)'
135
+ else if (r.action === 'missing') outcome = `skipped — npm i -g ${r.distribution}`
136
+ else {
137
+ const res = run(binOf(r.distribution), ['update', r.dir], r.dir)
138
+ if (res.status === 0) {
139
+ const n = countChanged(res.stdout)
140
+ outcome = n ? `updated ${n} file${n === 1 ? '' : 's'}` : 'current'
141
+ } else {
142
+ failed = true
143
+ const first = `${res.stderr || ''}\n${res.stdout || ''}`.split(/\r?\n/).find((l) => l.trim()) || `exit ${res.status}`
144
+ outcome = `failed — ${first.trim()}`
145
+ }
146
+ }
147
+ lines.push(` ${head} ${outcome}`)
148
+ }
149
+ return { lines, failed }
150
+ }
151
+
152
+ module.exports = { planUpdateAll, runUpdateAll, countChanged, distributionOf, MANIFEST }