@pharn-dev/pharn 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,268 +28,113 @@ npx @pharn-dev/pharn@latest init
28
28
 
29
29
  ## Contents
30
30
 
31
- - [What is PHARN?](#what-is-pharn)
32
- - [Why use it?](#why-use-it)
33
- - [Quick start](#quick-start)
34
- - [How it works](#how-it-works)
35
- - [What gets installed](#what-gets-installed)
36
- - [After install](#after-install)
37
- - [Day-to-day workflow](#day-to-day-workflow)
38
- - [CLI commands](#cli-commands)
39
- - [Agent skills](#agent-skills)
40
- - [Safety model](#safety-model)
41
- - [Current scope](#current-scope)
42
- - [Documentation](#documentation)
43
- - [Development](#development)
44
- - [Security](#security)
45
- - [License](#license)
31
+ [What is PHARN?](#what-is-pharn) · [Why use it?](#why-use-it) · [Quick start](#quick-start) · [How it works](#how-it-works) · [What gets installed](#what-gets-installed) · [After install](#after-install) · [Day-to-day workflow](#day-to-day-workflow) · [CLI commands](#cli-commands) · [Agent skills](#agent-skills) · [Safety model](#safety-model) · [Current scope](#current-scope) · [Documentation](#documentation) · [Development](#development) · [Security](#security) · [License](#license)
46
32
 
47
33
  ---
48
34
 
49
35
  ## What is PHARN?
50
36
 
51
- PHARN is a repo-local methodology for making AI-assisted development easier to
52
- review, repeat, and maintain. It gives Claude Code a structured path from
53
- feature intent to implementation review:
37
+ PHARN is a repo-local methodology for making AI-assisted development easier to review, repeat, and
38
+ maintain. It gives Claude Code a structured path from feature intent to implementation review:
54
39
 
55
40
  ```text
56
41
  spec -> plan -> grill -> test -> build -> regress -> verify -> ship
57
42
  ```
58
43
 
59
- The npm package, `@pharn-dev/pharn`, is the installer. It does not scaffold your
60
- app. It detects what kind of project you already have, installs the matching
61
- PHARN capabilities from [`pharn-dev/pharn-oss`](https://github.com/pharn-dev/pharn-oss),
62
- and records the install in `pharn.config.json` and `pharn.records.json`.
44
+ The npm package, `@pharn-dev/pharn`, is the installer. It does not scaffold your app. It detects what kind
45
+ of project you already have, installs the matching PHARN capabilities from
46
+ [`pharn-dev/pharn-oss`](https://github.com/pharn-dev/pharn-oss), and records the install in
47
+ `pharn.config.json` and `pharn.records.json`.
63
48
 
64
49
  ## Why use it?
65
50
 
66
- AI agents can move fast, but a fast diff without durable context is hard to
67
- trust. PHARN is built around a simple idea: the reasoning behind a change should
68
- be committed beside the change.
69
-
70
- - **Preserve intent.** Specs, plans, constraints, and review notes live in the
71
- repository, not only in an agent transcript.
72
- - **Make work inspectable.** PHARN installs grillers and lenses: pipeline
73
- checks and review perspectives that help interrogate a plan or diff before
74
- it ships.
75
- - **Keep updates safe.** `pharn update` uses per-file hashes to avoid
76
- overwriting local edits unless you explicitly choose `--force`.
77
- - **Stay tool-shaped, not service-shaped.** The CLI fetches open content,
78
- copies files into your project, and leaves the state in version-controlled
79
- markdown and JSON.
51
+ AI agents can move fast, but a fast diff without durable context is hard to trust. PHARN is built around a
52
+ simple idea: the reasoning behind a change should be committed beside the change.
80
53
 
81
- ## Quick start
82
-
83
- Run PHARN inside an existing git project:
54
+ - **Preserve intent.** Specs, plans, constraints, and review notes live in the repository, not only in an
55
+ agent transcript.
56
+ - **Make work inspectable.** PHARN installs grillers and lenses: pipeline checks and review perspectives
57
+ that help interrogate a plan or diff before it ships.
58
+ - **Keep updates safe.** `pharn update` uses per-file hashes to avoid overwriting local edits unless you
59
+ explicitly choose `--force`.
60
+ - **Stay tool-shaped, not service-shaped.** The CLI fetches open content, copies files into your project,
61
+ and leaves the state in version-controlled markdown and JSON.
84
62
 
85
- ```bash
86
- npx @pharn-dev/pharn@latest init
87
- ```
63
+ ## Quick start
88
64
 
89
- For a new app, initialize git before installing PHARN:
65
+ Run PHARN inside an existing git project. For a new app, make sure it is a git repository first
66
+ (`create-next-app` already runs `git init` and commits, unless git is missing or you pass `--disable-git`):
90
67
 
91
68
  ```bash
92
- npx create-next-app@latest my-app
93
- cd my-app
94
- git init
95
- git add -A
96
- git commit -m "init"
69
+ npx create-next-app@latest my-app && cd my-app
70
+ [ -d .git ] || { git init && git add -A && git commit -m "init"; }
97
71
  npx @pharn-dev/pharn@latest init
98
72
  ```
99
73
 
100
- After install, open Claude Code in the project and start with:
101
-
102
- ```text
103
- /pharn-spec
104
- ```
105
-
106
- Or run the whole chain in one command:
107
-
108
- ```text
109
- /pharn-loop implement password reset with a one-time token
110
- ```
74
+ Then open Claude Code and start with `/pharn-spec`, or run the whole chain with
75
+ `/pharn-loop implement password reset with a one-time token`. Either way the run begins at the spec:
76
+ `/pharn-plan` halts unless an **Approved**, un-drifted `SPEC.md` exists ([walkthrough](docs/getting-started.md)).
111
77
 
112
- Either way the run begins at the spec, and it has to: `/pharn-plan` enforces a
113
- deterministic input gate and halts unless an **Approved**, un-drifted `SPEC.md`
114
- already exists, so there is no entry point further down the chain. The exact
115
- command files come from the `pharn-dev/pharn-oss` version installed into your
116
- repo.
117
-
118
- **Your project needs a test runner with per-test results.** The `test` stage
119
- writes each acceptance criterion's test before any code exists and requires it
120
- to fail, so it needs a `test` script (plus `test:e2e` or `e2e` for end-to-end
121
- criteria) whose reporter writes per-test JSON, named under `testResults` in
122
- `pharn.config.json`. Without one, `/pharn-test` stops and asks, and
123
- `/pharn-loop` ends with `blocked: no-test-runner`. A fresh app like the
124
- `create-next-app` one above has no `test` script, so set the runner up first,
125
- as its own increment (a SPEC with `spec_kind: test-infra`). Setup is in
126
- upstream's
78
+ **Your project needs a test runner with per-test results.** The `test` stage writes each acceptance
79
+ criterion's test before any code exists and requires it to fail, so it needs a `test` script (plus
80
+ `test:e2e` or `e2e` for end-to-end criteria) whose reporter writes per-test JSON, named under
81
+ `testResults` in `pharn.config.json`. Without one, `/pharn-test` stops and asks, and `/pharn-loop` ends
82
+ with `blocked: no-test-runner`. A fresh `create-next-app` has no `test` script, so set the runner up
83
+ first, as its own increment (a SPEC with `spec_kind: test-infra`); see upstream's
127
84
  [Per-test results](https://github.com/pharn-dev/pharn-oss#per-test-results).
128
85
 
129
86
  ## How it works
130
87
 
131
- `pharn init` is archetype-driven. There is no stack questionnaire and no module
132
- catalog.
88
+ `pharn init` is archetype-driven. There is no stack questionnaire and no module catalog.
133
89
 
134
- | Step | What happens |
135
- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
- | Detect | Reads `package.json` dependency names and performs a bounded, symlink-safe file-tree scan to classify the project as `ssr`, `backend`, `spa`, `lib`, or a combination. |
137
- | Fetch | Resolves the newest **verified release** of `pharn-dev/pharn-oss` (a tag pharn-oss creates only after its post-merge CI passed) to its commit, downloads that commit's codeload tarball, extracts it into a temp directory, and checks its `SKILLS_VERSION` matches the tag. With no release resolvable it exits 1 and names `--ref main`, never falling back to the tip ([details](docs/troubleshooting.md#no-verified-release-could-be-resolved)). `--ref main` installs the tip of `main` instead, for contributors. |
138
- | Resolve | Selects capabilities whose `applies` value is `universal` or intersects your detected archetypes. Skipped capabilities are named with the reason. |
139
- | Install | Copies the selected capabilities plus fixed PHARN product surfaces into your repo, mirroring the upstream layout. |
140
- | Record | Writes `pharn.config.json` and `pharn.records.json` so future updates can tell PHARN-owned files from local edits. |
141
-
142
- The install layout places most runtime surfaces under `pharn/` and Claude Code
143
- integration under `.claude/`. The legacy flat layout (everything at the project
144
- root) was removed in v0.21.0: a project still recorded at it is asked to re-run
145
- `pharn init`, which reinstalls at `pharn/` and leaves the old top-level copies
146
- for you to delete ([support policy](docs/support-policy.md)).
90
+ | Step | What happens |
91
+ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
92
+ | Detect | Reads `package.json` dependency names and a bounded, symlink-safe file-tree scan to classify the project as `ssr`, `backend`, `spa`, `lib`, or a combination ([rules](docs/commands/init.md#3-detect-archetypes)). |
93
+ | Fetch | Downloads the newest **verified release** of `pharn-dev/pharn-oss` (a tag created only after its post-merge CI passed). With none resolvable it exits 1 and names `--ref main`, never falling back to the tip ([details](docs/troubleshooting.md#no-verified-release-could-be-resolved)). |
94
+ | Resolve | Selects capabilities whose `applies` value is `universal` or intersects your archetypes. Skipped capabilities are named with the reason. |
95
+ | Install | Copies the selected capabilities plus the fixed PHARN product surfaces into `.claude/` and `pharn/`. |
96
+ | Record | Writes `pharn.config.json` and `pharn.records.json` so future updates can tell PHARN-owned files from local edits. |
147
97
 
148
98
  ## What gets installed
149
99
 
150
- | Artifact | Purpose |
151
- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
152
- | `pharn/pharn-pipeline/grillers/<name>/`, `pharn/pharn-review/<name>/` | Pipeline grillers and review lenses selected for your project archetype(s). |
153
- | `.claude/commands/`, `.claude/hooks/` | The installed `/pharn-*` Claude Code slash commands and deterministic `.cjs`/`.mjs` hooks. |
154
- | `.claude/agents/` | The `pharn-review-lens` subagent each `/pharn-review` lens runs in (pharn-oss 6.64.0+). |
155
- | `pharn/pharn-contracts/`, `pharn/floor/` | Schemas shared across PHARN stages and floor checkers invoked by the workflow. |
156
- | `pharn/pharn-core/` | Agent-readable mechanism skills, including the seam resolver. |
157
- | `pharn/CONSTITUTION.md`, `pharn/ARCHITECTURE.md` | Trusted PHARN docs copied from upstream in the current layout. |
158
- | `pharn/THREAT-MODEL.md`, `pharn/LIMITS.md` | The other two trusted docs. |
159
- | `pharn/LICENSE` | PHARN's Apache-2.0 license copy. Your root `LICENSE` is never overwritten. |
160
- | `pharn/features/README.md` | The feature-loop boundary contract referenced by installed commands. |
161
- | `pharn.config.json` | Installed version, commit, layout, archetypes, capabilities, and defaults. |
162
- | `pharn.records.json` | Per-file hashes for drift-safe updates. Commit this with the config. |
163
-
164
- An existing `.claude/settings.json` is preserved. PHARN may create it when
165
- absent, but it never overwrites your Claude Code settings.
166
-
167
- As you run the workflow, PHARN writes one directory per increment —
168
- `pharn/features/<name>/` — holding that increment's `SPEC.md`, `PLAN.md`,
169
- `AC-TESTS.md`, `GRILL.md`, `BUILD.md`, `REGRESSION.md`, `VERIFY.md`, then
170
- `SHIP.md` + `BRIEFING.md` (`/pharn-ship`) or `LOOP.md` (`/pharn-loop`), a
171
- `RUN-REPORT.md`, and the machine-readable records beside them
172
- (`AC-TESTS.lock.json`, `cost.json`, the `*-report.json` files). Those are the
173
- durable record; commit them. `pharn/.run/` (runtime scratch; `.pharn/` before
174
- pharn-oss 7.0.0) and `pharn/.backup/` (see [Safety model](#safety-model)) are not:
175
- `pharn init` and `pharn update` append them to your `.gitignore` (creating it if
176
- needed) unless it already covers them — in any common spelling, such as
177
- `/pharn/.run`, `pharn/.run/**` or a negation `!pharn/.run/` you wrote on purpose.
178
- They only ever append: your lines are never reordered or rewritten, CRLF stays
179
- CRLF, and a second run changes nothing. A symlinked `.gitignore` is never written
180
- through (you get a warning naming the lines). Lines added to `.gitignore` do not
181
- untrack files you already committed (`git rm -r --cached pharn/.run` does).
182
- `pharn/.lock*` is a transient file — add it yourself if you like. When your
183
- `.gitignore` still names the old `.pharn/`, `pharn update` prints the
184
- replacement line; it never rewrites yours.
185
-
186
- Everything PHARN keeps in your project lives under `.claude/` and `pharn/`, plus
187
- the two JSON files at the root. An install made from a pharn-oss older than 7.0.0
188
- also has `THREAT-MODEL.md` and `LIMITS.md` at the root, and may have
189
- `memory-bank/` and `pharn.spec-template.md` there: the first `pharn update` to
190
- 7.0.0 or later deletes the two docs if you never edited them. It never moves the
191
- other two (nothing proves they are PHARN's); it prints the `git mv` command, or
192
- says to merge by hand when the `pharn/` copy already exists — see
193
- [update](docs/commands/update.md#the-root-footprint-migration).
194
-
195
- **Two version numbers, on purpose.** The npm package `@pharn-dev/pharn` carries
196
- the installer's version. The content it installs carries its own,
197
- recorded as `skillsVersion` in `pharn.config.json` and taken from upstream's
198
- `SKILLS_VERSION`. They move independently, and `pharn status` / `pharn update`
199
- are keyed to the latter.
100
+ Everything PHARN keeps in your project lives under `.claude/` (commands, hooks, agents) and `pharn/`
101
+ (capabilities, contracts, core, floor checkers, the trusted docs, a `LICENSE` copy and the features README),
102
+ plus `pharn.config.json` and `pharn.records.json` at the root: commit both. The full table is in
103
+ [Getting started: What you get](docs/getting-started.md#what-you-get). An existing `.claude/settings.json`
104
+ is never overwritten. As you run the workflow, PHARN writes one directory per increment,
105
+ `pharn/features/<name>/`, which is the durable record; commit it. `pharn init` and `pharn update` add
106
+ `pharn/.run/` and `pharn/.backup/` to your `.gitignore` ([how](docs/commands/init.md#gitignore)).
107
+
108
+ **Two version numbers, on purpose.** The npm package `@pharn-dev/pharn` carries the installer's version.
109
+ The content it installs carries its own, recorded as `skillsVersion` in `pharn.config.json` and taken from
110
+ upstream's `SKILLS_VERSION`. They move independently, and `pharn status` / `pharn update` are keyed to the
111
+ latter.
200
112
 
201
113
  ## After install
202
114
 
203
- Three things about the installed hooks are worth knowing on day one.
204
-
205
- **Hooks enforce only once they are registered in `.claude/settings.json`.** If
206
- your project already had that file, PHARN preserved it instead of overwriting
207
- it and printed a `HOOKS` note listing each hook it does not wire, as
208
- paste-ready JSON — until you copy those entries across, every guarantee that
209
- depends on a `PreToolUse` hook is inactive, and `pharn status --strict` fails.
210
-
211
- **Once wired, the default depends on your tree (pharn-oss 6.24.0+).** With no
212
- active scope, `enforce-writes-scope.cjs` applies that default.
213
-
214
- In an **installed** project (`pharn.config.json` carries a non-empty
215
- `skillsVersion`), you can edit ordinary application source **outside** an open
216
- PHARN run. The narrow fail-closed posture — Claude Code's
217
- Write/Edit/MultiEdit/NotebookEdit tools restricted to `pharn/features/**` and
218
- `.pharn/**` — applies **only while** `/pharn-ship`, `/pharn-loop`, or
219
- `/pharn-review` has an open marker (`.pharn/<command>/<name>/active.json`; ship
220
- and review via `pharn/floor/run-marker.mjs`, loop via
221
- `require-loop-record.cjs`). Outside those runs the guard **denies** PHARN's
222
- installed surface (`pharn/**` except `pharn/features/**`, `.claude/**`,
223
- `pharn.config.json`, and `.pharn/writes-scope.json`) and **allows** the rest of
224
- your project, including app source. While a stage is running it still sets
225
- explicit scope from the concrete paths your `PLAN.md` declared.
226
-
227
- In PHARN's own dev repo or an unsignalled tree, the pre-6.24.0 posture
228
- remains: fail-closed everywhere with no active scope. Clearing the scope
229
- (`set-writes-scope.cjs --clear`, or deleting `.pharn/writes-scope.json`)
230
- returns to whichever default your tree and open-run state compute; it does not
231
- by itself re-open source in those postures, or during an open install run.
232
-
233
- Writes issued through Bash bypass both write guards entirely.
234
-
235
- **`/pharn-loop` has a `Stop` guard too.** `require-loop-record.cjs` is not a
236
- write guard: while an unattended `/pharn-loop` run has written no `LOOP.md`, it
237
- refuses to let the turn end, a bounded number of times, and it fails open. It
238
- also does nothing until registered — under `Stop`, with no matcher. The
239
- `settings.json` upstream ships has registered it since pharn-oss 6.12.0, but a
240
- file PHARN preserved, or one created by an earlier install, lacks the entry:
241
- copy it across by hand. `pharn update` never edits `.claude/settings.json`;
242
- `pharn init`, `pharn status` and `pharn update` name the missing entry in a
243
- `HOOKS` note.
244
-
245
- The full set of bounds lives in upstream's
246
- [`LIMITS.md`](https://github.com/pharn-dev/pharn-oss/blob/main/LIMITS.md) and
247
- [README](https://github.com/pharn-dev/pharn-oss#readme).
115
+ - **Hooks enforce only once they are registered in `.claude/settings.json`.** If your project already had
116
+ that file, PHARN kept it and printed a `HOOKS` note listing each hook it does not wire, as paste-ready
117
+ JSON. Until you copy them across, the guarantees that depend on a `PreToolUse` hook are inactive, and
118
+ `pharn status --strict` fails.
119
+ - **`/pharn-loop` has a `Stop` guard** (`require-loop-record.cjs`) that also does nothing until it is
120
+ registered under `Stop`. `pharn init`, `pharn status` and `pharn update` name a missing entry.
121
+ - **`pharn update` never edits `.claude/settings.json`**, so copy new hook entries across by hand. Writes
122
+ issued through Bash bypass the write guards entirely.
123
+
124
+ What the write guards allow and deny, and the full set of bounds, are in upstream's
125
+ [README](https://github.com/pharn-dev/pharn-oss#what-gets-installed) and
126
+ [`LIMITS.md`](https://github.com/pharn-dev/pharn-oss/blob/main/LIMITS.md).
248
127
 
249
128
  ## Day-to-day workflow
250
129
 
251
- Once PHARN is installed, use the slash commands from Claude Code. The pipeline
252
- is eight typed stages, each reading what the previous one produced:
253
-
254
- | Stage | Command | Purpose |
255
- | ------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
256
- | Spec | `/pharn-spec` | Capture feature intent and scope. Stops for your approval. |
257
- | Plan | `/pharn-plan` | Turn the approved spec into an implementation plan, mapping each acceptance criterion to a test (`AC-TESTS.md`). |
258
- | Grill | `/pharn-grill` | Challenge the plan before code is written. |
259
- | Test | `/pharn-test` | Write each acceptance criterion's test before the build, run it, and require it to fail. `/pharn-build` refuses to start without that evidence. |
260
- | Build | `/pharn-build` | Implement an approved increment. |
261
- | Regress | `/pharn-regress` | Look for regressions outside the just-built feature. |
262
- | Verify | `/pharn-verify` | Verify behavior and PHARN floor requirements, including that every acceptance criterion's test now passes. |
263
- | Ship | `/pharn-ship` | Run stages 1-7 in order, then stop at the merge/fix/abandon gate. |
264
-
265
- `/pharn-ship` is itself the eighth stage: it orchestrates the seven before it in
266
- one pass, so you rarely run them by hand, and it keeps both human gates —
267
- approve the spec before code is written, decide merge/fix/abandon after
268
- verification. `/pharn-loop` runs that same chain unattended: the model approves
269
- the spec, iterates build -> regress -> verify until green, an iteration cap, or
270
- a terminal failure, commits a green result to a new local branch (never pushed
271
- or merged), and leaves the merge/fix/abandon decision to you after the run.
272
- From pharn-oss 7.7.0, a full `/pharn-loop` (not `--quick`) also runs
273
- `/pharn-triage` after the grill: it gives every grill finding one disposition.
274
- Since 7.8.0 a `replan` verdict sends the run back to `/pharn-plan` for at most
275
- two re-plan rounds, and since 7.9.0 a verdict that still escalates goes to
276
- `/pharn-supervise`, a fresh agent that decides `stop` or `proceed-at-risk` (the
277
- escalated findings are then named as known risk in the green commit and the run
278
- report); since 7.10.0 it may instead amend the SPEC once per run (`amend-spec`).
279
- That decision is one model's judgment, not a check. You can run `/pharn-triage`
280
- yourself after a full `/pharn-grill`.
281
-
282
- `/pharn-spec` fills PHARN's default SPEC template, or your own if you put one at
283
- `pharn.spec-template.md` in the project root. The write guard denies Claude
284
- Code's edit tools on that path, so edit it yourself; see upstream's
285
- [Your own SPEC template](https://github.com/pharn-dev/pharn-oss#your-own-spec-template).
286
-
287
- Two commands sit outside the pipeline:
288
-
289
- | Command | Purpose |
290
- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
291
- | `/pharn-review` | Run the review lenses in parallel over any code and merge their findings deterministically. Standalone — no pipeline stage invokes it. |
292
- | `/pharn-memory-promote` | Promote one lesson into `memory-bank/` through a gated provenance check. |
130
+ Once PHARN is installed, use the slash commands from Claude Code. The pipeline is eight typed stages, each
131
+ reading what the previous one produced ([what each does](docs/getting-started.md#after-init)).
132
+ `/pharn-ship` runs the first seven in one pass and keeps both human gates: approve the spec before code is
133
+ written, decide merge/fix/abandon after verification. `/pharn-loop` runs the same chain unattended and
134
+ commits a green result to a new local branch (never pushed or merged), leaving the merge decision to you. Outside the pipeline,
135
+ `/pharn-review` runs the review lenses over any code, and `/pharn-memory-promote` promotes one lesson into
136
+ `pharn/memory-bank/`. `/pharn-spec` uses your own SPEC template if you put one at `pharn/spec-template.md`
137
+ (see upstream's [Your own SPEC template](https://github.com/pharn-dev/pharn-oss#your-own-spec-template)).
293
138
 
294
139
  ## CLI commands
295
140
 
@@ -301,162 +146,79 @@ Two commands sit outside the pipeline:
301
146
  | `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). |
302
147
  | `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. |
303
148
  | `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. |
304
- | `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `.claude/settings.json` or `pharn/.backup/`. `--yes`/`-y` skips the confirmation prompt. |
149
+ | `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `pharn/.backup/` or a `.claude/settings.json` it did not create. `--yes`/`-y` skips the confirmation prompt. |
305
150
  | `pharn --help` | Show every command, option and environment variable. `pharn <command> --help` shows one command and only the options it takes. |
306
151
  | `pharn --version` | Show the installed CLI version. |
307
152
 
308
- `init` also takes `--archetype <list>` (for example `--archetype backend` or
309
- `--archetype ssr,backend`) to install for those archetypes instead of the
310
- detected ones — the in-product correction for a misdetected project. The value
311
- must be a comma-separated list of `ssr`, `backend` and `spa`, or `lib` alone,
312
- each at most once; anything else exits 1. The choice is recorded, so `update`
313
- keeps it. The install summary shows what triggered each detected archetype
314
- (`backend ← src/app/api/`), or that they came from the flag.
315
-
316
- Three behaviours matter if you script the CLI:
317
-
318
- - **Options are per-command.** Passing one a command does not take prints
319
- ``Unsupported option for `status`: "--force"`` to stderr with ``Run `pharn --help` for usage.``
320
- and exits **1**; an extra positional is refused the same way. Both previously
321
- parsed, were silently dropped, and exited 0.
322
- - **`init` and `update` prompt.** Off a TTY a plain run exits 1 rather than
323
- prompting into a dead stream. `update --yes` is the way through in CI. For
324
- `init`, `--yes` skips the summary confirm but never the overwrite one: it
325
- installs only into a project where none of its files exists yet, and
326
- otherwise exits 1 — so a re-install always refuses it (use `update`). Both
327
- commands' `--dry-run` needs no terminal and writes nothing. `uninstall`
328
- likewise exits 1 off a TTY unless it is given `--yes`.
329
- - **One writer at a time.** `init`, `add`, `remove`, `update` and `uninstall`
330
- take an advisory lock at `pharn/.lock`; a second run refuses rather than
331
- queueing. `add`, `remove`, `update` and `uninstall` also re-read
332
- `pharn.config.json` once they hold the lock, and refuse — writing nothing —
333
- if another run changed it after they read it (for example while a confirm
334
- prompt was open).
335
- `list` and `status` never take it and are never blocked by one, so
336
- `pharn status --strict` stays runnable in CI while an update is in flight.
153
+ `init` also takes `--archetype <list>` (for example `--archetype ssr,backend`) to install for those
154
+ archetypes instead of the detected ones; the choice is recorded, so `update` keeps it.
337
155
 
338
- ## Agent skills
156
+ If you script the CLI: an option a command does not take, or an extra positional, exits **1**
157
+ (``Unsupported option for `status`: "--force"``); off a TTY a plain `init`, `update` or `uninstall` exits 1
158
+ (`update --yes` is the CI line; `init --yes` never confirms an overwrite; `--dry-run` needs no terminal);
159
+ and one writer at a time holds `pharn/.lock`, while `list` and `status` never take it, so
160
+ `pharn status --strict` stays runnable in CI. A config changed while a prompt was open refuses the write.
339
161
 
340
- If you would rather ask than remember flags, the
341
- [`pharn-dev/skills`](https://github.com/pharn-dev/skills) repository ships a
342
- `pharn-cli` skill that operates this CLI for you. Ask your agent "Is PHARN up to
343
- date in this project?" or "What would an update change?" and it runs the
344
- read-only checks and a `--dry-run` preview first, applies the update without
345
- overwriting your edits, and adds or removes grillers and lenses. The same
346
- repository also carries `phargus` skills for setting up and diagnosing Node.js
347
- applications with [Phargus](https://github.com/pharn-dev/phargus).
348
-
349
- In Claude Code:
350
-
351
- ```text
352
- /plugin marketplace add pharn-dev/skills
353
- /plugin install pharn@pharn-dev
354
- ```
162
+ ## Agent skills
355
163
 
356
- Or with the Skills CLI: `npx skills add pharn-dev/skills --skill pharn-cli`.
357
- The skills are optional; every command above works without them.
164
+ The [`pharn-dev/skills`](https://github.com/pharn-dev/skills) repository ships a `pharn-cli` skill that
165
+ operates this CLI for you: ask "Is PHARN up to date in this project?" or "What would an update change?" and
166
+ it runs the read-only checks and a `--dry-run` first, applies updates without overwriting your edits, and
167
+ adds or removes grillers and lenses. It also carries `phargus` skills for
168
+ [Phargus](https://github.com/pharn-dev/phargus). In Claude Code, run `/plugin marketplace add pharn-dev/skills`
169
+ then `/plugin install pharn@pharn-dev`, or use `npx skills add pharn-dev/skills --skill pharn-cli`. The skills
170
+ are optional.
358
171
 
359
172
  ## Safety model
360
173
 
361
174
  PHARN is intentionally conservative about writes:
362
175
 
363
- - `init` checks for existing install targets and asks before overwriting them,
364
- and refuses the whole install — writing nothing — when a destination path
365
- crosses a symlinked directory.
366
- - `update` uses `pharn.records.json` to skip files it cannot prove are
367
- untouched. The only thing it deletes is the directory of a capability it
368
- drops from `pharn.config.json` (PHARN runs whatever capability directories
369
- are on disk), after backing up any file in it that `pharn` cannot prove it
370
- wrote; it never touches `.claude/settings.json`. A re-run `init` does the
371
- same, after listing those directories in its prompt.
372
- - `update --force` backs up overwritten files under `pharn/.backup/<timestamp>/`
373
- before writing. `add` does the same for any destination file that differs from
374
- upstream, and refuses the whole install — writing nothing — when a destination
375
- path crosses a symlinked directory.
176
+ - `init` checks for existing install targets and asks before overwriting them, and refuses the whole
177
+ install (writing nothing) when a destination path crosses a symlinked directory.
178
+ - `update` uses `pharn.records.json` to skip files it cannot prove are untouched. In your project it deletes
179
+ only the directory of a capability it drops from `pharn.config.json` (PHARN runs whatever capability
180
+ directories are on disk), after backing up any file in it that `pharn` cannot prove it wrote; it never
181
+ touches `.claude/settings.json`. A re-run `init` does the same, after listing those directories in its
182
+ prompt. Every delete, and what is never deleted: [What PHARN deletes](docs/reference/deletes.md).
183
+ - `update --force` backs up overwritten files under `pharn/.backup/<timestamp>/` before writing. `add` does
184
+ the same for any destination file that differs from upstream, and refuses the whole install (writing
185
+ nothing) when a destination path crosses a symlinked directory.
376
186
  - `status` and `list` are read-only.
377
- - `remove` deletes only the selected capability directory and prunes its records,
378
- after backing up to `pharn/.backup/<timestamp>/` any file in it that `pharn`
379
- cannot prove it wrote unchanged;
380
- it never touches `CONSTITUTION.md`, `memory-bank/`, or your detected
381
- archetypes, and refuses when that directory's path crosses a symlink.
382
- - `uninstall` deletes only files recorded in `pharn.records.json` that still
383
- match their recorded hash, inside `pharn`'s install paths; it keeps every file
384
- you changed or added and lists the ones it kept, backs up `pharn.config.json`
385
- before deleting it, never writes `.claude/settings.json` (it prints the hooks
386
- you need to unwire instead), and refuses — deleting nothing — without a usable
387
- record store.
388
-
389
- PHARN can also refuse to install at all: if upstream declares a minimum CLI
390
- version newer than yours, `init`/`add`/`update` stop with a named error before
391
- writing anything.
392
-
393
- Remote content is treated as untrusted input. Capability names, copyable file
394
- names, versions, commit SHAs, and paths are validated against strict allowlists;
395
- path traversal and symlink escapes are rejected; copied file contents are not
187
+ - `remove` deletes only the selected capability directory and prunes its records, after backing up to
188
+ `pharn/.backup/<timestamp>/` any file in it that `pharn` cannot prove it wrote unchanged; it never touches
189
+ `CONSTITUTION.md`, `pharn/memory-bank/`, or your detected archetypes, and refuses when that directory's
190
+ path crosses a symlink.
191
+ - `uninstall` deletes only files recorded in `pharn.records.json` that still match their recorded hash,
192
+ inside `pharn`'s install paths; it keeps every file you changed or added and lists the ones it kept, backs
193
+ up `pharn.config.json` before deleting it, never writes `.claude/settings.json` (it prints the hooks you
194
+ need to unwire instead), and refuses (deleting nothing) without a usable record store.
195
+
196
+ PHARN can also refuse to install at all: if upstream declares a minimum CLI version newer than yours,
197
+ `init`/`add`/`update` stop with a named error before writing anything. Remote content is treated as
198
+ untrusted input. Capability names, copyable file names, versions, commit SHAs, and paths are validated
199
+ against strict allowlists; path traversal and symlink escapes are rejected; copied file contents are not
396
200
  executed by the CLI.
397
201
 
398
202
  ## Current scope
399
203
 
400
- PHARN is intentionally scoped:
401
-
402
- - It targets **Claude Code today**. Codex and Cursor support are planned, not
403
- shipped.
404
- - It requires a git-initialized project and **Node >= 24.2.0**, for the CLI
405
- (`@pharn-dev/pharn`, `engines.node`) and for the **installed floor**
406
- (`pharn/floor/*.mjs`) alike. The floor's checkers gate on `import.meta.main`;
407
- on an older Node a guarded tool used to exit 0 without running its checks, so
408
- they now refuse to run there (one stderr line, exit 2). `pharn init` and
409
- `pharn update` therefore refuse up front on an older Node, with nothing
410
- written, and `pharn status` prints the floor beside the Node you are running.
411
- CI runs on Node 24, and a smoke job starts the packed CLI on exactly 24.2.0.
412
- - **Archetype detection is JS/TS-shaped.** The signals are `package.json`
413
- dependency names, `.tsx`/`.jsx` files, and — in a Next.js app only —
414
- `next.config.*`, `app/` route handlers and `app/api`/`pages/api`. A root
415
- `api/`, a `migrations/` directory and `.sql` files in a database directory
416
- count only when the project has a root `package.json`. A Python, Go, Rust,
417
- Ruby or PHP repo without one produces no signal, resolves to `lib`, and
418
- receives the universal capabilities only — a correct outcome, not a failure.
419
- One that also has a root `package.json` (a Vite frontend, or tooling only)
420
- can resolve `backend` from its migrations; `pharn init --archetype` corrects
421
- either way.
422
- - **Server and database packages count only as runtime dependencies.** A
423
- runtime database driver dependency (`pg`, `mongodb`, an ORM) means `backend`,
424
- like a server framework; the same package only in `devDependencies` (a mock
425
- server, a test database) does not. A backend bundled so that its framework is
426
- only a devDependency needs `pharn init --archetype backend`. SSR and UI
427
- frameworks count from `devDependencies` too.
428
- - **Detection is bounded.** The file-tree scan examines at most 50,000 entries,
429
- 24 directories deep (skipped directories such as `node_modules` do not
430
- count). When it stops at a bound before its result is settled, the install
431
- summary says `detection stopped early` and `init --dry-run --json` reports
432
- `"detectionTruncated": true`; check the archetypes and pass `--archetype` if
433
- they are wrong.
434
- - It does not scaffold your application or install framework packages.
435
- - It does not replace tests, human review, or release judgment. It gives those
436
- activities a structured record and repeatable workflow.
437
- - `status` reports modified, missing, and unreadable PHARN-owned paths, and
438
- the files upstream stopped shipping that are still in your project
439
- (orphans). Nothing deletes an orphan; that is yours to do by hand.
440
- - **Supported installs: the current minor and the previous one.** v0.20.x
441
- works with installs made by 0.19.x or 0.20.x; re-run `pharn init` on an older
442
- install, and it keeps the capabilities you added.
443
- `--json` reports stay additive within `schemaVersion: 1`. Compatibility code
444
- for older installs is removed on a named version: see the
445
- [support policy](docs/support-policy.md).
446
-
447
- See the [roadmap](docs/roadmap.md) for shipped versus planned work.
204
+ - It targets **Claude Code today**. Codex and Cursor support are planned, not shipped.
205
+ - It requires a git-initialized project and **Node >= 24.2.0**, for the CLI and for the installed floor
206
+ checkers (`pharn/floor/*.mjs`), which refuse to run on an older Node. `pharn init` and `pharn update`
207
+ refuse up front on an older Node, with nothing written.
208
+ - **Archetype detection is JS/TS-shaped and bounded.** A Python, Go, Rust, Ruby or PHP repo without a root
209
+ `package.json` resolves to `lib` and gets the universal capabilities, a correct outcome; `pharn init
210
+ --archetype` corrects any misdetection. The rules: [Detect archetypes](docs/commands/init.md#3-detect-archetypes).
211
+ - It does not scaffold your app, install framework packages, or replace tests, review or release judgment.
212
+ - **Supported installs: the current minor and the previous one.** Re-run `pharn init` on an older install;
213
+ it keeps the capabilities you added. `--json` reports stay additive within `schemaVersion: 1`. See the
214
+ [support policy](docs/support-policy.md) and the [roadmap](docs/roadmap.md).
448
215
 
449
216
  ## Documentation
450
217
 
451
- Start here: [docs/](docs/README.md)
452
-
453
- - [Getting started](docs/getting-started.md)
454
- - [Command reference](docs/README.md#commands)
455
- - [pharn.config.json](docs/reference/pharn-config.md)
456
- - [pharn.records.json](docs/reference/pharn-records.md)
457
- - [Support policy](docs/support-policy.md)
458
- - [Troubleshooting](docs/troubleshooting.md)
459
- - [Roadmap](docs/roadmap.md)
218
+ Start here: [docs/](docs/README.md). [Getting started](docs/getting-started.md) ·
219
+ [Commands](docs/README.md#commands) · [pharn.config.json](docs/reference/pharn-config.md) ·
220
+ [pharn.records.json](docs/reference/pharn-records.md) · [Support policy](docs/support-policy.md) ·
221
+ [Troubleshooting](docs/troubleshooting.md) · [Roadmap](docs/roadmap.md)
460
222
 
461
223
  ## Development
462
224
 
@@ -464,34 +226,21 @@ Start here: [docs/](docs/README.md)
464
226
  npm install
465
227
  npm run dev -- init
466
228
  npm run build
467
- npm run test
468
- npm run check
229
+ npm run check # format:check, lint, lint:md, typecheck, test
469
230
  ```
470
231
 
471
- Useful scripts:
472
-
473
- | Script | Purpose |
474
- | ----------------------------- | ----------------------------------------------------- |
475
- | `npm run typecheck` | Type-check source and tests. |
476
- | `npm run lint` | Run ESLint with zero warnings. |
477
- | `npm run lint:md` | Run markdownlint over docs and root markdown. |
478
- | `npm run test:coverage` | Run the Vitest coverage gate used by CI. |
479
- | `npm run build:install-local` | Build and install the local CLI into local test apps. |
480
-
481
- Set `PHARN_DEBUG=1` for verbose fetch and install errors; `NO_COLOR` / `FORCE_COLOR`
482
- control colour (see [Colour](docs/troubleshooting.md#colour)). See
232
+ Other scripts: `npm run test:coverage` (the coverage gate CI runs) and `npm run build:install-local` (build
233
+ and install the local CLI into local test apps). Set `PHARN_DEBUG=1` for verbose fetch and install errors;
234
+ `NO_COLOR` / `FORCE_COLOR` control colour (see [Colour](docs/troubleshooting.md#colour)). See
483
235
  [CONTRIBUTING.md](CONTRIBUTING.md) for contributor notes and release discipline.
484
236
 
485
237
  ## Security
486
238
 
487
- The CLI has a small trust boundary: it downloads PHARN content from GitHub,
488
- validates and extracts it, then copies selected files into your project. The
489
- security-sensitive path validation, tar extraction, symlink handling, and update
490
- decision tables are covered by tests.
491
-
492
- Please report vulnerabilities through [SECURITY.md](SECURITY.md), not public
493
- issues. The detailed model is in [THREAT-MODEL.md](THREAT-MODEL.md) and
494
- [LIMITS.md](LIMITS.md).
239
+ The CLI has a small trust boundary: it downloads PHARN content from GitHub, validates and extracts it, then
240
+ copies selected files into your project. The security-sensitive path validation, tar extraction, symlink
241
+ handling, and update decision tables are covered by tests. Please report vulnerabilities through
242
+ [SECURITY.md](SECURITY.md), not public issues. The detailed model is in [THREAT-MODEL.md](THREAT-MODEL.md)
243
+ and [LIMITS.md](LIMITS.md).
495
244
 
496
245
  ## License
497
246
 
@@ -1 +1 @@
1
- import{readDiskState}from"./chunk-26RZI2K7.js";import{capabilityOf,findSymlinkComponent,isInstallRootPath}from"./chunk-PL5ALKBN.js";import{CLAUDE_SETTINGS_FILE}from"./chunk-W3TXAEBT.js";import{color_default}from"./chunk-5YCL3WDS.js";import{isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{closeSync,constants,fstatSync,openSync,readSync}from"node:fs";import{dirname}from"node:path";var LOCAL_SETTINGS_FILE=".claude/settings.local.json",MAX_SETTINGS_BYTES=256*1024,OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readSettings(base,rel){let linked;try{linked=findSymlinkComponent(base,dirname(rel))}catch{return{kind:"unreadable",reason:"a path component is not a directory"}}if(linked!==null)return{kind:"unreadable",reason:`${linked} is a symbolic link`};let fd;try{fd=openSync(safeJoin(base,rel),OPEN_FLAGS)}catch(err){let code=err.code;return code==="ENOENT"?{kind:"absent"}:code==="ENOTDIR"?{kind:"unreadable",reason:"a path component is not a directory"}:{kind:"unreadable",reason:"it cannot be opened"}}try{let st=fstatSync(fd);if(!st.isFile())return{kind:"unreadable",reason:"it is not a regular file"};if(st.size>MAX_SETTINGS_BYTES)return{kind:"unreadable",reason:"it is larger than 256 KB"};let buf=Buffer.alloc(st.size),off=0;for(;off<buf.length;){let n=readSync(fd,buf,off,buf.length-off,off);if(n===0)break;off+=n}try{return{kind:"ok",value:JSON.parse(buf.subarray(0,off).toString("utf8"))}}catch{return{kind:"unreadable",reason:"it is not valid JSON"}}}catch{return{kind:"unreadable",reason:"it cannot be read"}}finally{closeSync(fd)}}function hookEntries(settings){if(!isPlainObject(settings)||!isPlainObject(settings.hooks))return null;let out=[];for(let[event,groups]of Object.entries(settings.hooks))if(Array.isArray(groups))for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks))continue;let matcher=typeof group.matcher=="string"?group.matcher:"";for(let hook of group.hooks){if(!isPlainObject(hook)||typeof hook.command!="string")continue;let args=Array.isArray(hook.args)?hook.args.filter(a=>typeof a=="string"):[];out.push({event,matcher,command:hook.command,args})}}return out}function entryKey(e){return JSON.stringify([e.event,e.matcher,e.command,e.args])}function projectEntries(result){return result.kind==="ok"?hookEntries(result.value)??[]:[]}function entryMentions(e,rels){let mentions=text=>rels.some(rel=>text.includes(rel));return mentions(e.command)||e.args.some(mentions)}var HOOK_SCRIPT_RE=/\.claude\/hooks\/[A-Za-z0-9._-]+/g;function hookScriptRels(e){let out=new Set;for(let text of[e.command,...e.args])for(let m of text.matchAll(HOOK_SCRIPT_RE))out.add(m[0]);return[...out]}function findReplacements(missing,upstreamKeys,project){let out=[];for(let upstream of missing){let rels=hookScriptRels(upstream);if(rels.length===0)continue;let existing=[];for(let{file,entries}of project)for(let entry of entries)entry.event===upstream.event&&entry.matcher===upstream.matcher&&!upstreamKeys.has(entryKey(entry))&&entryMentions(entry,rels)&&existing.push({file,entry});existing.length>0&&out.push({upstream,existing})}return out}function diffHookWiring(repoDir,projectRoot){let upstream=readSettings(repoDir,CLAUDE_SETTINGS_FILE),upstreamEntries=upstream.kind==="ok"?hookEntries(upstream.value):null;if(upstreamEntries===null||upstreamEntries.length===0)return{status:"no-upstream",missing:[]};let shared=readSettings(projectRoot,CLAUDE_SETTINGS_FILE),local=readSettings(projectRoot,LOCAL_SETTINGS_FILE);for(let[file,result]of[[CLAUDE_SETTINGS_FILE,shared],[LOCAL_SETTINGS_FILE,local]])if(result.kind==="unreadable")return{status:"unreadable",missing:upstreamEntries,file,reason:result.reason};if(shared.kind==="absent"&&local.kind==="absent")return{status:"project-absent",missing:upstreamEntries};let sharedEntries=projectEntries(shared),localEntries=projectEntries(local),inShared=new Set(sharedEntries.map(entryKey)),inLocal=new Set(localEntries.map(entryKey)),missing=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&!inLocal.has(entryKey(e))),localOnly=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&inLocal.has(entryKey(e)));if(missing.length){let replace=findReplacements(missing,new Set(upstreamEntries.map(entryKey)),[{file:CLAUDE_SETTINGS_FILE,entries:sharedEntries},{file:LOCAL_SETTINGS_FILE,entries:localEntries}]);return replace.length>0?{status:"missing",missing,replace}:{status:"missing",missing}}return localOnly.length?{status:"local-only",missing,localOnly}:{status:"match",missing}}function hooksReferencing(projectRoot,scriptRels){if(scriptRels.length===0)return[];let out=[];for(let file of[CLAUDE_SETTINGS_FILE,LOCAL_SETTINGS_FILE]){let read=readSettings(projectRoot,file);if(read.kind==="absent")continue;if(read.kind==="unreadable"){out.push({file,kind:"unreadable",reason:read.reason});continue}let entries=(hookEntries(read.value)??[]).filter(e=>entryMentions(e,scriptRels));entries.length>0&&out.push({file,kind:"ok",entries})}return out}function hookWiringFails(diff){return diff.status==="missing"||diff.status==="unreadable"||diff.status==="project-absent"}var MAX_LINE=300;function displayHook(e){let hook=e.args.length>0?{type:"command",command:e.command,args:e.args}:{type:"command",command:e.command},where=e.matcher?`${e.event} [${e.matcher}]`:e.event,line=`${escapeUnsafe(where)}: ${escapeUnsafe(JSON.stringify(hook))}`;return line.length>MAX_LINE?`${line.slice(0,MAX_LINE)}\u2026`:line}var FILES=`${CLAUDE_SETTINGS_FILE} or ${LOCAL_SETTINGS_FILE}`;function hookWiringLines(diff){if(diff.status==="match"||diff.status==="no-upstream")return null;if(diff.status==="local-only"){let only=diff.localOnly??[];return[` Every hook upstream wires is wired \u2014 ${only.length} of them only in ${LOCAL_SETTINGS_FILE}.`," They run for you, not for teammates or CI:",...only.map(e=>` ${displayHook(e)}`)]}let replace=diff.status==="missing"?diff.replace??[]:[];return replace.length>0?replaceAndAddLines(diff.missing,replace):[diff.status==="project-absent"?` Neither ${FILES} exists. Upstream wires:`:diff.status==="unreadable"?` ${diff.file??CLAUDE_SETTINGS_FILE} could not be read (${diff.reason??"unknown"}). Upstream wires:`:` Upstream wires ${diff.missing.length} hook(s) that neither ${FILES} does:`,...diff.missing.map(e=>` ${displayHook(e)}`),"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 merge these by hand:`,...FOOTER]}var FOOTER=[" each line is one hook, as JSON, under its event [matcher]. Matching is"," textual: an equivalent hook you wrote differently is listed too."];function replaceAndAddLines(missing,replace){let replaced=new Set(replace.map(r=>r.upstream)),add=missing.filter(e=>!replaced.has(e)),lines=[` Upstream wires ${missing.length} hook(s) that neither ${FILES} does.`,"",` REPLACE \u2014 ${replace.length} of them run a script you already wire under the same`," event [matcher], spelled differently. Replace your line with upstream's;"," adding it beside yours would run the script twice:"];for(let r of replace){for(let{file,entry}of r.existing)lines.push(` yours (${file}): ${displayHook(entry)}`);lines.push(` upstream: ${displayHook(r.upstream)}`)}return add.length>0&&lines.push("",` ADD \u2014 ${add.length} wired in neither file:`,...add.map(e=>` ${displayHook(e)}`)),[...lines,"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 edit these by hand:`,...FOOTER]}function preservedSettingsHookLines(diff){let lines=hookWiringLines(diff);return lines===null?null:hookWiringFails(diff)?[...lines," `pharn status --strict` fails until they are wired."]:lines}function countSkipped(settings){if(!("hooks"in settings))return 0;if(!isPlainObject(settings.hooks))return 1;let skipped=0;for(let groups of Object.values(settings.hooks)){if(!Array.isArray(groups)){skipped++;continue}for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks)){skipped++;continue}for(let hook of group.hooks)(!isPlainObject(hook)||typeof hook.command!="string")&&skipped++}}return skipped}function upstreamSettingsSummary(repoDir){let read=readSettings(repoDir,CLAUDE_SETTINGS_FILE);return read.kind==="absent"?{status:"unreadable",reason:"it does not exist"}:read.kind==="unreadable"?{status:"unreadable",reason:read.reason}:isPlainObject(read.value)?{status:"ok",hooks:hookEntries(read.value)??[],otherKeys:Object.keys(read.value).filter(k=>k!=="hooks"&&k!=="_comment").sort(),skipped:countSkipped(read.value)}:{status:"ok",hooks:[],otherKeys:[],skipped:0}}var MAX_KEY=100,MAX_KEYS=20;function displayKey(key){return escapeUnsafe(key.length>MAX_KEY?`${key.slice(0,MAX_KEY)}\u2026`:key)}function freshSettingsHookLines(summary){let review=" Claude Code runs these commands; review `.claude/settings.json`.";if(summary.status==="unreadable")return[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream, but could not list its hooks (${escapeUnsafe(summary.reason)}).`,review];let lines=summary.hooks.length>0?[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires ${summary.hooks.length} hook(s):`,...summary.hooks.map(e=>` ${displayHook(e)}`)]:[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires no hooks.`];if(summary.skipped>0&&lines.push(` ${summary.skipped} other hook entr${summary.skipped===1?"y":"ies"} not shown \u2014 review the file.`),summary.otherKeys.length>0){let shown=summary.otherKeys.slice(0,MAX_KEYS).map(displayKey),more=summary.otherKeys.length-shown.length;lines.push(` It also sets: ${shown.join(", ")}${more>0?` and ${more} more`:""}`)}return[...lines,review]}var MAX_ORPHANS_PER_GROUP=20;function findOrphans(params){let{projectRoot,records,expected}=params;if(records===null)return{orphans:[],records:{}};let key=cap=>`${cap.role}:${cap.name}`,owned=new Set(params.capabilities.map(key)),frozen=new Set(params.frozen.map(key)),orphans=[],carried={};for(let[rel,recorded]of Object.entries(records)){if(expected.has(rel)||!isInstallRootPath(rel))continue;let cap=capabilityOf(rel);if(cap!==null&&(frozen.has(cap)||!owned.has(cap)))continue;let disk=readDiskState(projectRoot,rel);disk.kind!=="absent"&&(carried[rel]=recorded,disk.kind==="unreadable"?orphans.push({path:rel,state:"unreadable",reason:disk.reason}):orphans.push({path:rel,state:disk.hash===recorded?"unchanged":"edited"}))}return orphans.sort((a,b)=>+(a.path>b.path)-+(a.path<b.path)),{orphans,records:carried}}var GROUPS=[{state:"unchanged",heading:"UNCHANGED \u2014 unchanged since pharn wrote it"},{state:"edited",heading:"EDITED \u2014 changed since pharn wrote it \u2014 review before deleting"},{state:"unreadable",heading:"UNREADABLE \u2014 not a readable regular file; inspect by hand"}];function orphanNoteLines(orphans){if(orphans.length===0)return null;let lines=[" Upstream no longer ships these files pharn installed. pharn never deletes"," them, and keeps listing each one until it is gone.",""],capped=!1;for(let{state,heading}of GROUPS){let group=orphans.filter(o=>o.state===state);if(group.length!==0){lines.push(` ${heading}`);for(let o of group.slice(0,MAX_ORPHANS_PER_GROUP)){let path=terminalSafe(o.path);lines.push(o.reason!==void 0?` ${path} \u2014 ${terminalSafe(o.reason)}`:` ${path}`)}group.length>MAX_ORPHANS_PER_GROUP&&(capped=!0,lines.push(` \u2026 and ${group.length-MAX_ORPHANS_PER_GROUP} more`)),lines.push("")}}return lines.push(color_default.dim(" Delete the ones you no longer need by hand (e.g. `git rm <path>`).")),capped&&lines.push(color_default.dim(" The full list: `pharn status --json` (`orphans`).")),lines}export{diffHookWiring,hooksReferencing,hookWiringFails,displayHook,hookWiringLines,preservedSettingsHookLines,upstreamSettingsSummary,freshSettingsHookLines,findOrphans,orphanNoteLines};
1
+ import{readDiskState}from"./chunk-26RZI2K7.js";import{capabilityOf,findSymlinkComponent,isInstallRootPath}from"./chunk-PL5ALKBN.js";import{CLAUDE_SETTINGS_FILE}from"./chunk-W3TXAEBT.js";import{color_default}from"./chunk-5YCL3WDS.js";import{isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{closeSync,constants,fstatSync,openSync,readSync}from"node:fs";import{dirname}from"node:path";var LOCAL_SETTINGS_FILE=".claude/settings.local.json",MAX_SETTINGS_BYTES=256*1024,OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readSettings(base,rel){let linked;try{linked=findSymlinkComponent(base,dirname(rel))}catch{return{kind:"unreadable",reason:"a path component is not a directory"}}if(linked!==null)return{kind:"unreadable",reason:`${linked} is a symbolic link`};let fd;try{fd=openSync(safeJoin(base,rel),OPEN_FLAGS)}catch(err){let code=err.code;return code==="ENOENT"?{kind:"absent"}:code==="ENOTDIR"?{kind:"unreadable",reason:"a path component is not a directory"}:{kind:"unreadable",reason:"it cannot be opened"}}try{let st=fstatSync(fd);if(!st.isFile())return{kind:"unreadable",reason:"it is not a regular file"};if(st.size>MAX_SETTINGS_BYTES)return{kind:"unreadable",reason:"it is larger than 256 KB"};let buf=Buffer.alloc(st.size),off=0;for(;off<buf.length;){let n=readSync(fd,buf,off,buf.length-off,off);if(n===0)break;off+=n}try{return{kind:"ok",value:JSON.parse(buf.subarray(0,off).toString("utf8"))}}catch{return{kind:"unreadable",reason:"it is not valid JSON"}}}catch{return{kind:"unreadable",reason:"it cannot be read"}}finally{closeSync(fd)}}function hookEntries(settings){if(!isPlainObject(settings)||!isPlainObject(settings.hooks))return null;let out=[];for(let[event,groups]of Object.entries(settings.hooks))if(Array.isArray(groups))for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks))continue;let matcher=typeof group.matcher=="string"?group.matcher:"";for(let hook of group.hooks){if(!isPlainObject(hook)||typeof hook.command!="string")continue;let args=Array.isArray(hook.args)?hook.args.filter(a=>typeof a=="string"):[];out.push({event,matcher,command:hook.command,args})}}return out}function entryKey(e){return JSON.stringify([e.event,e.matcher,e.command,e.args])}function projectEntries(result){return result.kind==="ok"?hookEntries(result.value)??[]:[]}function entryMentions(e,rels){let mentions=text=>rels.some(rel=>text.includes(rel));return mentions(e.command)||e.args.some(mentions)}var HOOK_SCRIPT_RE=/\.claude\/hooks\/[A-Za-z0-9._-]+/g;function hookScriptRels(e){let out=new Set;for(let text of[e.command,...e.args])for(let m of text.matchAll(HOOK_SCRIPT_RE))out.add(m[0]);return[...out]}function findReplacements(missing,upstreamKeys,project){let out=[];for(let upstream of missing){let rels=hookScriptRels(upstream);if(rels.length===0)continue;let existing=[];for(let{file,entries}of project)for(let entry of entries)entry.event===upstream.event&&entry.matcher===upstream.matcher&&!upstreamKeys.has(entryKey(entry))&&entryMentions(entry,rels)&&existing.push({file,entry});existing.length>0&&out.push({upstream,existing})}return out}function diffHookWiring(repoDir,projectRoot){let upstream=readSettings(repoDir,CLAUDE_SETTINGS_FILE),upstreamEntries=upstream.kind==="ok"?hookEntries(upstream.value):null;if(upstreamEntries===null||upstreamEntries.length===0)return{status:"no-upstream",missing:[]};let shared=readSettings(projectRoot,CLAUDE_SETTINGS_FILE),local=readSettings(projectRoot,LOCAL_SETTINGS_FILE);for(let[file,result]of[[CLAUDE_SETTINGS_FILE,shared],[LOCAL_SETTINGS_FILE,local]])if(result.kind==="unreadable")return{status:"unreadable",missing:upstreamEntries,file,reason:result.reason};if(shared.kind==="absent"&&local.kind==="absent")return{status:"project-absent",missing:upstreamEntries};let sharedEntries=projectEntries(shared),localEntries=projectEntries(local),inShared=new Set(sharedEntries.map(entryKey)),inLocal=new Set(localEntries.map(entryKey)),missing=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&!inLocal.has(entryKey(e))),localOnly=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&inLocal.has(entryKey(e)));if(missing.length){let replace=findReplacements(missing,new Set(upstreamEntries.map(entryKey)),[{file:CLAUDE_SETTINGS_FILE,entries:sharedEntries},{file:LOCAL_SETTINGS_FILE,entries:localEntries}]);return replace.length>0?{status:"missing",missing,replace}:{status:"missing",missing}}return localOnly.length?{status:"local-only",missing,localOnly}:{status:"match",missing}}function hooksReferencing(projectRoot,scriptRels){if(scriptRels.length===0)return[];let out=[];for(let file of[CLAUDE_SETTINGS_FILE,LOCAL_SETTINGS_FILE]){let read=readSettings(projectRoot,file);if(read.kind==="absent")continue;if(read.kind==="unreadable"){out.push({file,kind:"unreadable",reason:read.reason});continue}let entries=(hookEntries(read.value)??[]).filter(e=>entryMentions(e,scriptRels));entries.length>0&&out.push({file,kind:"ok",entries})}return out}function hookWiringFails(diff){return diff.status==="missing"||diff.status==="unreadable"||diff.status==="project-absent"}var MAX_LINE=300;function displayHook(e){let hook=e.args.length>0?{type:"command",command:e.command,args:e.args}:{type:"command",command:e.command},where=e.matcher?`${e.event} [${e.matcher}]`:e.event,line=`${escapeUnsafe(where)}: ${escapeUnsafe(JSON.stringify(hook))}`;return line.length>MAX_LINE?`${line.slice(0,MAX_LINE)}\u2026`:line}var FILES=`${CLAUDE_SETTINGS_FILE} or ${LOCAL_SETTINGS_FILE}`;function hookWiringLines(diff){if(diff.status==="match"||diff.status==="no-upstream")return null;if(diff.status==="local-only"){let only=diff.localOnly??[];return[` Every hook upstream wires is wired \u2014 ${only.length} of them only in ${LOCAL_SETTINGS_FILE}.`," They run for you, not for teammates or CI:",...only.map(e=>` ${displayHook(e)}`)]}let replace=diff.status==="missing"?diff.replace??[]:[];return replace.length>0?replaceAndAddLines(diff.missing,replace):[diff.status==="project-absent"?` Neither ${FILES} exists. Upstream wires:`:diff.status==="unreadable"?` ${diff.file??CLAUDE_SETTINGS_FILE} could not be read (${diff.reason??"unknown"}). Upstream wires:`:` Upstream wires ${diff.missing.length} hook(s) that neither ${FILES} does:`,...diff.missing.map(e=>` ${displayHook(e)}`),"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 merge these by hand:`,...FOOTER]}var FOOTER=[" each line is one hook, as JSON, under its event [matcher]. Matching is"," textual: an equivalent hook you wrote differently is listed too."];function replaceAndAddLines(missing,replace){let replaced=new Set(replace.map(r=>r.upstream)),add=missing.filter(e=>!replaced.has(e)),lines=[` Upstream wires ${missing.length} hook(s) that neither ${FILES} does.`,"",` REPLACE \u2014 ${replace.length} of them run a script you already wire under the same`," event [matcher], spelled differently. Replace your line with upstream's;"," adding it beside yours would run the script twice:"];for(let r of replace){for(let{file,entry}of r.existing)lines.push(` yours (${file}): ${displayHook(entry)}`);lines.push(` upstream: ${displayHook(r.upstream)}`)}return add.length>0&&lines.push("",` ADD \u2014 ${add.length} wired in neither file:`,...add.map(e=>` ${displayHook(e)}`)),[...lines,"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 edit these by hand:`,...FOOTER]}function preservedSettingsHookLines(diff){let lines=hookWiringLines(diff);return lines===null?null:hookWiringFails(diff)?[...lines," `pharn status --strict` fails until they are wired."]:lines}function countSkipped(settings){if(!("hooks"in settings))return 0;if(!isPlainObject(settings.hooks))return 1;let skipped=0;for(let groups of Object.values(settings.hooks)){if(!Array.isArray(groups)){skipped++;continue}for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks)){skipped++;continue}for(let hook of group.hooks)(!isPlainObject(hook)||typeof hook.command!="string")&&skipped++}}return skipped}function upstreamSettingsSummary(repoDir){let read=readSettings(repoDir,CLAUDE_SETTINGS_FILE);return read.kind==="absent"?{status:"unreadable",reason:"it does not exist"}:read.kind==="unreadable"?{status:"unreadable",reason:read.reason}:isPlainObject(read.value)?{status:"ok",hooks:hookEntries(read.value)??[],otherKeys:Object.keys(read.value).filter(k=>k!=="hooks"&&k!=="_comment").sort(),skipped:countSkipped(read.value)}:{status:"ok",hooks:[],otherKeys:[],skipped:0}}var MAX_KEY=100,MAX_KEYS=20;function displayKey(key){return escapeUnsafe(key.length>MAX_KEY?`${key.slice(0,MAX_KEY)}\u2026`:key)}function freshSettingsHookLines(summary){let review=" Claude Code runs these commands; review `.claude/settings.json`.";if(summary.status==="unreadable")return[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream, but could not list its hooks (${escapeUnsafe(summary.reason)}).`,review];let lines=summary.hooks.length>0?[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires ${summary.hooks.length} hook(s):`,...summary.hooks.map(e=>` ${displayHook(e)}`)]:[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires no hooks.`];if(summary.skipped>0&&lines.push(` ${summary.skipped} other hook entr${summary.skipped===1?"y":"ies"} not shown \u2014 review the file.`),summary.otherKeys.length>0){let shown=summary.otherKeys.slice(0,MAX_KEYS).map(displayKey),more=summary.otherKeys.length-shown.length;lines.push(` It also sets: ${shown.join(", ")}${more>0?` and ${more} more`:""}`)}return[...lines,review]}var MAX_ORPHANS_PER_GROUP=20;function findOrphans(params){let{projectRoot,records,expected}=params;if(records===null)return{orphans:[],records:{}};let key=cap=>`${cap.role}:${cap.name}`,owned=new Set(params.capabilities.map(key)),frozen=new Set(params.frozen.map(key)),orphans=[],carried={};for(let[rel,recorded]of Object.entries(records)){if(expected.has(rel)||!isInstallRootPath(rel))continue;let cap=capabilityOf(rel);if(cap!==null&&(frozen.has(cap)||!owned.has(cap)))continue;let disk=readDiskState(projectRoot,rel);disk.kind!=="absent"&&(carried[rel]=recorded,disk.kind==="unreadable"?orphans.push({path:rel,state:"unreadable",reason:disk.reason}):orphans.push({path:rel,state:disk.hash===recorded?"unchanged":"edited"}))}return orphans.sort((a,b)=>+(a.path>b.path)-+(a.path<b.path)),{orphans,records:carried}}var GROUPS=[{state:"unchanged",heading:"UNCHANGED \u2014 unchanged since pharn wrote it"},{state:"edited",heading:"EDITED \u2014 changed since pharn wrote it \u2014 review before deleting"},{state:"unreadable",heading:"UNREADABLE \u2014 not a readable regular file; inspect by hand"}];function orphanNoteLines(orphans){if(orphans.length===0)return null;let lines=[" Upstream no longer ships these files pharn installed. `pharn update` never"," deletes them, and keeps listing each one until it is gone.",""],capped=!1;for(let{state,heading}of GROUPS){let group=orphans.filter(o=>o.state===state);if(group.length!==0){lines.push(` ${heading}`);for(let o of group.slice(0,MAX_ORPHANS_PER_GROUP)){let path=terminalSafe(o.path);lines.push(o.reason!==void 0?` ${path} \u2014 ${terminalSafe(o.reason)}`:` ${path}`)}group.length>MAX_ORPHANS_PER_GROUP&&(capped=!0,lines.push(` \u2026 and ${group.length-MAX_ORPHANS_PER_GROUP} more`)),lines.push("")}}return lines.push(color_default.dim(" Delete the ones you no longer need by hand (e.g. `git rm <path>`).")),capped&&lines.push(color_default.dim(" The full list: `pharn status --json` (`orphans`).")),lines}export{diffHookWiring,hooksReferencing,hookWiringFails,displayHook,hookWiringLines,preservedSettingsHookLines,upstreamSettingsSummary,freshSettingsHookLines,findOrphans,orphanNoteLines};
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{parseArchetypeList}from"./chunk-IC45C3NS.js";import{REF_CHOICES}from"./chunk-256AIEPX.js";import{PHARN_VERSION}from"./chunk-W3TXAEBT.js";import"./chunk-L3QGAX2K.js";import{CliError,escapeUnsafe}from"./chunk-A77BLCF4.js";import{realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{parseArgs}from"node:util";var INTRO="Pharn - Installs and updates PHARN (a workflow for shipping features right with Claude Code) in your git project. npx @pharn-dev/pharn init detects your project's archetype and installs the applicable PHARN capabilities; pharn add installs another capability later; pharn update bumps to the latest skills version.",COMMANDS=[{name:"init",summary:"Detect archetypes and install capabilities (default)",page:"Detect archetypes and install capabilities. The default command: `pharn` alone runs it."},{name:"add",args:"[capability]",summary:"Add a capability, e.g. a11y (no arg: pick interactively)"},{name:"remove",args:"[capability]",aliases:["rm"],summary:"Remove an installed capability (no arg: pick interactively)"},{name:"update",summary:"Re-fetch installed capabilities at the latest version"},{name:"list",summary:"List installed archetypes + capabilities"},{name:"status",summary:"Show version + local-drift status (read-only)"},{name:"uninstall",summary:"Remove the PHARN files pharn wrote and you did not change"}],OPTIONS=[{key:"archetype",long:"--archetype <list>",value:!0,uses:[{commands:["init"],text:["use these archetypes instead of detecting them \u2014 a","comma-separated list of ssr, backend, spa (or lib alone)"]}]},{key:"ref",long:"--ref <ref>",value:!0,uses:[{commands:["init"],text:['install from "latest" (the newest verified pharn-oss','release \u2014 the default) or "main" (its tip, for',"contributors); recorded"]},{commands:["update"],text:['switch to "latest" (verified releases) or "main" (the',"tip); recorded \u2014 without it, update follows the","channel the install records (main when none is)"]}]},{key:"force",long:"--force",uses:[{commands:["update"],text:["overwrite files you changed (each is copied to pharn/.backup/ first)"]}]},{key:"yes",short:"y",long:"--yes",uses:[{commands:["update","uninstall"],text:["skip the confirmation prompt (for CI and scripts)"]},{commands:["init"],text:["install without prompts \u2014 only when no file would be overwritten"]}]},{key:"dry-run",long:"--dry-run",uses:[{commands:["update"],text:["show what would change and write nothing"]},{commands:["init"],text:["show what would be installed and write nothing"]}]},{key:"strict",long:"--strict",uses:[{commands:["status"],text:["exit 1 on any outdated/modified/missing file"]}]},{key:"no-drift",long:"--no-drift",uses:[{commands:["status"],text:["skip the byte-level drift check"]}]},{key:"json",long:"--json",uses:[{commands:["list"],text:["emit the inventory as JSON"]},{commands:["status"],text:["emit one JSON report on stdout (diagnostics on stderr)"]},{commands:["update"],text:["emit the plan as one JSON object (implies --dry-run)"]},{commands:["init"],text:["emit the plan as one JSON object (implies --dry-run)"]}]},{key:"compact",long:"--compact",uses:[{commands:["update"],text:["omit the unchanged files from the JSON plan (implies --json)"]}]},{key:"help",short:"h",long:"--help",uses:[{commands:[],text:["Show this help text"]}]},{key:"version",short:"v",long:"--version",uses:[{commands:[],text:["Show the version number"]}]}],ENVIRONMENT=`Environment:
2
+ import{parseArchetypeList}from"./chunk-IC45C3NS.js";import{REF_CHOICES}from"./chunk-256AIEPX.js";import{PHARN_VERSION}from"./chunk-W3TXAEBT.js";import"./chunk-L3QGAX2K.js";import{CliError,escapeUnsafe}from"./chunk-A77BLCF4.js";import{realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{parseArgs}from"node:util";var INTRO="Pharn - Installs and updates PHARN (a workflow for shipping features right with Claude Code) in your git project. npx @pharn-dev/pharn init detects your project's archetype and installs the applicable PHARN capabilities; pharn add installs another capability later; pharn update bumps to the latest skills version.",COMMANDS=[{name:"init",summary:"Detect archetypes and install capabilities (default)",page:"Detect archetypes and install capabilities. The default command: `pharn` alone runs it."},{name:"add",args:"[capability]",summary:"Add a capability, e.g. a11y (no arg: pick interactively)"},{name:"remove",args:"[capability]",aliases:["rm"],summary:"Remove an installed capability (no arg: pick interactively)"},{name:"update",summary:"Re-fetch installed capabilities at the latest version"},{name:"list",summary:"List installed archetypes + capabilities"},{name:"status",summary:"Show version + local-drift status (read-only)"},{name:"uninstall",summary:"Remove the PHARN files pharn wrote and you did not change"}],OPTIONS=[{key:"archetype",long:"--archetype <list>",value:!0,uses:[{commands:["init"],text:["use these archetypes instead of detecting them \u2014 a","comma-separated list of ssr, backend, spa (or lib alone)"]}]},{key:"ref",long:"--ref <ref>",value:!0,uses:[{commands:["init"],text:['install from "latest" (the newest verified pharn-oss','release \u2014 the default) or "main" (its tip, for',"contributors); recorded"]},{commands:["update"],text:['switch to "latest" (verified releases) or "main" (the',"tip); recorded \u2014 without it, update follows the","channel the install records (main when none is)"]}]},{key:"force",long:"--force",uses:[{commands:["update"],text:["overwrite files you changed (each is copied to pharn/.backup/ first)"]}]},{key:"yes",short:"y",long:"--yes",uses:[{commands:["update","uninstall"],text:["skip the confirmation prompt (for CI and scripts)"]},{commands:["init"],text:["install without prompts \u2014 only when no file would be overwritten"]}]},{key:"dry-run",long:"--dry-run",uses:[{commands:["update"],text:["show what would change and write nothing"]},{commands:["init"],text:["show what would be installed and write nothing"]}]},{key:"strict",long:"--strict",uses:[{commands:["status"],text:["exit 1 on an outdated install, a modified, missing or unreadable","file, a surface upstream no longer ships, or an unwired hook","(under --no-drift, only outdated is checked)"]}]},{key:"no-drift",long:"--no-drift",uses:[{commands:["status"],text:["skip the byte-level drift check"]}]},{key:"json",long:"--json",uses:[{commands:["list"],text:["emit the inventory as JSON"]},{commands:["status"],text:["emit one JSON report on stdout (diagnostics on stderr)"]},{commands:["update"],text:["emit the plan as one JSON object (implies --dry-run)"]},{commands:["init"],text:["emit the plan as one JSON object (implies --dry-run)"]}]},{key:"compact",long:"--compact",uses:[{commands:["update"],text:["omit the unchanged files from the JSON plan (implies --json)"]}]},{key:"help",short:"h",long:"--help",uses:[{commands:[],text:["Show this help text"]}]},{key:"version",short:"v",long:"--version",uses:[{commands:[],text:["Show the version number"]}]}],ENVIRONMENT=`Environment:
3
3
  PHARN_DEBUG=1 Print the full error (stack trace) when a download or
4
4
  install fails, instead of a one-line hint
5
5
  NODE_USE_ENV_PROXY=1 Let Node's fetch use https_proxy / HTTPS_PROXY (or
6
6
  http_proxy / HTTP_PROXY, honouring NO_PROXY); without it, or
7
7
  Node's --use-env-proxy, pharn's downloads connect directly,
8
8
  and pharn says which applies whenever a proxy variable is set
9
- NO_COLOR=1 Turn colored output off (FORCE_COLOR=1 turns it on)`,DESCRIPTION_COLUMN=21,COMMAND_COLUMN=29,isGlobal=opt=>opt.uses.some(u=>u.commands.length===0),takesOption=(opt,cmd)=>isGlobal(opt)||opt.uses.some(u=>u.commands.includes(cmd));function optionLines(opt,forCommand){let body=(forCommand===void 0?opt.uses:opt.uses.filter(u=>u.commands.length===0||u.commands.includes(forCommand))).flatMap(({commands,text})=>text.map((line,i)=>i===0&&forCommand===void 0&&commands.length>0?`${commands.join(", ")}: ${line}`:line)),indent=" ".repeat(DESCRIPTION_COLUMN),head=` ${opt.short?`-${opt.short}, `:" "}${opt.long}`;if(head.length+2>DESCRIPTION_COLUMN)return[head,...body.map(line=>indent+line)];let[first,...rest]=body;return[head.padEnd(DESCRIPTION_COLUMN)+(first??""),...rest.map(line=>indent+line)]}function commandLabel(c){let names=[c.name,...c.aliases??[]].join(", ");return c.args?`${names} ${c.args}`:names}var USAGE=[INTRO,"","Usage:"," pharn [command] [options]","","Commands:",...COMMANDS.map(c=>` ${commandLabel(c).padEnd(COMMAND_COLUMN-2)}${c.summary}`),"","Options (each belongs to ONE command; passing it to another is an error):",...OPTIONS.flatMap(opt=>optionLines(opt)),"",ENVIRONMENT,"","Run `pharn <command> --help` for one command and only its options."].join(`
9
+ NO_COLOR=1 Turn colored output off (FORCE_COLOR=1 turns it on)`,DESCRIPTION_COLUMN=21,COMMAND_COLUMN=29,isGlobal=opt=>opt.uses.some(u=>u.commands.length===0),takesOption=(opt,cmd)=>isGlobal(opt)||opt.uses.some(u=>u.commands.includes(cmd));function optionLines(opt,forCommand){let body=(forCommand===void 0?opt.uses:opt.uses.filter(u=>u.commands.length===0||u.commands.includes(forCommand))).flatMap(({commands,text})=>text.map((line,i)=>i===0&&forCommand===void 0&&commands.length>0?`${commands.join(", ")}: ${line}`:line)),indent=" ".repeat(DESCRIPTION_COLUMN),head=` ${opt.short?`-${opt.short}, `:" "}${opt.long}`;if(head.length+2>DESCRIPTION_COLUMN)return[head,...body.map(line=>indent+line)];let[first,...rest]=body;return[head.padEnd(DESCRIPTION_COLUMN)+(first??""),...rest.map(line=>indent+line)]}function commandLabel(c){let names=[c.name,...c.aliases??[]].join(", ");return c.args?`${names} ${c.args}`:names}var USAGE=[INTRO,"","Usage:"," pharn [command] [options]","","Commands:",...COMMANDS.map(c=>` ${commandLabel(c).padEnd(COMMAND_COLUMN-2)}${c.summary}`),"","Options (each names the commands that take it; any other command refuses it):",...OPTIONS.flatMap(opt=>optionLines(opt)),"",ENVIRONMENT,"","Run `pharn <command> --help` for one command and only its options."].join(`
10
10
  `);function commandUsage(doc){let args=doc.args?` ${doc.args}`:"",options=OPTIONS.some(opt=>!isGlobal(opt)&&takesOption(opt,doc.name))?" [options]":"";return["Usage:",` pharn ${doc.name}${args}${options}`,...(doc.aliases??[]).map(a=>` pharn ${a}${args}${options} (alias)`),"",doc.page??`${doc.summary}.`,"","Options:",...OPTIONS.filter(opt=>takesOption(opt,doc.name)).flatMap(opt=>optionLines(opt,doc.name)),"","Run `pharn --help` for every command and the environment variables pharn reads."].join(`
11
- `)}var USAGE_POINTER="Run `pharn --help` for usage.",PARSE_OPTIONS=Object.fromEntries(OPTIONS.map(opt=>[opt.key,{type:opt.value?"string":"boolean",...opt.short===void 0?{}:{short:opt.short}}])),OPTION_BY_KEY=new Map(OPTIONS.map(opt=>[opt.key,opt])),COMMAND_BY_WORD=new Map(COMMANDS.flatMap(c=>[c.name,...c.aliases??[]].map(word=>[word,c])));function refuse(label,offenders){return{kind:"refuse",message:`${label}: ${[...new Set(offenders)].map(o=>JSON.stringify(o)).join(", ")}`}}function parseCliArgs(args){let{tokens}=parseArgs({args:[...args],options:PARSE_OPTIONS,strict:!1,allowPositionals:!0,tokens:!0}),options=[],positionals=[];for(let t of tokens)t.kind==="option"?options.push(t):t.kind==="positional"&&positionals.push(t.value);let written=t=>args[t.index],word=positionals[0],doc=COMMAND_BY_WORD.get(word??"init"),unknown=options.filter(t=>!OPTION_BY_KEY.has(t.name));if(unknown.length>0)return refuse("Unknown option",unknown.map(written));if(doc!==void 0){let unsupported=options.filter(t=>!takesOption(OPTION_BY_KEY.get(t.name),doc.name));if(unsupported.length>0){let typed=[doc.name,...doc.aliases??[]].find(w=>w===word)??doc.name;return refuse(`Unsupported option for \`${typed}\``,unsupported.map(written))}}let valued=options.filter(t=>OPTION_BY_KEY.get(t.name).value!==!0&&t.inlineValue===!0);if(valued.length>0)return refuse("Option takes no value",valued.map(written));let repeated=OPTIONS.filter(opt=>opt.value&&options.filter(t=>t.name===opt.key).length>1);if(repeated.length>0)return refuse("Repeated option",repeated.map(opt=>`--${opt.key}`));let has=key=>options.some(t=>t.name===key),valueOf=key=>{let t=options.find(o=>o.name===key);return t===void 0?void 0:t.value??""},refValue=valueOf("ref"),ref=refValue===void 0?void 0:REF_CHOICES.find(choice=>choice===refValue);if(refValue!==void 0&&ref===void 0)return refuse(`Invalid value for --ref (expected ${REF_CHOICES.map(r=>`"${r}"`).join(" or ")})`,[refValue]);let archetypeValue=valueOf("archetype"),archetypes=archetypeValue===void 0?void 0:parseArchetypeList(archetypeValue);if(archetypes===null)return refuse('Invalid value for --archetype (expected a comma-separated list of "ssr", "backend", "spa" \u2014 or "lib" alone \u2014 each at most once)',[archetypeValue]);if(has("version"))return{kind:"print",text:PHARN_VERSION};if(has("help"))return{kind:"print",text:word!==void 0&&doc!==void 0?commandUsage(doc):USAGE};if(doc===void 0)return{kind:"refuse",message:`Unknown command: ${escapeUnsafe(word)}`};let maxPositionals=doc.args===void 0?1:2;if(positionals.length>maxPositionals)return refuse("Unexpected argument",positionals.slice(maxPositionals));let json=has("json");switch(doc.name){case"init":return run({command:"init",options:{ref,archetypes,yes:has("yes"),dryRun:has("dry-run")||json,json}});case"add":case"remove":return run({command:doc.name,capability:positionals[1]});case"update":{let compact=has("compact");return run({command:"update",options:{force:has("force"),yes:has("yes"),dryRun:has("dry-run")||json||compact,json:json||compact,compact,ref}})}case"list":return run({command:"list",options:{json}});case"status":return run({command:"status",options:{strict:has("strict"),drift:!has("no-drift"),json}});case"uninstall":return run({command:"uninstall",options:{yes:has("yes")}})}}function run(invocation){return{kind:"run",invocation}}async function main(args=process.argv.slice(2)){let parsed=parseCliArgs(args);if(parsed.kind==="refuse")throw console.error(parsed.message),console.error(USAGE_POINTER),CliError.reported();if(parsed.kind==="print"){console.log(parsed.text);return}let{invocation}=parsed;switch(invocation.command){case"init":{let{runInit}=await import("./init-3EJWD45N.js");await runInit(invocation.options);return}case"add":{let{runAdd}=await import("./add-RYPFFPXB.js");await runAdd(invocation.capability);return}case"remove":{let{runRemove}=await import("./remove-B5F6HDFM.js");await runRemove(invocation.capability);return}case"update":{let{runUpdate}=await import("./update-DUPETT53.js");await runUpdate(invocation.options);return}case"list":{let{runList}=await import("./list-JME23KNT.js");await runList(invocation.options);return}case"status":{let{runStatus}=await import("./status-LSU7LRGO.js");await runStatus(invocation.options);return}case"uninstall":{let{runUninstall}=await import("./uninstall-YZ67TV5B.js");await runUninstall(invocation.options);return}}}function isEntryPoint(){if(!process.argv[1])return!1;try{return realpathSync(process.argv[1])===fileURLToPath(import.meta.url)}catch{return!1}}async function runCli(args=process.argv.slice(2)){try{await main(args)}catch(err){if(err instanceof CliError&&err.form==="reported"){process.exitCode=err.exitCode;return}let{reportCliError}=await import("./report-error-63XMOBGV.js");process.exitCode=reportCliError(err)}}isEntryPoint()&&runCli();export{main,runCli};
11
+ `)}var USAGE_POINTER="Run `pharn --help` for usage.",PARSE_OPTIONS=Object.fromEntries(OPTIONS.map(opt=>[opt.key,{type:opt.value?"string":"boolean",...opt.short===void 0?{}:{short:opt.short}}])),OPTION_BY_KEY=new Map(OPTIONS.map(opt=>[opt.key,opt])),COMMAND_BY_WORD=new Map(COMMANDS.flatMap(c=>[c.name,...c.aliases??[]].map(word=>[word,c])));function refuse(label,offenders){return{kind:"refuse",message:`${label}: ${[...new Set(offenders)].map(o=>JSON.stringify(o)).join(", ")}`}}function parseCliArgs(args){let{tokens}=parseArgs({args:[...args],options:PARSE_OPTIONS,strict:!1,allowPositionals:!0,tokens:!0}),options=[],positionals=[];for(let t of tokens)t.kind==="option"?options.push(t):t.kind==="positional"&&positionals.push(t.value);let written=t=>args[t.index],word=positionals[0],doc=COMMAND_BY_WORD.get(word??"init"),unknown=options.filter(t=>!OPTION_BY_KEY.has(t.name));if(unknown.length>0)return refuse("Unknown option",unknown.map(written));if(doc!==void 0){let unsupported=options.filter(t=>!takesOption(OPTION_BY_KEY.get(t.name),doc.name));if(unsupported.length>0){let typed=[doc.name,...doc.aliases??[]].find(w=>w===word)??doc.name;return refuse(`Unsupported option for \`${typed}\``,unsupported.map(written))}}let valued=options.filter(t=>OPTION_BY_KEY.get(t.name).value!==!0&&t.inlineValue===!0);if(valued.length>0)return refuse("Option takes no value",valued.map(written));let repeated=OPTIONS.filter(opt=>opt.value&&options.filter(t=>t.name===opt.key).length>1);if(repeated.length>0)return refuse("Repeated option",repeated.map(opt=>`--${opt.key}`));let has=key=>options.some(t=>t.name===key),valueOf=key=>{let t=options.find(o=>o.name===key);return t===void 0?void 0:t.value??""},refValue=valueOf("ref"),ref=refValue===void 0?void 0:REF_CHOICES.find(choice=>choice===refValue);if(refValue!==void 0&&ref===void 0)return refuse(`Invalid value for --ref (expected ${REF_CHOICES.map(r=>`"${r}"`).join(" or ")})`,[refValue]);let archetypeValue=valueOf("archetype"),archetypes=archetypeValue===void 0?void 0:parseArchetypeList(archetypeValue);if(archetypes===null)return refuse('Invalid value for --archetype (expected a comma-separated list of "ssr", "backend", "spa" \u2014 or "lib" alone \u2014 each at most once)',[archetypeValue]);if(has("version"))return{kind:"print",text:PHARN_VERSION};if(has("help"))return{kind:"print",text:word!==void 0&&doc!==void 0?commandUsage(doc):USAGE};if(doc===void 0)return{kind:"refuse",message:`Unknown command: ${escapeUnsafe(word)}`};let maxPositionals=doc.args===void 0?1:2;if(positionals.length>maxPositionals)return refuse("Unexpected argument",positionals.slice(maxPositionals));let json=has("json");switch(doc.name){case"init":return run({command:"init",options:{ref,archetypes,yes:has("yes"),dryRun:has("dry-run")||json,json}});case"add":case"remove":return run({command:doc.name,capability:positionals[1]});case"update":{let compact=has("compact");return run({command:"update",options:{force:has("force"),yes:has("yes"),dryRun:has("dry-run")||json||compact,json:json||compact,compact,ref}})}case"list":return run({command:"list",options:{json}});case"status":return run({command:"status",options:{strict:has("strict"),drift:!has("no-drift"),json}});case"uninstall":return run({command:"uninstall",options:{yes:has("yes")}})}}function run(invocation){return{kind:"run",invocation}}async function main(args=process.argv.slice(2)){let parsed=parseCliArgs(args);if(parsed.kind==="refuse")throw console.error(parsed.message),console.error(USAGE_POINTER),CliError.reported();if(parsed.kind==="print"){console.log(parsed.text);return}let{invocation}=parsed;switch(invocation.command){case"init":{let{runInit}=await import("./init-ZFHRQ5DR.js");await runInit(invocation.options);return}case"add":{let{runAdd}=await import("./add-RYPFFPXB.js");await runAdd(invocation.capability);return}case"remove":{let{runRemove}=await import("./remove-B5F6HDFM.js");await runRemove(invocation.capability);return}case"update":{let{runUpdate}=await import("./update-BHK2J6Z5.js");await runUpdate(invocation.options);return}case"list":{let{runList}=await import("./list-JME23KNT.js");await runList(invocation.options);return}case"status":{let{runStatus}=await import("./status-XGNMVK36.js");await runStatus(invocation.options);return}case"uninstall":{let{runUninstall}=await import("./uninstall-4BWRYLXI.js");await runUninstall(invocation.options);return}}}function isEntryPoint(){if(!process.argv[1])return!1;try{return realpathSync(process.argv[1])===fileURLToPath(import.meta.url)}catch{return!1}}async function runCli(args=process.argv.slice(2)){try{await main(args)}catch(err){if(err instanceof CliError&&err.form==="reported"){process.exitCode=err.exitCode;return}let{reportCliError}=await import("./report-error-63XMOBGV.js");process.exitCode=reportCliError(err)}}isEntryPoint()&&runCli();export{main,runCli};
@@ -1,4 +1,4 @@
1
- import{archetypesFromSignals,classifyEntry,evidenceFor,isBaseDir,isNextConfigName,mergeSignals,packageFacts,recordedArchetypes}from"./chunk-IC45C3NS.js";import{installPrepared,manifestSources,prepareInstall,scanDest,upstreamSettingsCopyable}from"./chunk-ZL3KBIIS.js";import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackups,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{minCliGate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,replacedConfigBackup,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignoreReport,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,freshSettingsHookLines,preservedSettingsHookLines,upstreamSettingsSummary}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import"./chunk-26RZI2K7.js";import{DEFAULT_INIT_REF,ReleaseResolveError,channelOf,resolveSource,sourceLabel}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,PHARN_CONFIG_FILE,UpstreamManifestError,absentInstallSurfaces,buildRecords,carriedSettingsRecord,collectExpectedInstallPaths,conflictingWriteTargets,detectLayout,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_AGENTS_DIR,CLAUDE_SETTINGS_FILE,FIRST_FEATURE_COMMAND,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,readJsonBounded,readPharnConfig,row,userOwnedConfigEntries,writePharnConfig}from"./chunk-5YCL3WDS.js";import{VERSION_RE,isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log as log3,note as note3,outro as outro2,spinner as spinner2}from"@clack/prompts";var LOGO=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D"];function showBanner(){console.log();for(let line of LOGO)console.log(` ${color_default.cyan(color_default.bold(line))}`);console.log(),console.log(` ${color_default.dim(`Ship features right with Claude Code \xB7 v${PHARN_VERSION}`)}`),console.log()}import{closeSync,constants,fstatSync,lstatSync,openSync,readSync,readdirSync}from"node:fs";import{join,resolve}from"node:path";var SKIP_DIRS=new Set(["node_modules",".git","dist","build",".next","out","coverage",".turbo",".vercel",".nuxt",".svelte-kit",".astro",".cache",".parcel-cache","storybook-static","__pycache__",".yarn"]),ECOSYSTEM_DIRS=new Map([["target",{siblings:["Cargo.toml","pom.xml","build.sbt"]}],["vendor",{siblings:["go.mod","composer.json","Gemfile"]}],["venv",{inside:"pyvenv.cfg"}],[".venv",{inside:"pyvenv.cfg"}]]);function isEcosystemTree(dir,name,siblingFiles){let marker=ECOSYSTEM_DIRS.get(name.toLowerCase());return marker===void 0?!1:"siblings"in marker?marker.siblings.some(file=>siblingFiles.has(file)):lstatSync(join(dir,name,marker.inside),{throwIfNoEntry:!1})?.isFile()===!0}var WALK_LIMITS=Object.freeze({maxDepth:24,maxEntries:5e4}),NO_PACKAGE_JSON={jsProject:!1,nextDependency:!1},NO_SIGNALS={ssr:!1,backend:!1,clientUi:!1},SIGNAL_KEYS=["ssr","backend","clientUi"];function scanFileTree(root,facts=NO_PACKAGE_JSON,limits=WALK_LIMITS){let acc={ssr:!1,backend:!1,clientUi:!1},evidence={},pkg=facts.packageSignals??NO_SIGNALS,budget=limits.maxEntries,truncated=!1,settled=()=>(pkg.ssr||acc.ssr)&&(pkg.backend||acc.backend),readEntries=dir=>{try{return readdirSync(dir,{withFileTypes:!0})}catch{return[]}},walk=(dir,depth,segments,names,inherited)=>{if(budget<=0&&truncated||settled())return;let entries=readEntries(dir).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0),siblingFiles=new Set(entries.filter(e=>e.isFile()).map(e=>e.name)),ctx=isBaseDir(segments)?{jsProject:facts.jsProject,baseDepth:segments.length,nextBase:segments.length===0&&facts.nextDependency||[...siblingFiles].some(isNextConfigName)}:inherited;for(let entry of entries){if(settled())return;let name=entry.name;if(entry.isSymbolicLink())continue;let isDir=entry.isDirectory();if(isDir&&SKIP_DIRS.has(name.toLowerCase())||isDir&&isEcosystemTree(dir,name,siblingFiles)||!isDir&&name.toLowerCase().startsWith(".env")||!isDir&&!entry.isFile())continue;if(depth>limits.maxDepth||budget<=0){truncated=!0;return}budget-=1;let sig=classifyEntry(name,isDir,segments,ctx);for(let key2 of SIGNAL_KEYS)sig[key2]&&evidence[key2]===void 0&&(evidence[key2]=[...names,name].join("/")+(isDir?"/":""));acc=mergeSignals(acc,sig),isDir&&walk(join(dir,name),depth+1,[...segments,name.toLowerCase()],[...names,name],ctx)}};return walk(root,0,[],[],{jsProject:facts.jsProject,baseDepth:0,nextBase:!1}),{signals:acc,evidence,truncated:truncated&&!settled()}}var MAX_PACKAGE_JSON_BYTES=4*1024*1024,PKG_OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readPackageJsonText(pkgPath){let fd;try{fd=openSync(pkgPath,PKG_OPEN_FLAGS)}catch{return null}try{if(!fstatSync(fd).isFile())return null;let buf=Buffer.alloc(MAX_PACKAGE_JSON_BYTES+1),total=0;for(;total<buf.length;){let n=readSync(fd,buf,total,buf.length-total,null);if(n===0)break;total+=n}return total>MAX_PACKAGE_JSON_BYTES?null:buf.subarray(0,total).toString("utf8").replace(/^\uFEFF/,"")}catch{return null}finally{closeSync(fd)}}function readPackageFacts(cwd){let empty=packageFacts({}),text=readPackageJsonText(resolve(cwd,"package.json"));if(text===null)return{pkg:empty,packageJsonFound:!1};try{let parsed=JSON.parse(text);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{pkg:empty,packageJsonFound:!1}:{pkg:packageFacts(parsed),packageJsonFound:!0}}catch{return{pkg:empty,packageJsonFound:!1}}}function detectArchetypesFromProject(cwd){let{pkg,packageJsonFound}=readPackageFacts(cwd),tree=scanFileTree(cwd,{jsProject:packageJsonFound,nextDependency:pkg.nextDependency,packageSignals:pkg.signals}),archetypes=archetypesFromSignals(mergeSignals(pkg.signals,tree.signals));return{archetypes,evidence:evidenceFor(archetypes,pkg.evidence,tree.evidence,pkg.devEvidence),truncated:tree.truncated}}import{existsSync as existsSync2}from"node:fs";import{existsSync}from"node:fs";var MAX_LISTED=10,DRIFT_MARKERS={modified:"(edited)",unrecorded:"(no pharn record)",unverifiable:"(differs from upstream)"},DRIFT_LABEL_ORDER=["modified","unrecorded","unverifiable"],CONFIG_MARKER="(will be rewritten \u2014 backed up first)";function planWriteTargets(params){let{repoDir,projectRoot,capabilities,manifest,records}=params,removals=params.removals??[],conflicts=conflictingWriteTargets({repoDir,projectRoot,capabilities,expected:manifest});if(conflicts.length===0)return{conflicts,labels:new Map,configBackedUp:!1,removals};let labels=params.labels??scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}).labels,configBackedUp=conflicts.includes(PHARN_CONFIG_FILE)&&replacedConfigBackup(projectRoot).length>0,rank=p=>{let label=labels.get(p);return label!==void 0?DRIFT_LABEL_ORDER.indexOf(label):configBackedUp&&p===PHARN_CONFIG_FILE?DRIFT_LABEL_ORDER.length:DRIFT_LABEL_ORDER.length+1};return{conflicts:[...conflicts].sort((a,b)=>rank(a)-rank(b)),labels,configBackedUp,removals}}function removalLines(removals){return removals.filter(r=>r.present).map(r=>{let n=r.backups.length;return n===0?` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name})`:` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name} \u2014 ${n} file(s) backed up to ${BACKUP_DIR}/ first)`})}function targetLines(plan,max){let{conflicts:paths,labels,configBackedUp}=plan,shown=max===void 0?paths:paths.slice(0,max),lines=shown.map(p=>{let label=labels.get(p);return label!==void 0?` \u2022 ${p} ${DRIFT_MARKERS[label]}`:configBackedUp&&p===PHARN_CONFIG_FILE?` \u2022 ${p} ${CONFIG_MARKER}`:` \u2022 ${p}`}),more=paths.length-shown.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}},YES_WAYS_FORWARD=["--yes never overwrites. Run `pharn init` in a terminal to review and confirm the overwrite,","`pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."];function existingConfigRefusal(projectRoot){return existsSync(safeJoin(projectRoot,PHARN_CONFIG_FILE))?[`pharn init --yes installs only into a project where none of its files exists yet, and ${PHARN_CONFIG_FILE} already exists.`,...YES_WAYS_FORWARD].join(`
1
+ import{archetypesFromSignals,classifyEntry,evidenceFor,isBaseDir,isNextConfigName,mergeSignals,packageFacts,recordedArchetypes}from"./chunk-IC45C3NS.js";import{installPrepared,manifestSources,prepareInstall,scanDest,upstreamSettingsCopyable}from"./chunk-ZL3KBIIS.js";import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackups,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{minCliGate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,replacedConfigBackup,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignoreReport,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,freshSettingsHookLines,preservedSettingsHookLines,upstreamSettingsSummary}from"./chunk-VWZNENTT.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import"./chunk-26RZI2K7.js";import{DEFAULT_INIT_REF,ReleaseResolveError,channelOf,resolveSource,sourceLabel}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,PHARN_CONFIG_FILE,UpstreamManifestError,absentInstallSurfaces,buildRecords,carriedSettingsRecord,collectExpectedInstallPaths,conflictingWriteTargets,detectLayout,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_AGENTS_DIR,CLAUDE_SETTINGS_FILE,FIRST_FEATURE_COMMAND,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,readJsonBounded,readPharnConfig,row,userOwnedConfigEntries,writePharnConfig}from"./chunk-5YCL3WDS.js";import{VERSION_RE,isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log as log3,note as note3,outro as outro2,spinner as spinner2}from"@clack/prompts";var LOGO=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D"];function showBanner(){console.log();for(let line of LOGO)console.log(` ${color_default.cyan(color_default.bold(line))}`);console.log(),console.log(` ${color_default.dim(`Ship features right with Claude Code \xB7 v${PHARN_VERSION}`)}`),console.log()}import{closeSync,constants,fstatSync,lstatSync,openSync,readSync,readdirSync}from"node:fs";import{join,resolve}from"node:path";var SKIP_DIRS=new Set(["node_modules",".git","dist","build",".next","out","coverage",".turbo",".vercel",".nuxt",".svelte-kit",".astro",".cache",".parcel-cache","storybook-static","__pycache__",".yarn"]),ECOSYSTEM_DIRS=new Map([["target",{siblings:["Cargo.toml","pom.xml","build.sbt"]}],["vendor",{siblings:["go.mod","composer.json","Gemfile"]}],["venv",{inside:"pyvenv.cfg"}],[".venv",{inside:"pyvenv.cfg"}]]);function isEcosystemTree(dir,name,siblingFiles){let marker=ECOSYSTEM_DIRS.get(name.toLowerCase());return marker===void 0?!1:"siblings"in marker?marker.siblings.some(file=>siblingFiles.has(file)):lstatSync(join(dir,name,marker.inside),{throwIfNoEntry:!1})?.isFile()===!0}var WALK_LIMITS=Object.freeze({maxDepth:24,maxEntries:5e4}),NO_PACKAGE_JSON={jsProject:!1,nextDependency:!1},NO_SIGNALS={ssr:!1,backend:!1,clientUi:!1},SIGNAL_KEYS=["ssr","backend","clientUi"];function scanFileTree(root,facts=NO_PACKAGE_JSON,limits=WALK_LIMITS){let acc={ssr:!1,backend:!1,clientUi:!1},evidence={},pkg=facts.packageSignals??NO_SIGNALS,budget=limits.maxEntries,truncated=!1,settled=()=>(pkg.ssr||acc.ssr)&&(pkg.backend||acc.backend),readEntries=dir=>{try{return readdirSync(dir,{withFileTypes:!0})}catch{return[]}},walk=(dir,depth,segments,names,inherited)=>{if(budget<=0&&truncated||settled())return;let entries=readEntries(dir).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0),siblingFiles=new Set(entries.filter(e=>e.isFile()).map(e=>e.name)),ctx=isBaseDir(segments)?{jsProject:facts.jsProject,baseDepth:segments.length,nextBase:segments.length===0&&facts.nextDependency||[...siblingFiles].some(isNextConfigName)}:inherited;for(let entry of entries){if(settled())return;let name=entry.name;if(entry.isSymbolicLink())continue;let isDir=entry.isDirectory();if(isDir&&SKIP_DIRS.has(name.toLowerCase())||isDir&&isEcosystemTree(dir,name,siblingFiles)||!isDir&&name.toLowerCase().startsWith(".env")||!isDir&&!entry.isFile())continue;if(depth>limits.maxDepth||budget<=0){truncated=!0;return}budget-=1;let sig=classifyEntry(name,isDir,segments,ctx);for(let key2 of SIGNAL_KEYS)sig[key2]&&evidence[key2]===void 0&&(evidence[key2]=[...names,name].join("/")+(isDir?"/":""));acc=mergeSignals(acc,sig),isDir&&walk(join(dir,name),depth+1,[...segments,name.toLowerCase()],[...names,name],ctx)}};return walk(root,0,[],[],{jsProject:facts.jsProject,baseDepth:0,nextBase:!1}),{signals:acc,evidence,truncated:truncated&&!settled()}}var MAX_PACKAGE_JSON_BYTES=4*1024*1024,PKG_OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readPackageJsonText(pkgPath){let fd;try{fd=openSync(pkgPath,PKG_OPEN_FLAGS)}catch{return null}try{if(!fstatSync(fd).isFile())return null;let buf=Buffer.alloc(MAX_PACKAGE_JSON_BYTES+1),total=0;for(;total<buf.length;){let n=readSync(fd,buf,total,buf.length-total,null);if(n===0)break;total+=n}return total>MAX_PACKAGE_JSON_BYTES?null:buf.subarray(0,total).toString("utf8").replace(/^\uFEFF/,"")}catch{return null}finally{closeSync(fd)}}function readPackageFacts(cwd){let empty=packageFacts({}),text=readPackageJsonText(resolve(cwd,"package.json"));if(text===null)return{pkg:empty,packageJsonFound:!1};try{let parsed=JSON.parse(text);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{pkg:empty,packageJsonFound:!1}:{pkg:packageFacts(parsed),packageJsonFound:!0}}catch{return{pkg:empty,packageJsonFound:!1}}}function detectArchetypesFromProject(cwd){let{pkg,packageJsonFound}=readPackageFacts(cwd),tree=scanFileTree(cwd,{jsProject:packageJsonFound,nextDependency:pkg.nextDependency,packageSignals:pkg.signals}),archetypes=archetypesFromSignals(mergeSignals(pkg.signals,tree.signals));return{archetypes,evidence:evidenceFor(archetypes,pkg.evidence,tree.evidence,pkg.devEvidence),truncated:tree.truncated}}import{existsSync as existsSync2}from"node:fs";import{existsSync}from"node:fs";var MAX_LISTED=10,DRIFT_MARKERS={modified:"(edited)",unrecorded:"(no pharn record)",unverifiable:"(differs from upstream)"},DRIFT_LABEL_ORDER=["modified","unrecorded","unverifiable"],CONFIG_MARKER="(will be rewritten \u2014 backed up first)";function planWriteTargets(params){let{repoDir,projectRoot,capabilities,manifest,records}=params,removals=params.removals??[],conflicts=conflictingWriteTargets({repoDir,projectRoot,capabilities,expected:manifest});if(conflicts.length===0)return{conflicts,labels:new Map,configBackedUp:!1,removals};let labels=params.labels??scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}).labels,configBackedUp=conflicts.includes(PHARN_CONFIG_FILE)&&replacedConfigBackup(projectRoot).length>0,rank=p=>{let label=labels.get(p);return label!==void 0?DRIFT_LABEL_ORDER.indexOf(label):configBackedUp&&p===PHARN_CONFIG_FILE?DRIFT_LABEL_ORDER.length:DRIFT_LABEL_ORDER.length+1};return{conflicts:[...conflicts].sort((a,b)=>rank(a)-rank(b)),labels,configBackedUp,removals}}function removalLines(removals){return removals.filter(r=>r.present).map(r=>{let n=r.backups.length;return n===0?` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name})`:` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name} \u2014 ${n} file(s) backed up to ${BACKUP_DIR}/ first)`})}function targetLines(plan,max){let{conflicts:paths,labels,configBackedUp}=plan,shown=max===void 0?paths:paths.slice(0,max),lines=shown.map(p=>{let label=labels.get(p);return label!==void 0?` \u2022 ${p} ${DRIFT_MARKERS[label]}`:configBackedUp&&p===PHARN_CONFIG_FILE?` \u2022 ${p} ${CONFIG_MARKER}`:` \u2022 ${p}`}),more=paths.length-shown.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}},YES_WAYS_FORWARD=["--yes never overwrites. Run `pharn init` in a terminal to review and confirm the overwrite,","`pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."];function existingConfigRefusal(projectRoot){return existsSync(safeJoin(projectRoot,PHARN_CONFIG_FILE))?[`pharn init --yes installs only into a project where none of its files exists yet, and ${PHARN_CONFIG_FILE} already exists.`,...YES_WAYS_FORWARD].join(`
2
2
  `):null}function refuseExistingTargets(plan){if(plan.conflicts.length===0)return;let n=plan.conflicts.length;throw new OverwriteRefusedError([`pharn init --yes installs only into a project where none of its files exists yet, and ${n} of them already exist:`,...targetLines(plan,MAX_LISTED),...YES_WAYS_FORWARD].join(`
3
3
  `))}function capabilityKey(cap2){return`${cap2.role}:${cap2.name}`}var UNREADABLE_REASON_MAX=200;function readPreviousConfig(cwd){let fingerprint=configFingerprint(cwd);try{let config=readPharnConfig(cwd),unreadable=config===null&&fingerprint!=="absent"?describeUnreadConfig(cwd):null;return{fingerprint,config,unreadable}}catch(err){let reason=escapeUnsafe(firstSentence(errorMessage(err)));return{fingerprint,config:null,unreadable:terminalSafe(reason,{max:UNREADABLE_REASON_MAX})}}}function firstSentence(text){let quoted=!1;for(let i=0;i<text.length;i++){let ch=text[i];if(ch==="\\")i++;else if(ch==='"')quoted=!quoted;else if(ch==="."&&!quoted&&(i+1===text.length||/\s/.test(text[i+1])))return text.slice(0,i)}return text}function describeUnreadConfig(cwd){let read=readJsonBounded(configPath(cwd));if(read.kind==="unusable")return`it ${read.reason}`;if(read.kind!=="ok")return"it changed while init was reading it";let raw=read.value;return isPlainObject(raw)?typeof raw.skillsVersion!="string"?'it has no "skillsVersion" string':'it has neither a "capabilities" key nor a "modules" array':"it is not a JSON object"}function previousConfigLines(previous){return previous.unreadable===null?[]:[` the previous pharn.config.json could not be read (${previous.unreadable}); nothing is carried over, so manual capabilities will be dropped`]}function carryOver(previous,index,resolved){let inIndex=new Set(index.capabilities.map(capabilityKey)),frozen=new Set(index.unknown.map(capabilityKey)),selected=new Set(resolved.selected.map(capabilityKey)),manualKeys=new Set,kept=[],extra=[],gone=[],dropped=[],seen=new Set;for(let cap2 of previous?.capabilities??[]){let k=capabilityKey(cap2);if(!seen.has(k)){if(seen.add(k),frozen.has(k)){kept.push({...cap2});continue}if(cap2.source!=="manual"){selected.has(k)||dropped.push({cap:cap2,reason:cap2.source==="auto"||inIndex.has(k)?"dropped-unselected":"dropped-gone"});continue}if(!inIndex.has(k)){gone.push(cap2),dropped.push({cap:cap2,reason:"dropped-gone"});continue}manualKeys.add(k),selected.has(k)||extra.push(cap2)}}return{manualKeys,kept,extra,gone,dropped,previousStamp:previous?{skillsVersion:previous.skillsVersion,commit:previous.commit}:null}}function planInitRemovals(cwd,carry,records){let drops=carry.dropped??[];return drops.length===0?[]:planCapabilityRemovals({cwd,paths:layoutPaths("pharn"),drops,records,command:"init"})}function resolveInitSelection(params){let{cwd,archetypes,index}=params,resolved=resolveCapabilities(archetypes,index),previous=readPreviousConfig(cwd),carry=carryOver(previous.config,index,resolved),extraKeys=new Set(carry.extra.map(capabilityKey)),selection=carry.extra.length?{selected:[...resolved.selected,...carry.extra.map(c=>({name:c.name,role:c.role,matched:"manual"}))],skipped:resolved.skipped.filter(s=>!extraKeys.has(capabilityKey(s)))}:resolved;return{previous,carry,selection}}function reinstallBaseline(cwd,carry){return carry.previousStamp===null?null:recordsBaseline(readRecords(cwd)).records}function initRecordedPaths(params){let{cwd,manifest,carry,capabilities,layout,baseline}=params,kept=carry.kept.length===0||baseline===null?{}:recordsUnderCapabilities(baseline,layoutPaths(layout),carry.kept),orphans=findOrphans({projectRoot:cwd,records:baseline,expected:manifest,capabilities:[...capabilities,...carry.kept],frozen:carry.kept}).records;return[...Object.keys(kept),...Object.keys(orphans),...manifest.keys()]}function readCarriedEntries(cwd){let read=readJsonBounded(configPath(cwd));return read.kind!=="ok"?{}:isPlainObject(read.value)?userOwnedConfigEntries(read.value):{}}function previousChannelLines(params){let{previous,channel,explicit,source}=params;if(previous===null||explicit)return[];if(channel!=="latest"||channelOf(previous)!=="main")return[];let lines=[" previously followed: main (the pharn-oss tip) \u2014 pass --ref main to keep it"],installed=previous.skillsVersion;return source.kind==="release"&&typeof installed=="string"&&versionStatus({installed,latest:source.version}).ahead&&lines.push(` installed v${terminalSafe(installed,{max:40})} is newer than release ${source.tag} \u2014 this re-install goes back to it`),lines}function buildInitPlan(params){let{repoDir,cwd,sha,source,channel,archetypes,index,chosen}=params,origin=params.origin??{kind:"detected",evidence:[],truncated:!1},{selection,carry}=chosen,layout=detectLayout(repoDir),manifest=collectExpectedInstallPaths({repoDir,capabilities:selection.selected}),prepared=prepareInstall(repoDir,cwd,selection.selected,manifest),baseline=reinstallBaseline(cwd,carry),removals=planInitRemovals(cwd,carry,baseline),scan=scanDest({repoDir,projectRoot:cwd,rels:[...manifest.keys()],sources:manifestSources(repoDir,manifest),records:baseline}),writeTargets=planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest,records:baseline,removals,labels:scan.labels}),{conflicts,labels,configBackedUp}=writeTargets,existing=new Set(conflicts),targets=[...new Set([...manifest.keys(),PHARN_CONFIG_FILE])].sort().map(rel=>({rel,action:existing.has(rel)?"overwrite":"create",label:labels.get(rel)??(configBackedUp&&rel===PHARN_CONFIG_FILE?"rewritten":null)})),backups=[...new Set([...[...labels.keys()].sort(),...configBackedUp?[PHARN_CONFIG_FILE]:[],...removalBackups(removals)])],settingsPreserved=existsSync2(safeJoin(cwd,CLAUDE_SETTINGS_FILE)),upstreamModels=readUpstreamModels(repoDir);return{report:{archetypes,archetypeOrigin:origin,previousArchetypes:recordedArchetypes(chosen.previous.config?.archetypes),channelLines:previousChannelLines({previous:chosen.previous.config,channel,explicit:params.refExplicit??!1,source}),previousConfigLines:previousConfigLines(chosen.previous),channel,source,commit:sha,skillsVersion:readSkillsVersion(repoDir),layout,selection,carry:{manual:[...carry.manualKeys].sort(),extra:carry.extra,kept:[...carry.kept],gone:carry.gone},unknownCapabilities:index.unknown,targets,conflicts,configBackedUp,removals,backups,counts:{create:targets.length-existing.size,overwrite:existing.size,backup:backups.length},settingsPreserved,hookWiring:settingsPreserved?diffHookWiring(repoDir,cwd):null,freshSettings:!settingsPreserved&&upstreamSettingsCopyable(repoDir)?upstreamSettingsSummary(repoDir):null,models:upstreamModels.kind==="ok"?{outcome:"copy",reasons:[]}:upstreamModels.kind==="absent"?{outcome:"none",reasons:[]}:{outcome:"rejected",reasons:upstreamModels.reasons},absentUpstream:absentInstallSurfaces({repoDir}),carriedConfigKeys:Object.keys(readCarriedEntries(cwd)),gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,initRecordedPaths({cwd,manifest,carry,capabilities:selection.selected,layout,baseline}))},apply:{prepared,drifted:scan.drifted,seen:scan.seen,baseline,removals,targets:writeTargets,fingerprint:chosen.previous.fingerprint}}}var INIT_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,MAX_EVIDENCE=200,key=c=>`${c.role}:${c.name}`;function buildInitReport(p){return{schemaVersion:INIT_SCHEMA_VERSION,command:"init",dryRun:!0,status:"planned",channel:p.channel,source:{kind:p.source.kind,tag:p.source.kind==="release"?p.source.tag:null},commit:p.commit,skillsVersion:p.skillsVersion,layout:p.layout,archetypes:[...p.archetypes],archetypeSource:p.archetypeOrigin.kind,detectedArchetypes:p.archetypeOrigin.kind==="flag"?[...p.archetypeOrigin.detected]:null,archetypeEvidence:p.archetypeOrigin.evidence.map(e=>({archetype:e.archetype,source:e.source,value:e.source==="dependency"||e.source==="devDependency"?e.name:e.source==="path"?cap(e.path,MAX_EVIDENCE):null})),...p.archetypeOrigin.truncated?{detectionTruncated:!0}:{},capabilities:{selected:p.selection.selected.map(c=>({role:c.role,name:c.name,matched:Array.isArray(c.matched)?[...c.matched]:c.matched})),skipped:p.selection.skipped.map(c=>({role:c.role,name:c.name,reason:cap(c.reason,MAX_REASON)})),carried:{manual:[...p.carry.manual],kept:p.carry.kept.map(key),dropped:p.carry.gone.map(key)},...p.removals.length>0?{removals:p.removals.map(r=>({role:r.cap.role,name:r.cap.name,reason:r.reason,dir:r.dir,present:r.present,backups:[...r.backups]}))}:{}},unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),targets:p.targets.map(t=>({rel:t.rel,action:t.action,label:t.label})),backups:[...p.backups],counts:{create:p.counts.create,overwrite:p.counts.overwrite,backup:p.counts.backup},yesWouldProceed:p.counts.overwrite===0,settings:{preserved:p.settingsPreserved},hooks:p.hookWiring===null?null:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null,...p.hookWiring.replace?.length?{replace:p.hookWiring.replace}:{}},...p.freshSettings===null?{}:{settingsHooks:p.freshSettings.status==="ok"?{status:"ok",hooks:p.freshSettings.hooks.map(e=>({event:e.event,matcher:e.matcher,command:e.command,args:[...e.args]})),otherKeys:p.freshSettings.otherKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD)),skipped:p.freshSettings.skipped}:{status:"unreadable",reason:cap(p.freshSettings.reason,MAX_REASON)}},...p.absentUpstream.length>0?{absentUpstream:p.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))}:{},models:{outcome:p.models.outcome,reasons:p.models.reasons.map(r=>cap(r,MAX_REASON))},config:{carriedKeys:p.carriedConfigKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD))},...gitignoreKey(p.gitignore),...prettierignoreKey(p.prettierignore)}}function prettierignoreKey(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey(plan){let report=gitignoreReport(plan);return report===null?{}:{gitignore:report}}import{existsSync as existsSync3}from"node:fs";import{dirname,join as join2,resolve as resolve2}from"node:path";function runGitPrereq(opts={}){let cwd=process.cwd();if(!existsSync3(resolve2(cwd,".git"))){let root=findAncestorGitRoot(cwd);fail(root===null?`git not found.
4
4
  Run: git init && git add -A && git commit -m 'init'
@@ -1,4 +1,4 @@
1
- import{NODE_FLOOR,cap,checkModelsBlock,modelsCheckerCommand,modelsLabelLines,nodeFloorLines,nodeFloorStatus,planPrettierignore,prettierignoreLines,prettierignoreReport,resolveStageRows,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringFails,hookWiringLines,orphanNoteLines}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveLatestReleaseVersion,resolveSource,sourceDescription,sourceLabel}from"./chunk-256AIEPX.js";import{absentInstallSurfaces,collectExpectedInstallPaths,contentHash,fetchRemoteSkillsVersion,layoutPaths,readRecords,readSkillsVersion,recordsBaseline,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{REPO}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{color_default,loadArchetypeConfig,row}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log,note,outro,spinner}from"@clack/prompts";var STATUS_SCHEMA_VERSION=1,MAX_RED_DETAIL=300,MAX_UNKNOWN_FIELD=200,MAX_RUNNING_NODE=40;function strictFails(input){let{outdated,diff,hooks,absentUpstream}=input;return outdated||absentUpstream!==void 0&&absentUpstream.length>0||diff!==void 0&&(diff.modified.length>0||diff.missing.length>0||diff.unreadable.length>0)||hooks!==void 0&&hookWiringFails(hooks)}function modelsReport(models){if(models===void 0)return null;let check=checkModelsBlock(models);return check.kind==="invalid"?{conversionNeeded:!1,verdict:"invalid",stages:null,reds:check.reds.map(r=>({kind:r.kind,detail:cap(r.detail,MAX_RED_DETAIL)}))}:check.kind==="no-stages"?{conversionNeeded:!1,verdict:"no-stages",stages:null,reds:null}:{conversionNeeded:!1,verdict:"valid",stages:resolveStageRows(check.stages),reds:null}}function buildStatusReport(input){let{node,config,drift}=input,layout={recorded:"pharn",upstream:drift===null?null:"pharn"},{ahead,outdated}=versionStatus({installed:config.skillsVersion,latest:input.latest});return{schemaVersion:STATUS_SCHEMA_VERSION,node:{floor:NODE_FLOOR,running:node.kind==="unparseable"?node.raw===void 0?null:cap(node.raw,MAX_RUNNING_NODE):cap(node.current,MAX_RUNNING_NODE),status:node.kind},version:{installed:config.skillsVersion,latest:input.latest,channel:input.channel,source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},ahead,outdated},archetypes:config.archetypes??[],capabilities:{count:(config.capabilities??[]).length},layout,drift:drift===null?null:{modified:drift.diff.modified,missing:drift.diff.missing,unreadable:drift.diff.unreadable,okCount:drift.diff.okCount,absentUpstream:drift.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))},hooks:drift===null?null:{status:drift.hooks.status,missing:drift.hooks.missing,localOnly:drift.hooks.localOnly??[],file:drift.hooks.file??null,reason:drift.hooks.reason??null,...drift.hooks.replace?.length?{replace:drift.hooks.replace}:{}},models:modelsReport(config.models),unknownCapabilities:drift===null?null:drift.unknown.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),orphans:drift===null||drift.orphans===null?null:drift.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_RED_DETAIL)}:{}})),prettierignore:input.prettierignore===null?null:prettierignoreReport(input.prettierignore),strict:{enabled:input.strict,failed:input.strict&&strictFails({outdated,diff:drift?.diff,hooks:drift?.hooks,absentUpstream:drift?.absentUpstream})}}}function serializeStatusReport(report){return serializeJsonReport(report)}function diffInstalledCapabilities(params){let{repoDir,projectRoot,capabilities}=params,expected=collectExpectedInstallPaths({repoDir,capabilities});return compareExpected(expected,projectRoot)}function compareExpected(expected,baseDir){let modified=[],missing=[],unreadable=[],okCount=0;for(let[rel,repoPath]of expected){let state=readDiskState(baseDir,rel);state.kind==="absent"?missing.push(rel):state.kind==="unreadable"?unreadable.push({rel,reason:state.reason}):state.hash===contentHash(repoPath)?okCount+=1:modified.push(rel)}return modified.sort(),missing.sort(),unreadable.sort((a,b)=>+(a.rel>b.rel)-+(a.rel<b.rel)),{modified,missing,unreadable,okCount}}async function runStatus(opts={}){let strict=opts.strict??!1,drift=opts.drift??!0,json=opts.json??!1;json||intro("pharn status");let cwd=process.cwd(),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let node=nodeFloorStatus(process.versions.node);json||note(nodeFloorLines(node).join(`
1
+ import{NODE_FLOOR,cap,checkModelsBlock,modelsCheckerCommand,modelsLabelLines,nodeFloorLines,nodeFloorStatus,planPrettierignore,prettierignoreLines,prettierignoreReport,resolveStageRows,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringFails,hookWiringLines,orphanNoteLines}from"./chunk-VWZNENTT.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveLatestReleaseVersion,resolveSource,sourceDescription,sourceLabel}from"./chunk-256AIEPX.js";import{absentInstallSurfaces,collectExpectedInstallPaths,contentHash,fetchRemoteSkillsVersion,layoutPaths,readRecords,readSkillsVersion,recordsBaseline,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{REPO}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{color_default,loadArchetypeConfig,row}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log,note,outro,spinner}from"@clack/prompts";var STATUS_SCHEMA_VERSION=1,MAX_RED_DETAIL=300,MAX_UNKNOWN_FIELD=200,MAX_RUNNING_NODE=40;function strictFails(input){let{outdated,diff,hooks,absentUpstream}=input;return outdated||absentUpstream!==void 0&&absentUpstream.length>0||diff!==void 0&&(diff.modified.length>0||diff.missing.length>0||diff.unreadable.length>0)||hooks!==void 0&&hookWiringFails(hooks)}function modelsReport(models){if(models===void 0)return null;let check=checkModelsBlock(models);return check.kind==="invalid"?{conversionNeeded:!1,verdict:"invalid",stages:null,reds:check.reds.map(r=>({kind:r.kind,detail:cap(r.detail,MAX_RED_DETAIL)}))}:check.kind==="no-stages"?{conversionNeeded:!1,verdict:"no-stages",stages:null,reds:null}:{conversionNeeded:!1,verdict:"valid",stages:resolveStageRows(check.stages),reds:null}}function buildStatusReport(input){let{node,config,drift}=input,layout={recorded:"pharn",upstream:drift===null?null:"pharn"},{ahead,outdated}=versionStatus({installed:config.skillsVersion,latest:input.latest});return{schemaVersion:STATUS_SCHEMA_VERSION,node:{floor:NODE_FLOOR,running:node.kind==="unparseable"?node.raw===void 0?null:cap(node.raw,MAX_RUNNING_NODE):cap(node.current,MAX_RUNNING_NODE),status:node.kind},version:{installed:config.skillsVersion,latest:input.latest,channel:input.channel,source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},ahead,outdated},archetypes:config.archetypes??[],capabilities:{count:(config.capabilities??[]).length},layout,drift:drift===null?null:{modified:drift.diff.modified,missing:drift.diff.missing,unreadable:drift.diff.unreadable,okCount:drift.diff.okCount,absentUpstream:drift.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))},hooks:drift===null?null:{status:drift.hooks.status,missing:drift.hooks.missing,localOnly:drift.hooks.localOnly??[],file:drift.hooks.file??null,reason:drift.hooks.reason??null,...drift.hooks.replace?.length?{replace:drift.hooks.replace}:{}},models:modelsReport(config.models),unknownCapabilities:drift===null?null:drift.unknown.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),orphans:drift===null||drift.orphans===null?null:drift.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_RED_DETAIL)}:{}})),prettierignore:input.prettierignore===null?null:prettierignoreReport(input.prettierignore),strict:{enabled:input.strict,failed:input.strict&&strictFails({outdated,diff:drift?.diff,hooks:drift?.hooks,absentUpstream:drift?.absentUpstream})}}}function serializeStatusReport(report){return serializeJsonReport(report)}function diffInstalledCapabilities(params){let{repoDir,projectRoot,capabilities}=params,expected=collectExpectedInstallPaths({repoDir,capabilities});return compareExpected(expected,projectRoot)}function compareExpected(expected,baseDir){let modified=[],missing=[],unreadable=[],okCount=0;for(let[rel,repoPath]of expected){let state=readDiskState(baseDir,rel);state.kind==="absent"?missing.push(rel):state.kind==="unreadable"?unreadable.push({rel,reason:state.reason}):state.hash===contentHash(repoPath)?okCount+=1:modified.push(rel)}return modified.sort(),missing.sort(),unreadable.sort((a,b)=>+(a.rel>b.rel)-+(a.rel<b.rel)),{modified,missing,unreadable,okCount}}async function runStatus(opts={}){let strict=opts.strict??!1,drift=opts.drift??!0,json=opts.json??!1;json||intro("pharn status");let cwd=process.cwd(),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let node=nodeFloorStatus(process.versions.node);json||note(nodeFloorLines(node).join(`
2
2
  `),"NODE");let proxyNotice=detectProxyNotice(process.env);if(proxyNotice){let message=proxyNoticeMessage(proxyNotice);json?logErrorPlain(message):log.warn(message)}let channel=channelOf(config),s=json?null:spinner(),input;if(drift){s?.start(`Comparing against ${REPO}`);let repo;try{repo=await fetchRepo(await resolveSource(channel)),s?.stop(`Compared against ${sourceLabel(repo.source)}`)}catch(err){throw s?.stop(`Failed to reach ${REPO}`),CliError.failure(err,{json})}try{input=cloneInput(repo,{node,config,channel,strict},cwd)}catch(err){throw CliError.failure(err,{json})}finally{repo.cleanup()}}else{s?.start("Checking for updates");let found;try{found=await latestWithoutClone(channel),s?.stop(`Latest skills v${found.latest}`)}catch(err){throw s?.stop("Failed to check for updates"),CliError.failure(err,{json})}input={node,config,channel,...found,drift:null,prettierignore:statusPrettierignore(cwd),strict}}let report=buildStatusReport(input);if(json){console.log(serializeStatusReport(report)),report.strict.failed&&(process.exitCode=1);return}if(renderStatus(report,input),report.strict.failed)throw CliError.reported();outro(color_default.dim(drift?"Read-only \u2014 nothing changed.":"Read-only \u2014 nothing changed (drift check skipped)."))}function cloneInput(repo,base,cwd){let{config}=base,index=parseCapabilityIndex(repo.dir),frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`));return{...base,latest:readSkillsVersion(repo.dir),source:repo.source,drift:{diff:diffInstalledCapabilities({repoDir:repo.dir,projectRoot:cwd,capabilities:(config.capabilities??[]).filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`))}),absentUpstream:absentInstallSurfaces({repoDir:repo.dir}),hooks:diffHookWiring(repo.dir,cwd),unknown:index.unknown,orphans:statusOrphans(repo.dir,cwd,config,frozen)},prettierignore:statusPrettierignore(cwd)}}function renderStatus(report,input){printArchetypeVersion(report,input.source),printModels(input.config),printPrettierignore(input.prettierignore);let drift=input.drift;if(drift===null||report.drift===null)return;let unknownWarning=unknownCapabilitiesWarning(drift.unknown);unknownWarning&&log.warn(unknownWarning),printDriftSection(report.drift,sourceLabel(input.source));let orphanLines=orphanNoteLines(report.orphans??[]);orphanLines&&note(orphanLines.join(`
3
3
  `),"ORPHANED");let hookLines=hookWiringLines(drift.hooks);hookLines&&note(hookLines.join(`
4
4
  `),"HOOKS")}async function latestWithoutClone(channel){if(channel==="latest"){let release=await resolveLatestReleaseVersion();return{latest:release.version,source:release}}return{latest:await fetchRemoteSkillsVersion(),source:await resolveSource("main")}}function channelRow(channel){return channel==="latest"?row("Channel","latest \u2014 verified releases"):`${row("Channel","main \u2014 the pharn-oss tip")} ${color_default.dim("(`pharn update --ref latest` follows verified releases)")}`}function printArchetypeVersion(report,source){let{ahead,outdated,latest,channel}=report.version,installed=terminalSafe(report.version.installed),aheadNote=source.kind==="release"?`(ahead of the latest verified release v${latest} \u2014 installed from main)`:`(ahead of pharn-oss main (v${latest}) \u2014 main has moved back; \`pharn update --force\` downgrades)`,outdatedNote=source.kind==="release"?`(newer verified release ${source.tag} \u2014 run \`pharn update\`)`:"(update available, run `pharn update`)",currentNote=source.kind==="release"?"(no newer verified release)":"(up to date)",skillsLine=ahead?`${row("Skills version",`v${installed}`)} ${color_default.dim(aheadNote)}`:outdated?`${row("Skills version",`v${installed} \u2192 v${latest}`)} ${color_default.dim(outdatedNote)}`:`${row("Skills version",`v${installed}`)} ${color_default.dim(currentNote)}`;note([skillsLine,channelRow(channel),row("Source",sourceDescription(source)),"",row("Archetypes",report.archetypes.join(", ")||"(none)"),row("Capabilities",String(report.capabilities.count))].join(`
@@ -1,4 +1,4 @@
1
- import{BACKUP_DIR,LOCK_DIR,ProjectLockedError,backupDirIgnored,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{displayHook,hooksReferencing}from"./chunk-7UE7LQQP.js";import"./chunk-26RZI2K7.js";import{MODELS_RECORD_KEY,RECORDS_FILE,contentHash,findSymlinkComponent,isInstallRootPath,readRecords,recordsBaseline,recordsPath,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{CLAUDE_HOOKS_DIR,CLAUDE_SETTINGS_FILE}from"./chunk-W3TXAEBT.js";import"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,loadArchetypeConfig}from"./chunk-5YCL3WDS.js";import{safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe}from"./chunk-A77BLCF4.js";import{lstatSync as lstatSync2,readdirSync,rmdirSync,unlinkSync}from"node:fs";import{posix as posix2}from"node:path";import{confirm,intro,isCancel,note,outro}from"@clack/prompts";import{lstatSync}from"node:fs";import{posix}from"node:path";function planUninstall(projectRoot,records){let plan={delete:[],edited:[],unverifiable:[],absent:[],outside:[],unsafe:[]};for(let rel of Object.keys(records).sort()){if(rel===MODELS_RECORD_KEY)continue;if(rel!==CLAUDE_SETTINGS_FILE&&!isInstallRootPath(rel)){plan.outside.push(rel);continue}let verdict=classify(projectRoot,rel,records[rel]);typeof verdict=="object"?plan.unsafe.push(verdict):plan[verdict].push(rel)}return plan}function reclassifyDeletes(projectRoot,records,plan){let subset={};for(let rel of plan.delete)subset[rel]=records[rel];let now=planUninstall(projectRoot,subset),merged=(a,b)=>[...a,...b].sort();return{delete:now.delete,edited:merged(plan.edited,now.edited),unverifiable:merged(plan.unverifiable,now.unverifiable),absent:merged(plan.absent,now.absent),outside:plan.outside,unsafe:[...plan.unsafe,...now.unsafe]}}function classify(projectRoot,rel,recorded){let linked;try{let parent=posix.dirname(rel);linked=parent==="."?null:findSymlinkComponent(projectRoot,parent)}catch{return"absent"}if(linked!==null)return{rel,component:linked};let abs=safeJoin(projectRoot,rel),stat;try{stat=lstatSync(abs,{throwIfNoEntry:!1})}catch(err){return err.code==="ENOTDIR"?"absent":"unverifiable"}if(stat===void 0)return"absent";if(!stat.isFile())return"unverifiable";let hash;try{hash=contentHash(abs)}catch{return"unverifiable"}return hash===recorded?"delete":"edited"}var MAX_LISTED=10,UninstallError=class extends Error{constructor(message){super(message),this.name="UninstallError"}};async function runUninstall(opts={}){intro("pharn uninstall");let cwd=process.cwd(),result;try{result=await withProjectLock(cwd,"uninstall",()=>uninstallProject(cwd,opts))}catch(err){throw err instanceof ProjectLockedError||err instanceof UninstallError?CliError.error(err.message):err}result!==null&&(reportResult(cwd,result,finishPharnDir(cwd)),outro(`${color_default.green("\u2714")} PHARN was uninstalled.`))}async function uninstallProject(cwd,opts){if(lstatSync2(configPath(cwd),{throwIfNoEntry:!1})===void 0)return outro(`PHARN is not installed here (no ${CONFIG_FILENAME}). Nothing was removed.`),null;let fingerprint=configFingerprint(cwd);warnIfOlderCli(loadArchetypeConfig(cwd));let records=usableRecords(cwd);if(typeof records=="string")throw CliError.error(records);let preview=planUninstall(cwd,records);if(preview.unsafe.length>0)throw CliError.error(unsafeMessage(preview));if(note(planLines(preview,settingsRecorded(records)).join(`
1
+ import{BACKUP_DIR,LOCK_DIR,ProjectLockedError,backupDirIgnored,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{displayHook,hooksReferencing}from"./chunk-VWZNENTT.js";import"./chunk-26RZI2K7.js";import{MODELS_RECORD_KEY,RECORDS_FILE,contentHash,findSymlinkComponent,isInstallRootPath,readRecords,recordsBaseline,recordsPath,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{CLAUDE_HOOKS_DIR,CLAUDE_SETTINGS_FILE}from"./chunk-W3TXAEBT.js";import"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,loadArchetypeConfig}from"./chunk-5YCL3WDS.js";import{safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe}from"./chunk-A77BLCF4.js";import{lstatSync as lstatSync2,readdirSync,rmdirSync,unlinkSync}from"node:fs";import{posix as posix2}from"node:path";import{confirm,intro,isCancel,note,outro}from"@clack/prompts";import{lstatSync}from"node:fs";import{posix}from"node:path";function planUninstall(projectRoot,records){let plan={delete:[],edited:[],unverifiable:[],absent:[],outside:[],unsafe:[]};for(let rel of Object.keys(records).sort()){if(rel===MODELS_RECORD_KEY)continue;if(rel!==CLAUDE_SETTINGS_FILE&&!isInstallRootPath(rel)){plan.outside.push(rel);continue}let verdict=classify(projectRoot,rel,records[rel]);typeof verdict=="object"?plan.unsafe.push(verdict):plan[verdict].push(rel)}return plan}function reclassifyDeletes(projectRoot,records,plan){let subset={};for(let rel of plan.delete)subset[rel]=records[rel];let now=planUninstall(projectRoot,subset),merged=(a,b)=>[...a,...b].sort();return{delete:now.delete,edited:merged(plan.edited,now.edited),unverifiable:merged(plan.unverifiable,now.unverifiable),absent:merged(plan.absent,now.absent),outside:plan.outside,unsafe:[...plan.unsafe,...now.unsafe]}}function classify(projectRoot,rel,recorded){let linked;try{let parent=posix.dirname(rel);linked=parent==="."?null:findSymlinkComponent(projectRoot,parent)}catch{return"absent"}if(linked!==null)return{rel,component:linked};let abs=safeJoin(projectRoot,rel),stat;try{stat=lstatSync(abs,{throwIfNoEntry:!1})}catch(err){return err.code==="ENOTDIR"?"absent":"unverifiable"}if(stat===void 0)return"absent";if(!stat.isFile())return"unverifiable";let hash;try{hash=contentHash(abs)}catch{return"unverifiable"}return hash===recorded?"delete":"edited"}var MAX_LISTED=10,UninstallError=class extends Error{constructor(message){super(message),this.name="UninstallError"}};async function runUninstall(opts={}){intro("pharn uninstall");let cwd=process.cwd(),result;try{result=await withProjectLock(cwd,"uninstall",()=>uninstallProject(cwd,opts))}catch(err){throw err instanceof ProjectLockedError||err instanceof UninstallError?CliError.error(err.message):err}result!==null&&(reportResult(cwd,result,finishPharnDir(cwd)),outro(`${color_default.green("\u2714")} PHARN was uninstalled.`))}async function uninstallProject(cwd,opts){if(lstatSync2(configPath(cwd),{throwIfNoEntry:!1})===void 0)return outro(`PHARN is not installed here (no ${CONFIG_FILENAME}). Nothing was removed.`),null;let fingerprint=configFingerprint(cwd);warnIfOlderCli(loadArchetypeConfig(cwd));let records=usableRecords(cwd);if(typeof records=="string")throw CliError.error(records);let preview=planUninstall(cwd,records);if(preview.unsafe.length>0)throw CliError.error(unsafeMessage(preview));if(note(planLines(preview,settingsRecorded(records)).join(`
2
2
  `),"PLAN"),!opts.yes){if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("`pharn uninstall` asks for confirmation, and this is not an interactive terminal. Re-run it in a terminal, or pass --yes to uninstall without asking. Nothing was removed.");let ok=await confirm({message:`Uninstall PHARN \u2014 delete ${preview.delete.length} file(s), ${RECORDS_FILE} and ${CONFIG_FILENAME}?`,initialValue:!1});if(isCancel(ok)||ok!==!0)throw CliError.cancel()}return applyUninstall(cwd,records,preview,fingerprint)}function usableRecords(cwd){let read=readRecords(cwd),baseline=recordsBaseline(read);return baseline.records!==null?baseline.records:`Cannot uninstall: ${read.kind==="invalid"?escapeUnsafe(read.message):`there is no ${RECORDS_FILE}`}. ${RECORDS_FILE} is the only proof of which files pharn wrote, so without a usable one nothing was removed. Remove PHARN by hand instead (docs/troubleshooting.md, "Removing PHARN by hand").`}function unsafeMessage(plan){let first=plan.unsafe[0];return`Refusing to uninstall: ${escapeUnsafe(first.component)} is a symbolic link, so deleting ${escapeUnsafe(first.rel)} through it would delete a file OUTSIDE the project. Nothing was removed.`}async function applyUninstall(cwd,records,planned,fingerprint){assertConfigFingerprintUnchanged(cwd,fingerprint,"uninstall");let proof=usableRecords(cwd);if(typeof proof=="string")throw new UninstallError(proof);let plan=reclassifyDeletes(cwd,records,planned);if(plan.unsafe.length>0)throw new UninstallError(unsafeMessage(plan));let backupDir;try{backupDir=createBackup(cwd,[CONFIG_FILENAME])}catch(err){throw new UninstallError(`Could not back up ${CONFIG_FILENAME} before uninstalling: ${errorMessage(err).replace(/\.$/,"")}. Nothing was removed.`)}printBackupNotice({dir:backupDir,saved:CONFIG_FILENAME,gitignored:backupDirIgnored(cwd)});let deleted=[];for(let rel of plan.delete)try{unlinkSync(safeJoin(cwd,rel)),deleted.push(rel)}catch(err){if(err.code==="ENOENT")continue;throw new UninstallError(`Could not delete ${escapeUnsafe(rel)}: ${errorMessage(err).replace(/\.$/,"")}. ${deleted.length} file(s) were deleted before it; ${RECORDS_FILE} and ${CONFIG_FILENAME} were kept, so re-running \`pharn uninstall\` continues from here.`)}let{removedDirs,keptDirs}=removeEmptyDirs(cwd,deleted);return unlinkIfPresent(recordsPath(cwd),RECORDS_FILE),unlinkIfPresent(configPath(cwd),CONFIG_FILENAME),{plan,deleted,removedDirs,keptDirs,backupDir,records}}function unlinkIfPresent(abs,label){try{unlinkSync(abs)}catch(err){if(err.code==="ENOENT")return;throw new UninstallError(`Could not delete ${label}: ${errorMessage(err).replace(/\.$/,"")}. Every file pharn could prove it wrote is already gone; delete ${label} yourself to finish.`)}}function removeEmptyDirs(cwd,deleted){let candidates=new Set;for(let rel of deleted)for(let dir=posix2.dirname(rel);dir!==".";dir=posix2.dirname(dir))candidates.add(dir);let deepestFirst=[...candidates].sort((a,b)=>b.split("/").length-a.split("/").length||a.localeCompare(b)),removedDirs=[],keptDirs=[],blocked=new Set;for(let dir of deepestFirst)if(!blocked.has(dir))try{rmdirSync(safeJoin(cwd,dir)),removedDirs.push(dir)}catch(err){if(err.code==="ENOENT")continue;keptDirs.push(dir);for(let up=posix2.dirname(dir);up!==".";up=posix2.dirname(up))blocked.add(up)}return{removedDirs:removedDirs.sort(),keptDirs:keptDirs.sort()}}function listed(rels){let shown=rels.slice(0,MAX_LISTED).map(r=>` \u2022 ${escapeUnsafe(r)}`),more=rels.length-MAX_LISTED;return more>0?[...shown,` \u2026and ${more} more`]:shown}function settingsRecorded(records){return Object.hasOwn(records,CLAUDE_SETTINGS_FILE)}function untouchedLine(settingsIsRecorded){return`${settingsIsRecorded?"":`${CLAUDE_SETTINGS_FILE}, `}.claude/settings.local.json, every ${BACKUP_DIR}/ directory and the lines pharn added to .gitignore and .prettierignore are left untouched.`}function planLines(plan,settingsIsRecorded){let lines=[`Delete ${plan.delete.length} file(s) pharn installed and nobody changed.`];return plan.edited.length>0&&lines.push(`Keep ${plan.edited.length} file(s) you changed (they stay where they are):`,...listed(plan.edited)),plan.unverifiable.length>0&&lines.push(`Keep ${plan.unverifiable.length} path(s) that cannot be verified (not a regular file, or unreadable):`,...listed(plan.unverifiable)),plan.outside.length>0&&lines.push(`Leave ${plan.outside.length} recorded path(s) outside pharn's install paths (never deleted, whatever their hash):`,...listed(plan.outside)),plan.absent.length>0&&lines.push(`${plan.absent.length} recorded file(s) are already gone.`),lines.push(`Then remove directories left empty, and delete ${RECORDS_FILE} and ${CONFIG_FILENAME} (backed up to ${BACKUP_DIR}/ first).`,`Files pharn has no record of are never deleted. ${untouchedLine(settingsIsRecorded)}`),lines}function finishPharnDir(cwd){let dir=safeJoin(cwd,LOCK_DIR);try{return rmdirSync(dir),null}catch(err){if(err.code==="ENOENT")return null;try{return readdirSync(dir).sort()}catch{return[]}}}function reportResult(cwd,result,pharnLeft){let{plan,deleted,removedDirs,keptDirs,backupDir}=result,lines=[`Deleted ${deleted.length} file(s) and ${removedDirs.length} empty director${removedDirs.length===1?"y":"ies"}, plus ${RECORDS_FILE} and ${CONFIG_FILENAME}.`],kept=[...plan.edited,...plan.unverifiable].sort();if(kept.length>0&&lines.push(`Kept ${kept.length} file(s) pharn could not prove are unchanged \u2014 they are yours now:`,...listed(kept)),keptDirs.length>0&&lines.push(`Left ${keptDirs.length} director${keptDirs.length===1?"y":"ies"} that still hold other files:`,...listed(keptDirs)),lines.push(`${CONFIG_FILENAME} was backed up to ${backupDir}.`,`${untouchedLine(settingsRecorded(result.records))} Delete ${BACKUP_DIR}/ yourself once you no longer need it.`),pharnLeft!==null){let names=pharnLeft.slice(0,MAX_LISTED).map(n=>escapeUnsafe(n)),more=pharnLeft.length-names.length;lines.push(`${LOCK_DIR}/ was left because it still holds files pharn has no record of${names.length>0?` (${names.join(", ")}${more>0?`, \u2026and ${more} more`:""})`:""} \u2014 you may delete it once you no longer need them.`)}note(lines.join(`
3
3
  `),"UNINSTALLED");let hookLines=danglingHookLines(cwd,result.records);hookLines.length>0&&note(hookLines.join(`
4
4
  `),"HOOKS")}function danglingHookLines(cwd,records){let gone=Object.keys(records).filter(rel=>rel.startsWith(`${CLAUDE_HOOKS_DIR}/`)&&isInstallRootPath(rel)&&isGone(cwd,rel)),refs=hooksReferencing(cwd,gone);if(refs.length===0)return[];let lines=[];for(let ref of refs){if(ref.kind==="unreadable"){lines.push(` ${ref.file} could not be read (${ref.reason}); check it for hooks that run a removed script.`);continue}lines.push(` ${ref.file} still wires ${ref.entries.length} hook(s) whose script was removed:`,...ref.entries.map(e=>` ${displayHook(e)}`))}return lines.push(""," pharn never edits these files \u2014 remove those entries by hand."," Matching is textual: a hook that reaches a removed script another way is not listed."),lines}function isGone(cwd,rel){try{return lstatSync2(safeJoin(cwd,rel),{throwIfNoEntry:!1})===void 0}catch{return!0}}export{runUninstall};
@@ -1,4 +1,4 @@
1
- import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{decideFileAction,minCliGate,planUpdate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignorePending,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignorePending,prettierignoreReport,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringLines,orphanNoteLines}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{ApplyError,applyWrites,changedSince,readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveSource,sourceDescription}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,RECORDS_FILE,RECORDS_SCHEMA_VERSION,absentInstallSurfaces,buildRecords,capabilitySubtree,carriedSettingsRecord,collectExpectedInstallPaths,contentHash,detectLayout,fetchRemoteSkillsVersion,isInstalledHookFile,isProductCommandFile,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_COMMANDS_DIR,CLAUDE_HOOKS_DIR,FEATURES_README,PHARN_FEATURES_README,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain,reportFatal}from"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,row,writePharnConfig}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";function key(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key)),inIndex=new Set([...selection.selected.map(key),...selection.skipped.map(key)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key(sel);if(!seenPrevious.has(k)){let cap2={name:sel.name,role:sel.role,source:"auto"};capabilities.push(cap2),changes.push({cap:cap2,reason:"added"});continue}let source=previousSource.get(k)==="manual"?"manual":"auto";capabilities.push({name:sel.name,role:sel.role,source})}for(let cap2 of previous){let k=key(cap2);if(resolved.has(k))continue;if(frozen.has(k)){let kept={...cap2};capabilities.push(kept),changes.push({cap:kept,reason:"kept-frozen"});continue}if(cap2.source==="auto"){changes.push({cap:cap2,reason:"dropped-unselected"});continue}let inferred={...cap2,source:"manual"};if(!inIndex.has(k)){changes.push({cap:inferred,reason:"dropped-gone"});continue}capabilities.push(inferred),cap2.source===void 0&&changes.push({cap:inferred,reason:"kept-manual"})}return{capabilities,changes}}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,backup:!1,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok")return{...none,...keep(current),outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]};let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),decision=decideFileAction({diskHash,latestHash,recordedHash:recorded,recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,next:upstream.block,nextRecord:latestHash,backup:decision.backup}:decision.action==="noop"?{...none,outcome:"ok",next:current,nextRecord:latestHash}:{...none,...keep(current),outcome:"kept",label:decision.label,nextRecord:recorded}}function keep(current){if(current===void 0)return{next:void 0,problems:[]};let check=checkModelsBlock(current);return{next:current,problems:check.kind==="invalid"?check.reds.map(red=>red.detail):[]}}function isExecutableUnitPath(rel,paths){if(rel.startsWith(`${paths.floor}/`))return!0;let hooksPrefix=`${CLAUDE_HOOKS_DIR}/`;if(rel.startsWith(hooksPrefix))return isInstalledHookFile(rel.slice(hooksPrefix.length));let commandsPrefix=`${CLAUDE_COMMANDS_DIR}/`;return rel.startsWith(commandsPrefix)?isProductCommandFile(rel.slice(commandsPrefix.length)):!1}import{isDeepStrictEqual}from"node:util";function nextRecordStore(apply,extra){let files={...apply.frozenRecords,...apply.orphanRecords,...apply.settingsRecords,...apply.plan.nextRecords,...extra.written,...apply.models.nextRecord!==null?{[MODELS_RECORD_KEY]:apply.models.nextRecord}:{}};for(let rel of extra.unwritten??[]){let previous=apply.records?.[rel];previous!==void 0?files[rel]=previous:delete files[rel]}return{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files}}function nextConfig(config,report,apply,channel,stamp){let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return{...rest,pharnVersion:stamp.pharnVersion,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:apply.configCapabilities,layout:report.layout,updatedAt:stamp.updatedAt,models:apply.models.next}}function jsonValue(value){return JSON.parse(JSON.stringify(value))}function loadResolved(config){let{updatedAt:_updatedAt,pharnVersion:_pharnVersion,ref:_ref,commit:_commit,...rest}=config;return jsonValue({...rest,commit:config.commit??null,...channelOf(config)==="latest"?{ref:"latest"}:{}})}function planStateChanges(input){let{config,report,apply,channel,loadedRecords}=input,next=nextConfig(config,report,apply,channel,{pharnVersion:"",updatedAt:""}),store={schemaVersion:RECORDS_SCHEMA_VERSION,...nextRecordStore(apply,{written:{}})};return{config:!isDeepStrictEqual(loadResolved(next),loadResolved(config)),records:loadedRecords.kind!=="ok"||!isDeepStrictEqual(jsonValue(store),jsonValue(loadedRecords.store))}}function changesNoFiles(report){return report.writes.length===0&&!report.removals.some(r=>r.present)&&!gitignorePending(report.gitignore)&&!prettierignorePending(report.prettierignore)}function changesNothing(report,state){return changesNoFiles(report)&&!state.config&&!state.records}var USER_EDIT_SKIPS=new Set(["modified","unrecorded"]),DROP_REASONS=new Set(["dropped-unselected","dropped-gone"]);function isDrop(reason){return DROP_REASONS.has(reason)}function buildUpdatePlan(input){let{repoDir,sha,config,cwd,force,channel,onUnknownWarning}=input,index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&onUnknownWarning?.(unknownWarning);let frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),selection=resolveCapabilities(config.archetypes??[],index),merged=mergeCapabilities(selection,config.capabilities??[],frozen),configCapabilities=merged.capabilities,manifestCapabilities=configCapabilities.filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),installedVersion=readSkillsVersion(repoDir),layout=detectLayout(repoDir),expected=collectExpectedInstallPaths({repoDir,capabilities:manifestCapabilities}),latestHashes=new Map;for(let[rel,source]of expected)latestHashes.set(rel,contentHash(source));let diskStates=new Map;for(let rel of expected.keys())diskStates.set(rel,readDiskState(cwd,rel));let loadedRecords=readRecords(cwd),{records,note:recordsNote}=recordsBaseline(loadedRecords),paths=layoutPaths(layout),plan=planUpdate({latestHashes,diskStates,records,force,unit:rel=>isExecutableUnitPath(rel,paths),holdUnit:installedVersion!==config.skillsVersion}),removals=planCapabilityRemovals({cwd,paths,drops:merged.changes.flatMap(({cap:cap2,reason})=>isDrop(reason)?[{cap:cap2,reason}]:[]),records,command:"update"}),models=decideModelsUpdate({current:config.models,upstream:readUpstreamModels(repoDir),recorded:records?.[MODELS_RECORD_KEY]??null,recordsAvailable:records!==null,force}),backups=models.backup?[...plan.backups,CONFIG_FILENAME]:plan.backups,versionWithheld=plan.counts.skipped>0,nextSkillsVersion=versionWithheld?config.skillsVersion:installedVersion,nextCommit=versionWithheld?config.commit:sha,pendingSkillsVersion=versionWithheld&&installedVersion!==nextSkillsVersion&&plan.skipped.every(g=>USER_EDIT_SKIPS.has(g.label)||g.label==="held")?installedVersion:null,frozenRecords=records===null?{}:recordsUnderCapabilities(records,paths,configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))),orphanScan=findOrphans({projectRoot:cwd,records,expected,capabilities:configCapabilities,frozen:configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))}),orphans=orphanScan.orphans,prettierignorePaths=[...expected.keys(),...Object.keys(frozenRecords),...Object.keys(orphanScan.records)],previouslyFrozen=new Set(config.frozenCapabilities??[]),skippedRels=plan.skipped.flatMap(group=>group.rels),hasSkippedFile=cap2=>{let prefix=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}/`;return skippedRels.some(rel=>rel.startsWith(prefix))},frozenKeys=[...new Set(configCapabilities.filter(cap2=>{let key2=`${cap2.role}:${cap2.name}`;return frozen.has(key2)||previouslyFrozen.has(key2)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort(),report={currentVersion:config.skillsVersion,installedVersion,recordedVersion:nextSkillsVersion,versionWithheld,pendingSkillsVersion,frozenCapabilities:frozenKeys,capCount:configCapabilities.length,layout,featuresReadmeRelocation:records!==null&&FEATURES_README in records&&expected.has(PHARN_FEATURES_README),capabilityChanges:merged.changes,removals,files:plan.files,writes:plan.writes,backups,skipped:plan.skipped,counts:plan.counts,executableUnit:plan.held,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),absentUpstream:absentInstallSurfaces({repoDir}),recordsNote,unknownWarning,unknownCapabilities:index.unknown,orphans,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply={expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,settingsRecords:carriedSettingsRecord(cwd,records),nextSkillsVersion,nextCommit,frozenKeys,removalPaths:paths,prettierignorePaths,seen:new Map(plan.writes.map(rel=>{let disk=diskStates.get(rel);return[rel,disk?.kind==="file"?disk.hash:null]}))},stateChanges=planStateChanges({config,report,apply,channel,loadedRecords});return{report:{...report,stateChanges,changesNothing:changesNothing(report,stateChanges)},apply}}import{log,note,outro}from"@clack/prompts";function defaultChannelNotice(config,ref){return ref!==void 0||channelOf(config)!=="main"?null:"Verified releases are now the default for new installs. This install keeps following pharn-oss main; run `pharn update --ref latest` to switch (recorded on first use)."}function noChangeVerdict(r){return r.counts.skipped===0&&r.recordedVersion===r.installedVersion?"Up to date.":"Nothing to change."}function forcedOverwriteSections(r,verb){let sections=["modified","unrecorded","unverifiable"].map(label=>({heading:`${verb} OVERWRITE (--force) \u2014 ${label}`,rels:r.files.filter(f=>f.action==="write"&&f.forced&&f.label===label).map(f=>f.rel)}));return sections.push({heading:`${verb} OVERWRITE (--force) \u2014 your models block`,rels:r.models.backup?[CONFIG_FILENAME]:[]}),sections.filter(s=>s.rels.length>0)}function reportForcedOverwrites(r){let sections=forcedOverwriteSections(r,"WILL");if(sections.length===0)return;let lines=[];for(let{heading,rels}of sections){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}lines.push(color_default.dim(` Each is copied to ${BACKUP_DIR}/<timestamp>/ first (${r.backups.length} file(s)).`)),note(lines.join(`
1
+ import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{decideFileAction,minCliGate,planUpdate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignorePending,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignorePending,prettierignoreReport,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringLines,orphanNoteLines}from"./chunk-VWZNENTT.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{ApplyError,applyWrites,changedSince,readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveSource,sourceDescription}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,RECORDS_FILE,RECORDS_SCHEMA_VERSION,absentInstallSurfaces,buildRecords,capabilitySubtree,carriedSettingsRecord,collectExpectedInstallPaths,contentHash,detectLayout,fetchRemoteSkillsVersion,isInstalledHookFile,isProductCommandFile,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_COMMANDS_DIR,CLAUDE_HOOKS_DIR,FEATURES_README,PHARN_FEATURES_README,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain,reportFatal}from"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,row,writePharnConfig}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";function key(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key)),inIndex=new Set([...selection.selected.map(key),...selection.skipped.map(key)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key(sel);if(!seenPrevious.has(k)){let cap2={name:sel.name,role:sel.role,source:"auto"};capabilities.push(cap2),changes.push({cap:cap2,reason:"added"});continue}let source=previousSource.get(k)==="manual"?"manual":"auto";capabilities.push({name:sel.name,role:sel.role,source})}for(let cap2 of previous){let k=key(cap2);if(resolved.has(k))continue;if(frozen.has(k)){let kept={...cap2};capabilities.push(kept),changes.push({cap:kept,reason:"kept-frozen"});continue}if(cap2.source==="auto"){changes.push({cap:cap2,reason:"dropped-unselected"});continue}let inferred={...cap2,source:"manual"};if(!inIndex.has(k)){changes.push({cap:inferred,reason:"dropped-gone"});continue}capabilities.push(inferred),cap2.source===void 0&&changes.push({cap:inferred,reason:"kept-manual"})}return{capabilities,changes}}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,backup:!1,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok")return{...none,...keep(current),outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]};let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),decision=decideFileAction({diskHash,latestHash,recordedHash:recorded,recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,next:upstream.block,nextRecord:latestHash,backup:decision.backup}:decision.action==="noop"?{...none,outcome:"ok",next:current,nextRecord:latestHash}:{...none,...keep(current),outcome:"kept",label:decision.label,nextRecord:recorded}}function keep(current){if(current===void 0)return{next:void 0,problems:[]};let check=checkModelsBlock(current);return{next:current,problems:check.kind==="invalid"?check.reds.map(red=>red.detail):[]}}function isExecutableUnitPath(rel,paths){if(rel.startsWith(`${paths.floor}/`))return!0;let hooksPrefix=`${CLAUDE_HOOKS_DIR}/`;if(rel.startsWith(hooksPrefix))return isInstalledHookFile(rel.slice(hooksPrefix.length));let commandsPrefix=`${CLAUDE_COMMANDS_DIR}/`;return rel.startsWith(commandsPrefix)?isProductCommandFile(rel.slice(commandsPrefix.length)):!1}import{isDeepStrictEqual}from"node:util";function nextRecordStore(apply,extra){let files={...apply.frozenRecords,...apply.orphanRecords,...apply.settingsRecords,...apply.plan.nextRecords,...extra.written,...apply.models.nextRecord!==null?{[MODELS_RECORD_KEY]:apply.models.nextRecord}:{}};for(let rel of extra.unwritten??[]){let previous=apply.records?.[rel];previous!==void 0?files[rel]=previous:delete files[rel]}return{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files}}function nextConfig(config,report,apply,channel,stamp){let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return{...rest,pharnVersion:stamp.pharnVersion,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:apply.configCapabilities,layout:report.layout,updatedAt:stamp.updatedAt,models:apply.models.next}}function jsonValue(value){return JSON.parse(JSON.stringify(value))}function loadResolved(config){let{updatedAt:_updatedAt,pharnVersion:_pharnVersion,ref:_ref,commit:_commit,...rest}=config;return jsonValue({...rest,commit:config.commit??null,...channelOf(config)==="latest"?{ref:"latest"}:{}})}function planStateChanges(input){let{config,report,apply,channel,loadedRecords}=input,next=nextConfig(config,report,apply,channel,{pharnVersion:"",updatedAt:""}),store={schemaVersion:RECORDS_SCHEMA_VERSION,...nextRecordStore(apply,{written:{}})};return{config:!isDeepStrictEqual(loadResolved(next),loadResolved(config)),records:loadedRecords.kind!=="ok"||!isDeepStrictEqual(jsonValue(store),jsonValue(loadedRecords.store))}}function changesNoFiles(report){return report.writes.length===0&&!report.removals.some(r=>r.present)&&!gitignorePending(report.gitignore)&&!prettierignorePending(report.prettierignore)}function changesNothing(report,state){return changesNoFiles(report)&&!state.config&&!state.records}var USER_EDIT_SKIPS=new Set(["modified","unrecorded"]),DROP_REASONS=new Set(["dropped-unselected","dropped-gone"]);function isDrop(reason){return DROP_REASONS.has(reason)}function buildUpdatePlan(input){let{repoDir,sha,config,cwd,force,channel,onUnknownWarning}=input,index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&onUnknownWarning?.(unknownWarning);let frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),selection=resolveCapabilities(config.archetypes??[],index),merged=mergeCapabilities(selection,config.capabilities??[],frozen),configCapabilities=merged.capabilities,manifestCapabilities=configCapabilities.filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),installedVersion=readSkillsVersion(repoDir),layout=detectLayout(repoDir),expected=collectExpectedInstallPaths({repoDir,capabilities:manifestCapabilities}),latestHashes=new Map;for(let[rel,source]of expected)latestHashes.set(rel,contentHash(source));let diskStates=new Map;for(let rel of expected.keys())diskStates.set(rel,readDiskState(cwd,rel));let loadedRecords=readRecords(cwd),{records,note:recordsNote}=recordsBaseline(loadedRecords),paths=layoutPaths(layout),plan=planUpdate({latestHashes,diskStates,records,force,unit:rel=>isExecutableUnitPath(rel,paths),holdUnit:installedVersion!==config.skillsVersion}),removals=planCapabilityRemovals({cwd,paths,drops:merged.changes.flatMap(({cap:cap2,reason})=>isDrop(reason)?[{cap:cap2,reason}]:[]),records,command:"update"}),models=decideModelsUpdate({current:config.models,upstream:readUpstreamModels(repoDir),recorded:records?.[MODELS_RECORD_KEY]??null,recordsAvailable:records!==null,force}),backups=models.backup?[...plan.backups,CONFIG_FILENAME]:plan.backups,versionWithheld=plan.counts.skipped>0,nextSkillsVersion=versionWithheld?config.skillsVersion:installedVersion,nextCommit=versionWithheld?config.commit:sha,pendingSkillsVersion=versionWithheld&&installedVersion!==nextSkillsVersion&&plan.skipped.every(g=>USER_EDIT_SKIPS.has(g.label)||g.label==="held")?installedVersion:null,frozenRecords=records===null?{}:recordsUnderCapabilities(records,paths,configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))),orphanScan=findOrphans({projectRoot:cwd,records,expected,capabilities:configCapabilities,frozen:configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))}),orphans=orphanScan.orphans,prettierignorePaths=[...expected.keys(),...Object.keys(frozenRecords),...Object.keys(orphanScan.records)],previouslyFrozen=new Set(config.frozenCapabilities??[]),skippedRels=plan.skipped.flatMap(group=>group.rels),hasSkippedFile=cap2=>{let prefix=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}/`;return skippedRels.some(rel=>rel.startsWith(prefix))},frozenKeys=[...new Set(configCapabilities.filter(cap2=>{let key2=`${cap2.role}:${cap2.name}`;return frozen.has(key2)||previouslyFrozen.has(key2)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort(),report={currentVersion:config.skillsVersion,installedVersion,recordedVersion:nextSkillsVersion,versionWithheld,pendingSkillsVersion,frozenCapabilities:frozenKeys,capCount:configCapabilities.length,layout,featuresReadmeRelocation:records!==null&&FEATURES_README in records&&expected.has(PHARN_FEATURES_README),capabilityChanges:merged.changes,removals,files:plan.files,writes:plan.writes,backups,skipped:plan.skipped,counts:plan.counts,executableUnit:plan.held,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),absentUpstream:absentInstallSurfaces({repoDir}),recordsNote,unknownWarning,unknownCapabilities:index.unknown,orphans,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply={expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,settingsRecords:carriedSettingsRecord(cwd,records),nextSkillsVersion,nextCommit,frozenKeys,removalPaths:paths,prettierignorePaths,seen:new Map(plan.writes.map(rel=>{let disk=diskStates.get(rel);return[rel,disk?.kind==="file"?disk.hash:null]}))},stateChanges=planStateChanges({config,report,apply,channel,loadedRecords});return{report:{...report,stateChanges,changesNothing:changesNothing(report,stateChanges)},apply}}import{log,note,outro}from"@clack/prompts";function defaultChannelNotice(config,ref){return ref!==void 0||channelOf(config)!=="main"?null:"Verified releases are now the default for new installs. This install keeps following pharn-oss main; run `pharn update --ref latest` to switch (recorded on first use)."}function noChangeVerdict(r){return r.counts.skipped===0&&r.recordedVersion===r.installedVersion?"Up to date.":"Nothing to change."}function forcedOverwriteSections(r,verb){let sections=["modified","unrecorded","unverifiable"].map(label=>({heading:`${verb} OVERWRITE (--force) \u2014 ${label}`,rels:r.files.filter(f=>f.action==="write"&&f.forced&&f.label===label).map(f=>f.rel)}));return sections.push({heading:`${verb} OVERWRITE (--force) \u2014 your models block`,rels:r.models.backup?[CONFIG_FILENAME]:[]}),sections.filter(s=>s.rels.length>0)}function reportForcedOverwrites(r){let sections=forcedOverwriteSections(r,"WILL");if(sections.length===0)return;let lines=[];for(let{heading,rels}of sections){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}lines.push(color_default.dim(` Each is copied to ${BACKUP_DIR}/<timestamp>/ first (${r.backups.length} file(s)).`)),note(lines.join(`
2
2
  `),"OVERWRITE")}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable","held"]),MAX_UNIT_BLOCKERS=20;function executableUnitLines(hold,preview){return hold===null?null:[...unitBlockerLines(hold,preview),...unitMissingLines(hold.missing??[],preview),""," To upgrade the unit: revert the skipped files, or run",` \`pharn update --force\` (it backs them up to ${BACKUP_DIR}/ first).`]}function unitBlockerLines(hold,preview){let shown=hold.blocking.slice(0,MAX_UNIT_BLOCKERS),more=hold.blocking.length-shown.length;return[" The floor, the hooks and the pharn-* commands run together, so pharn"," writes them all or none. These unit files "+(preview?"would be skipped":"were skipped")+":",...shown.map(b=>` ${b.label.padEnd(12)} ${terminalSafe(b.rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[],"",` So ${hold.held.length} other unit file(s) `+(preview?"would not be written":"were not written")+" either, and the"," unit stays at the version you had: upgrading part of it would mix two"," versions that may not load together."]}function unitMissingLines(missing,preview){if(missing.length===0)return[];let shown=missing.slice(0,MAX_UNIT_BLOCKERS),more=missing.length-shown.length;return[""," Of those, these are not on disk, so they "+(preview?"would stay":"stay")+" missing until the hold ends:",...shown.map(rel=>` ${terminalSafe(rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[]]}function reportExecutableUnit(hold,preview){let lines=executableUnitLines(hold,preview);lines&&note(lines.join(`
3
3
  `),"EXECUTABLE UNIT")}function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log.warn(`\u26A0 ${escapeUnsafe(recordsNote)}`),reportCapabilityChanges(outcome.capabilityChanges,outcome.removals,!1),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&&note(hookLines.join(`
4
4
  `),"HOOKS"),reportAbsentSurfaces(outcome.absentUpstream??[]),reportExecutableUnit(plan.held,!1);let forceable=reportSkipped(plan.skipped,!1);if(reportOrphans(outcome.orphans),reportLayoutWarnings(outcome.featuresReadmeRelocation,!1),versionWithheld&&log.warn(withheldVersionLine({skipped:counts.skipped,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion,forceable,preview:!1})),outcome.unchanged){outro(`${noChangeVerdict({counts,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion})} ${color_default.dim(`(unchanged ${counts.ok} \xB7 skipped ${counts.skipped} \xB7 ${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`);return}let summary=`updated ${counts.updated} \xB7 restored ${counts.restored} \xB7 unchanged ${counts.ok}`+(force?` \xB7 forced ${counts.forced}`:"")+` \xB7 skipped ${counts.skipped}`;outro(`${color_default.green("\u2714")} ${summary} ${color_default.dim(`(${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`)}function reportAbsentSurfaces(absent){let lines=absentSurfaceLines(absent);lines&&note(lines.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pharn-dev/pharn",
3
- "version": "0.21.0",
3
+ "version": "0.21.1",
4
4
  "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.",
5
5
  "keywords": [
6
6
  "claude-code",