specpilot 2.19.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 (131) hide show
  1. package/README.md +38 -15
  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 +13 -7
  7. package/dist/commands/add-specs.js.map +1 -1
  8. package/dist/commands/archive.d.ts +5 -0
  9. package/dist/commands/archive.d.ts.map +1 -1
  10. package/dist/commands/archive.js +15 -10
  11. package/dist/commands/archive.js.map +1 -1
  12. package/dist/commands/backfill.js +8 -9
  13. package/dist/commands/backfill.js.map +1 -1
  14. package/dist/commands/init.d.ts +1 -0
  15. package/dist/commands/init.d.ts.map +1 -1
  16. package/dist/commands/init.js +12 -39
  17. package/dist/commands/init.js.map +1 -1
  18. package/dist/commands/migrate.js +1 -1
  19. package/dist/commands/migrate.js.map +1 -1
  20. package/dist/commands/refine.d.ts.map +1 -1
  21. package/dist/commands/refine.js +21 -9
  22. package/dist/commands/refine.js.map +1 -1
  23. package/dist/commands/serve.d.ts +13 -1
  24. package/dist/commands/serve.d.ts.map +1 -1
  25. package/dist/commands/serve.js +38 -12
  26. package/dist/commands/serve.js.map +1 -1
  27. package/dist/commands/validate.d.ts.map +1 -1
  28. package/dist/commands/validate.js +7 -3
  29. package/dist/commands/validate.js.map +1 -1
  30. package/dist/core/agentConfig.js +6 -2
  31. package/dist/core/agentConfig.js.map +1 -1
  32. package/dist/core/chatFlow.d.ts +15 -1
  33. package/dist/core/chatFlow.d.ts.map +1 -1
  34. package/dist/core/chatFlow.js +45 -4
  35. package/dist/core/chatFlow.js.map +1 -1
  36. package/dist/core/ideConfig.d.ts +0 -1
  37. package/dist/core/ideConfig.d.ts.map +1 -1
  38. package/dist/core/ideConfig.js +1 -2
  39. package/dist/core/ideConfig.js.map +1 -1
  40. package/dist/core/render.d.ts +2 -0
  41. package/dist/core/render.d.ts.map +1 -1
  42. package/dist/core/render.js +1 -0
  43. package/dist/core/render.js.map +1 -1
  44. package/dist/core/slashCommands.js +7 -7
  45. package/dist/core/specFiles.d.ts.map +1 -1
  46. package/dist/core/specFiles.js +12 -9
  47. package/dist/core/specFiles.js.map +1 -1
  48. package/dist/core/templateEngine.d.ts +12 -0
  49. package/dist/core/templateEngine.d.ts.map +1 -1
  50. package/dist/core/templateEngine.js +44 -9
  51. package/dist/core/templateEngine.js.map +1 -1
  52. package/dist/utils/addSpecsQuestions.d.ts +7 -0
  53. package/dist/utils/addSpecsQuestions.d.ts.map +1 -1
  54. package/dist/utils/addSpecsQuestions.js +7 -1
  55. package/dist/utils/addSpecsQuestions.js.map +1 -1
  56. package/dist/utils/codeAnalyzer.d.ts +5 -0
  57. package/dist/utils/codeAnalyzer.d.ts.map +1 -1
  58. package/dist/utils/codeAnalyzer.js +52 -22
  59. package/dist/utils/codeAnalyzer.js.map +1 -1
  60. package/dist/utils/folderPicker.d.ts.map +1 -1
  61. package/dist/utils/folderPicker.js +5 -2
  62. package/dist/utils/folderPicker.js.map +1 -1
  63. package/dist/utils/gitClone.js +2 -2
  64. package/dist/utils/gitClone.js.map +1 -1
  65. package/dist/utils/ideConfigGenerator.d.ts +3 -8
  66. package/dist/utils/ideConfigGenerator.d.ts.map +1 -1
  67. package/dist/utils/ideConfigGenerator.js +9 -15
  68. package/dist/utils/ideConfigGenerator.js.map +1 -1
  69. package/dist/utils/logger.d.ts +5 -0
  70. package/dist/utils/logger.d.ts.map +1 -1
  71. package/dist/utils/logger.js +18 -11
  72. package/dist/utils/logger.js.map +1 -1
  73. package/dist/utils/mcpLocal.d.ts +2 -0
  74. package/dist/utils/mcpLocal.d.ts.map +1 -1
  75. package/dist/utils/mcpLocal.js +5 -5
  76. package/dist/utils/mcpLocal.js.map +1 -1
  77. package/dist/utils/nodeCheck.d.ts +20 -0
  78. package/dist/utils/nodeCheck.d.ts.map +1 -0
  79. package/dist/utils/nodeCheck.js +50 -0
  80. package/dist/utils/nodeCheck.js.map +1 -0
  81. package/dist/utils/projectDetector.d.ts +5 -0
  82. package/dist/utils/projectDetector.d.ts.map +1 -1
  83. package/dist/utils/projectDetector.js +16 -12
  84. package/dist/utils/projectDetector.js.map +1 -1
  85. package/dist/utils/projectRegistry.d.ts +4 -0
  86. package/dist/utils/projectRegistry.d.ts.map +1 -1
  87. package/dist/utils/projectRegistry.js +8 -1
  88. package/dist/utils/projectRegistry.js.map +1 -1
  89. package/dist/utils/slashCommandGenerator.d.ts.map +1 -1
  90. package/dist/utils/slashCommandGenerator.js +20 -67
  91. package/dist/utils/slashCommandGenerator.js.map +1 -1
  92. package/dist/utils/specArchiver.d.ts +22 -4
  93. package/dist/utils/specArchiver.d.ts.map +1 -1
  94. package/dist/utils/specArchiver.js +52 -16
  95. package/dist/utils/specArchiver.js.map +1 -1
  96. package/dist/utils/specBackfiller.d.ts +19 -12
  97. package/dist/utils/specBackfiller.d.ts.map +1 -1
  98. package/dist/utils/specBackfiller.js +81 -64
  99. package/dist/utils/specBackfiller.js.map +1 -1
  100. package/dist/utils/specGenerator.d.ts.map +1 -1
  101. package/dist/utils/specGenerator.js +15 -3
  102. package/dist/utils/specGenerator.js.map +1 -1
  103. package/dist/utils/specPaths.d.ts +30 -0
  104. package/dist/utils/specPaths.d.ts.map +1 -1
  105. package/dist/utils/specPaths.js +145 -2
  106. package/dist/utils/specPaths.js.map +1 -1
  107. package/dist/utils/specReader.d.ts +9 -0
  108. package/dist/utils/specReader.d.ts.map +1 -1
  109. package/dist/utils/specReader.js +50 -1
  110. package/dist/utils/specReader.js.map +1 -1
  111. package/dist/utils/specServer.d.ts +24 -0
  112. package/dist/utils/specServer.d.ts.map +1 -1
  113. package/dist/utils/specServer.js +252 -106
  114. package/dist/utils/specServer.js.map +1 -1
  115. package/dist/utils/specSetup.d.ts.map +1 -1
  116. package/dist/utils/specSetup.js +7 -16
  117. package/dist/utils/specSetup.js.map +1 -1
  118. package/dist/utils/specValidator.d.ts +6 -0
  119. package/dist/utils/specValidator.d.ts.map +1 -1
  120. package/dist/utils/specValidator.js +215 -29
  121. package/dist/utils/specValidator.js.map +1 -1
  122. package/dist/utils/taskMover.d.ts +9 -3
  123. package/dist/utils/taskMover.d.ts.map +1 -1
  124. package/dist/utils/taskMover.js +61 -54
  125. package/dist/utils/taskMover.js.map +1 -1
  126. package/package.json +3 -3
  127. package/ui/app.css +107 -11
  128. package/ui/app.js +333 -48
  129. package/ui/index.html +41 -23
  130. package/ui/md.js +13 -11
  131. package/ui/route.js +42 -13
@@ -1,41 +1,9 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.MAX_EVENT_STREAMS = exports.MAX_MCP_BODY = exports.MAX_MOVE_BODY = void 0;
37
4
  exports.isAllowedHost = isAllowedHost;
38
5
  exports.readBranch = readBranch;
6
+ exports.readCommits = readCommits;
39
7
  exports.buildSpecsPayload = buildSpecsPayload;
40
8
  exports.regenerateReport = regenerateReport;
41
9
  exports.displayRoot = displayRoot;
@@ -45,7 +13,6 @@ const http_1 = require("http");
45
13
  const fs_1 = require("fs");
46
14
  const path_1 = require("path");
47
15
  const os_1 = require("os");
48
- const yaml = __importStar(require("js-yaml"));
49
16
  const crypto_1 = require("crypto");
50
17
  const specReader_1 = require("./specReader");
51
18
  const taskMover_1 = require("./taskMover");
@@ -60,8 +27,11 @@ const specBackfiller_1 = require("./specBackfiller");
60
27
  const slashCommandGenerator_1 = require("./slashCommandGenerator");
61
28
  const slashCommands_1 = require("../core/slashCommands");
62
29
  const agentConfig_1 = require("../core/agentConfig");
30
+ const ideConfig_1 = require("../core/ideConfig");
63
31
  const specValidator_1 = require("./specValidator");
64
32
  const mcpLocal_1 = require("./mcpLocal");
33
+ const specArchiver_1 = require("./specArchiver");
34
+ const nodeCheck_1 = require("./nodeCheck");
65
35
  // Local server behind `specpilot serve` (BL-051, ARCH-004.33, SEC-004.8). Every request re-reads disk;
66
36
  // nothing is cached. The server writes nothing itself: task moves go through taskMover.ts (BL-053),
67
37
  // guided setup and new projects through specSetup.ts (BL-055, BL-PM-003), the project registry through
@@ -94,15 +64,84 @@ function readBranch(root) {
94
64
  gitDir = (0, path_1.resolve)(root, m[1].trim());
95
65
  }
96
66
  const head = (0, fs_1.readFileSync)((0, path_1.join)(gitDir, 'HEAD'), 'utf-8').trim();
97
- const ref = /^ref: refs\/heads\/(\S+)$/.exec(head);
67
+ // No control character (git's ref rules refuse them), and not a reftable repository's placeholder (BL-132).
68
+ // eslint-disable-next-line no-control-regex
69
+ const ref = /^ref: refs\/heads\/([^\s\x00-\x1f\x7f]+)$/.exec(head);
98
70
  if (ref)
99
- return ref[1];
71
+ return ref[1] === '.invalid' ? null : ref[1];
100
72
  return /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head) ? head : null;
101
73
  }
102
74
  catch {
103
75
  return null;
104
76
  }
105
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
+ }
106
145
  /** `key: value` lines of a leading `---` block, values as written; null when there is none. */
107
146
  function frontMatter(text) {
108
147
  const lines = text.split('\n');
@@ -132,7 +171,7 @@ function projectName(yamlText) {
132
171
  if (yamlText === undefined)
133
172
  return null;
134
173
  try {
135
- const doc = yaml.load(yamlText);
174
+ const doc = (0, specReader_1.loadRepoYaml)(yamlText);
136
175
  return doc && typeof doc.name === 'string' ? doc.name : null;
137
176
  }
138
177
  catch {
@@ -154,6 +193,10 @@ function tasksHash(root) {
154
193
  return real ? (0, taskMover_1.sha256)((0, fs_1.readFileSync)(real)) : null;
155
194
  }
156
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
157
200
  /** Everything `GET /api/specs` returns: project metadata, readSpecs() output, the nav tree. */
158
201
  function buildSpecsPayload(root, specpilotVersion) {
159
202
  const scanned = (0, specPaths_1.listAllowedFiles)(root).files;
@@ -164,14 +207,25 @@ function buildSpecsPayload(root, specpilotVersion) {
164
207
  contents[p.slice('.specs/'.length)] = (0, fs_1.readFileSync)(real, 'utf-8');
165
208
  }
166
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));
167
218
  return {
168
219
  project: {
169
220
  name: projectName(contents['project/project.yaml']),
170
221
  root,
171
222
  branch: readBranch(root),
172
223
  specs: !(0, specSetup_1.specsMissing)(root), // false → the page offers guided setup (BL-055)
173
- // the file SpecPilot writes for Cursor; checked, never served (BL-PM-010, SEC-004.8)
174
- 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,
175
229
  },
176
230
  specpilotVersion, // top level since BL-080: the page's footer reads it with or without a project
177
231
  files,
@@ -179,19 +233,20 @@ function buildSpecsPayload(root, specpilotVersion) {
179
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,
180
234
  nav: {
181
235
  specs: Object.keys(contents),
182
- instructions: specPaths_1.ALLOWED_FILES.map(path => {
183
- const real = (0, specPaths_1.resolveAllowedPath)(root, path);
184
- return { path, exists: real !== null, bytes: real ? (0, fs_1.statSync)(real).size : 0 };
185
- }),
236
+ instructions: instructions.map(f => ({ ...f, ides: writesFor(f.path) })), // ides: the IDEs of uses SpecPilot writes it for
186
237
  // generated: the page's "From SpecPilot" group, else "Yours" (BL-PM-006)
187
- commands: navFiles(root, scanned, '.claude/commands', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
188
- 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
189
240
  prompts: navFiles(root, scanned, '.github/prompts', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
190
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
+ },
191
248
  };
192
249
  }
193
- /** The command folders the Commands view lists; the result names any other folder Regenerate touched. */
194
- const LISTED_COMMAND_FOLDERS = ['.claude/commands/', '.github/prompts/'];
195
250
  /** What Regenerate All did, as project-relative paths, and the lines the page shows verbatim (BL-PM-006, REQ-002.H.30). */
196
251
  function regenerateReport(results, skill = null) {
197
252
  const pathOf = (ide, name) => {
@@ -214,10 +269,6 @@ function regenerateReport(results, skill = null) {
214
269
  message.push(`Added: ${added.join(', ')}.`);
215
270
  if (kept.length)
216
271
  message.push(`Kept as they were: ${kept.map(k => `${k.path} (${k.reason})`).join(', ')}.`);
217
- const folders = [...new Set([...updated, ...added, ...kept.map(k => k.path)].filter(p => p !== skill?.path).map(p => p.slice(0, p.lastIndexOf('/') + 1)))];
218
- const unlisted = folders.filter(f => !LISTED_COMMAND_FOLDERS.includes(f));
219
- if (unlisted.length)
220
- message.push(`Not listed on this page: ${unlisted.join(', ')}.`);
221
272
  return { added, updated, kept, message };
222
273
  }
223
274
  /** `~` or `~/…` for the home directory and anything under it, else the path as given (BL-054). */
@@ -226,25 +277,36 @@ function displayRoot(root, home = (0, os_1.homedir)()) {
226
277
  return '~';
227
278
  return root.startsWith(home + path_1.sep) ? '~' + root.slice(home.length) : root;
228
279
  }
229
- /** One entry per served project, in index order: what the rail shows (BL-054). */
230
- function projectList(roots) {
231
- 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 };
232
285
  const yamlFile = (0, specPaths_1.resolveAllowedPath)(root, '.specs/project/project.yaml');
233
286
  return { name: projectName(yamlFile ? (0, fs_1.readFileSync)(yamlFile, 'utf-8') : undefined), root: displayRoot(root), branch: readBranch(root) };
234
287
  });
235
288
  }
236
- /** `?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). */
237
- 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()) {
238
292
  const given = url.searchParams.getAll('project');
239
- if (given.length === 0)
240
- 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
+ }
241
299
  if (given.length > 1 || !/^(0|[1-9][0-9]*)$/.test(given[0]))
242
300
  return null;
243
301
  const n = Number(given[0]);
244
- return n < count ? n : null;
302
+ return n < count && !closed.has(n) ? n : null;
245
303
  }
246
304
  const SECURITY_HEADERS = {
247
- 'Content-Security-Policy': "default-src 'self'",
305
+ // No other page may frame the UI (BL-143): its writes are one click each.
306
+ 'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'",
307
+ 'X-Frame-Options': 'DENY',
308
+ 'Cross-Origin-Resource-Policy': 'same-origin',
309
+ 'Cross-Origin-Opener-Policy': 'same-origin',
248
310
  'X-Content-Type-Options': 'nosniff',
249
311
  'Cache-Control': 'no-store',
250
312
  };
@@ -262,6 +324,10 @@ exports.MAX_MOVE_BODY = 16 * 1024;
262
324
  const TOKEN_SLOT = '<!-- specpilot-token -->';
263
325
  /** Where index.html learns that /mcp is on, and whose token it takes: `page` or `env` (BL-PM-007). */
264
326
  const MCP_SLOT = '<!-- specpilot-mcp -->';
327
+ /** Sent where an earlier program's service worker shows itself: removes it (and this origin's localStorage) (BL-142). */
328
+ const CLEAR_STORAGE = { 'Clear-Site-Data': '"storage"' };
329
+ /** The reads only the page itself may make (BL-144). */
330
+ const READS = new Set(['/api/events', '/api/specs', '/api/file', '/api/projects']);
265
331
  /** Largest accepted body on /mcp: the setup answers, as the page's setup routes took them (BL-104). */
266
332
  exports.MAX_MCP_BODY = 64 * 1024;
267
333
  // The CLI's question list as the chat core takes it: the page's own rule, also read here since BL-104.
@@ -273,7 +339,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
273
339
  // The served roots: the command line's, then those opened from the page (BL-067). Append-only for the
274
340
  // life of the server, so an index never changes and nothing is dropped.
275
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 };
276
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));
277
350
  // ---- live reload (BL-052): streams, heartbeat, and one poller per project (BL-054) that runs
278
351
  // only while that project has a stream open; the heartbeat runs while any stream is open
279
352
  const projectFor = (root) => {
@@ -307,6 +380,17 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
307
380
  clearInterval(heartbeat);
308
381
  heartbeat = null;
309
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
+ };
310
394
  const openStream = (i, req, res) => {
311
395
  if (allStreams().length >= exports.MAX_EVENT_STREAMS)
312
396
  return send(res, 503, TEXT, 'Too many open event streams\n');
@@ -328,13 +412,15 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
328
412
  const token = opts.readOnly ? null : (0, crypto_1.randomBytes)(32).toString('hex');
329
413
  // /mcp's token (BL-PM-007): its own variable, because a null `token` is what turns the page's writes off.
330
414
  const mcpToken = !opts.mcp ? null : (opts.mcpToken ?? token ?? (0, crypto_1.randomBytes)(32).toString('hex'));
415
+ // Per start, on every asset reference: an entry another program cached for /assets/* is never used (BL-142).
416
+ const assetVersion = (0, crypto_1.randomBytes)(8).toString('hex');
331
417
  let writeLock = Promise.resolve(); // writes run strictly one after another, in every project
332
418
  // The MCP client whose initialize /mcp last answered (BL-103): null until then; `name` sanitized, '' when none was sent.
333
419
  let mcpClient = null;
334
420
  // `named`: whether the Setup view is offered there (REQ-002.H.15's current-directory rule, BL-103).
335
421
  const payload = (i) => {
336
422
  const p = buildSpecsPayload(roots[i], specpilotVersion);
337
- 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 };
338
424
  };
339
425
  /** Run `fn` under the write lock and settle with its outcome; a throw never breaks the chain for later writes. */
340
426
  const locked = (fn) => {
@@ -400,7 +486,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
400
486
  if (!writeAllowed(req, res))
401
487
  return;
402
488
  // The project is picked only now, so a request that failed the checks above learns nothing about it (SEC-004.11).
403
- const i = projectIndex(url, roots.length);
489
+ const i = projectIndex(url, roots.length, closed);
404
490
  if (i === null)
405
491
  return send(res, 404, TEXT, 'Not Found\n');
406
492
  readJson(req, res, body => {
@@ -411,6 +497,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
411
497
  if (!ifMatch)
412
498
  return sendJson(res, 428, { error: 'The move needs an If-Match header with the file hash the page last loaded.' });
413
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)
414
502
  let out;
415
503
  try {
416
504
  out = (0, taskMover_1.moveTask)(roots[i], body, ifMatch);
@@ -430,7 +518,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
430
518
  const handleNewTask = (req, res, url) => {
431
519
  if (!writeAllowed(req, res))
432
520
  return;
433
- const i = projectIndex(url, roots.length);
521
+ const i = projectIndex(url, roots.length, closed);
434
522
  if (i === null)
435
523
  return send(res, 404, TEXT, 'Not Found\n');
436
524
  readJson(req, res, body => {
@@ -442,6 +530,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
442
530
  return sendJson(res, 428, { error: 'A new task needs an If-Match header with the file hash the page last loaded.' });
443
531
  const { description, section, type, priority } = body;
444
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)
445
535
  let out;
446
536
  try {
447
537
  out = (0, taskMover_1.newTask)(roots[i], { description, section, type, priority }, ifMatch);
@@ -461,7 +551,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
461
551
  const handleReview = (req, res, url) => {
462
552
  if (!writeAllowed(req, res))
463
553
  return;
464
- const i = projectIndex(url, roots.length);
554
+ const i = projectIndex(url, roots.length, closed);
465
555
  if (i === null)
466
556
  return send(res, 404, TEXT, 'Not Found\n');
467
557
  readJson(req, res, body => {
@@ -473,6 +563,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
473
563
  return sendJson(res, 428, { error: 'This action needs an If-Match header with the file hash the page last loaded.' });
474
564
  const { id, action, note, date, toIndex } = body;
475
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)
476
568
  let out;
477
569
  try {
478
570
  out = (0, taskMover_1.reviewTask)(roots[i], { id, action, note, date, toIndex }, ifMatch);
@@ -492,7 +584,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
492
584
  const handleFields = (req, res, url) => {
493
585
  if (!writeAllowed(req, res))
494
586
  return;
495
- const i = projectIndex(url, roots.length);
587
+ const i = projectIndex(url, roots.length, closed);
496
588
  if (i === null)
497
589
  return send(res, 404, TEXT, 'Not Found\n');
498
590
  readJson(req, res, body => {
@@ -502,11 +594,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
502
594
  const ifMatch = String(req.headers['if-match'] ?? '').replace(/^W\//, '').replace(/"/g, '').trim();
503
595
  if (!ifMatch)
504
596
  return sendJson(res, 428, { error: 'This change needs an If-Match header with the file hash the page last loaded.' });
505
- const { id, type, priority } = body;
597
+ const { id, type, priority, description } = body;
506
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)
507
601
  let out;
508
602
  try {
509
- out = (0, taskMover_1.setTaskFields)(roots[i], { id, type, priority }, ifMatch);
603
+ out = (0, taskMover_1.setTaskFields)(roots[i], { id, type, priority, description }, ifMatch);
510
604
  }
511
605
  catch {
512
606
  return sendJson(res, 500, { error: 'planning/tasks.md could not be written. Nothing was changed.' });
@@ -523,7 +617,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
523
617
  const handleArchive = (req, res, url) => {
524
618
  if (!writeAllowed(req, res))
525
619
  return;
526
- const i = projectIndex(url, roots.length);
620
+ const i = projectIndex(url, roots.length, closed);
527
621
  if (i === null)
528
622
  return send(res, 404, TEXT, 'Not Found\n');
529
623
  readJson(req, res, body => {
@@ -537,6 +631,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
537
631
  if (!ifMatch)
538
632
  return sendJson(res, 428, { error: 'The archive needs an If-Match header with the file hash the page last loaded.' });
539
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)
540
636
  let out;
541
637
  try {
542
638
  out = (0, taskMover_1.archiveCompleted)(roots[i], ifMatch, force === true);
@@ -556,7 +652,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
556
652
  const handleRegenerate = (req, res, url) => {
557
653
  if (!writeAllowed(req, res))
558
654
  return;
559
- const i = projectIndex(url, roots.length);
655
+ const i = projectIndex(url, roots.length, closed);
560
656
  if (i === null)
561
657
  return send(res, 404, TEXT, 'Not Found\n');
562
658
  readJson(req, res, body => {
@@ -564,6 +660,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
564
660
  return sendJson(res, 422, { error: 'Regenerate All takes an empty JSON object, {}.' });
565
661
  }
566
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)
567
665
  if ((0, specSetup_1.specsMissing)(roots[i]))
568
666
  return sendJson(res, 422, { error: `No .specs/ folder in ${displayRoot(roots[i])}.` });
569
667
  // The skill is its own step (BL-PM-012): the MCP tool calls only the command step.
@@ -590,7 +688,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
590
688
  return {
591
689
  path: displayRoot(registry, home),
592
690
  entries: entries.map(e => {
593
- const i = roots.indexOf(e.path);
691
+ const i = openRoots().indexOf(e.path);
594
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) };
595
693
  }),
596
694
  error: read.error,
@@ -613,6 +711,9 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
613
711
  return null;
614
712
  };
615
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;
616
717
  /**
617
718
  * Serve `root` as the next index and record it in the registry: the success body of an open, or null
618
719
  * after answering 422 because the folder's allowlisted files cannot be read (it is then not half-opened).
@@ -631,7 +732,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
631
732
  namedFlags.push(true);
632
733
  projects.push(project);
633
734
  const error = changeRegistry(entries => (0, projectRegistry_1.upsertEntry)(entries, root, new Date()));
634
- 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 } : {}) } };
635
736
  };
636
737
  /** `addRoot()` for a route: answers 422 itself when the folder cannot be read (it is then not half-opened). */
637
738
  const serveRoot = (res, root) => {
@@ -650,13 +751,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
650
751
  if (problem)
651
752
  return sendJson(res, 422, { error: problem });
652
753
  underLock(res, () => {
653
- const check = (0, projectRegistry_1.checkOpenPath)(body.path, roots, home);
754
+ const check = (0, projectRegistry_1.checkOpenPath)(body.path, openRoots(), home);
654
755
  if ('status' in check)
655
756
  return sendJson(res, check.status, check.project === undefined ? { error: check.error } : { error: check.error, project: check.project });
656
757
  if (cloningTarget && (check.root === cloningTarget || check.root.startsWith(cloningTarget + path_1.sep)))
657
758
  return sendJson(res, 409, { error: `${cloningTarget} is being cloned. Wait for it to finish.` });
658
- if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
659
- 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 });
660
762
  const body200 = serveRoot(res, check.root);
661
763
  if (body200)
662
764
  sendJson(res, 200, body200);
@@ -675,9 +777,10 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
675
777
  return sendJson(res, 422, { error: problem });
676
778
  const { parent, name } = body;
677
779
  underLock(res, () => {
678
- if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
679
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
680
- 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);
681
784
  if ('status' in out)
682
785
  pendingTarget = null; // a refusal leaves no path writable that the page no longer shows (BL-104)
683
786
  if ('status' in out)
@@ -702,9 +805,10 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
702
805
  await underLock(res, () => {
703
806
  if (signal.aborted)
704
807
  return;
705
- if (roots.length >= projectRegistry_1.MAX_PROJECTS)
706
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
707
- 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);
708
812
  if (!('status' in r)) {
709
813
  reserved = r;
710
814
  cloningTarget = r.target;
@@ -820,10 +924,15 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
820
924
  if (problem)
821
925
  return sendJson(res, 422, { error: problem });
822
926
  underLock(res, () => {
823
- 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));
824
929
  if (error)
825
930
  return sendJson(res, 422, { error });
826
- 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) });
827
936
  });
828
937
  });
829
938
  };
@@ -839,6 +948,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
839
948
  const n = args.project ?? 0;
840
949
  if (!Number.isInteger(n) || n < 0 || n >= roots.length)
841
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));
842
953
  return n;
843
954
  };
844
955
  const mcpHash = (args) => {
@@ -848,12 +959,20 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
848
959
  };
849
960
  const asJson = (data) => ({ text: JSON.stringify(data, null, 2), data });
850
961
  /** A task write's outcome as the tool's answer: the page's refusals, with the stale one worded for an agent. */
851
- 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) => {
852
965
  let out;
853
966
  try {
854
- 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
+ });
855
972
  }
856
- catch {
973
+ catch (err) {
974
+ if (err instanceof mcpLocal_1.ToolRefusal)
975
+ throw err;
857
976
  throw new mcpLocal_1.ToolRefusal('planning/tasks.md could not be written. Nothing was changed.');
858
977
  }
859
978
  if (out.status !== 200) {
@@ -885,7 +1004,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
885
1004
  return r;
886
1005
  }
887
1006
  };
888
- const index = roots.findIndex(r => r === norm || real(r) === norm);
1007
+ const index = openRoots().findIndex(r => r && (r === norm || real(r) === norm));
889
1008
  if (index >= 0 && namedFlags[index]) {
890
1009
  if (!(0, specSetup_1.specsMissing)(roots[index]))
891
1010
  throw new mcpLocal_1.ToolRefusal(BACKFILL(norm));
@@ -903,7 +1022,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
903
1022
  const line = JSON.stringify({ ...(t.kind === 'existing' ? { project: t.index } : { pending: true }), ...data });
904
1023
  allStreams().forEach(st => st.write(`event: setup\ndata: ${line}\n\n`));
905
1024
  };
906
- /** The questions for a target: the CLI's, then the 23 optional fields with the chat core's wording, labels and options. */
1025
+ /** The questions for a target: the CLI's, then the 28 optional fields with the chat core's wording, labels and options. */
907
1026
  const setupQuestionList = async (t) => {
908
1027
  let q;
909
1028
  try {
@@ -914,8 +1033,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
914
1033
  }
915
1034
  const mode = t.kind === 'existing' ? 'setup' : 'new';
916
1035
  // Answers that open every optional field's question: databases and realtime follow a REST or GraphQL API, sync
917
- // follows an offline store, constraint detail follows a technical constraint. The agent answers what applies.
918
- const open = { apiParadigm: 'rest', localDatabases: ['SQLite'], technicalConstraints: ['Budget cap'] };
1036
+ // follows an offline store, constraint detail follows a technical constraint, the design assets follow a Yes. The agent answers what applies.
1037
+ const open = { apiParadigm: 'rest', localDatabases: ['SQLite'], technicalConstraints: ['Budget cap'], hasDesignAssets: 'Yes' };
919
1038
  const core = (0, chatFlow_1.chatQuestions)(q.questions, flowQuestions(q, {}, []), open, mode, q.files.outside);
920
1039
  const cli = q.questions.map(x => ({
921
1040
  key: x.key, label: x.label ?? x.key, question: x.message, required: !!x.required,
@@ -927,6 +1046,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
927
1046
  key: c.key, label: c.label, question: c.chat, kind: chatFlow_1.OPTIONAL_FIELD_LIMITS[c.key].kind, max: chatFlow_1.OPTIONAL_FIELD_LIMITS[c.key].max,
928
1047
  ...(c.options?.length ? { options: c.options.filter(o => !o.todo).map(o => o.label) } : {}),
929
1048
  ...(c.categories ? { categories: c.categories.map(k => ({ id: k.id, label: k.label, options: k.options })) } : {}),
1049
+ ...(chatFlow_1.DESIGN_GATED.includes(c.key) ? { when: { hasDesignAssets: 'Yes' } } : {}),
930
1050
  }));
931
1051
  const detected = 'detected' in q && q.detected ? q.detected.rows.map(r => ({ label: r.label, value: r.value })) : [];
932
1052
  const name = t.kind === 'new' ? (0, path_1.basename)(t.target) : ('detected' in q && q.detected ? q.detected.name : (0, path_1.basename)(t.root));
@@ -950,17 +1070,19 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
950
1070
  const counts = { fromCode: Object.keys(a).length - asked.length, fromUser: asked.length, topics: asked.flatMap(k => (labels.has(k) ? [labels.get(k)] : [])) };
951
1071
  const written = await locked(async () => {
952
1072
  const t = setupTarget(args.path); // again under the lock: the folder may have changed since (SEC-004.27)
953
- if (t.kind !== first.kind)
1073
+ const same = t.kind === 'existing' ? first.kind === 'existing' && t.root === first.root : first.kind === 'new' && t.target === first.target;
1074
+ if (!same)
954
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.`);
955
1076
  emitSetup(t, { row: 'questions', state: 'done', ...counts });
956
1077
  emitSetup(t, { row: 'write', state: 'running' });
1078
+ let cap;
957
1079
  let out;
958
1080
  if (t.kind === 'existing')
959
1081
  out = await (0, specSetup_1.setupProject)(t.root, a);
960
- else if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
961
- out = { status: 409, error: TOO_MANY_PROJECTS };
1082
+ else if ((cap = capError(cloningTarget ? 1 : 0)))
1083
+ out = { status: 409, error: cap };
962
1084
  else
963
- 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);
964
1086
  if (out.status !== 200) {
965
1087
  emitSetup(t, { row: 'write', state: 'idle' });
966
1088
  throw new mcpLocal_1.ToolRefusal(out.error);
@@ -993,9 +1115,11 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
993
1115
  return setupProjectTool(args);
994
1116
  if (name === 'specpilot_list_projects') {
995
1117
  return asJson({
996
- 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
997
1121
  const p = buildSpecsPayload(root, specpilotVersion);
998
- 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) }];
999
1123
  }),
1000
1124
  });
1001
1125
  }
@@ -1018,7 +1142,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1018
1142
  if (problem)
1019
1143
  throw new mcpLocal_1.ToolRefusal(problem);
1020
1144
  const hash = mcpHash(args);
1021
- 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));
1022
1146
  return asJson({ id: out.id, section: out.section, index: out.index, sha256: out.sha256 });
1023
1147
  }
1024
1148
  if (name === 'specpilot_move_task') {
@@ -1027,16 +1151,16 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1027
1151
  if (problem)
1028
1152
  throw new mcpLocal_1.ToolRefusal(problem);
1029
1153
  const hash = mcpHash(args);
1030
- 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));
1031
1155
  return asJson({ from: out.from, fromIndex: out.fromIndex, sha256: out.sha256 });
1032
1156
  }
1033
1157
  if (name === 'specpilot_set_task') {
1034
1158
  const req = { id: args.id, type: args.type, priority: args.priority };
1035
- const problem = (0, taskMover_1.fieldsShapeError)(req);
1159
+ const problem = (0, taskMover_1.fieldsShapeError)(req, false);
1036
1160
  if (problem)
1037
1161
  throw new mcpLocal_1.ToolRefusal(problem);
1038
1162
  const hash = mcpHash(args);
1039
- 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));
1040
1164
  return asJson({ sha256: out.sha256 });
1041
1165
  }
1042
1166
  if (name === 'specpilot_validate_specs') {
@@ -1107,7 +1231,20 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1107
1231
  const { port } = server.address();
1108
1232
  if (!isAllowedHost(req.headers.host, port))
1109
1233
  return send(res, 403, TEXT, 'Forbidden: unexpected Host header\n');
1234
+ // A worker's install or update fetch: SpecPilot registers none, so this one is an earlier program's (BL-142).
1235
+ if (req.headers['service-worker'] === 'script') {
1236
+ res.writeHead(404, { 'Content-Type': TEXT, ...SECURITY_HEADERS, ...CLEAR_STORAGE });
1237
+ return res.end('Not Found\n');
1238
+ }
1110
1239
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
1240
+ // From this origin, an address typed in, or a client that sends no fetch metadata (BL-143, BL-144).
1241
+ const site = req.headers['sec-fetch-site'];
1242
+ const ours = site === undefined || site === 'none' || site === 'same-origin';
1243
+ // Another page may neither hold an event slot nor read the data (BL-144); the page itself sends no foreign Origin.
1244
+ const foreignOrigin = req.headers.origin !== undefined && req.headers.origin !== `http://${req.headers.host}`;
1245
+ if (req.method === 'GET' && READS.has(url.pathname) && (!ours || foreignOrigin)) {
1246
+ return sendJson(res, 403, { error: 'This request did not come from the SpecPilot page, so it was refused.' });
1247
+ }
1111
1248
  if (mcpToken && url.pathname === '/mcp')
1112
1249
  return handleMcp(req, res);
1113
1250
  if (url.pathname === '/api/projects') {
@@ -1189,9 +1326,17 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1189
1326
  return send(res, 405, TEXT, 'Method Not Allowed\n');
1190
1327
  }
1191
1328
  if (url.pathname === '/') {
1192
- const page = (0, fs_1.readFileSync)((0, path_1.join)(UI_DIR, 'index.html'), 'utf-8');
1193
- const mcpMeta = token && mcpToken ? `<meta name="specpilot-mcp" content="${opts.mcpToken ? 'env' : 'page'}">` : '';
1194
- return send(res, 200, UI_ROUTES['/'][1], page.replace(TOKEN_SLOT, token ? `<meta name="specpilot-token" content="${token}">` : '').replace(MCP_SLOT, mcpMeta));
1329
+ // The token only into a top-level load: not a worker's pass-through (`empty`), a frame or a navigation preload (BL-142).
1330
+ const dest = req.headers['sec-fetch-dest'];
1331
+ const topLevel = (dest === undefined || dest === 'document') && req.headers['service-worker-navigation-preload'] === undefined;
1332
+ const pageToken = topLevel ? token : null;
1333
+ const page = (0, fs_1.readFileSync)((0, path_1.join)(UI_DIR, 'index.html'), 'utf-8').replace(/"\/assets\/([\w.]+)"/g, (_, file) => file === 'favicon.svg'
1334
+ ? `"/assets/${file}?v=${assetVersion}"`
1335
+ : `"/assets/${file}?v=${assetVersion}" integrity="sha384-${(0, crypto_1.createHash)('sha384').update((0, fs_1.readFileSync)((0, path_1.join)(UI_DIR, file))).digest('base64')}"`);
1336
+ const mcpMeta = pageToken && mcpToken ? `<meta name="specpilot-mcp" content="${opts.mcpToken ? 'env' : 'page'}">` : '';
1337
+ // Only this origin's own requests clear storage: a frame from another port or site must not wipe it (BL-143).
1338
+ res.writeHead(200, { 'Content-Type': UI_ROUTES['/'][1], ...SECURITY_HEADERS, ...(topLevel || !ours ? {} : CLEAR_STORAGE) });
1339
+ return res.end(page.replace(TOKEN_SLOT, pageToken ? `<meta name="specpilot-token" content="${pageToken}">` : '').replace(MCP_SLOT, mcpMeta));
1195
1340
  }
1196
1341
  const ui = UI_ROUTES[url.pathname];
1197
1342
  if (ui)
@@ -1200,13 +1345,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1200
1345
  return send(res, 404, TEXT, 'Not Found\n');
1201
1346
  // No project served yet (BL-080): the page learns the state from /api/specs and listens for the
1202
1347
  // server-level events; the one place the omitted-project rule bends (REQ-002.H.44).
1203
- if (!roots.length && !url.searchParams.has('project')) {
1348
+ if (roots.length === closed.size && !url.searchParams.has('project')) { // none served, or none open (BL-166)
1204
1349
  if (url.pathname === '/api/specs')
1205
- 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 }));
1206
1351
  if (url.pathname === '/api/events')
1207
1352
  return openStream(null, req, res);
1208
1353
  }
1209
- const i = projectIndex(url, roots.length);
1354
+ const i = projectIndex(url, roots.length, closed);
1210
1355
  if (i === null)
1211
1356
  return send(res, 404, TEXT, 'Not Found\n');
1212
1357
  if (url.pathname === '/api/specs')
@@ -1243,7 +1388,8 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
1243
1388
  }));
1244
1389
  projects.forEach(p => p.poller.stop());
1245
1390
  server.close(() => resolveClose());
1246
- server.closeIdleConnections?.();
1391
+ // Every socket, not only the idle ones: a page's stream can reopen on a kept-alive socket while close() waits (BL-146).
1392
+ server.closeAllConnections();
1247
1393
  });
1248
1394
  },
1249
1395
  };