specpilot 2.20.0 → 2.21.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.
Files changed (92) hide show
  1. package/README.md +35 -14
  2. package/dist/cli.js +6 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/add-specs.d.ts +1 -0
  5. package/dist/commands/add-specs.d.ts.map +1 -1
  6. package/dist/commands/add-specs.js +8 -2
  7. package/dist/commands/add-specs.js.map +1 -1
  8. package/dist/commands/backfill.js +8 -9
  9. package/dist/commands/backfill.js.map +1 -1
  10. package/dist/commands/init.d.ts +1 -0
  11. package/dist/commands/init.d.ts.map +1 -1
  12. package/dist/commands/init.js +10 -4
  13. package/dist/commands/init.js.map +1 -1
  14. package/dist/commands/refine.d.ts.map +1 -1
  15. package/dist/commands/refine.js +6 -1
  16. package/dist/commands/refine.js.map +1 -1
  17. package/dist/commands/serve.d.ts +1 -1
  18. package/dist/commands/serve.d.ts.map +1 -1
  19. package/dist/commands/serve.js +22 -7
  20. package/dist/commands/serve.js.map +1 -1
  21. package/dist/commands/validate.d.ts.map +1 -1
  22. package/dist/commands/validate.js +4 -0
  23. package/dist/commands/validate.js.map +1 -1
  24. package/dist/core/chatFlow.js +1 -1
  25. package/dist/core/chatFlow.js.map +1 -1
  26. package/dist/core/ideConfig.d.ts +0 -1
  27. package/dist/core/ideConfig.d.ts.map +1 -1
  28. package/dist/core/ideConfig.js +1 -2
  29. package/dist/core/ideConfig.js.map +1 -1
  30. package/dist/core/render.d.ts +2 -0
  31. package/dist/core/render.d.ts.map +1 -1
  32. package/dist/core/render.js +1 -0
  33. package/dist/core/render.js.map +1 -1
  34. package/dist/core/slashCommands.js +7 -7
  35. package/dist/core/specFiles.js +8 -6
  36. package/dist/core/specFiles.js.map +1 -1
  37. package/dist/core/templateEngine.d.ts +1 -0
  38. package/dist/core/templateEngine.d.ts.map +1 -1
  39. package/dist/core/templateEngine.js +4 -0
  40. package/dist/core/templateEngine.js.map +1 -1
  41. package/dist/utils/addSpecsQuestions.d.ts +7 -0
  42. package/dist/utils/addSpecsQuestions.d.ts.map +1 -1
  43. package/dist/utils/addSpecsQuestions.js +7 -1
  44. package/dist/utils/addSpecsQuestions.js.map +1 -1
  45. package/dist/utils/folderPicker.d.ts.map +1 -1
  46. package/dist/utils/folderPicker.js +3 -1
  47. package/dist/utils/folderPicker.js.map +1 -1
  48. package/dist/utils/ideConfigGenerator.d.ts +2 -8
  49. package/dist/utils/ideConfigGenerator.d.ts.map +1 -1
  50. package/dist/utils/ideConfigGenerator.js +2 -9
  51. package/dist/utils/ideConfigGenerator.js.map +1 -1
  52. package/dist/utils/mcpLocal.js +1 -1
  53. package/dist/utils/mcpLocal.js.map +1 -1
  54. package/dist/utils/nodeCheck.d.ts +20 -0
  55. package/dist/utils/nodeCheck.d.ts.map +1 -0
  56. package/dist/utils/nodeCheck.js +50 -0
  57. package/dist/utils/nodeCheck.js.map +1 -0
  58. package/dist/utils/projectRegistry.d.ts +2 -0
  59. package/dist/utils/projectRegistry.d.ts.map +1 -1
  60. package/dist/utils/projectRegistry.js +3 -1
  61. package/dist/utils/projectRegistry.js.map +1 -1
  62. package/dist/utils/slashCommandGenerator.d.ts.map +1 -1
  63. package/dist/utils/slashCommandGenerator.js +12 -0
  64. package/dist/utils/slashCommandGenerator.js.map +1 -1
  65. package/dist/utils/specArchiver.d.ts +17 -4
  66. package/dist/utils/specArchiver.d.ts.map +1 -1
  67. package/dist/utils/specArchiver.js +20 -4
  68. package/dist/utils/specArchiver.js.map +1 -1
  69. package/dist/utils/specBackfiller.d.ts +19 -12
  70. package/dist/utils/specBackfiller.d.ts.map +1 -1
  71. package/dist/utils/specBackfiller.js +54 -56
  72. package/dist/utils/specBackfiller.js.map +1 -1
  73. package/dist/utils/specPaths.d.ts.map +1 -1
  74. package/dist/utils/specPaths.js +5 -2
  75. package/dist/utils/specPaths.js.map +1 -1
  76. package/dist/utils/specServer.d.ts +24 -0
  77. package/dist/utils/specServer.d.ts.map +1 -1
  78. package/dist/utils/specServer.js +205 -62
  79. package/dist/utils/specServer.js.map +1 -1
  80. package/dist/utils/specValidator.d.ts +6 -0
  81. package/dist/utils/specValidator.d.ts.map +1 -1
  82. package/dist/utils/specValidator.js +153 -8
  83. package/dist/utils/specValidator.js.map +1 -1
  84. package/dist/utils/taskMover.d.ts +9 -3
  85. package/dist/utils/taskMover.d.ts.map +1 -1
  86. package/dist/utils/taskMover.js +42 -18
  87. package/dist/utils/taskMover.js.map +1 -1
  88. package/package.json +3 -3
  89. package/ui/app.css +107 -11
  90. package/ui/app.js +320 -43
  91. package/ui/index.html +41 -23
  92. package/ui/route.js +41 -12
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MAX_EVENT_STREAMS = exports.MAX_MCP_BODY = exports.MAX_MOVE_BODY = void 0;
4
4
  exports.isAllowedHost = isAllowedHost;
5
5
  exports.readBranch = readBranch;
6
+ exports.readCommits = readCommits;
6
7
  exports.buildSpecsPayload = buildSpecsPayload;
7
8
  exports.regenerateReport = regenerateReport;
8
9
  exports.displayRoot = displayRoot;
@@ -26,8 +27,11 @@ const specBackfiller_1 = require("./specBackfiller");
26
27
  const slashCommandGenerator_1 = require("./slashCommandGenerator");
27
28
  const slashCommands_1 = require("../core/slashCommands");
28
29
  const agentConfig_1 = require("../core/agentConfig");
30
+ const ideConfig_1 = require("../core/ideConfig");
29
31
  const specValidator_1 = require("./specValidator");
30
32
  const mcpLocal_1 = require("./mcpLocal");
33
+ const specArchiver_1 = require("./specArchiver");
34
+ const nodeCheck_1 = require("./nodeCheck");
31
35
  // Local server behind `specpilot serve` (BL-051, ARCH-004.33, SEC-004.8). Every request re-reads disk;
32
36
  // nothing is cached. The server writes nothing itself: task moves go through taskMover.ts (BL-053),
33
37
  // guided setup and new projects through specSetup.ts (BL-055, BL-PM-003), the project registry through
@@ -71,6 +75,73 @@ function readBranch(root) {
71
75
  return null;
72
76
  }
73
77
  }
78
+ const REFLOG_TAIL = 64 * 1024;
79
+ const REFLOG_LINE = /^[0-9a-f]{40}(?:[0-9a-f]{24})? ([0-9a-f]{40}(?:[0-9a-f]{24})?) .*? (\d+) ([+-])(\d{2})(\d{2})\t(?:commit|commit \((?:initial|merge|amend)\)): (.*)$/;
80
+ /**
81
+ * The newest commits made in this clone, from `.git/logs/HEAD` read as a file (BL-171, REQ-002.H.76, SEC-004.38): a linked
82
+ * worktree's `gitdir:` is followed only into `.git/worktrees/<name>`; the log must be a regular file and only its last 64 KB is
83
+ * read. Each entry gives a seven-character hash, its date in ISO 8601 with its own zone, and its message; never the author.
84
+ */
85
+ function readCommits(root, count = 5) {
86
+ try {
87
+ let gitDir = (0, path_1.join)(root, '.git');
88
+ const st = (0, fs_1.lstatSync)(gitDir);
89
+ if (st.isFile()) {
90
+ const m = /^gitdir:\s*(.+)$/m.exec((0, fs_1.readFileSync)(gitDir, 'utf-8'));
91
+ if (!m)
92
+ return [];
93
+ gitDir = (0, fs_1.realpathSync)((0, path_1.resolve)(root, m[1].trim()));
94
+ if (!/\/\.git\/worktrees\/[^/]+$/.test(gitDir.split(path_1.sep).join('/')))
95
+ return [];
96
+ }
97
+ else if (!st.isDirectory())
98
+ return [];
99
+ const file = (0, path_1.join)(gitDir, 'logs', 'HEAD');
100
+ const fst = (0, fs_1.lstatSync)(file);
101
+ if (!fst.isFile())
102
+ return [];
103
+ const len = Math.min(fst.size, REFLOG_TAIL);
104
+ const buf = Buffer.alloc(len);
105
+ const fd = (0, fs_1.openSync)(file, 'r');
106
+ try {
107
+ (0, fs_1.readSync)(fd, buf, 0, len, fst.size - len);
108
+ }
109
+ finally {
110
+ (0, fs_1.closeSync)(fd);
111
+ }
112
+ const lines = buf.toString('utf-8').split('\n');
113
+ if (fst.size > REFLOG_TAIL)
114
+ lines.shift(); // the tail starts mid-line
115
+ const out = [];
116
+ for (let i = lines.length - 1; i >= 0 && out.length < count; i--) {
117
+ const m = REFLOG_LINE.exec(lines[i]);
118
+ if (!m)
119
+ continue;
120
+ const offset = (m[3] === '-' ? -1 : 1) * (Number(m[4]) * 60 + Number(m[5]));
121
+ const local = new Date((Number(m[2]) + offset * 60) * 1000).toISOString().slice(0, 19);
122
+ out.push({ hash: m[1].slice(0, 7), date: `${local}${m[3]}${m[4]}:${m[5]}`, message: m[6] });
123
+ }
124
+ return out;
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ }
130
+ const OVERVIEW_KEYS = ['name', 'description', 'version', 'language', 'framework', 'license'];
131
+ /** Overview's Project card (BL-171): six top-level project.yaml keys, each a string, number or boolean as written, else null. */
132
+ function overviewProject(yamlText) {
133
+ let doc = null;
134
+ try {
135
+ const d = yamlText === undefined ? null : (0, specReader_1.loadRepoYaml)(yamlText);
136
+ if (d && typeof d === 'object' && !Array.isArray(d))
137
+ doc = d;
138
+ }
139
+ catch {
140
+ doc = null;
141
+ }
142
+ const scalar = (v) => (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? v : null);
143
+ return Object.fromEntries(OVERVIEW_KEYS.map(k => [k, scalar(doc?.[k])]));
144
+ }
74
145
  /** `key: value` lines of a leading `---` block, values as written; null when there is none. */
75
146
  function frontMatter(text) {
76
147
  const lines = text.split('\n');
@@ -122,6 +193,10 @@ function tasksHash(root) {
122
193
  return real ? (0, taskMover_1.sha256)((0, fs_1.readFileSync)(real)) : null;
123
194
  }
124
195
  const CURSOR_RULES = '.cursor/rules/specpilot.mdc';
196
+ /** The command folders `nav.commands` lists, in this order; `nav.prompts` is Copilot's `.github/prompts` (BL-152). */
197
+ const COMMAND_FOLDERS = ['.claude/commands', '.cursor/commands', '.windsurf/workflows', '.agent/workflows', '.codex/prompts', '.devin/workflows']; // the last: Devin Desktop's, BL-175
198
+ /** The project skills folders `nav.skills` lists, in this order: each IDE's documented one (BL-156, REQ-002.H.67). */
199
+ const SKILL_FOLDERS = ['.claude/skills', '.agents/skills', '.cursor/skills', '.github/skills', '.agent/skills', '.devin/skills', '.windsurf/skills']; // the last two: Windsurf's, BL-164
125
200
  /** Everything `GET /api/specs` returns: project metadata, readSpecs() output, the nav tree. */
126
201
  function buildSpecsPayload(root, specpilotVersion) {
127
202
  const scanned = (0, specPaths_1.listAllowedFiles)(root).files;
@@ -132,14 +207,25 @@ function buildSpecsPayload(root, specpilotVersion) {
132
207
  contents[p.slice('.specs/'.length)] = (0, fs_1.readFileSync)(real, 'utf-8');
133
208
  }
134
209
  const { files, tasks } = (0, specReader_1.readSpecs)(contents);
210
+ const ides = (0, specBackfiller_1.projectIdes)(root);
211
+ const instructions = specPaths_1.ALLOWED_FILES.map(path => {
212
+ const real = (0, specPaths_1.resolveAllowedPath)(root, path);
213
+ return { path, exists: real !== null, bytes: real ? (0, fs_1.statSync)(real).size : 0 };
214
+ });
215
+ // The IDEs the project uses: its list, else the IDEs whose instruction file is shown present (BL-161, REQ-002.H.69)
216
+ const uses = ides ?? specBackfiller_1.IDE_SIGNALS.filter(s => instructions.some(f => f.path === s.signalFile && f.exists)).map(s => s.ide);
217
+ const writesFor = (path) => uses.filter(ide => (0, ideConfig_1.aiContextTarget)(ide) === path || (0, agentConfig_1.agentTargets)(ide).includes(path));
135
218
  return {
136
219
  project: {
137
220
  name: projectName(contents['project/project.yaml']),
138
221
  root,
139
222
  branch: readBranch(root),
140
223
  specs: !(0, specSetup_1.specsMissing)(root), // false → the page offers guided setup (BL-055)
141
- // the file SpecPilot writes for Cursor; checked, never served (BL-PM-010, SEC-004.8)
142
- cursor: (0, specPaths_1.resolveAllowedPath)(root, CURSOR_RULES, [CURSOR_RULES]) !== null,
224
+ ides, // project.yaml's IDEs, or null without a list (BL-158, REQ-002.A.13)
225
+ // with a list, whether it names Cursor; else the file SpecPilot writes for Cursor, exactly this path, so a link
226
+ // to another allowlisted file is false (REQ-002.H.34, BL-153)
227
+ cursor: ides ? ides.includes('cursor') : (0, specPaths_1.resolveAllowedPath)(root, CURSOR_RULES, [CURSOR_RULES]) !== null,
228
+ uses,
143
229
  },
144
230
  specpilotVersion, // top level since BL-080: the page's footer reads it with or without a project
145
231
  files,
@@ -147,19 +233,20 @@ function buildSpecsPayload(root, specpilotVersion) {
147
233
  tasks: tasks ? { ...tasks, intro: tasksIntro(contents['planning/tasks.md']), sha256: tasksHash(root), nextIds: (0, taskMover_1.suggestedIds)(root, contents['planning/tasks.md']), archive: (0, taskMover_1.completedArchiveStatus)(contents['planning/tasks.md']), moves: taskMover_1.MOVES } : null,
148
234
  nav: {
149
235
  specs: Object.keys(contents),
150
- instructions: specPaths_1.ALLOWED_FILES.map(path => {
151
- const real = (0, specPaths_1.resolveAllowedPath)(root, path);
152
- return { path, exists: real !== null, bytes: real ? (0, fs_1.statSync)(real).size : 0 };
153
- }),
236
+ instructions: instructions.map(f => ({ ...f, ides: writesFor(f.path) })), // ides: the IDEs of uses SpecPilot writes it for
154
237
  // generated: the page's "From SpecPilot" group, else "Yours" (BL-PM-006)
155
- commands: navFiles(root, scanned, '.claude/commands', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
156
- skills: navFiles(root, scanned, '.claude/skills', p => p.endsWith('/SKILL.md')).map(f => ({ ...f, generated: (0, agentConfig_1.agentTargets)('claude-code').includes(f.path) && (0, slashCommandGenerator_1.isSpecPilotSkill)(root) })), // by the commands' rule, BL-PM-012
238
+ commands: COMMAND_FOLDERS.flatMap(d => navFiles(root, scanned, d, p => p.endsWith('.md'))).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
239
+ skills: SKILL_FOLDERS.flatMap(d => navFiles(root, scanned, d, p => p.endsWith('/SKILL.md'))).map(f => ({ ...f, generated: (0, agentConfig_1.agentTargets)('claude-code').includes(f.path) && (0, slashCommandGenerator_1.isSpecPilotSkill)(root) })), // by the commands' rule, BL-PM-012
157
240
  prompts: navFiles(root, scanned, '.github/prompts', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
158
241
  },
242
+ // Overview (BL-171, REQ-002.H.76): page-only, no MCP tool returns it
243
+ overview: {
244
+ project: overviewProject(contents['project/project.yaml']),
245
+ commits: readCommits(root),
246
+ prompts: contents['development/prompts.md'] === undefined ? [] : (0, specArchiver_1.newestPrompts)(contents['development/prompts.md'], 3),
247
+ },
159
248
  };
160
249
  }
161
- /** The command folders the Commands view lists; the result names any other folder Regenerate touched. */
162
- const LISTED_COMMAND_FOLDERS = ['.claude/commands/', '.github/prompts/'];
163
250
  /** What Regenerate All did, as project-relative paths, and the lines the page shows verbatim (BL-PM-006, REQ-002.H.30). */
164
251
  function regenerateReport(results, skill = null) {
165
252
  const pathOf = (ide, name) => {
@@ -182,10 +269,6 @@ function regenerateReport(results, skill = null) {
182
269
  message.push(`Added: ${added.join(', ')}.`);
183
270
  if (kept.length)
184
271
  message.push(`Kept as they were: ${kept.map(k => `${k.path} (${k.reason})`).join(', ')}.`);
185
- const folders = [...new Set([...updated, ...added, ...kept.map(k => k.path)].filter(p => p !== skill?.path).map(p => p.slice(0, p.lastIndexOf('/') + 1)))];
186
- const unlisted = folders.filter(f => !LISTED_COMMAND_FOLDERS.includes(f));
187
- if (unlisted.length)
188
- message.push(`Not listed on this page: ${unlisted.join(', ')}.`);
189
272
  return { added, updated, kept, message };
190
273
  }
191
274
  /** `~` or `~/…` for the home directory and anything under it, else the path as given (BL-054). */
@@ -194,22 +277,29 @@ function displayRoot(root, home = (0, os_1.homedir)()) {
194
277
  return '~';
195
278
  return root.startsWith(home + path_1.sep) ? '~' + root.slice(home.length) : root;
196
279
  }
197
- /** One entry per served project, in index order: what the rail shows (BL-054). */
198
- function projectList(roots) {
199
- return roots.map(root => {
280
+ /** One entry per served project, in index order: what the rail shows (BL-054); a closed one keeps its slot as {closed: true} (BL-166). */
281
+ function projectList(roots, closed = new Set()) {
282
+ return roots.map((root, i) => {
283
+ if (closed.has(i))
284
+ return { closed: true };
200
285
  const yamlFile = (0, specPaths_1.resolveAllowedPath)(root, '.specs/project/project.yaml');
201
286
  return { name: projectName(yamlFile ? (0, fs_1.readFileSync)(yamlFile, 'utf-8') : undefined), root: displayRoot(root), branch: readBranch(root) };
202
287
  });
203
288
  }
204
- /** `?project=<n>` → index into the served roots: omitted = 0 when a project 0 exists (BL-080); one canonical whole number in range, else null (404). */
205
- function projectIndex(url, count) {
289
+ /** `?project=<n>` → index into the served roots: omitted = the first open project (BL-080, BL-166); one canonical whole
290
+ * number in range and not closed (REQ-002.H.75), else null (404). */
291
+ function projectIndex(url, count, closed = new Set()) {
206
292
  const given = url.searchParams.getAll('project');
207
- if (given.length === 0)
208
- return 0 < count ? 0 : null;
293
+ if (given.length === 0) {
294
+ for (let i = 0; i < count; i++)
295
+ if (!closed.has(i))
296
+ return i;
297
+ return null;
298
+ }
209
299
  if (given.length > 1 || !/^(0|[1-9][0-9]*)$/.test(given[0]))
210
300
  return null;
211
301
  const n = Number(given[0]);
212
- return n < count ? n : null;
302
+ return n < count && !closed.has(n) ? n : null;
213
303
  }
214
304
  const SECURITY_HEADERS = {
215
305
  // No other page may frame the UI (BL-143): its writes are one click each.
@@ -249,7 +339,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
249
339
  // The served roots: the command line's, then those opened from the page (BL-067). Append-only for the
250
340
  // life of the server, so an index never changes and nothing is dropped.
251
341
  const roots = [...initialRoots];
342
+ // The server's Node.js against engines.node (BL-190, REQ-002.H.78): computed once, in every body the page reads, never in an MCP result.
343
+ const node = { ...(0, nodeCheck_1.nodeStatus)(opts.nodeVersion), release: nodeCheck_1.RELEASE };
252
344
  const namedFlags = roots.map((_, i) => opts.named?.[i] ?? true);
345
+ // Closed projects (BL-166, REQ-002.H.75, SEC-004.37): removing a served project's entry retires its index; the
346
+ // slot stays so no other index moves, and the index is never reused. openRoots() is the one view of the open
347
+ // roots: the array with each closed slot blanked to '', which no path equals, so every lookup by path skips it.
348
+ const closed = new Set();
349
+ const openRoots = () => roots.map((root, i) => (closed.has(i) ? '' : root));
253
350
  // ---- live reload (BL-052): streams, heartbeat, and one poller per project (BL-054) that runs
254
351
  // only while that project has a stream open; the heartbeat runs while any stream is open
255
352
  const projectFor = (root) => {
@@ -283,6 +380,17 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
283
380
  clearInterval(heartbeat);
284
381
  heartbeat = null;
285
382
  };
383
+ /** Close project i for the run (BL-166): its index retired, its poller stopped, its streams told and ended. */
384
+ const closeProject = (i) => {
385
+ closed.add(i);
386
+ const { streams, poller } = projects[i];
387
+ poller.stop();
388
+ for (const res of [...streams]) {
389
+ res.write('event: closed\ndata: {}\n\n');
390
+ res.end();
391
+ drop(i, res);
392
+ }
393
+ };
286
394
  const openStream = (i, req, res) => {
287
395
  if (allStreams().length >= exports.MAX_EVENT_STREAMS)
288
396
  return send(res, 503, TEXT, 'Too many open event streams\n');
@@ -312,7 +420,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
312
420
  // `named`: whether the Setup view is offered there (REQ-002.H.15's current-directory rule, BL-103).
313
421
  const payload = (i) => {
314
422
  const p = buildSpecsPayload(roots[i], specpilotVersion);
315
- return { ...p, project: { ...p.project, named: namedFlags[i] }, projects: projectList(roots), mcp: { client: mcpClient } };
423
+ return { ...p, project: { ...p.project, named: namedFlags[i] }, projects: projectList(roots, closed), mcp: { client: mcpClient }, node };
316
424
  };
317
425
  /** Run `fn` under the write lock and settle with its outcome; a throw never breaks the chain for later writes. */
318
426
  const locked = (fn) => {
@@ -378,7 +486,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
378
486
  if (!writeAllowed(req, res))
379
487
  return;
380
488
  // The project is picked only now, so a request that failed the checks above learns nothing about it (SEC-004.11).
381
- const i = projectIndex(url, roots.length);
489
+ const i = projectIndex(url, roots.length, closed);
382
490
  if (i === null)
383
491
  return send(res, 404, TEXT, 'Not Found\n');
384
492
  readJson(req, res, body => {
@@ -389,6 +497,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
389
497
  if (!ifMatch)
390
498
  return sendJson(res, 428, { error: 'The move needs an If-Match header with the file hash the page last loaded.' });
391
499
  underLock(res, () => {
500
+ if (closed.has(i))
501
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
392
502
  let out;
393
503
  try {
394
504
  out = (0, taskMover_1.moveTask)(roots[i], body, ifMatch);
@@ -408,7 +518,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
408
518
  const handleNewTask = (req, res, url) => {
409
519
  if (!writeAllowed(req, res))
410
520
  return;
411
- const i = projectIndex(url, roots.length);
521
+ const i = projectIndex(url, roots.length, closed);
412
522
  if (i === null)
413
523
  return send(res, 404, TEXT, 'Not Found\n');
414
524
  readJson(req, res, body => {
@@ -420,6 +530,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
420
530
  return sendJson(res, 428, { error: 'A new task needs an If-Match header with the file hash the page last loaded.' });
421
531
  const { description, section, type, priority } = body;
422
532
  underLock(res, () => {
533
+ if (closed.has(i))
534
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
423
535
  let out;
424
536
  try {
425
537
  out = (0, taskMover_1.newTask)(roots[i], { description, section, type, priority }, ifMatch);
@@ -439,7 +551,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
439
551
  const handleReview = (req, res, url) => {
440
552
  if (!writeAllowed(req, res))
441
553
  return;
442
- const i = projectIndex(url, roots.length);
554
+ const i = projectIndex(url, roots.length, closed);
443
555
  if (i === null)
444
556
  return send(res, 404, TEXT, 'Not Found\n');
445
557
  readJson(req, res, body => {
@@ -451,6 +563,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
451
563
  return sendJson(res, 428, { error: 'This action needs an If-Match header with the file hash the page last loaded.' });
452
564
  const { id, action, note, date, toIndex } = body;
453
565
  underLock(res, () => {
566
+ if (closed.has(i))
567
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
454
568
  let out;
455
569
  try {
456
570
  out = (0, taskMover_1.reviewTask)(roots[i], { id, action, note, date, toIndex }, ifMatch);
@@ -470,7 +584,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
470
584
  const handleFields = (req, res, url) => {
471
585
  if (!writeAllowed(req, res))
472
586
  return;
473
- const i = projectIndex(url, roots.length);
587
+ const i = projectIndex(url, roots.length, closed);
474
588
  if (i === null)
475
589
  return send(res, 404, TEXT, 'Not Found\n');
476
590
  readJson(req, res, body => {
@@ -480,11 +594,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
480
594
  const ifMatch = String(req.headers['if-match'] ?? '').replace(/^W\//, '').replace(/"/g, '').trim();
481
595
  if (!ifMatch)
482
596
  return sendJson(res, 428, { error: 'This change needs an If-Match header with the file hash the page last loaded.' });
483
- const { id, type, priority } = body;
597
+ const { id, type, priority, description } = body;
484
598
  underLock(res, () => {
599
+ if (closed.has(i))
600
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
485
601
  let out;
486
602
  try {
487
- out = (0, taskMover_1.setTaskFields)(roots[i], { id, type, priority }, ifMatch);
603
+ out = (0, taskMover_1.setTaskFields)(roots[i], { id, type, priority, description }, ifMatch);
488
604
  }
489
605
  catch {
490
606
  return sendJson(res, 500, { error: 'planning/tasks.md could not be written. Nothing was changed.' });
@@ -501,7 +617,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
501
617
  const handleArchive = (req, res, url) => {
502
618
  if (!writeAllowed(req, res))
503
619
  return;
504
- const i = projectIndex(url, roots.length);
620
+ const i = projectIndex(url, roots.length, closed);
505
621
  if (i === null)
506
622
  return send(res, 404, TEXT, 'Not Found\n');
507
623
  readJson(req, res, body => {
@@ -515,6 +631,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
515
631
  if (!ifMatch)
516
632
  return sendJson(res, 428, { error: 'The archive needs an If-Match header with the file hash the page last loaded.' });
517
633
  underLock(res, () => {
634
+ if (closed.has(i))
635
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
518
636
  let out;
519
637
  try {
520
638
  out = (0, taskMover_1.archiveCompleted)(roots[i], ifMatch, force === true);
@@ -534,7 +652,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
534
652
  const handleRegenerate = (req, res, url) => {
535
653
  if (!writeAllowed(req, res))
536
654
  return;
537
- const i = projectIndex(url, roots.length);
655
+ const i = projectIndex(url, roots.length, closed);
538
656
  if (i === null)
539
657
  return send(res, 404, TEXT, 'Not Found\n');
540
658
  readJson(req, res, body => {
@@ -542,6 +660,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
542
660
  return sendJson(res, 422, { error: 'Regenerate All takes an empty JSON object, {}.' });
543
661
  }
544
662
  underLock(res, () => {
663
+ if (closed.has(i))
664
+ return send(res, 404, TEXT, 'Not Found\n'); // closed while this write waited for the lock (BL-166)
545
665
  if ((0, specSetup_1.specsMissing)(roots[i]))
546
666
  return sendJson(res, 422, { error: `No .specs/ folder in ${displayRoot(roots[i])}.` });
547
667
  // The skill is its own step (BL-PM-012): the MCP tool calls only the command step.
@@ -568,7 +688,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
568
688
  return {
569
689
  path: displayRoot(registry, home),
570
690
  entries: entries.map(e => {
571
- const i = roots.indexOf(e.path);
691
+ const i = openRoots().indexOf(e.path);
572
692
  return { path: e.path, root: displayRoot(e.path, home), lastOpened: e.lastOpened, pinned: e.pinned, project: i >= 0 ? i : null, exists: isDir(e.path) };
573
693
  }),
574
694
  error: read.error,
@@ -591,6 +711,9 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
591
711
  return null;
592
712
  };
593
713
  const TOO_MANY_PROJECTS = `This server already serves ${projectRegistry_1.MAX_PROJECTS} projects. Start another specpilot serve for more.`;
714
+ const TOO_MANY_SLOTS = `This server has opened ${projectRegistry_1.MAX_SLOTS} projects since it started. Quit and start specpilot serve again to open more.`;
715
+ /** Why one more project cannot be opened now, or null: open ones against MAX_PROJECTS, every index against MAX_SLOTS (BL-166). */
716
+ const capError = (pending) => roots.length - closed.size + pending >= projectRegistry_1.MAX_PROJECTS ? TOO_MANY_PROJECTS : roots.length + pending >= projectRegistry_1.MAX_SLOTS ? TOO_MANY_SLOTS : null;
594
717
  /**
595
718
  * Serve `root` as the next index and record it in the registry: the success body of an open, or null
596
719
  * after answering 422 because the folder's allowlisted files cannot be read (it is then not half-opened).
@@ -609,7 +732,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
609
732
  namedFlags.push(true);
610
733
  projects.push(project);
611
734
  const error = changeRegistry(entries => (0, projectRegistry_1.upsertEntry)(entries, root, new Date()));
612
- return { project: n, specs: { ...specs, project: { ...specs.project, named: true }, projects: projectList(roots), mcp: { client: mcpClient } }, registry: { ...registryBody(), ...(error ? { error } : {}) } };
735
+ return { project: n, specs: { ...specs, project: { ...specs.project, named: true }, projects: projectList(roots, closed), mcp: { client: mcpClient }, node }, registry: { ...registryBody(), ...(error ? { error } : {}) } };
613
736
  };
614
737
  /** `addRoot()` for a route: answers 422 itself when the folder cannot be read (it is then not half-opened). */
615
738
  const serveRoot = (res, root) => {
@@ -628,13 +751,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
628
751
  if (problem)
629
752
  return sendJson(res, 422, { error: problem });
630
753
  underLock(res, () => {
631
- const check = (0, projectRegistry_1.checkOpenPath)(body.path, roots, home);
754
+ const check = (0, projectRegistry_1.checkOpenPath)(body.path, openRoots(), home);
632
755
  if ('status' in check)
633
756
  return sendJson(res, check.status, check.project === undefined ? { error: check.error } : { error: check.error, project: check.project });
634
757
  if (cloningTarget && (check.root === cloningTarget || check.root.startsWith(cloningTarget + path_1.sep)))
635
758
  return sendJson(res, 409, { error: `${cloningTarget} is being cloned. Wait for it to finish.` });
636
- if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
637
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
759
+ const cap = capError(cloningTarget ? 1 : 0);
760
+ if (cap)
761
+ return sendJson(res, 409, { error: cap });
638
762
  const body200 = serveRoot(res, check.root);
639
763
  if (body200)
640
764
  sendJson(res, 200, body200);
@@ -653,9 +777,10 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
653
777
  return sendJson(res, 422, { error: problem });
654
778
  const { parent, name } = body;
655
779
  underLock(res, () => {
656
- if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
657
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
658
- const out = (0, specSetup_1.checkTarget)(parent, name, roots, home, cloningTarget);
780
+ const cap = capError(cloningTarget ? 1 : 0);
781
+ if (cap)
782
+ return sendJson(res, 409, { error: cap });
783
+ const out = (0, specSetup_1.checkTarget)(parent, name, openRoots(), home, cloningTarget);
659
784
  if ('status' in out)
660
785
  pendingTarget = null; // a refusal leaves no path writable that the page no longer shows (BL-104)
661
786
  if ('status' in out)
@@ -680,9 +805,10 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
680
805
  await underLock(res, () => {
681
806
  if (signal.aborted)
682
807
  return;
683
- if (roots.length >= projectRegistry_1.MAX_PROJECTS)
684
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
685
- const r = (0, specSetup_1.reserveTarget)(parent, name, roots, home);
808
+ const cap = capError(0);
809
+ if (cap)
810
+ return sendJson(res, 409, { error: cap });
811
+ const r = (0, specSetup_1.reserveTarget)(parent, name, openRoots(), home);
686
812
  if (!('status' in r)) {
687
813
  reserved = r;
688
814
  cloningTarget = r.target;
@@ -798,10 +924,15 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
798
924
  if (problem)
799
925
  return sendJson(res, 422, { error: problem });
800
926
  underLock(res, () => {
801
- const error = changeRegistry(entries => (0, projectRegistry_1.removeEntry)(entries, body.path));
927
+ const path = body.path;
928
+ const error = changeRegistry(entries => (0, projectRegistry_1.removeEntry)(entries, path));
802
929
  if (error)
803
930
  return sendJson(res, 422, { error });
804
- sendJson(res, 200, registryBody());
931
+ // BL-166: the served project with that stored path, byte for byte (no realpath or stat, REQ-002.H.20), closes
932
+ const i = openRoots().indexOf(path);
933
+ if (i >= 0)
934
+ closeProject(i);
935
+ sendJson(res, 200, { ...registryBody(), closed: i >= 0 ? i : null, projects: projectList(roots, closed) });
805
936
  });
806
937
  });
807
938
  };
@@ -817,6 +948,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
817
948
  const n = args.project ?? 0;
818
949
  if (!Number.isInteger(n) || n < 0 || n >= roots.length)
819
950
  throw new mcpLocal_1.ToolRefusal(`No project ${String(n)} is served. specpilot_list_projects lists them.`);
951
+ if (closed.has(n))
952
+ throw new mcpLocal_1.ToolRefusal(closedRefusal(n));
820
953
  return n;
821
954
  };
822
955
  const mcpHash = (args) => {
@@ -826,12 +959,20 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
826
959
  };
827
960
  const asJson = (data) => ({ text: JSON.stringify(data, null, 2), data });
828
961
  /** A task write's outcome as the tool's answer: the page's refusals, with the stale one worded for an agent. */
829
- const taskWrite = async (write) => {
962
+ const closedRefusal = (n) => `Project ${n} was closed. specpilot_list_projects lists the open ones.`;
963
+ /** A task write for project i under the lock; i is checked again there, since a remove may have closed it meanwhile (BL-166). */
964
+ const taskWrite = async (i, write) => {
830
965
  let out;
831
966
  try {
832
- out = await locked(write);
967
+ out = await locked(() => {
968
+ if (closed.has(i))
969
+ throw new mcpLocal_1.ToolRefusal(closedRefusal(i));
970
+ return write();
971
+ });
833
972
  }
834
- catch {
973
+ catch (err) {
974
+ if (err instanceof mcpLocal_1.ToolRefusal)
975
+ throw err;
835
976
  throw new mcpLocal_1.ToolRefusal('planning/tasks.md could not be written. Nothing was changed.');
836
977
  }
837
978
  if (out.status !== 200) {
@@ -863,7 +1004,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
863
1004
  return r;
864
1005
  }
865
1006
  };
866
- const index = roots.findIndex(r => r === norm || real(r) === norm);
1007
+ const index = openRoots().findIndex(r => r && (r === norm || real(r) === norm));
867
1008
  if (index >= 0 && namedFlags[index]) {
868
1009
  if (!(0, specSetup_1.specsMissing)(roots[index]))
869
1010
  throw new mcpLocal_1.ToolRefusal(BACKFILL(norm));
@@ -934,13 +1075,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
934
1075
  throw new mcpLocal_1.ToolRefusal(`${t.kind === 'new' ? t.target : t.root} changed while it was being set up. Call specpilot_setup_questions again.`);
935
1076
  emitSetup(t, { row: 'questions', state: 'done', ...counts });
936
1077
  emitSetup(t, { row: 'write', state: 'running' });
1078
+ let cap;
937
1079
  let out;
938
1080
  if (t.kind === 'existing')
939
1081
  out = await (0, specSetup_1.setupProject)(t.root, a);
940
- else if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
941
- out = { status: 409, error: TOO_MANY_PROJECTS };
1082
+ else if ((cap = capError(cloningTarget ? 1 : 0)))
1083
+ out = { status: 409, error: cap };
942
1084
  else
943
- out = await (0, specSetup_1.createProject)((0, path_1.dirname)(t.target), (0, path_1.basename)(t.target), a, roots, home, cloningTarget);
1085
+ out = await (0, specSetup_1.createProject)((0, path_1.dirname)(t.target), (0, path_1.basename)(t.target), a, openRoots(), home, cloningTarget);
944
1086
  if (out.status !== 200) {
945
1087
  emitSetup(t, { row: 'write', state: 'idle' });
946
1088
  throw new mcpLocal_1.ToolRefusal(out.error);
@@ -973,9 +1115,11 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
973
1115
  return setupProjectTool(args);
974
1116
  if (name === 'specpilot_list_projects') {
975
1117
  return asJson({
976
- projects: roots.map((root, n) => {
1118
+ projects: roots.flatMap((root, n) => {
1119
+ if (closed.has(n))
1120
+ return []; // BL-166: open projects only, each with its own number
977
1121
  const p = buildSpecsPayload(root, specpilotVersion);
978
- return { project: n, name: p.project.name, root: displayRoot(root), branch: p.project.branch, specs: p.project.specs, files: p.nav.specs.map(f => '.specs/' + f) };
1122
+ return [{ project: n, name: p.project.name, root: displayRoot(root), branch: p.project.branch, specs: p.project.specs, files: p.nav.specs.map(f => '.specs/' + f) }];
979
1123
  }),
980
1124
  });
981
1125
  }
@@ -998,7 +1142,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
998
1142
  if (problem)
999
1143
  throw new mcpLocal_1.ToolRefusal(problem);
1000
1144
  const hash = mcpHash(args);
1001
- const out = await taskWrite(() => (0, taskMover_1.newTask)(roots[i], task, hash));
1145
+ const out = await taskWrite(i, () => (0, taskMover_1.newTask)(roots[i], task, hash));
1002
1146
  return asJson({ id: out.id, section: out.section, index: out.index, sha256: out.sha256 });
1003
1147
  }
1004
1148
  if (name === 'specpilot_move_task') {
@@ -1007,16 +1151,16 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1007
1151
  if (problem)
1008
1152
  throw new mcpLocal_1.ToolRefusal(problem);
1009
1153
  const hash = mcpHash(args);
1010
- const out = await taskWrite(() => (0, taskMover_1.moveTask)(roots[i], move, hash));
1154
+ const out = await taskWrite(i, () => (0, taskMover_1.moveTask)(roots[i], move, hash));
1011
1155
  return asJson({ from: out.from, fromIndex: out.fromIndex, sha256: out.sha256 });
1012
1156
  }
1013
1157
  if (name === 'specpilot_set_task') {
1014
1158
  const req = { id: args.id, type: args.type, priority: args.priority };
1015
- const problem = (0, taskMover_1.fieldsShapeError)(req);
1159
+ const problem = (0, taskMover_1.fieldsShapeError)(req, false);
1016
1160
  if (problem)
1017
1161
  throw new mcpLocal_1.ToolRefusal(problem);
1018
1162
  const hash = mcpHash(args);
1019
- const out = await taskWrite(() => (0, taskMover_1.setTaskFields)(roots[i], req, hash));
1163
+ const out = await taskWrite(i, () => (0, taskMover_1.setTaskFields)(roots[i], req, hash));
1020
1164
  return asJson({ sha256: out.sha256 });
1021
1165
  }
1022
1166
  if (name === 'specpilot_validate_specs') {
@@ -1201,13 +1345,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1201
1345
  return send(res, 404, TEXT, 'Not Found\n');
1202
1346
  // No project served yet (BL-080): the page learns the state from /api/specs and listens for the
1203
1347
  // server-level events; the one place the omitted-project rule bends (REQ-002.H.44).
1204
- if (!roots.length && !url.searchParams.has('project')) {
1348
+ if (roots.length === closed.size && !url.searchParams.has('project')) { // none served, or none open (BL-166)
1205
1349
  if (url.pathname === '/api/specs')
1206
- return send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ project: null, projects: [], files: {}, specpilotVersion, mcp: { client: mcpClient } }));
1350
+ return send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ project: null, projects: [], files: {}, specpilotVersion, mcp: { client: mcpClient }, node }));
1207
1351
  if (url.pathname === '/api/events')
1208
1352
  return openStream(null, req, res);
1209
1353
  }
1210
- const i = projectIndex(url, roots.length);
1354
+ const i = projectIndex(url, roots.length, closed);
1211
1355
  if (i === null)
1212
1356
  return send(res, 404, TEXT, 'Not Found\n');
1213
1357
  if (url.pathname === '/api/specs')
@@ -1245,8 +1389,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1245
1389
  projects.forEach(p => p.poller.stop());
1246
1390
  server.close(() => resolveClose());
1247
1391
  // Every socket, not only the idle ones: a page's stream can reopen on a kept-alive socket while close() waits (BL-146).
1248
- // Node 18.2+; before that there is no sweep at all, as before.
1249
- server.closeAllConnections?.();
1392
+ server.closeAllConnections();
1250
1393
  });
1251
1394
  },
1252
1395
  };