project-spec 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WorldStoryCm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,324 @@
1
- # Temporary Holding Version
1
+ # Project Spec Skills
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Turn a repository into knowledge you can navigate, question, and maintain.**
4
+
5
+ Two agent skills: one to understand existing software and keep that understanding true, one to change it starting from the spec. Start with the code you already have. Keep explanations in English Markdown with links to the evidence.
6
+
7
+ The knowledge skill produces an **Obsidian-compatible vault** with two clearly separated layers:
8
+
9
+ - an **as-built spec**: exactly how the code is implemented now, derived only from source. Each feature has one page: what it is for, how it works, its fields and its business rules, every rule with a number you can quote. What people or agents agreed in chats is not part of it.
10
+ - a **gap queue**: the agent's guesses about what is missing, doubtful or worth adding, one question per page. People re-check each gap and decide it, with a separate discussion and decision for every item.
11
+
12
+ To read it there is a small **local viewer**: one command opens the spec as a plain document in your browser, straight from the files on disk, and turns what you read into a request for your agent. [See how it works](#read-the-spec-then-work-from-it). Obsidian works too and is optional. The other skills work with ordinary repository files, with or without a vault.
13
+
14
+ ![A feature page in the viewer: what the feature is for, how it works, and its business rules as numbered rows](docs/images/viewer-page.png)
15
+
16
+ ## Pick a skill
17
+
18
+ | For | Skill | What you get |
19
+ | --- | --- | --- |
20
+ | Understand | [project-knowledge](skills/project-knowledge/SKILL.md) | An as-built spec of capabilities and behavior and a separate queue of individually tracked gaps. It also audits written requirements against the code, answers one question or re-checks one gap, keeps the spec in step with Git history and reconciles concurrent vault updates. It never changes application code. |
21
+ | Change (experimental) | [spec-change](skills/spec-change/SKILL.md) | A source-grounded plan with decision gates and observable acceptance criteria, or the change itself: you edit the spec on a branch, the agent reviews the diff and asks its questions before any code, then implements it and checks each changed statement against the code. |
22
+
23
+ Each skill is independently usable. A useful sequence is:
24
+
25
+ ```mermaid
26
+ flowchart LR
27
+ A[Map the project] --> B[Read it in the viewer]
28
+ B --> C[Audit a spec or re-check a gap]
29
+ C --> D[A person decides, then plan]
30
+ B --> E[Edit the spec: spec-change]
31
+ D --> F[Implement and verify]
32
+ E --> F
33
+ F --> A
34
+ ```
35
+
36
+ `project-knowledge` never changes application code; `spec-change` is the one that does, and only after it has asked its questions. Reading a test establishes what it expects; only running it produces a test result.
37
+
38
+ ## Read the spec, then work from it
39
+
40
+ The vault is plain Markdown: easy for an agent to write, tiring for a person to read file by file. The viewer is the reading side. It is one local page that reads the vault from disk every time it loads, so there is nothing to build first.
41
+
42
+ It is made for one loop:
43
+
44
+ 1. **Read.** A tree lists the areas and the features in each. A feature page says in plain words what the feature is for and how it works, then lists its fields and its numbered business rules; the source files and the properties are folded away. A breadcrumb, Back and Forward and a "You are here" card say where you are, and the related pages are listed beside the text.
45
+ 2. **Find.** Search (Cmd/Ctrl+K) covers pages, gaps and the text of the files the pages cite. A rule number such as `BR-CANCEL-02` finds its page.
46
+ 3. **Ask.** "Copy for AI" on any page turns the page and your own words into a request for your agent that names the page file. For a gap: recheck it, record a check you did yourself, record your decision, lay out the options, plan it. For any page: change the behavior, ask a question, or remove a page that is only noise. Each choice says what will happen, and you see the exact text before you copy it.
47
+ 4. **Let the agent work.** Paste the brief into your agent. With `spec-change` it asks its questions first, edits the spec on a branch, builds the change and checks every changed statement against the code.
48
+ 5. **See what moved.** Recent changes lists the pages whose cited sources changed since the last review, the pages not committed yet, and the vault's Git history with what each summary said before and after.
49
+
50
+ | Search | Copy for AI |
51
+ | --- | --- |
52
+ | ![Search results grouped into features, gaps and files](docs/images/viewer-search.png) | ![The Copy for AI dialog with the exact text that will be copied](docs/images/viewer-copy.png) |
53
+ | **Recent changes** | **Gap queue** |
54
+ | ![The vault's Git history, one line per commit](docs/images/viewer-changes.png) | ![The gap queue filtered by state, kind and area](docs/images/viewer-gaps.png) |
55
+
56
+ ![The map of pages, one frame per area](docs/images/viewer-map.png)
57
+
58
+ The screenshots show the fictional [Parcel Desk](examples/parcel-desk/README.md) example. The viewer only reads: it listens on `127.0.0.1`, makes no network requests and writes nothing to the repository. "Copy for AI" puts text on your clipboard; the only thing it keeps in your browser is the name you sign a check or a decision with. A link to a file in the repository opens inside the viewer, Markdown rendered and code with the cited lines marked.
59
+
60
+ ### Open it with one command
61
+
62
+ With the [package](#with-npm) installed in your project, add a script to `package.json`:
63
+
64
+ ```json
65
+ {
66
+ "scripts": {
67
+ "spec": "project-spec serve"
68
+ }
69
+ }
70
+ ```
71
+
72
+ `npm run spec` then opens the viewer for that project. Without the package, the command is the helper itself, where `<skill>` is the `project-knowledge` folder (`~/.claude/skills/project-knowledge`, `~/.codex/skills/project-knowledge`, or a copy kept inside the repository):
73
+
74
+ ```sh
75
+ python3 <skill>/scripts/knowledge.py serve --repo . --open
76
+ ```
77
+
78
+ Give that a short name once, as a `Makefile` target (the second line starts with a tab) or a shell alias:
79
+
80
+ ```make
81
+ spec:
82
+ python3 <skill>/scripts/knowledge.py serve --repo . --open
83
+ ```
84
+
85
+ ```sh
86
+ alias spec='python3 ~/.claude/skills/project-knowledge/scripts/knowledge.py serve --open --repo'
87
+ ```
88
+
89
+ The vault is found by itself when the repository has one under `knowledge/`; otherwise add `--vault PATH`. The page is served on port 8757, or another free port when that one is taken; `--port N` picks one. `project-spec serve` opens the browser unless you add `--no-open`; the helper opens it only with `--open`. If the vault has errors, the page lists them.
90
+
91
+ ## What a feature page says
92
+
93
+ Every feature, screen or flow has one page, and all of them have the same sections in the same order. A section the feature does not have is left out.
94
+
95
+ | Section | What it holds |
96
+ | --- | --- |
97
+ | Opening | What the feature is for, who uses it and where it is found. |
98
+ | `How it works` | What happens, step by step, in the product's words. |
99
+ | `Fields` | One row per input: whether it is required, its rule, the message when it is refused. |
100
+ | `Business rules` | One numbered row per rule, with the values from the code. |
101
+
102
+ This is the page in the screenshot above, as the agent wrote it:
103
+
104
+ ```markdown
105
+ # Only requested pickups are currently cancellable
106
+
107
+ A customer who no longer needs a pickup cancels it, and the service lets that
108
+ happen only before anyone has started work on it.
109
+
110
+ ## How it works
111
+
112
+ `cancel_pickup` in the service first runs the ownership check, then looks at the
113
+ pickup's state. A pickup that passes both is set to `cancelled` and returned.
114
+
115
+ ## Business rules
116
+
117
+ | ID | Rule |
118
+ | --- | --- |
119
+ | BR-CANCEL-01 | A pickup can be cancelled only while its state is `requested`. |
120
+ | BR-CANCEL-02 | In any other state the cancellation is refused with "Only requested pickups can be cancelled" and nothing is changed. |
121
+ ```
122
+
123
+ A rule's number is its name. It stays the same when the rule's text changes, a new rule gets the next free number, and a removed rule's number is never used again, so a number quoted in a ticket, a test or a chat keeps pointing at one rule. `check` fails when a number appears twice in the vault.
124
+
125
+ Things the code registers in one place and no single feature owns (background jobs, emails, routes, roles, plan limits) are listed in reference pages: one table with every item. A page cites the one to five files that decide its behavior. When one of them changes, the page is marked "Code changed since the last check" until someone re-reads it.
126
+
127
+ ## Why use this?
128
+
129
+ - **Onboarding:** follow a workflow across UI, API, policy, persistence and tests without rediscovering the same paths every session.
130
+ - **Change planning:** see which rules and related areas a change can affect before writing code.
131
+ - **Rules you can point at:** a reviewer, a tester or a support person can say "BR-CANCEL-02 is wrong" instead of describing a screen.
132
+ - **Useful gap reports:** each doubt is its own page, typed as a missing capability, outdated documentation, an unverified scenario, a conflict or an undecided product proposal, and carries who re-checked it and who decided it.
133
+ - **Team memory:** commit the notes with the project. A manual sync reviews changes from all contributors since the last reviewed commit, including older commits and merges.
134
+
135
+ The graph records relationships between explanations. It does not infer a complete runtime dependency graph or prove that the deployed application works. The agent never records a decision nobody made: accepting, rejecting or deferring a gap is a person's act.
136
+
137
+ ## Install and run
138
+
139
+ These are [Agent Skills](https://agentskills.io/specification): each folder has a `SKILL.md` entry point. They require an agent that can read your repository. The knowledge helpers need **Python 3.10+** and **Git**; they have no package dependencies. No MCP server, cloud service, paid API or Obsidian plugin is required by the bundle.
140
+
141
+ ### With npm
142
+
143
+ The package is [`project-spec`](https://www.npmjs.com/package/project-spec) on the npm registry, with one command of the same name. It needs Node 18+ in addition to Python. Nothing has to be installed first:
144
+
145
+ ```sh
146
+ npx project-spec install --claude # or --codex, or --dir knowledge/tooling
147
+ npx project-spec serve # the viewer for the project in the current folder
148
+ ```
149
+
150
+ Then ask your agent to use the `project-knowledge` skill ([example prompts](#example-prompts)).
151
+
152
+ To pin one version for everyone on a project, add it as a development dependency:
153
+
154
+ ```sh
155
+ npm install --save-dev project-spec
156
+ ```
157
+
158
+ The lockfile then pins the version, and `npm update project-spec` moves it forward. The command keeps every copy of the skills in step with that version:
159
+
160
+ ```sh
161
+ npx project-spec status # where the copies are and whether each is current
162
+ npx project-spec update # refresh every copy that status lists
163
+ ```
164
+
165
+ `status` and `update` look in `~/.claude/skills`, `~/.codex/skills` and the usual folders of the current project (`knowledge/tooling`, `.claude/skills`, `.codex/skills`, `.agents/skills`). `update` refreshes what is there and adds nothing new; `install` adds. A copy you edited by hand is not replaced unless you pass `--force`, and the old files are kept under `~/.project-spec/backups` first. `--skills project-knowledge` limits an install to the skills you name.
166
+
167
+ To run the unreleased version from this repository, use `npx github:WorldStoryCm/project-spec-skills status` in place of `npx project-spec status`.
168
+
169
+ ### Claude Code plugin
170
+
171
+ The repository is also a plugin marketplace for Claude Code. Inside Claude Code:
172
+
173
+ ```text
174
+ /plugin marketplace add WorldStoryCm/project-spec-skills
175
+ /plugin install project-spec@project-spec-skills
176
+ ```
177
+
178
+ The two skills then appear as `/project-spec:project-knowledge` and `/project-spec:spec-change`, and Claude Code updates them with the plugin. The plugin does not add the `project-spec` command; ask the agent to open the viewer, or use `npx project-spec serve`.
179
+
180
+ ### Codex
181
+
182
+ Ask the built-in skill installer:
183
+
184
+ ```text
185
+ Install these skills from WorldStoryCm/project-spec-skills:
186
+ skills/project-knowledge
187
+ skills/spec-change
188
+ ```
189
+
190
+ If you already have a skill with the same name, compare versions before replacing it. The installer in Codex handles its own destination. In Codex you can name a skill with `$name`, for example `$spec-change`.
191
+
192
+ ### Claude Code, by hand
193
+
194
+ Copy the whole skill folder (it contains the references and helper scripts) to one of:
195
+
196
+ - `~/.claude/skills/<name>/` to use it in all your projects, or
197
+ - `.claude/skills/<name>/` inside one project.
198
+
199
+ ```sh
200
+ git clone https://github.com/WorldStoryCm/project-spec-skills.git
201
+ mkdir -p ~/.claude/skills
202
+ cp -R project-spec-skills/skills/project-knowledge ~/.claude/skills/
203
+ cp -R project-spec-skills/skills/spec-change ~/.claude/skills/
204
+ ```
205
+
206
+ Then ask in plain language, or invoke a skill by name with `/<name>`, for example `/spec-change`. Claude Code finds a skill from its description, so an ordinary request often picks the right one.
207
+
208
+ ### Example prompts
209
+
210
+ These work in any host; use `$name` or `/name` where your host supports it, or just say which skill you mean.
211
+
212
+ ```text
213
+ Use the project-knowledge skill to build an English knowledge vault for this repository.
214
+ Describe only what the code does: one page per feature with its business rules,
215
+ each claim linked to source, and every doubt as its own gap.
216
+ ```
217
+
218
+ ```text
219
+ Use the project-knowledge skill to audit docs/checkout.md against the checkout implementation.
220
+ Prioritize real mismatches; record each as a separate open gap.
221
+ ```
222
+
223
+ ```text
224
+ Use the project-knowledge skill to re-check the gap "cancelled order still reserves stock".
225
+ Read the call path and relevant tests, write the result into the gap's Recheck
226
+ section, and leave the decision to me.
227
+ ```
228
+
229
+ ```text
230
+ Use the spec-change skill to plan the accepted gap "reservation-release".
231
+ Include affected modules, concurrency checks and acceptance criteria. Plan only.
232
+ ```
233
+
234
+ ```text
235
+ Use the spec-change skill. I edited the spec on this branch; the diff against main
236
+ is the change request. Ask your questions first, then implement it and show me
237
+ which statement is covered by which check.
238
+ ```
239
+
240
+ ### Any agent with repository access
241
+
242
+ Clone this repository, then ask the agent to read the chosen `skills/<name>/SKILL.md` and follow it in your target project. Keep that skill's directory intact so its references and scripts resolve. Use your host's documented installation mechanism if it supports skills. Hosts other than Codex and Claude Code have not been integration-tested, and the format change described in [VALIDATION.md](VALIDATION.md) has not yet been tested with an agent on any host.
243
+
244
+ ## Try the example first
245
+
246
+ [Parcel Desk](examples/parcel-desk/README.md) is a small, fictional pickup service with a real spec/code disagreement and a ready-made knowledge vault. The vault shows three gaps at different points of the lifecycle (needs recheck, needs decision, accepted with a plan). It includes example audit, investigation and plan outputs.
247
+
248
+ ```sh
249
+ git clone https://github.com/WorldStoryCm/project-spec-skills.git
250
+ cd project-spec-skills
251
+ python3 scripts/verify.py
252
+ ```
253
+
254
+ Start the viewer on the example:
255
+
256
+ ```sh
257
+ python3 skills/project-knowledge/scripts/knowledge.py serve --repo examples/parcel-desk --open
258
+ ```
259
+
260
+ Search for **cancellation**, open a gap, follow its links and try "Copy for AI" on it. [Read the spec, then work from it](#read-the-spec-then-work-from-it) describes every screen.
261
+
262
+ To use Obsidian, choose **Open folder as vault** and select `examples/parcel-desk/knowledge/parcel-desk`. Open `00-index`, then **Graph view: Open graph view** from the command palette (Cmd/Ctrl+G). In graph settings, **Existing files only** hides unresolved source links outside the vault. Pages cluster around their area because each page links to it; run pages carry no links, so they do not pull the clusters together. To see the spec alone, put `-path:gaps -path:plans -path:runs` in the graph's search filter, and add a color group per folder (`path:areas`, `path:notes`, `path:gaps`) under **Groups**. **Open local graph** shows only the neighbours of the page you are reading. Gap properties are searchable, for example `[decision:open]` or `[kind:verification-gap]`. See [Obsidian's graph guide](https://help.obsidian.md/plugins/graph).
263
+
264
+ Source links point outside the vault into the repository. Some hosts do not open these paths; the note's `sources` property gives the repository-relative path for your editor. All example application data is invented.
265
+
266
+ ## Keep knowledge current
267
+
268
+ ```text
269
+ Use the project-knowledge skill to sync: review all integrated changes since the last
270
+ reviewed checkpoint, update the affected spec notes, and revisit gaps whose
271
+ sources changed.
272
+ ```
273
+
274
+ Or narrow the work:
275
+
276
+ ```text
277
+ Ask project-knowledge to explore permissions and deepen the access-control notes.
278
+ Ask project-knowledge to work the gaps: re-verify open ones against the current code
279
+ and list which are waiting for my decision.
280
+ Ask project-knowledge to check links and source freshness.
281
+ ```
282
+
283
+ The agent researches and writes the claims. The Python helpers validate structure, track source fingerprints and render views; running a helper alone does not understand your code. A scan identifies candidate changes, and fingerprints are accepted and the Git checkpoint advanced only after review. See the [sync workflow](skills/project-knowledge/references/sync.md). If part of the range cannot be accepted yet, for example because another contributor has uncommitted edits to a file, mark it `deferred`: the rest is accepted, the checkpoint stays where it is and the helper exits with status 3 (not 0, and not 2, which is a usage error).
284
+
285
+ If `check` fails on a vault written before the spec/gap split, follow the [migration guide](skills/project-knowledge/references/migrate.md). The same guide has the regroup pass for a vault whose feature pages lack the sections above, or whose rules were spread over separate table pages per kind.
286
+
287
+ Everything is manual and nothing is published: the bundle installs no schedule or hooks, and does not commit, push or synchronize other clones. Share the Markdown, reviewed state and chosen skill version through your normal Git workflow. Personal Obsidian settings and local scan reports should stay ignored.
288
+
289
+ ### Gaps are decided by people
290
+
291
+ A gap starts open. Anyone can re-check it (ask `project-knowledge` to recheck it) and the result is written into the gap with who did it and when. Then a person accepts, rejects or defers it, or the agent finds the code already closes it and marks it done. Only an accepted gap gets a plan. Each gap page has its own `Discussion` and `Decision` sections, and the viewer lists the queue by state. A recheck means the same thing for every kind of gap, proposals included: it asks only whether the page's description of current behavior still holds in the code ("confirmed (still holds)" or "not reproduced (no longer holds)"), never whether the proposal is a good idea. Details are in [gaps.md](skills/project-knowledge/references/gaps.md).
292
+
293
+ ### When two people update the vault
294
+
295
+ ```text
296
+ Use the project-knowledge skill to merge our knowledge updates from main
297
+ and teammate/knowledge. Preserve both contributors' useful pages and stable IDs,
298
+ check overlapping claims against source, and report unresolved conflicts.
299
+ ```
300
+
301
+ The agent compares the common base and both versions, combines supported changes, and retains unresolved claims with their provenance. If two people recorded different decisions on the same gap, it reopens that gap, keeps both positions in its discussion and reports it. A read-only inspector finds changed paths, overlaps and ID collisions. Reviewed fingerprints and Git checkpoints need explicit reconciliation; they are never made current by picking the newest JSON. Derived views are rebuilt from the resolved pages. See the [merge workflow](skills/project-knowledge/references/merge.md).
302
+
303
+ Use separate branches or worktrees, or one writer per page, for concurrent work. The local finish lock protects bookkeeping, not simultaneous editing across computers. Merge is an agent workflow, not an automatic Git merge driver.
304
+
305
+ ## What the files mean
306
+
307
+ ```text
308
+ knowledge/<project>/
309
+ 00-index.md start here
310
+ areas/ maps of related capabilities (spec)
311
+ notes/ one page per feature, plus reference lists (spec)
312
+ gaps/ one question per page (gap)
313
+ plans/ one plan per accepted gap (gap)
314
+ runs/ review history and evidence limits
315
+ .knowledge/ sources.json (reviewed fingerprints), review.json (reviewed Git checkpoint)
316
+ ```
317
+
318
+ Spec pages never link to gaps; a gap links to the spec notes it is about. A gap that needs attention is a reason to look, not a defect list: it can mean unverified behavior, an unmet requirement or an undecided proposal. The [format contract](skills/project-knowledge/references/format.md) explains the page types, properties and evidence model. Helpers support this format; they are not a general Obsidian vault importer.
319
+
320
+ ## Contributing and verification
321
+
322
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the checks, skill boundaries and expectations for examples. [VALIDATION.md](VALIDATION.md) records the actual release checks and limitations. Small, evidence-backed improvements are welcome, especially reproducible cases where a skill confuses intended behavior, implemented behavior and runtime evidence.
323
+
324
+ The shipped skills and examples are original work, licensed under [MIT](LICENSE). This is an independent project; Obsidian and the agent hosts are not its sponsors. No third-party skill collection is bundled.
@@ -0,0 +1,279 @@
1
+ #!/usr/bin/env node
2
+ // project-spec: one command for the viewer and for keeping the skill copies current.
3
+ // No dependencies. The skills themselves are Python and Markdown; this only starts them and copies them.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
12
+ const SKILLS = path.join(ROOT, 'skills');
13
+ const PACKAGE = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
14
+ const MARKER = '.project-spec.json'; // written into every copy: which version it is and what its files looked like
15
+ const SKIP = new Set(['__pycache__', '.DS_Store', MARKER]);
16
+ const KNOWLEDGE = new Set(['serve', 'check', 'snapshot']);
17
+ const MAINTAIN = new Set(['scan', 'receipt', 'finish']);
18
+ // Skills earlier versions shipped; project-knowledge and spec-change took over what they did.
19
+ const RETIRED = ['spec-audit', 'spec-investigation', 'spec-plan'];
20
+ // Folders inside a project where a copy of the skills may live.
21
+ const PROJECT_PLACES = ['knowledge/tooling', '.claude/skills', '.codex/skills', '.agents/skills'];
22
+
23
+ const USAGE = `project-spec ${PACKAGE.version}
24
+
25
+ Read the spec
26
+ project-spec serve [--repo DIR] [--vault DIR] [--port N] [--no-open]
27
+ Open the viewer for the repository (default: the current folder).
28
+ project-spec check | snapshot [options]
29
+ The knowledge helper; --repo defaults to the current folder.
30
+ project-spec scan | receipt | finish [options]
31
+ The sync helper; --repo defaults to the current folder.
32
+
33
+ Keep the skills current
34
+ project-spec status
35
+ Where copies of the skills are and whether they match this version.
36
+ project-spec install [--claude] [--codex] [--dir DIR]... [--skills a,b] [--force]
37
+ Copy the skills into ~/.claude/skills, ~/.codex/skills or a folder you name.
38
+ project-spec update [--force]
39
+ Refresh every copy that status lists and remove retired skills. Nothing new is added.
40
+
41
+ A copy you edited by hand is never replaced unless you pass --force; the old files
42
+ are kept under ~/.project-spec/backups first.`;
43
+
44
+ class Problem extends Error {}
45
+
46
+ function commit() {
47
+ if (typeof PACKAGE.gitHead === 'string') return PACKAGE.gitHead;
48
+ const git = spawnSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
49
+ // Only when this folder is itself the work tree, not a package sitting inside someone's repository.
50
+ const top = spawnSync('git', ['-C', ROOT, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
51
+ return git.status === 0 && top.status === 0 && fs.realpathSync(top.stdout.trim()) === fs.realpathSync(ROOT) ? git.stdout.trim() : '';
52
+ }
53
+
54
+ const skillNames = () =>
55
+ fs.readdirSync(SKILLS, { withFileTypes: true })
56
+ .filter(e => e.isDirectory() && fs.existsSync(path.join(SKILLS, e.name, 'SKILL.md')))
57
+ .map(e => e.name)
58
+ .sort();
59
+
60
+ function filesOf(dir, base = dir, out = {}) {
61
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
62
+ if (SKIP.has(entry.name) || entry.name.endsWith('.pyc')) continue;
63
+ const full = path.join(dir, entry.name);
64
+ if (entry.isDirectory()) filesOf(full, base, out);
65
+ else if (entry.isFile()) out[path.relative(base, full).split(path.sep).join('/')] = createHash('sha256').update(fs.readFileSync(full)).digest('hex');
66
+ }
67
+ return out;
68
+ }
69
+
70
+ function readMarker(dir) {
71
+ try {
72
+ const marker = JSON.parse(fs.readFileSync(path.join(dir, MARKER), 'utf8'));
73
+ return marker && typeof marker === 'object' && marker.files && typeof marker.files === 'object' ? marker : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ // What a copy is, compared with this package: current, older, modified by hand, unknown, or absent.
80
+ function inspect(dir, name) {
81
+ if (!fs.existsSync(path.join(dir, 'SKILL.md'))) return { state: 'absent' };
82
+ const fresh = filesOf(path.join(SKILLS, name));
83
+ const now = filesOf(dir);
84
+ const same = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(k => a[k] === b[k]);
85
+ const marker = readMarker(dir);
86
+ if (!marker) return same(now, fresh) ? { state: 'current', adopt: true } : { state: 'unknown' };
87
+ const edited = Object.keys(marker.files).filter(f => now[f] !== undefined && now[f] !== marker.files[f]).sort();
88
+ if (edited.length) return { state: 'modified', edited, version: marker.version };
89
+ const tracked = Object.fromEntries(Object.keys(marker.files).filter(f => now[f] !== undefined).map(f => [f, now[f]]));
90
+ return same(tracked, fresh) ? { state: 'current', version: marker.version } : { state: 'older', version: marker.version };
91
+ }
92
+
93
+ const STATE_TEXT = {
94
+ current: () => 'current',
95
+ older: i => `older (${i.version || 'unknown version'})`,
96
+ modified: i => `edited by hand: ${i.edited.join(', ')}`,
97
+ unknown: () => 'differs, no version recorded',
98
+ absent: () => 'not installed',
99
+ };
100
+
101
+ function backup(dir, name) {
102
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '');
103
+ let target = path.join(os.homedir(), '.project-spec', 'backups', stamp, name);
104
+ for (let n = 2; fs.existsSync(target); n++) target = path.join(os.homedir(), '.project-spec', 'backups', `${stamp}-${n}`, name);
105
+ fs.mkdirSync(path.dirname(target), { recursive: true });
106
+ fs.cpSync(dir, target, { recursive: true });
107
+ return target;
108
+ }
109
+
110
+ // Copies one skill into place. Files an earlier install put there and this version no longer has are removed;
111
+ // files nobody recorded (yours) are left alone.
112
+ function place(dir, name) {
113
+ const source = path.join(SKILLS, name);
114
+ const fresh = filesOf(source);
115
+ const marker = readMarker(dir);
116
+ for (const old of Object.keys(marker ? marker.files : {})) {
117
+ if (fresh[old] === undefined) fs.rmSync(path.join(dir, old), { force: true });
118
+ }
119
+ for (const rel of Object.keys(fresh)) {
120
+ const to = path.join(dir, rel);
121
+ fs.mkdirSync(path.dirname(to), { recursive: true });
122
+ fs.copyFileSync(path.join(source, rel), to);
123
+ }
124
+ fs.writeFileSync(path.join(dir, MARKER), JSON.stringify({ package: PACKAGE.name, version: PACKAGE.version, commit: commit(), files: fresh }, null, 2) + '\n');
125
+ }
126
+
127
+ function apply(root, name, force, lines) {
128
+ const dir = path.join(root, name);
129
+ const found = inspect(dir, name);
130
+ const label = `${shorten(dir)}`;
131
+ if (found.state === 'current' && !found.adopt) return lines.push(` ${label}: already current`);
132
+ if (found.state === 'modified' && !force) {
133
+ lines.push(` ${label}: NOT updated, edited by hand (${found.edited.join(', ')}); pass --force to replace it`);
134
+ return false;
135
+ }
136
+ let kept = '';
137
+ if (found.state === 'modified' || found.state === 'unknown') kept = `; the old copy is in ${shorten(backup(dir, name))}`;
138
+ place(dir, name);
139
+ lines.push(` ${label}: ${found.state === 'absent' ? 'installed' : found.adopt ? 'recorded as current' : 'updated'} to ${PACKAGE.version}${kept}`);
140
+ }
141
+
142
+ const shorten = p => (p.startsWith(os.homedir() + path.sep) ? '~' + p.slice(os.homedir().length) : p);
143
+ const homes = () => [path.join(os.homedir(), '.claude', 'skills'), path.join(os.homedir(), '.codex', 'skills')];
144
+
145
+ // Every folder that holds at least one of the skills: the two home folders and the usual places in this project.
146
+ function knownRoots() {
147
+ const roots = [...homes(), ...PROJECT_PLACES.map(p => path.resolve(p))];
148
+ const names = [...skillNames(), ...RETIRED];
149
+ return [...new Set(roots)].filter(root => names.some(name => fs.existsSync(path.join(root, name, 'SKILL.md'))));
150
+ }
151
+
152
+ // A retired skill is recognised by its folder name and by the name its SKILL.md declares.
153
+ function retiredIn(root) {
154
+ return RETIRED.filter(name => {
155
+ try {
156
+ return new RegExp(`^name:\\s*${name}\\s*$`, 'm').test(fs.readFileSync(path.join(root, name, 'SKILL.md'), 'utf8'));
157
+ } catch {
158
+ return false;
159
+ }
160
+ });
161
+ }
162
+
163
+ function take(args, flag) {
164
+ const out = [];
165
+ for (let i = args.indexOf(flag); i >= 0; i = args.indexOf(flag)) {
166
+ if (args[i + 1] === undefined || args[i + 1].startsWith('--')) throw new Problem(`${flag} needs a value`);
167
+ out.push(args[i + 1]);
168
+ args.splice(i, 2);
169
+ }
170
+ return out;
171
+ }
172
+ function flag(args, name) {
173
+ const i = args.indexOf(name);
174
+ if (i >= 0) args.splice(i, 1);
175
+ return i >= 0;
176
+ }
177
+ function done(args) {
178
+ if (args.length) throw new Problem(`unknown option: ${args[0]}`);
179
+ }
180
+
181
+ function status(args) {
182
+ done(args);
183
+ const names = skillNames();
184
+ const roots = knownRoots();
185
+ console.log(`project-spec ${PACKAGE.version}${commit() ? ' (' + commit().slice(0, 7) + ')' : ''}`);
186
+ if (!roots.length) return console.log('No copies found. Install with: project-spec install --claude (or --codex, or --dir DIR)');
187
+ let behind = 0;
188
+ for (const root of roots) {
189
+ console.log(`\n${shorten(root)}`);
190
+ for (const name of names) {
191
+ const found = inspect(path.join(root, name), name);
192
+ if (found.state !== 'current' && found.state !== 'absent') behind++;
193
+ console.log(` ${name}: ${STATE_TEXT[found.state](found)}`);
194
+ }
195
+ for (const name of retiredIn(root)) {
196
+ behind++;
197
+ console.log(` ${name}: retired, update removes it`);
198
+ }
199
+ }
200
+ console.log(behind ? `\n${behind} to refresh: project-spec update` : '\nEverything installed is current.');
201
+ }
202
+
203
+ function install(args) {
204
+ const force = flag(args, '--force');
205
+ const roots = [];
206
+ if (flag(args, '--claude')) roots.push(homes()[0]);
207
+ if (flag(args, '--codex')) roots.push(homes()[1]);
208
+ roots.push(...take(args, '--dir').map(d => path.resolve(d)));
209
+ const only = take(args, '--skills').flatMap(v => v.split(',')).map(v => v.trim()).filter(Boolean);
210
+ done(args);
211
+ if (!roots.length) throw new Problem('say where to install: --claude, --codex or --dir DIR');
212
+ const names = skillNames();
213
+ const unknown = only.filter(n => !names.includes(n));
214
+ if (unknown.length) throw new Problem(`no such skill: ${unknown.join(', ')} (there are: ${names.join(', ')})`);
215
+ let ok = true;
216
+ for (const root of roots) {
217
+ const lines = [];
218
+ for (const name of only.length ? only : names) if (apply(root, name, force, lines) === false) ok = false;
219
+ console.log(lines.join('\n'));
220
+ }
221
+ return ok ? 0 : 1;
222
+ }
223
+
224
+ function update(args) {
225
+ const force = flag(args, '--force');
226
+ done(args);
227
+ const roots = knownRoots();
228
+ if (!roots.length) throw new Problem('no copies found to update; install first: project-spec install --claude (or --codex, or --dir DIR)');
229
+ let ok = true;
230
+ for (const root of roots) {
231
+ const lines = [];
232
+ for (const name of skillNames()) {
233
+ if (fs.existsSync(path.join(root, name, 'SKILL.md')) && apply(root, name, force, lines) === false) ok = false;
234
+ }
235
+ for (const name of retiredIn(root)) {
236
+ const dir = path.join(root, name);
237
+ const kept = backup(dir, name);
238
+ fs.rmSync(dir, { recursive: true, force: true });
239
+ lines.push(` ${shorten(dir)}: removed, this skill is retired; the old copy is in ${shorten(kept)}`);
240
+ }
241
+ console.log(lines.join('\n'));
242
+ }
243
+ const missing = roots.flatMap(root => skillNames().filter(name => !fs.existsSync(path.join(root, name, 'SKILL.md'))).map(name => `${shorten(root)}/${name}`));
244
+ if (missing.length) console.log(`\nNot installed there, so left out: ${missing.join(', ')}`);
245
+ return ok ? 0 : 1;
246
+ }
247
+
248
+ function python(script, command, args) {
249
+ if (!args.includes('--repo')) args.push('--repo', '.');
250
+ if (command === 'serve') {
251
+ if (!flag(args, '--no-open') && !args.includes('--open')) args.push('--open');
252
+ }
253
+ const exe = process.env.PROJECT_SPEC_PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
254
+ const full = [path.join(SKILLS, 'project-knowledge', 'scripts', script), command, ...args];
255
+ if (process.env.PROJECT_SPEC_DRY_RUN) return console.log([exe, ...full].join(' ')), 0;
256
+ const run = spawnSync(exe, full, { stdio: 'inherit' });
257
+ if (run.error) throw new Problem(`could not start ${exe}: ${run.error.message}. The helpers need Python 3.10 or newer; set PROJECT_SPEC_PYTHON to its path.`);
258
+ return run.status === null ? 1 : run.status;
259
+ }
260
+
261
+ function main(argv) {
262
+ const [command, ...args] = argv;
263
+ if (!command || command === 'help' || command === '--help' || command === '-h') return console.log(USAGE), 0;
264
+ if (command === 'version' || command === '--version') return console.log(PACKAGE.version), 0;
265
+ if (command === 'status') return status(args) || 0;
266
+ if (command === 'install') return install(args);
267
+ if (command === 'update') return update(args);
268
+ if (KNOWLEDGE.has(command)) return python('knowledge.py', command, args);
269
+ if (MAINTAIN.has(command)) return python('maintain.py', command, args);
270
+ throw new Problem(`unknown command: ${command}\n\n${USAGE}`);
271
+ }
272
+
273
+ try {
274
+ process.exitCode = main(process.argv.slice(2));
275
+ } catch (error) {
276
+ if (!(error instanceof Problem)) throw error;
277
+ console.error(`project-spec: ${error.message}`);
278
+ process.exitCode = 2;
279
+ }