project-spec 0.9.2 → 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.2",
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",
@@ -43,7 +43,7 @@ Natural-language requests are fine; these are modes, not a required CLI.
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.
@@ -151,7 +151,7 @@ python3 "$SKILL_DIR/scripts/knowledge.py" snapshot --repo "$REPO" --vault "$VAUL
151
151
 
152
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`.
153
153
 
154
- 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.
155
155
 
156
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:
157
157
 
@@ -250,7 +250,9 @@ Canonical Markdown must not contain raw merge conflicts. Validation rejects comp
250
250
 
251
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.
252
252
 
253
- `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.
254
256
 
255
257
  ## Format references
256
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
 
@@ -1,128 +0,0 @@
1
- import json
2
- import subprocess
3
- import sys
4
- import tempfile
5
- import unittest
6
- from contextlib import redirect_stderr, redirect_stdout
7
- from io import StringIO
8
- from pathlib import Path
9
-
10
- sys.path.insert(0, str(Path(__file__).resolve().parent))
11
- import coverage as c # noqa: E402
12
-
13
-
14
- class CoverageTests(unittest.TestCase):
15
- def setUp(self):
16
- self.temp = tempfile.TemporaryDirectory()
17
- self.repo = Path(self.temp.name).resolve() / 'repo'
18
- self.vault = self.repo / 'knowledge/demo'
19
- (self.vault / 'notes').mkdir(parents=True)
20
- (self.vault / 'areas').mkdir()
21
- self.page('00-index.md', 'index', 'index', areas=[], body='[[areas/chat]]')
22
- self.page('areas/chat.md', 'chat', 'area', areas=[], body='[[notes/chats]]')
23
- self.page('notes/chats.md', 'chats', sources=['src/chat/send.ts'],
24
- body='A message is refused with "Message can’t be empty". At most 10 photos (`CHAT_MAX_MEDIA`).\n\n'
25
- '| ID | Rule |\n| --- | --- |\n| BR-CHAT-01 | Only group chats can be renamed, by a member \\| staff. |')
26
- self.code('src/chat/send.ts', '''
27
- export const CHAT_MAX_MEDIA = 10;
28
- export const COLD_OUTREACH_PER_HOUR: number = 5; // new people
29
- const RETRY_MS = 60 * 1000
30
- const queryKey = "chats.list";
31
- throw new Error("Message can't be empty");
32
- throw new Error('Only group chats can be renamed');
33
- throw new Error("You cannot remove yourself");
34
- console.error("Failed to load the chat list");
35
- const cls = "flex items-center gap-2 Text here";
36
- const sql = "SELECT id FROM chats WHERE owner = 1";
37
- ''')
38
- self.code('src/chat/window/Header.tsx', '<Button>Back to chat list</Button>\n<p>{count} unread</p>\nconst t = `Hello ${name}, welcome back`;')
39
- self.code('src/chat/window/deep/Picker.tsx', 'const label = "Smileys and people";')
40
- self.code('src/chat/send.test.ts', 'it("says this in a test only", () => {})')
41
- self.code('src/chat/__tests__/more.ts', 'const s = "Only in a test folder";')
42
- self.code('src/orders/pay.py', 'MAX_TOTAL = 5000\nmessage = "The order was already paid"\n')
43
- self.code('database/migrations/001.sql', "INSERT INTO t VALUES ('A sentence in a migration');")
44
- self.code('node_modules/x/index.js', 'const s = "A sentence in a dependency";')
45
- self.code('src/help/article.ts', '\n'.join(f'const p{i} = "This is paragraph number {i} of an article";' for i in range(45)))
46
- (self.repo / 'README.md').write_text('Not code. "A sentence in the readme file"', encoding='utf-8')
47
-
48
- def tearDown(self):
49
- self.temp.cleanup()
50
-
51
- def page(self, path, ident, ptype='note', areas=None, sources=None, body=''):
52
- meta = {'id': ident, 'title': 'Page ' + ident, 'type': ptype, 'status': 'current', 'areas': ['chat'] if areas is None else areas,
53
- 'sources': sources or [], 'updated': '2026-11-18'}
54
- (self.vault / path).write_text('---\n' + ''.join(f'{key}: {json.dumps(value)}\n' for key, value in meta.items()) + '---\n' + body, encoding='utf-8')
55
-
56
- def code(self, path, text):
57
- file = self.repo / path
58
- file.parent.mkdir(parents=True, exist_ok=True)
59
- file.write_text(text, encoding='utf-8')
60
-
61
- def run_cli(self, *args):
62
- out, err = StringIO(), StringIO()
63
- with redirect_stdout(out), redirect_stderr(err):
64
- status = c.main(['--repo', str(self.repo), *args])
65
- return status, out.getvalue(), err.getvalue()
66
-
67
- def measured(self, *prefixes):
68
- import knowledge
69
- notes = knowledge.load_vault(self.repo, self.vault, freshness=False, absent=[])[0]
70
- return c.measure(self.repo, self.vault, notes, prefixes)
71
-
72
- def test_reads_only_the_application_code(self):
73
- self.assertEqual(sorted(self.measured()), ['src/chat/send.ts', 'src/chat/window/Header.tsx', 'src/chat/window/deep/Picker.tsx',
74
- 'src/help/article.ts', 'src/orders/pay.py'])
75
- # with Git, an ignored folder is left out as well, and an untracked file is still read
76
- subprocess.run(['git', '-C', str(self.repo), 'init', '-q'], check=True)
77
- (self.repo / '.gitignore').write_text('src/orders/\n', encoding='utf-8')
78
- self.assertNotIn('src/orders/pay.py', self.measured())
79
- self.assertIn('src/chat/send.ts', self.measured())
80
-
81
- def test_finds_the_sentences_and_numbers_no_page_mentions(self):
82
- files = self.measured()
83
- send = files['src/chat/send.ts']
84
- self.assertEqual((send['cited'], send['sentences'], send['limits']), (True, 3, 3))
85
- self.assertEqual(send['unquoted'], ['You cannot remove yourself'], 'a curly apostrophe and a table row still match; logs, class lists and queries are not sentences')
86
- self.assertEqual(send['unnamed'], [('COLD_OUTREACH_PER_HOUR', '5'), ('RETRY_MS', '60 * 1000')])
87
- self.assertEqual(files['src/chat/window/Header.tsx']['unquoted'], ['Back to chat list'], 'text between tags counts; text with a placeholder does not')
88
- self.assertEqual(files['src/orders/pay.py']['unnamed'], [('MAX_TOTAL', '5000')])
89
- article = files['src/help/article.ts']
90
- self.assertEqual((article['content'], article['sentences'], article['unquoted']), (True, 0, []), 'an article counts as a file only')
91
-
92
- def test_groups_by_folder_and_keeps_an_uncited_folder_as_one_line(self):
93
- groups = c.folders(self.measured())
94
- self.assertEqual(sorted(groups), ['src/chat', 'src/chat/window', 'src/help', 'src/orders'])
95
- self.assertEqual(groups['src/chat/window'], {'files': 2, 'lines': 4, 'cited': 0, 'sentences': 2, 'unquoted': 2, 'limits': 0, 'unnamed': 0})
96
- self.assertEqual((groups['src/chat']['files'], groups['src/chat']['cited']), (1, 1))
97
- # nothing cited anywhere: one line per top folder, and never above the folder that was asked for
98
- self.page('notes/chats.md', 'chats', sources=['README.md'])
99
- self.assertEqual(sorted(c.folders(self.measured())), ['src'])
100
- self.assertEqual(sorted(c.folders(self.measured('src/chat'), ['src/chat'])), ['src/chat'])
101
-
102
- def test_report_lists_what_to_read(self):
103
- status, out, err = self.run_cli()
104
- self.assertEqual((status, err), (0, ''))
105
- self.assertIn('coverage: 5 code files, ', out)
106
- self.assertIn('pages cite 1 of them', out)
107
- self.assertIn('6 sentences a person can see, 4 on no page; 4 named numbers, 3 on no page', out)
108
- self.assertIn('1 files that are mostly text (articles, templates) count as files only', out)
109
- self.assertLess(out.index('src/chat/window'), out.index('src/help'), 'the folder with the most to read comes first')
110
- self.assertNotIn('things under', out)
111
- status, out, _ = self.run_cli('--path', 'src/chat/')
112
- self.assertIn('coverage: 3 code files', out)
113
- self.assertIn('5 things under src/chat that no page mentions:', out)
114
- self.assertIn(' src/chat/send.ts says: You cannot remove yourself', out)
115
- self.assertIn(' src/chat/send.ts sets: RETRY_MS = 60 * 1000', out)
116
- self.assertIn('2 of 3 files there are cited by no page', out)
117
- self.assertEqual(self.run_cli('--path', 'nowhere')[1].strip(), 'coverage: no code files found under nowhere')
118
-
119
- def test_a_vault_with_errors_is_reported_and_still_measured(self):
120
- self.page('notes/bad.md', 'bad', sources=['src/chat/send.ts'], body='[[missing-page]]')
121
- status, out, err = self.run_cli()
122
- self.assertEqual(status, 0)
123
- self.assertIn('the vault has 1 errors', err)
124
- self.assertIn('coverage: 5 code files', out)
125
-
126
-
127
- if __name__ == '__main__':
128
- unittest.main()