project-spec 0.9.1 → 0.10.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/README.md CHANGED
@@ -59,7 +59,7 @@ A rule keeps its number for good, so a reviewer, a tester or a support person ca
59
59
 
60
60
  ## The viewer
61
61
 
62
- One local page, read from the files on disk. Nothing is built or uploaded.
62
+ One local page, read from the files on disk. Nothing is built or uploaded. It comes with the npm package and is not copied into your project; the vault also opens in Obsidian, so the viewer is optional.
63
63
 
64
64
  1. **Read** a feature page: its purpose, its flow, its rules.
65
65
  2. **Find** anything with search, including a rule number.
@@ -10,6 +10,11 @@ import { fileURLToPath } from 'node:url';
10
10
 
11
11
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
12
12
  const SKILLS = path.join(ROOT, 'skills');
13
+ // The viewer is not part of a skill: a skill holds only what writing a spec needs. It lives in the package, and a
14
+ // copy of the skill gets it only when asked (--with-viewer) or when it already had one.
15
+ const VIEWER = path.join(ROOT, 'viewer', 'viewer.html');
16
+ const VIEWER_SKILL = 'project-knowledge';
17
+ const VIEWER_REL = 'assets/viewer.html';
13
18
  const PACKAGE = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
14
19
  const MARKER = '.project-spec.json'; // written into every copy: which version it is and what its files looked like
15
20
  const SKIP = new Set(['__pycache__', '.DS_Store', MARKER]);
@@ -38,8 +43,10 @@ Read the spec
38
43
  Keep the skills current
39
44
  project-spec status
40
45
  Where copies of the skills are and whether they match this version.
41
- project-spec install [--claude] [--codex] [--dir DIR]... [--skills a,b] [--force]
46
+ project-spec install [--claude] [--codex] [--dir DIR]... [--skills a,b] [--with-viewer | --no-viewer] [--force]
42
47
  Copy the skills into ~/.claude/skills, ~/.codex/skills or a folder you name.
48
+ A copy holds the instructions and the helpers. --with-viewer adds the viewer page to it, for a
49
+ place without Node; --no-viewer takes it out of a copy that has it.
43
50
  project-spec update [--force]
44
51
  Refresh every copy that status lists and remove retired skills. Nothing new is added.
45
52
 
@@ -62,6 +69,15 @@ const skillNames = () =>
62
69
  .map(e => e.name)
63
70
  .sort();
64
71
 
72
+ const sha = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
73
+ const hasViewer = dir => fs.existsSync(path.join(dir, VIEWER_REL));
74
+ // The files a copy of a skill should have: the skill's own, and the viewer when this copy carries it.
75
+ function freshFiles(name, viewer) {
76
+ const fresh = filesOf(path.join(SKILLS, name));
77
+ if (viewer && name === VIEWER_SKILL) fresh[VIEWER_REL] = sha(VIEWER);
78
+ return fresh;
79
+ }
80
+
65
81
  function filesOf(dir, base = dir, out = {}) {
66
82
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
67
83
  if (SKIP.has(entry.name) || entry.name.endsWith('.pyc')) continue;
@@ -82,9 +98,10 @@ function readMarker(dir) {
82
98
  }
83
99
 
84
100
  // What a copy is, compared with this package: current, older, modified by hand, unknown, or absent.
85
- function inspect(dir, name) {
101
+ // `viewer` says whether the copy should carry the viewer; left out, a copy keeps what it has.
102
+ function inspect(dir, name, viewer = hasViewer(dir)) {
86
103
  if (!fs.existsSync(path.join(dir, 'SKILL.md'))) return { state: 'absent' };
87
- const fresh = filesOf(path.join(SKILLS, name));
104
+ const fresh = freshFiles(name, viewer);
88
105
  const now = filesOf(dir);
89
106
  const same = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(k => a[k] === b[k]);
90
107
  const marker = readMarker(dir);
@@ -114,24 +131,32 @@ function backup(dir, name) {
114
131
 
115
132
  // Copies one skill into place. Files an earlier install put there and this version no longer has are removed;
116
133
  // files nobody recorded (yours) are left alone.
117
- function place(dir, name) {
134
+ function place(dir, name, viewer) {
118
135
  const source = path.join(SKILLS, name);
119
- const fresh = filesOf(source);
136
+ const fresh = freshFiles(name, viewer);
120
137
  const marker = readMarker(dir);
121
138
  for (const old of Object.keys(marker ? marker.files : {})) {
122
139
  if (fresh[old] === undefined) fs.rmSync(path.join(dir, old), { force: true });
123
140
  }
141
+ if (name === VIEWER_SKILL && !viewer) {
142
+ fs.rmSync(path.join(dir, VIEWER_REL), { force: true });
143
+ try {
144
+ fs.rmdirSync(path.dirname(path.join(dir, VIEWER_REL))); // only when nothing else is in it
145
+ } catch {}
146
+ }
124
147
  for (const rel of Object.keys(fresh)) {
125
148
  const to = path.join(dir, rel);
126
149
  fs.mkdirSync(path.dirname(to), { recursive: true });
127
- fs.copyFileSync(path.join(source, rel), to);
150
+ fs.copyFileSync(rel === VIEWER_REL && name === VIEWER_SKILL ? VIEWER : path.join(source, rel), to);
128
151
  }
129
152
  fs.writeFileSync(path.join(dir, MARKER), JSON.stringify({ package: PACKAGE.name, version: PACKAGE.version, commit: commit(), files: fresh }, null, 2) + '\n');
130
153
  }
131
154
 
132
- function apply(root, name, force, lines) {
155
+ // `viewer`: true adds the viewer to the copy, false takes it out, undefined keeps what the copy has (none when new).
156
+ function apply(root, name, force, lines, viewer) {
133
157
  const dir = path.join(root, name);
134
- const found = inspect(dir, name);
158
+ const carries = name === VIEWER_SKILL && (viewer === undefined ? hasViewer(dir) : viewer);
159
+ const found = inspect(dir, name, carries);
135
160
  const label = `${shorten(dir)}`;
136
161
  if (found.state === 'current' && !found.adopt) return lines.push(` ${label}: already current`);
137
162
  if (found.state === 'modified' && !force) {
@@ -140,8 +165,8 @@ function apply(root, name, force, lines) {
140
165
  }
141
166
  let kept = '';
142
167
  if (found.state === 'modified' || found.state === 'unknown') kept = `; the old copy is in ${shorten(backup(dir, name))}`;
143
- place(dir, name);
144
- lines.push(` ${label}: ${found.state === 'absent' ? 'installed' : found.adopt ? 'recorded as current' : 'updated'} to ${PACKAGE.version}${kept}`);
168
+ place(dir, name, carries);
169
+ lines.push(` ${label}: ${found.state === 'absent' ? 'installed' : found.adopt ? 'recorded as current' : 'updated'} to ${PACKAGE.version}${carries ? ', with the viewer' : ''}${kept}`);
145
170
  }
146
171
 
147
172
  const shorten = p => (p.startsWith(os.homedir() + path.sep) ? '~' + p.slice(os.homedir().length) : p);
@@ -195,7 +220,7 @@ function status(args) {
195
220
  for (const name of names) {
196
221
  const found = inspect(path.join(root, name), name);
197
222
  if (found.state !== 'current' && found.state !== 'absent') behind++;
198
- console.log(` ${name}: ${STATE_TEXT[found.state](found)}`);
223
+ console.log(` ${name}: ${STATE_TEXT[found.state](found)}${name === VIEWER_SKILL && hasViewer(path.join(root, name)) ? ', with the viewer' : ''}`);
199
224
  }
200
225
  for (const name of retiredIn(root)) {
201
226
  behind++;
@@ -212,7 +237,11 @@ function install(args) {
212
237
  if (flag(args, '--codex')) roots.push(homes()[1]);
213
238
  roots.push(...take(args, '--dir').map(d => path.resolve(d)));
214
239
  const only = take(args, '--skills').flatMap(v => v.split(',')).map(v => v.trim()).filter(Boolean);
240
+ const withViewer = flag(args, '--with-viewer');
241
+ const noViewer = flag(args, '--no-viewer');
215
242
  done(args);
243
+ if (withViewer && noViewer) throw new Problem('--with-viewer and --no-viewer cannot be used together');
244
+ const viewer = withViewer ? true : noViewer ? false : undefined;
216
245
  if (!roots.length) throw new Problem('say where to install: --claude, --codex or --dir DIR');
217
246
  const names = skillNames();
218
247
  const unknown = only.filter(n => !names.includes(n));
@@ -220,7 +249,7 @@ function install(args) {
220
249
  let ok = true;
221
250
  for (const root of roots) {
222
251
  const lines = [];
223
- for (const name of only.length ? only : names) if (apply(root, name, force, lines) === false) ok = false;
252
+ for (const name of only.length ? only : names) if (apply(root, name, force, lines, viewer) === false) ok = false;
224
253
  console.log(lines.join('\n'));
225
254
  }
226
255
  return ok ? 0 : 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-spec",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "Agent skills that read a repository and keep a spec people can read: one page per feature, every business rule numbered. Local viewer and one command to install and update the skills.",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -28,6 +28,7 @@
28
28
  "files": [
29
29
  "bin",
30
30
  "skills",
31
+ "viewer",
31
32
  "!**/__pycache__",
32
33
  "!**/*.pyc",
33
34
  "LICENSE",
@@ -38,12 +38,12 @@ The full property list, section layout and example are in [gaps.md](references/g
38
38
 
39
39
  Natural-language requests are fine; these are modes, not a required CLI.
40
40
 
41
- - **map** (a new vault): take the inventory of what the product has, then go through its features one at a time and finish each before starting the next ([Research before writing](#research-before-writing)). A first map is measured by how many features are finished, not by how many pages exist: thirty finished features and a list of forty not started is a better first map than seventy thin pages. A pass that runs out of time says on the run page which features are finished, which are partial and which were not started, and never calls itself full.
41
+ - **map** (a new vault): take the inventory of what the product has, then go through its features one at a time and finish each before starting the next ([Research before writing](#research-before-writing)). A first map is measured by how many features are finished, not by how many pages exist: thirty finished features and a list of forty not started is a better first map than seventy thin pages. The inventory is kept in a file in the vault ([The inventory file](#the-inventory-file)), which is also where a pass that was interrupted continues. A pass that runs out of time leaves that file saying which features are finished, which one is in progress and which were not started, and never calls itself full.
42
42
  - **update**: revisit claims affected since the previous run, preserve manually written knowledge, add discoveries, and fill in what the pages you touch are missing (see [Leave each page better](#leave-each-page-better)).
43
43
  - **sync**: reconcile changes from all contributors since the last reviewed Git checkpoint. Read [the sync workflow](references/sync.md); a sync with work you cannot accept yet (for example another contributor's uncommitted files) uses `deferred` and ends as a partial finish with exit status 3 and the checkpoint unmoved.
44
44
  - **merge**: reconcile two contributors' vault updates from their common Git base. Read [the merge workflow](references/merge.md).
45
45
  - **explore <area or question>**: deepen a bounded area and link the result into the vault. Deepening an area means its feature notes first: what each one is for and every rule a person would look up, with its values, until [the feature is finished](#when-a-feature-is-finished). Then the lists the code keeps in one place, such as its background jobs. A request to "fill in", "complete", "backfill" or "go deeper" means this mode, and so does a reader saying a page is thin.
46
- - **gaps**: work the queue. List gaps by state; re-verify open gaps against the current code; every kind of gap is rechecked, proposals and questions about unexplained behavior included, because the recheck asks only whether the page's `Current behavior` still describes the code (`confirmed (still holds)` or `not reproduced (no longer holds)`) and never whether a proposal is worth doing, which is the person's decision. For a proposal that usually means confirming the capability is absent. Record each result in the gap's `Recheck` section with `recheck`, `rechecked_by` (`agent` for checks you ran), `rechecked_on`; set `recheck: "outdated"` on a gap whose cited source changed since its recorded recheck (keeping the other two fields); set `done` where the code now closes the question, recording that reading as a `not-reproduced` recheck by `agent` ([closing a gap as done](references/gaps.md#closing-a-gap-as-done)); mark duplicates. Then hand the `needs-decision` gaps to people with the options you found in `Discussion`. Never decide one yourself. When a person decides in the conversation, record it with their name; if you do not know their name, ask rather than writing `agent`.
46
+ - **gaps**: work the queue. List gaps by state; re-verify open gaps against the current code; every kind of gap is rechecked, proposals and questions about unexplained behavior included, because the recheck asks only whether the page's `Current behavior` still describes the code (`confirmed (still holds)` or `not reproduced (no longer holds)`) and never whether a proposal is worth doing, which is the person's decision. For a proposal that usually means confirming the capability is absent. Record each result in the gap's `Recheck` section with `recheck`, `rechecked_by` (`agent` for checks you ran), `rechecked_on`; set `recheck: "outdated"` on a gap whose cited source changed since its recorded recheck (keeping the other two fields); set `done` where the code now closes the question, recording that reading as a `not-reproduced` recheck by `agent`, and make sure the feature's page states the answer as a numbered rule that the gap's `Decision` names ([closing a gap as done](references/gaps.md#closing-a-gap-as-done)); mark duplicates. Then hand the `needs-decision` gaps to people with the options you found in `Discussion`. Never decide one yourself. When a person decides in the conversation, record it with their name; if you do not know their name, ask rather than writing `agent`.
47
47
  - **audit <document or feature>**: compare written requirements with the code, keeping what the code satisfies apart from what needs action. Read [the audit guide](references/audit.md). In a vault each finding that needs action becomes its own gap; without a vault the audit is a report.
48
48
  - **investigate <question>** or **recheck <gap>**: answer one question about behavior from repository and runtime evidence, or re-check a single gap and write the result into it. Read [the investigation guide](references/investigate.md). It works without a vault too.
49
49
  - **remove <page>**: delete a page the person calls noise. Delete the file, remove or reword every link to it on other pages, run `check`, and say what you removed. Do this only on the person's word, and do not put another page in its place. A real question the person disagrees with is not noise: record their decision as `rejected` so the answer is kept.
@@ -58,11 +58,21 @@ Write vault content in English unless the user asks for another language, whatev
58
58
 
59
59
  1. Read the repository's instructions and any task coordination they require. Preserve existing edits. Record the exact revision and whether you read uncommitted files. Application source is read-only: this skill writes only inside the vault.
60
60
  2. Inspect manifests, entrypoints, routes, schema and migrations, services and tests. Skip dependencies, build output, credential files, raw logs and customer data. Never use the vault itself as evidence about the application.
61
- 3. **Take the inventory before writing a page.** List what the product has from the places that register it, every item and not a sample: the pages or screens of every client (web, mobile, admin), the API procedures or endpoints, the jobs, the emails. Count them. Run `coverage` (below) for the size of each folder. Group the items into features and write that list on the run page with each feature's size: its entry points, its folders, its lines. This list is the plan and the ledger of the whole map. A directory name establishes neither a feature nor a behavior, so check a group against what its entry points do.
61
+ 3. **Take the inventory before writing a page.** List what the product has from the places that register it, every item and not a sample: the pages or screens of every client (web, mobile, admin), the API procedures or endpoints, the jobs, the emails. Count them. Run `coverage` (below) for the size of each folder. Group the items into features and write that list into [the inventory file](#the-inventory-file) with each feature's size: its entry points, its folders, its lines. This list is the plan and the checklist of the whole map. A directory name establishes neither a feature nor a behavior, so check a group against what its entry points do.
62
62
  4. **Split a big feature before writing it.** One page holds what a person reads in one sitting: about twenty rules. A feature with more than about eight entry points, more than about 2,000 lines of its own code, or several kinds of user or flow (direct, group and support chats) will not fit, and squeezing it into one page is how fifty rules become thirteen. Give it a feature note and one note per part ("A feature with parts" under [Write the spec](#write-the-spec)).
63
63
  5. **Go deep before going wide.** Take one feature and finish it before starting the next. Read every one of its entry points on every client and follow each to the file that decides the behavior (the schema, the service, the policy, the component). Read its rules off the code: a `max(60)` in a schema, a `disabled={items.length === 0}` on a button, a `CHECK` constraint, a default value, a permission check, every `throw` and every refusal. Read the words a person sees too, the labels, the error messages and what an empty list says, and quote them. For the things the code registers in one place (the queue and cron registrations, the route table, the email templates, the roles, the flags), enumerate from that place, every item.
64
64
  6. **Read each client.** When the product has more than one client, read the feature in each of them. Two clients calling the same server procedure does not make them the same: one may lack a screen, a check or a confirmation. Write what differs on the feature's page ([Write the spec](#write-the-spec)); a difference that looks unintended is also a gap.
65
- 7. Track what was read, merely discovered, excluded or changing in each area. Discovery is not review, and a note count is not completeness. When the session will not cover everything, stop at the end of a feature, not in the middle of all of them.
65
+ 7. Track what was read, merely discovered, excluded or changing in the inventory file, as you go and not from memory at the end. Discovery is not review, and a note count is not completeness. When the session will not cover everything, stop at the end of a feature, not in the middle of all of them.
66
+
67
+ ### The inventory file
68
+
69
+ `$VAULT/.knowledge/inventory.md` is the checklist of the whole map and the place a later session continues from ([format](references/format.md#the-inventory-file)). No helper writes or reads it: keeping it true is your job, and it is what stops a large map from losing a feature or being started again from nothing.
70
+
71
+ - **First pass: the list.** Start from what the repository is made of: every app and package (workspaces, manifests, folders with their own entry file). For each one list its entry points from the place that registers them, then group them into features. A feature gets a heading with its state (`not started`, `in progress`, `finished`), its folders, and one checkbox per entry point. Something that is not part of the product (a developer tool, a component gallery, generated code) goes under "Left out" with the reason, so nobody takes it for forgotten. Write the whole file before the first page.
72
+ - **Second pass: one feature at a time.** Take the first feature that is not finished. Set it to `in progress` before reading it, tick an entry point once you have followed it to the code that decides the behavior, and set the feature to `finished` with the paths of its pages when [it is finished](#when-a-feature-is-finished). While a feature is `in progress` its pages are `partial`. Save the file after every feature and whenever you stop: a session can end at any moment, and what is not in the file is lost.
73
+ - **A new find goes into the list at once.** An entry point, a package or a whole feature the list does not have is added the moment you see it, unticked or `not started`, even in the middle of another feature. Do not keep it in your head, and do not leave your feature to read it out of turn.
74
+ - **Last pass: check the list against the code.** When no feature is `not started` or `in progress`, or when the session is about to end: list the entry points again from the places that register them and compare with the file; run `coverage` for the whole repository and look at the folders at the top of the report, each of which is a feature missing from the list, a part of one, or something for "Left out"; confirm that no `finished` feature has an unticked entry point or a `partial` page. Whatever this turns up goes into the list and is worked like the rest.
75
+ - **Continuing.** When the file exists, read it before anything else in **map**, **explore** and **update**. Go on with the feature that is `in progress`, its unticked entry points first, then with the first `not started` one. Do not retake the inventory from nothing and do not rewrite the pages of finished features. If the code moved since the revision the file names, add the entry points that are new and remove the ones that are gone; files that changed under existing pages are the business of **sync**. A vault that has no such file (it was made by an earlier version) gets one the first time you map or explore it: take the inventory, and give a feature that already has pages `in progress` until you have checked it as above.
66
76
 
67
77
  ### When a feature is finished
68
78
 
@@ -141,7 +151,7 @@ python3 "$SKILL_DIR/scripts/knowledge.py" snapshot --repo "$REPO" --vault "$VAUL
141
151
 
142
152
  `check` validates structure and freshness; it cannot judge prose or coverage. `coverage.py` lists what the code has that no page mentions ([When a feature is finished](#when-a-feature-is-finished)). `--strict` turns freshness warnings into a failing exit status, for CI. In a working tree shared with someone else's uncommitted work, `--strict --ignore-dirty` still prints warnings for sources with uncommitted changes but does not fail on them when the accepted fingerprint equals the file at `HEAD` (the only drift is uncommitted); committed drift still fails, and it is not for CI ([details](references/format.md)). `serve` shows the vault in a browser and writes nothing. `snapshot` accepts source fingerprints as reviewed; run it only for pages you actually re-read against their sources, never to clear a warning. An initial reviewed pass may use `--all`.
143
153
 
144
- To read the result, run `python3 <skill>/scripts/knowledge.py serve --repo <repository> --open` (add `--vault` when the repository has several vaults under `knowledge/`), or open the folder as an Obsidian vault. The command is long, so when you hand over offer to give it a short name in the project: a `spec` script in `package.json` (`project-spec serve` when the project has the `project-spec-skills` package, otherwise the full command), a `spec` target in a `Makefile`, or a shell alias. That file is outside the vault, so add it only when the person agrees. The viewer is one page on `127.0.0.1`; it reads the vault and the files the pages cite from disk on every page load, so it needs no build and shows the current state after a reload. It shows a note as written, under its title and summary, with the source files folded away at the end; an area page shows its notes with their summaries. So the first paragraph and the summary are what most readers see. Its **Copy for AI** turns a page and the reader's own words into a request for an agent that names the page file. It only copies text, so an agent that receives one still follows the skill it names, and a recheck or decision the reader states there is recorded under the reader's name, never as the agent's. If the vault has errors the page lists them instead. When the person wants the spec on a server for people without the repository, `knowledge.py build --repo <repository> --out <file outside the vault>` writes that same viewer as one file ([options](references/format.md)); run it only when asked, never commit the file into the vault, and leave `--with-sources` out unless the person says everyone who can open the page may read the code.
154
+ To read the result, run `npx project-spec serve` in the repository (add `--vault` when it has several vaults under `knowledge/`), or open the folder as an Obsidian vault. The viewer is not part of this skill, which holds only what writing a spec needs: it comes with the `project-spec` npm package. Where this copy of the skill has `assets/viewer.html`, or sits in a clone of the skills repository, `python3 <skill>/scripts/knowledge.py serve --repo <repository> --open` shows the same page without Node; without the viewer that command says so and names the other ways. When you hand over, offer to give the command a short name in the project: a `spec` script in `package.json` (`project-spec serve`), a `spec` target in a `Makefile`, or a shell alias. That file is outside the vault, so add it only when the person agrees. The viewer is one page on `127.0.0.1`; it reads the vault and the files the pages cite from disk on every page load, so it needs no build and shows the current state after a reload. It shows a note as written, under its title and summary, with the source files folded away at the end; an area page shows its notes with their summaries. So the first paragraph and the summary are what most readers see. Its **Copy for AI** turns a page and the reader's own words into a request for an agent that names the page file. It only copies text, so an agent that receives one still follows the skill it names, and a recheck or decision the reader states there is recorded under the reader's name, never as the agent's. If the vault has errors the page lists them instead. When the person wants the spec on a server for people without the repository, `npx project-spec build --out <file outside the vault>` (or `knowledge.py build` in a copy that has the viewer) writes that same viewer as one file ([options](references/format.md)); run it only when asked, never commit the file into the vault, and leave `--with-sources` out unless the person says everyone who can open the page may read the code.
145
155
 
146
156
  Before handing over, read what you wrote as the person who will use it, not as its author. Open one area page and two of the notes you wrote or changed, and ask:
147
157
 
@@ -149,10 +159,11 @@ Before handing over, read what you wrote as the person who will use it, not as i
149
159
  - Is each rule one numbered row a person could quote, with its value, and did every rule that was already there keep its number?
150
160
  - Could someone answer "how long may a name be", "when is this button disabled" or "which jobs run at night" from the page without opening the code? If the answer is in the code you read but not on the page, add it.
151
161
  - Did `coverage --path` for the feature's folders end with only things the spec leaves out on purpose? Is every page whose feature is not finished marked `partial`, with what is left?
162
+ - Does the inventory file say what is true now: each feature you finished with its pages, the one you stopped in as `in progress` with what is left, and everything you came across on the way listed?
152
163
  - Does a feature with more than about twenty rules have parts, and does a product with several clients say on each feature page where they differ?
153
164
  - Is everything about one feature on its own page, or does the reader have to collect it from several?
154
165
  - Would a person who never opens the code understand every sentence? Would the page survive a file being renamed?
155
166
  - Does the area page only map, with its missing lists named?
156
167
  - Is every doubt a gap about the product, and nothing in the queue a to-do of the vault itself?
157
168
 
158
- Then validate and, when tools allow, open the viewer. Report real counts: how many features of the inventory are finished, partial and not started, the first lines of the `coverage` report for the whole repository, the checks you ran and how to open the result. Do not describe a map as full or complete while the inventory has features that are not finished. Keep structural validation, application tests and GUI checks separate. Committing and pushing are left to the user.
169
+ Then validate and, when tools allow, open the viewer. Report real counts: how many features of the inventory file are finished, in progress and not started, what is under "Left out", the first lines of the `coverage` report for the whole repository, the checks you ran and how to open the result. Do not describe a map as full or complete while the inventory has features that are not finished. Keep structural validation, application tests and GUI checks separate. Committing and pushing are left to the user.
@@ -14,7 +14,8 @@ knowledge/<project>/
14
14
  gaps/ one question per page (gap)
15
15
  plans/ one plan per accepted gap (gap)
16
16
  runs/ review history and evidence limits
17
- .knowledge/ sources.json (reviewed fingerprints), review.json (reviewed Git checkpoint)
17
+ .knowledge/ sources.json (reviewed fingerprints), review.json (reviewed Git checkpoint),
18
+ inventory.md (the checklist of the map)
18
19
  ```
19
20
 
20
21
  Nothing in the vault is generated for reading: every file is a page someone wrote or the reviewed state under `.knowledge/`. The local reports of a sync scan (`sync.html`, `.knowledge/sync-plan.json`, `.knowledge/sync-status.md`) are ignored by Git and are not part of the vault's content. The viewer shows the spec and the gap queue from the pages themselves.
@@ -165,6 +166,44 @@ The validator enforces these body rules:
165
166
  5. A gap has six `##` sections with exactly these headings, each once: `Current behavior`, `Gap`, `Evidence`, `Recheck`, `Discussion`, `Decision`. Headings inside code fences do not count.
166
167
  6. When `decision` is not `open`, `Decision` needs text; when `recheck` is not `not-checked`, `Recheck` needs text.
167
168
 
169
+ ## The inventory file
170
+
171
+ `.knowledge/inventory.md` is the checklist of a map: what the product has, and how far the spec has got with it. The agent writes it before the first page and keeps it true afterwards ([the rules](../SKILL.md#the-inventory-file)); no helper reads it, and like everything under `.knowledge/` it is not a page of the vault. It is committed with the vault, which is how a second session, or a second person, continues where the first one stopped.
172
+
173
+ ```markdown
174
+ # Inventory
175
+
176
+ Taken at `4f2a9c1` on 2026-11-18. Apps and packages: web-app, mobile-app, packages/api, packages/jobs.
177
+
178
+ ## Chats: in progress
179
+
180
+ Folders: web-app/src/features/messages, mobile-app/src/features/messages, packages/api/src/chat
181
+ Pages: notes/chats, notes/chats-group
182
+ Left: the support chat screens, the mobile app
183
+
184
+ - [x] web /messages
185
+ - [x] web /messages/[id]
186
+ - [ ] mobile ChatScreen
187
+ - [x] api chat.send
188
+ - [ ] job chat-digest
189
+
190
+ ## Reviews: not started
191
+
192
+ Folders: web-app/src/features/reviews
193
+
194
+ - [ ] web /products/[id]/reviews
195
+ - [ ] api review.create
196
+
197
+ ## Left out
198
+
199
+ - packages/storybook: a component gallery for developers, no behavior of the product
200
+ ```
201
+
202
+ - A feature's heading is its name and one of three states: `not started`, `in progress`, `finished`. A feature with parts is still one heading; its parts are among its pages.
203
+ - One checkbox per entry point: the client or kind (`web`, `mobile`, `admin`, `api`, `job`, `email`) and the name the code registers it under. A box is ticked when the entry point was followed to the code that decides its behavior, not when it was seen.
204
+ - `Pages` names the feature's pages by path. `Left` says in words what is not read yet, and is the same thing the `partial` page says in its last line. A `finished` feature has every box ticked and no `Left` line.
205
+ - "Left out" holds what was looked at and is not part of the product, each with its reason.
206
+
168
207
  ## Helper
169
208
 
170
209
  Four scripts in `$SKILL_DIR/scripts/`; see [SKILL.md](../SKILL.md) for the variables.
@@ -211,7 +250,9 @@ Canonical Markdown must not contain raw merge conflicts. Validation rejects comp
211
250
 
212
251
  `build` writes the same viewer as one file, for a server that shows the spec to people who do not have the repository: `knowledge.py build --repo REPO [--vault VAULT] --out FILE [--source-url URL] [--with-sources]`. `--out` must be a file outside the vault. The command stops with the `check` errors when the vault has any, and writes nothing then; freshness warnings do not stop it. The page data is the graph plus `built: true`, `commit` (the full `HEAD`, empty outside Git), `sourceUrl`, `vaultPath`, `history`, `pending` and `files`. `files` is empty unless `--with-sources` is given, because the text of cited files is source code. `--source-url` must be an `http(s)` address; `{commit}` in it is replaced by `HEAD`, and it is an error to name `{commit}` outside a Git work tree. `--allow-missing-sources` is for a build that sees only part of the repository (a Docker build context): a cited path where nothing exists is not an error and does not mark its page as changed, and the command lists those files; `check` and `snapshot` never accept it. On a built page a cited file whose text is not included is a link to `sourceUrl/<repository path>` (with `#L10-L20` when lines are named) in a new tab, or plain text when there is no `sourceUrl`; it is never a relative link, which would lead into the site that hosts the page. In a shallow clone the commit whose parents were not fetched is left out of `history` (by `serve` too), since Git would show every page as added there, and `build` says that the history is short.
213
252
 
214
- `assets/viewer.html` has exactly one `__KNOWLEDGE_DATA__` placeholder for script-safe JSON. Treat contents as untrusted text: no raw Markdown HTML execution, unsafe URL schemes, external scripts, fonts, analytics or fetches. Render readable basic Markdown, pipe tables and wikilinks; leave unsupported syntax as text. The viewer has a tree of areas with their notes (a note is listed under its first area; superseded notes are not listed), a search over pages, gaps and the cited files, and five places: the overview, a page, the gap queue, the map and recent changes. A note shows its title, `summary`, the page text and the gaps about it that are not closed, then its source files folded; an area shows its notes with their summaries and folds its own text. The pages linked to or from the page are a short list beside it. Navigation keeps a trail for Back and Forward and writes the place into the address (`#/page/notes/example`, `#/gaps`), so a reload or a copied link returns to it. The map draws one frame per primary area (the area page, or the first entry of `areas`) with its pages inside; an edge between a page and its primary area is not drawn because the frame says it, links inside one area are solid and links across areas dashed; `nav` pages are not drawn. Recent changes reads `history`, `pending` and the "changed source" lines of `warnings`. "Copy for AI" only composes text from the page, a choice of what the agent should do and the reader's own words, and copies it to the clipboard. The reader's name, the recently viewed pages and the last commit seen are kept in the browser's `localStorage`, and the viewer works without it.
253
+ `serve` and `build` need the viewer page, which is not part of the skill folder. They look for `assets/viewer.html` in this copy of the skill (`project-spec install --with-viewer` puts it there), then for `viewer/viewer.html` in the package or clone the skill sits in, and stop with a message naming `npx project-spec serve` when there is neither; every other command works without it. `--viewer FILE` shows the vault with a page of your own instead: any HTML file with the placeholder once, which receives the data described above.
254
+
255
+ The viewer page has exactly one `__KNOWLEDGE_DATA__` placeholder for script-safe JSON. Treat contents as untrusted text: no raw Markdown HTML execution, unsafe URL schemes, external scripts, fonts, analytics or fetches. Render readable basic Markdown, pipe tables and wikilinks; leave unsupported syntax as text. The viewer has a tree of areas with their notes (a note is listed under its first area; superseded notes are not listed), a search over pages, gaps and the cited files, and five places: the overview, a page, the gap queue, the map and recent changes. A note shows its title, `summary`, the page text and the gaps about it that are not closed, then its source files folded; an area shows its notes with their summaries and folds its own text. The pages linked to or from the page are a short list beside it. Navigation keeps a trail for Back and Forward and writes the place into the address (`#/page/notes/example`, `#/gaps`), so a reload or a copied link returns to it. The map draws one frame per primary area (the area page, or the first entry of `areas`) with its pages inside; an edge between a page and its primary area is not drawn because the frame says it, links inside one area are solid and links across areas dashed; `nav` pages are not drawn. Recent changes reads `history`, `pending` and the "changed source" lines of `warnings`. "Copy for AI" only composes text from the page, a choice of what the agent should do and the reader's own words, and copies it to the clipboard. The reader's name, the recently viewed pages and the last commit seen are kept in the browser's `localStorage`, and the viewer works without it.
215
256
 
216
257
  ## Format references
217
258
 
@@ -94,6 +94,10 @@ Never guess a decision from silence, from a plan existing, or from a task being
94
94
 
95
95
  When an agent sets `decision: "done"` because it read (or ran) the current code and the gap no longer holds, that reading is itself a recheck, and the page should say so. In the same edit record `recheck: "not-reproduced"`, `rechecked_by: "agent"`, today's `rechecked_on`, and add a dated entry to `Recheck` saying what was read or run. In `Decision`, say where in the code the question is now closed. The two sections answer different questions: `Recheck` is how you know it no longer holds, `Decision` is where the code does it. Without the recheck fields a closed gap looks as if nobody ever looked at the code. When a person closes a gap as done, they record the decision in `decided_by` and `Decision`. Their name goes in `rechecked_by` (not `agent`) only if they read or ran the current code themselves and add a `Recheck` entry saying what they did; if they decided without doing so, leave the recheck fields as they are. If you are not sure the question is closed, leave it open.
96
96
 
97
+ Closing a gap is also the moment its answer becomes part of the spec. Before you set `done`, open the page of the feature the gap is about and make sure it states what is true now as a numbered rule, read from the current code: add the rule, or correct the one that was there. Then name that rule in the gap's `Decision` ("Closed by BR-USERS-07") next to the place in the code. The same goes for `rejected`: the behavior stays as it is, so the feature's page should already state it as a rule, and `Decision` names that rule beside the person's reason. The link goes one way, from the gap to the spec page; a spec page still never mentions a gap.
98
+
99
+ A closed gap is not deleted. The spec says what the code does; the closed gap is the only place that says why, who decided and what was checked. The viewer takes closed gaps (`done`, `rejected`, `duplicate`) out of the queue, lists them under History with the most recently closed first, and shows them on the feature's page as closed questions, folded under the text. Delete a gap only when a person calls the page noise.
100
+
97
101
  ## Derived state
98
102
 
99
103
  Computed by the helper, never written into Markdown:
@@ -683,10 +683,28 @@ def graph_of(notes, edges, warnings):
683
683
  'edges': [{'source': a, 'target': b} for a, b in edges], 'warnings': warnings}
684
684
 
685
685
 
686
- def viewer_html(payload):
687
- template = (Path(__file__).resolve().parent.parent / 'assets/viewer.html').read_text(encoding='utf-8')
686
+ VIEWER = None # --viewer FILE: a page of your own to show the vault with
687
+
688
+
689
+ def viewer_template():
690
+ """The text of the viewer page. The page is not part of the skill, which holds only what writing a spec needs:
691
+ it comes with the project-spec package, with a copy made by `install --with-viewer`, or from --viewer."""
692
+ here = Path(__file__).resolve().parent
693
+ places = [Path(VIEWER)] if VIEWER else [here.parent / 'assets/viewer.html', *([here.parents[2] / 'viewer/viewer.html'] if len(here.parents) > 2 else [])]
694
+ found = next((place for place in places if place.is_file()), None)
695
+ if not found:
696
+ raise ValueError(f'--viewer {VIEWER} is not a file' if VIEWER else
697
+ 'the viewer is not part of this copy of the skill. Run `npx project-spec serve` in the repository (the viewer comes '
698
+ 'with the npm package), add it to this copy with `npx project-spec install --dir <folder of the skill copies> --with-viewer`, '
699
+ 'or open the vault folder in Obsidian')
700
+ template = found.read_text(encoding='utf-8')
688
701
  if template.count('__KNOWLEDGE_DATA__') != 1:
689
- raise ValueError('viewer template must contain exactly one placeholder')
702
+ raise ValueError(f'{found} must contain the placeholder __KNOWLEDGE_DATA__ exactly once')
703
+ return template
704
+
705
+
706
+ def viewer_html(payload):
707
+ template = viewer_template()
690
708
  serialized = json.dumps(payload, ensure_ascii=False).replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e').replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
691
709
  return template.replace('__KNOWLEDGE_DATA__', serialized)
692
710
 
@@ -903,6 +921,8 @@ def main(argv=None):
903
921
  parser.add_argument('--port', type=int, default=8757, help='serve: port on 127.0.0.1 (another free port is used if it is taken)')
904
922
  parser.add_argument('--open', action='store_true', help='serve: open the page in the default browser')
905
923
  parser.add_argument('--out', type=Path, help='build: the HTML file to write, outside the vault')
924
+ parser.add_argument('--viewer', type=Path, metavar='FILE',
925
+ help='serve, build: a page of your own instead of the viewer; it gets the data where it says __KNOWLEDGE_DATA__')
906
926
  parser.add_argument('--with-sources', action='store_true', help='build: include the text of the repository files the pages cite')
907
927
  parser.add_argument('--source-url', default='', help='build: where a cited file can be read, e.g. https://github.com/OWNER/REPO/blob/{commit}')
908
928
  parser.add_argument('--allow-missing-sources', action='store_true',
@@ -933,6 +953,15 @@ def main(argv=None):
933
953
  vault = args.vault.resolve() if args.vault else find_vault(repo)
934
954
  if not vault.is_dir():
935
955
  parser.error('repo and vault must be existing directories')
956
+ if args.viewer and args.command not in ('serve', 'build'):
957
+ parser.error('--viewer is only for serve and build')
958
+ if args.command in ('serve', 'build'):
959
+ global VIEWER
960
+ VIEWER = args.viewer.resolve() if args.viewer else None
961
+ try:
962
+ viewer_template()
963
+ except (OSError, ValueError) as exc:
964
+ parser.error(str(exc))
936
965
  if args.command == 'serve':
937
966
  try:
938
967
  server = make_server(repo, vault, args.port)
@@ -94,6 +94,10 @@ Never guess a decision from silence, from a plan existing, or from a task being
94
94
 
95
95
  When an agent sets `decision: "done"` because it read (or ran) the current code and the gap no longer holds, that reading is itself a recheck, and the page should say so. In the same edit record `recheck: "not-reproduced"`, `rechecked_by: "agent"`, today's `rechecked_on`, and add a dated entry to `Recheck` saying what was read or run. In `Decision`, say where in the code the question is now closed. The two sections answer different questions: `Recheck` is how you know it no longer holds, `Decision` is where the code does it. Without the recheck fields a closed gap looks as if nobody ever looked at the code. When a person closes a gap as done, they record the decision in `decided_by` and `Decision`. Their name goes in `rechecked_by` (not `agent`) only if they read or ran the current code themselves and add a `Recheck` entry saying what they did; if they decided without doing so, leave the recheck fields as they are. If you are not sure the question is closed, leave it open.
96
96
 
97
+ Closing a gap is also the moment its answer becomes part of the spec. Before you set `done`, open the page of the feature the gap is about and make sure it states what is true now as a numbered rule, read from the current code: add the rule, or correct the one that was there. Then name that rule in the gap's `Decision` ("Closed by BR-USERS-07") next to the place in the code. The same goes for `rejected`: the behavior stays as it is, so the feature's page should already state it as a rule, and `Decision` names that rule beside the person's reason. The link goes one way, from the gap to the spec page; a spec page still never mentions a gap.
98
+
99
+ A closed gap is not deleted. The spec says what the code does; the closed gap is the only place that says why, who decided and what was checked. The viewer takes closed gaps (`done`, `rejected`, `duplicate`) out of the queue, lists them under History with the most recently closed first, and shows them on the feature's page as closed questions, folded under the text. Delete a gap only when a person calls the page noise.
100
+
97
101
  ## Derived state
98
102
 
99
103
  Computed by the helper, never written into Markdown:
@@ -791,6 +791,15 @@
791
791
  details.fold > :last-child {
792
792
  margin-bottom: 20px;
793
793
  }
794
+ .fold-rows .row {
795
+ padding-left: 0;
796
+ padding-right: 0;
797
+ }
798
+ .more-row {
799
+ display: flex;
800
+ align-items: center;
801
+ gap: 14px;
802
+ }
794
803
  .here-path {
795
804
  display: flex;
796
805
  flex-direction: column;
@@ -1697,7 +1706,12 @@
1697
1706
  "Someone has to confirm that the page's description of the current code is still right.",
1698
1707
  "needs-decision":
1699
1708
  "Rechecked; waiting for a person to accept, reject or defer.",
1709
+ history:
1710
+ "Closed questions: done, rejected, or a duplicate of another. They are kept for the reason behind a rule.",
1700
1711
  };
1712
+ // A closed gap is out of the queue: it is history, read for the reason behind a rule.
1713
+ const CLOSED_STATES = ["done", "rejected", "duplicate"],
1714
+ OPEN_STATES = STATES.filter((s) => !CLOSED_STATES.includes(s));
1701
1715
  const recheckLabels = {
1702
1716
  "not-checked": "Not checked",
1703
1717
  confirmed: "Confirmed (still holds)",
@@ -1727,6 +1741,10 @@
1727
1741
  : "needs-recheck";
1728
1742
  return STATES.includes(decision) ? decision : "needs-recheck";
1729
1743
  };
1744
+ const isClosed = (n) => CLOSED_STATES.includes(stateOf(n));
1745
+ // The day a gap was closed, as far as the page says: the decision, else the recheck that closed it.
1746
+ const closedOn = (n) => str(n.decidedOn) || str(n.recheckedOn) || str(n.updated);
1747
+ const byClosed = (a, b) => closedOn(b).localeCompare(closedOn(a)) || byTitle(a, b);
1730
1748
  const recheckOutdated = (n) =>
1731
1749
  isGap(n) && (n.recheckOutdated === true || n.recheck === "outdated");
1732
1750
  const stateRank = (n) => {
@@ -2784,7 +2802,10 @@
2784
2802
  // A note is read as written: what the feature is for and its rules. An area is a map of its notes.
2785
2803
  if (n.type === "area") main.append(featureList(featuresOf(n)));
2786
2804
  else main.append(markdown(bodyOf(n), n));
2787
- const about = gapsAbout(n).filter((g) => !["done", "rejected", "duplicate"].includes(stateOf(g)));
2805
+ const asked = gapsAbout(n),
2806
+ about = asked.filter((g) => !isClosed(g)),
2807
+ // a duplicate is answered on the gap it repeats, so it is not a closed question of its own
2808
+ closed = asked.filter((g) => isClosed(g) && stateOf(g) !== "duplicate").sort(byClosed);
2788
2809
  if (about.length) {
2789
2810
  const card = el("section", null, "card"),
2790
2811
  head = el("div", null, "card-head");
@@ -2795,6 +2816,11 @@
2795
2816
  }
2796
2817
  const folds = el("div");
2797
2818
  if (n.type === "area") folds.append(fold("More about this area", markdown(bodyOf(n), n)));
2819
+ if (closed.length) {
2820
+ const list = el("div", null, "fold-rows");
2821
+ closed.forEach((g) => list.append(gapRow(g)));
2822
+ folds.append(fold("Closed questions (" + closed.length + ")", list));
2823
+ }
2798
2824
  const sources = (Array.isArray(n.sources) ? n.sources : []).filter(str);
2799
2825
  if (sources.length) {
2800
2826
  const ul = el("ul", null, "link-list");
@@ -2815,7 +2841,9 @@
2815
2841
  view.append(page);
2816
2842
  }
2817
2843
 
2818
- let gapState = "all",
2844
+ const GAP_PORTION = 40;
2845
+ let gapState = "open", // "open", one of the open states, or "history"
2846
+ gapShown = GAP_PORTION,
2819
2847
  gapArea = "",
2820
2848
  gapKind = "",
2821
2849
  gapPriority = ""; // "" for all, "none" for gaps without one, otherwise the value
@@ -2846,17 +2874,21 @@
2846
2874
  (!gapKind || n.kind === gapKind) &&
2847
2875
  (!gapPriority || (priorityOf(n) || "none") === gapPriority),
2848
2876
  ),
2849
- again = () => show();
2877
+ again = () => {
2878
+ gapShown = GAP_PORTION;
2879
+ show();
2880
+ },
2881
+ history = pool.filter(isClosed).length;
2850
2882
  head.append(
2851
2883
  pills(
2852
2884
  "State",
2853
- // A state with no gaps under the current filters is left out, unless it is the one selected.
2885
+ // The queue is the open work; what is closed is one step away, under History. A state with
2886
+ // no gaps under the current filters is left out, unless it is the one selected.
2854
2887
  [
2855
- ["all", "All", pool.length],
2856
- ...STATES.map((s) => [s, stateLabels[s], pool.filter((g) => stateOf(g) === s).length]).filter(
2857
- ([s, , count]) => count || s === gapState,
2858
- ),
2859
- ],
2888
+ ["open", "Open", pool.length - history],
2889
+ ...OPEN_STATES.map((s) => [s, stateLabels[s], pool.filter((g) => stateOf(g) === s).length]),
2890
+ ["history", "History", history],
2891
+ ].filter(([s, , count]) => count || s === gapState || s === "open"),
2860
2892
  gapState,
2861
2893
  (s) => {
2862
2894
  gapState = s;
@@ -2900,14 +2932,30 @@
2900
2932
  ),
2901
2933
  );
2902
2934
  const shown = pool
2903
- .filter((g) => gapState === "all" || stateOf(g) === gapState)
2904
- .sort(byGapOrder);
2935
+ .filter((g) => (gapState === "open" ? !isClosed(g) : gapState === "history" ? isClosed(g) : stateOf(g) === gapState))
2936
+ .sort(gapState === "history" ? byClosed : byGapOrder);
2905
2937
  if (shown.length) {
2906
- const card = el("section", null, "card");
2938
+ // A long queue comes in portions: the most urgent are in the first one, the rest one press away.
2939
+ const card = el("section", null, "card"),
2940
+ more = el("div", null, "more-row");
2907
2941
  card.id = "gap-list";
2908
- shown.forEach((g) => card.append(gapRow(g)));
2909
- box.append(card);
2910
- } else box.append(el("p", "No gaps match. Try other filters.", "empty"));
2942
+ const fill = () => {
2943
+ const upto = Math.min(gapShown, shown.length);
2944
+ card.replaceChildren(...shown.slice(0, upto).map(gapRow));
2945
+ more.replaceChildren();
2946
+ if (shown.length <= GAP_PORTION) return;
2947
+ if (upto < shown.length)
2948
+ more.append(
2949
+ button("Show " + Math.min(GAP_PORTION, shown.length - upto) + " more", "btn", () => {
2950
+ gapShown += GAP_PORTION;
2951
+ fill();
2952
+ }),
2953
+ );
2954
+ more.append(el("span", upto + " of " + shown.length, "muted small"));
2955
+ };
2956
+ fill();
2957
+ box.append(card, more);
2958
+ } else box.append(el("p", gapState === "history" ? "Nothing is closed yet." : "No gaps match. Try other filters.", "empty"));
2911
2959
  view.append(box);
2912
2960
  }
2913
2961