specpilot 2.13.0 → 2.15.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 (71) hide show
  1. package/README.md +27 -22
  2. package/dist/cli.js +4 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/backfill.d.ts.map +1 -1
  5. package/dist/commands/backfill.js +24 -13
  6. package/dist/commands/backfill.js.map +1 -1
  7. package/dist/commands/serve.d.ts +3 -1
  8. package/dist/commands/serve.d.ts.map +1 -1
  9. package/dist/commands/serve.js +75 -4
  10. package/dist/commands/serve.js.map +1 -1
  11. package/dist/core/agentConfig.d.ts +10 -0
  12. package/dist/core/agentConfig.d.ts.map +1 -1
  13. package/dist/core/agentConfig.js +47 -3
  14. package/dist/core/agentConfig.js.map +1 -1
  15. package/dist/core/chatFlow.js +2 -2
  16. package/dist/core/chatFlow.js.map +1 -1
  17. package/dist/core/slashCommands.d.ts.map +1 -1
  18. package/dist/core/slashCommands.js +25 -16
  19. package/dist/core/slashCommands.js.map +1 -1
  20. package/dist/core/specFiles.js +3 -0
  21. package/dist/core/specFiles.js.map +1 -1
  22. package/dist/core/templateEngine.d.ts +5 -0
  23. package/dist/core/templateEngine.d.ts.map +1 -1
  24. package/dist/core/templateEngine.js +13 -1
  25. package/dist/core/templateEngine.js.map +1 -1
  26. package/dist/utils/addSpecsQuestions.d.ts.map +1 -1
  27. package/dist/utils/addSpecsQuestions.js +2 -0
  28. package/dist/utils/addSpecsQuestions.js.map +1 -1
  29. package/dist/utils/folderPicker.d.ts +28 -0
  30. package/dist/utils/folderPicker.d.ts.map +1 -0
  31. package/dist/utils/folderPicker.js +96 -0
  32. package/dist/utils/folderPicker.js.map +1 -0
  33. package/dist/utils/mcpLocal.d.ts +10 -0
  34. package/dist/utils/mcpLocal.d.ts.map +1 -1
  35. package/dist/utils/mcpLocal.js +61 -2
  36. package/dist/utils/mcpLocal.js.map +1 -1
  37. package/dist/utils/projectDetector.d.ts +11 -0
  38. package/dist/utils/projectDetector.d.ts.map +1 -1
  39. package/dist/utils/projectDetector.js +86 -0
  40. package/dist/utils/projectDetector.js.map +1 -1
  41. package/dist/utils/slashCommandGenerator.d.ts +21 -0
  42. package/dist/utils/slashCommandGenerator.d.ts.map +1 -1
  43. package/dist/utils/slashCommandGenerator.js +166 -0
  44. package/dist/utils/slashCommandGenerator.js.map +1 -1
  45. package/dist/utils/specArchiver.d.ts.map +1 -1
  46. package/dist/utils/specArchiver.js +2 -1
  47. package/dist/utils/specArchiver.js.map +1 -1
  48. package/dist/utils/specBackfiller.d.ts +9 -3
  49. package/dist/utils/specBackfiller.d.ts.map +1 -1
  50. package/dist/utils/specBackfiller.js +52 -48
  51. package/dist/utils/specBackfiller.js.map +1 -1
  52. package/dist/utils/specServer.d.ts +12 -7
  53. package/dist/utils/specServer.d.ts.map +1 -1
  54. package/dist/utils/specServer.js +263 -123
  55. package/dist/utils/specServer.js.map +1 -1
  56. package/dist/utils/specSetup.d.ts +21 -23
  57. package/dist/utils/specSetup.d.ts.map +1 -1
  58. package/dist/utils/specSetup.js +69 -57
  59. package/dist/utils/specSetup.js.map +1 -1
  60. package/dist/utils/specValidator.d.ts.map +1 -1
  61. package/dist/utils/specValidator.js +4 -1
  62. package/dist/utils/specValidator.js.map +1 -1
  63. package/package.json +1 -1
  64. package/ui/app.css +43 -109
  65. package/ui/app.js +155 -305
  66. package/ui/index.html +25 -29
  67. package/ui/route.js +3 -101
  68. package/dist/__tests__/fixtures/allFields.d.ts +0 -3
  69. package/dist/__tests__/fixtures/allFields.d.ts.map +0 -1
  70. package/dist/__tests__/fixtures/allFields.js +0 -31
  71. package/dist/__tests__/fixtures/allFields.js.map +0 -1
@@ -33,8 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.MAX_EVENT_STREAMS = exports.MAX_SETUP_BODY = exports.MAX_MOVE_BODY = void 0;
37
- exports.chatCoreScript = chatCoreScript;
36
+ exports.MAX_EVENT_STREAMS = exports.MAX_MCP_BODY = exports.MAX_MOVE_BODY = void 0;
38
37
  exports.isAllowedHost = isAllowedHost;
39
38
  exports.readBranch = readBranch;
40
39
  exports.buildSpecsPayload = buildSpecsPayload;
@@ -53,7 +52,9 @@ const taskMover_1 = require("./taskMover");
53
52
  const specPaths_1 = require("./specPaths");
54
53
  const specPoller_1 = require("./specPoller");
55
54
  const specSetup_1 = require("./specSetup");
55
+ const chatFlow_1 = require("../core/chatFlow");
56
56
  const gitClone_1 = require("./gitClone");
57
+ const folderPicker_1 = require("./folderPicker");
57
58
  const projectRegistry_1 = require("./projectRegistry");
58
59
  const specBackfiller_1 = require("./specBackfiller");
59
60
  const slashCommandGenerator_1 = require("./slashCommandGenerator");
@@ -69,12 +70,6 @@ const mcpLocal_1 = require("./mcpLocal");
69
70
  // functions for an AI IDE on this machine (BL-PM-007, mcpLocal.ts).
70
71
  /** Resolved from this module's own location, never from cwd: dist/utils → <package>/ui. */
71
72
  const UI_DIR = (0, path_1.join)(__dirname, '..', '..', 'ui');
72
- /** The chat core's compiled file, which the page runs as /assets/chat-core.js (BL-PM-004b, REQ-002.I.7). */
73
- const CHAT_CORE = (0, path_1.join)(__dirname, '..', 'core', 'chatFlow.js');
74
- /** tsc's CommonJS output of `src/core/chatFlow.ts` as a page script: `exports` supplied, the source map line dropped. */
75
- function chatCoreScript(compiled) {
76
- return `(function (exports) {\n${compiled.replace(/^\/\/# sourceMappingURL=.*$/m, '')}\n})(window.SpecPilotChat = {});\n`;
77
- }
78
73
  const UI_ROUTES = {
79
74
  '/': ['index.html', 'text/html; charset=utf-8'],
80
75
  '/assets/app.css': ['app.css', 'text/css; charset=utf-8'],
@@ -189,7 +184,7 @@ function buildSpecsPayload(root, specpilotVersion) {
189
184
  }),
190
185
  // generated: the page's "From SpecPilot" group, else "Yours" (BL-PM-006)
191
186
  commands: navFiles(root, scanned, '.claude/commands', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
192
- skills: navFiles(root, scanned, '.claude/skills', p => p.endsWith('/SKILL.md')).map(f => ({ ...f, generated: (0, agentConfig_1.agentTargets)('claude-code').includes(f.path) })),
187
+ 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
193
188
  prompts: navFiles(root, scanned, '.github/prompts', p => p.endsWith('.md')).map(f => ({ ...f, generated: (0, slashCommandGenerator_1.isSpecPilotCommand)(root, f.path) })),
194
189
  },
195
190
  };
@@ -197,14 +192,16 @@ function buildSpecsPayload(root, specpilotVersion) {
197
192
  /** The command folders the Commands view lists; the result names any other folder Regenerate touched. */
198
193
  const LISTED_COMMAND_FOLDERS = ['.claude/commands/', '.github/prompts/'];
199
194
  /** What Regenerate All did, as project-relative paths, and the lines the page shows verbatim (BL-PM-006, REQ-002.H.30). */
200
- function regenerateReport(results) {
195
+ function regenerateReport(results, skill = null) {
201
196
  const pathOf = (ide, name) => {
202
197
  const target = (0, slashCommands_1.resolveTarget)(ide, slashCommands_1.SLASH_COMMANDS.find(c => c.name === name));
203
198
  return `${target.dir}/${target.fileName}`;
204
199
  };
205
- const added = results.flatMap(r => r.added.map(name => pathOf(r.ide, name)));
206
- const updated = results.flatMap(r => r.updated.map(name => pathOf(r.ide, name)));
207
- const kept = results.flatMap(r => r.kept.map(k => ({ path: k.path, reason: k.reason })));
200
+ // The skill (BL-PM-012) joins the same lists; the Skills view lists it, so its folder is never "not listed".
201
+ const skillIf = (action) => (skill && skill.action === action ? [skill.path] : []);
202
+ const added = [...results.flatMap(r => r.added.map(name => pathOf(r.ide, name))), ...skillIf('added')];
203
+ const updated = [...results.flatMap(r => r.updated.map(name => pathOf(r.ide, name))), ...skillIf('updated')];
204
+ const kept = [...results.flatMap(r => r.kept.map(k => ({ path: k.path, reason: k.reason }))), ...(skill?.action === 'kept' ? [{ path: skill.path, reason: skill.reason }] : [])];
208
205
  const message = [];
209
206
  if (!results.length)
210
207
  message.push('No IDE instruction file found, so no command files were written.');
@@ -216,7 +213,7 @@ function regenerateReport(results) {
216
213
  message.push(`Added: ${added.join(', ')}.`);
217
214
  if (kept.length)
218
215
  message.push(`Kept as they were: ${kept.map(k => `${k.path} (${k.reason})`).join(', ')}.`);
219
- const folders = [...new Set([...updated, ...added, ...kept.map(k => k.path)].map(p => p.slice(0, p.lastIndexOf('/') + 1)))];
216
+ const folders = [...new Set([...updated, ...added, ...kept.map(k => k.path)].filter(p => p !== skill?.path).map(p => p.slice(0, p.lastIndexOf('/') + 1)))];
220
217
  const unlisted = folders.filter(f => !LISTED_COMMAND_FOLDERS.includes(f));
221
218
  if (unlisted.length)
222
219
  message.push(`Not listed on this page: ${unlisted.join(', ')}.`);
@@ -260,12 +257,15 @@ function sendJson(res, status, body) {
260
257
  }
261
258
  /** Largest accepted request body for a move (BL-053) and the other write routes. */
262
259
  exports.MAX_MOVE_BODY = 16 * 1024;
263
- /** Largest accepted body for a setup, a new project or a preview, which carry the 23 optional fields (BL-PM-004b). */
264
- exports.MAX_SETUP_BODY = 64 * 1024;
265
260
  /** Where index.html receives the per-start CSRF token (nothing with --read-only). */
266
261
  const TOKEN_SLOT = '<!-- specpilot-token -->';
267
262
  /** Where index.html learns that /mcp is on, and whose token it takes: `page` or `env` (BL-PM-007). */
268
263
  const MCP_SLOT = '<!-- specpilot-mcp -->';
264
+ /** Largest accepted body on /mcp: the setup answers, as the page's setup routes took them (BL-104). */
265
+ exports.MAX_MCP_BODY = 64 * 1024;
266
+ // The CLI's question list as the chat core takes it: the page's own rule, also read here since BL-104.
267
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
268
+ const { flowQuestions } = require('../../ui/route.js');
269
269
  /** Most `/api/events` streams open at once; the next one gets 503 (SEC-004.9). */
270
270
  exports.MAX_EVENT_STREAMS = 8;
271
271
  function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
@@ -317,7 +317,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
317
317
  // /mcp's token (BL-PM-007): its own variable, because a null `token` is what turns the page's writes off.
318
318
  const mcpToken = !opts.mcp ? null : (opts.mcpToken ?? token ?? (0, crypto_1.randomBytes)(32).toString('hex'));
319
319
  let writeLock = Promise.resolve(); // writes run strictly one after another, in every project
320
- const payload = (i) => ({ ...buildSpecsPayload(roots[i], specpilotVersion), projects: projectList(roots) });
320
+ // The MCP client whose initialize /mcp last answered (BL-103): null until then; `name` sanitized, '' when none was sent.
321
+ let mcpClient = null;
322
+ // `named`: whether the Setup view is offered there (REQ-002.H.15's current-directory rule, BL-103).
323
+ const payload = (i) => {
324
+ const p = buildSpecsPayload(roots[i], specpilotVersion);
325
+ return { ...p, project: { ...p.project, named: namedFlags[i] }, projects: projectList(roots), mcp: { client: mcpClient } };
326
+ };
321
327
  /** Run `fn` under the write lock and settle with its outcome; a throw never breaks the chain for later writes. */
322
328
  const locked = (fn) => {
323
329
  const run = writeLock.then(fn);
@@ -453,66 +459,12 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
453
459
  underLock(res, () => {
454
460
  if ((0, specSetup_1.specsMissing)(roots[i]))
455
461
  return sendJson(res, 422, { error: `No .specs/ folder in ${displayRoot(roots[i])}.` });
456
- const report = regenerateReport(new specBackfiller_1.SpecBackfiller().backfillSlashCommands(roots[i], false));
462
+ // The skill is its own step (BL-PM-012): the MCP tool calls only the command step.
463
+ const report = regenerateReport(new specBackfiller_1.SpecBackfiller().backfillSlashCommands(roots[i], false), new slashCommandGenerator_1.SlashCommandGenerator().refreshSkill(roots[i], '.specs', false));
457
464
  sendJson(res, 200, { ...report, specs: payload(i) });
458
465
  });
459
466
  });
460
467
  };
461
- // ---- guided setup (BL-055): only for a named root (command line, or opened from the page) that has no .specs/
462
- const named = (i) => namedFlags[i];
463
- const setupIndex = (url) => {
464
- const i = projectIndex(url, roots.length);
465
- return i !== null && named(i) && (0, specSetup_1.specsMissing)(roots[i]) ? i : null;
466
- };
467
- const handleSetupGet = (res, url) => {
468
- const i = setupIndex(url);
469
- if (i === null)
470
- return send(res, 404, TEXT, 'Not Found\n');
471
- (0, specSetup_1.setupQuestions)(roots[i]).then(q => sendJson(res, 200, q), err => sendJson(res, 422, { error: `This folder could not be read: ${err.message}` }));
472
- };
473
- const handleSetupPost = (req, res, url) => {
474
- if (!writeAllowed(req, res, exports.MAX_SETUP_BODY))
475
- return;
476
- const i = projectIndex(url, roots.length);
477
- if (i === null || !named(i))
478
- return send(res, 404, TEXT, 'Not Found\n');
479
- readJson(req, res, body => {
480
- const problem = (0, specSetup_1.answersShapeError)(body);
481
- if (problem)
482
- return sendJson(res, 422, { error: problem });
483
- writeLock = writeLock
484
- .then(() => (0, specSetup_1.setupProject)(roots[i], body))
485
- .then(out => {
486
- if (out.status === 200)
487
- return sendJson(res, 200, { specs: payload(i), kept: out.kept, notice: out.notice });
488
- if (out.status === 409 && out.specsExists)
489
- return sendJson(res, 409, { error: out.error, specs: payload(i) });
490
- return sendJson(res, out.status, { error: out.error });
491
- })
492
- .catch(() => {
493
- if (!res.headersSent)
494
- sendJson(res, 500, { error: 'Setup could not finish.' });
495
- });
496
- }, exports.MAX_SETUP_BODY);
497
- };
498
- // ---- preview (BL-PM-004b): what a create would write, rendered and returned; no lock, nothing written
499
- const handlePreview = (req, res, url) => {
500
- if (!writeAllowed(req, res, exports.MAX_SETUP_BODY))
501
- return;
502
- const guided = url.searchParams.has('project');
503
- const i = guided ? projectIndex(url, roots.length) : null;
504
- if (guided && (i === null || !named(i)))
505
- return send(res, 404, TEXT, 'Not Found\n');
506
- if (!guided && !registry)
507
- return send(res, 404, TEXT, 'Not Found\n');
508
- readJson(req, res, body => {
509
- const problem = guided ? (0, specSetup_1.answersShapeError)(body) : (0, specSetup_1.newProjectShapeError)(body, true);
510
- if (problem)
511
- return sendJson(res, 422, { error: problem });
512
- const b = body;
513
- Promise.resolve(guided ? (0, specSetup_1.previewSetup)(roots[i], b) : (0, specSetup_1.previewNewProject)(b)).then(out => ('status' in out ? sendJson(res, out.status, { error: out.error }) : sendJson(res, 200, out)), () => sendJson(res, 500, { error: 'The preview could not be made.' }));
514
- }, exports.MAX_SETUP_BODY);
515
- };
516
468
  // ---- project registry (BL-067): list, open a folder, forget an entry; all absent with --read-only
517
469
  const registry = token && opts.registry ? opts.registry : null;
518
470
  const home = (0, projectRegistry_1.homeDir)();
@@ -558,14 +510,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
558
510
  * Serve `root` as the next index and record it in the registry: the success body of an open, or null
559
511
  * after answering 422 because the folder's allowlisted files cannot be read (it is then not half-opened).
560
512
  */
561
- const serveRoot = (res, root) => {
513
+ const addRoot = (root) => {
562
514
  let specs;
563
515
  try {
564
516
  specs = buildSpecsPayload(root, specpilotVersion);
565
517
  }
566
518
  catch (err) {
567
- sendJson(res, 422, { error: `This folder could not be read: ${err.message}` });
568
- return null;
519
+ return { error: `This folder could not be read: ${err.message}` };
569
520
  }
570
521
  const project = projectFor(root); // built before anything is pushed, so the three lists never disagree
571
522
  const n = roots.length;
@@ -573,7 +524,16 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
573
524
  namedFlags.push(true);
574
525
  projects.push(project);
575
526
  const error = changeRegistry(entries => (0, projectRegistry_1.upsertEntry)(entries, root, new Date()));
576
- return { project: n, specs: { ...specs, projects: projectList(roots) }, registry: { ...registryBody(), ...(error ? { error } : {}) } };
527
+ return { project: n, specs: { ...specs, project: { ...specs.project, named: true }, projects: projectList(roots), mcp: { client: mcpClient } }, registry: { ...registryBody(), ...(error ? { error } : {}) } };
528
+ };
529
+ /** `addRoot()` for a route: answers 422 itself when the folder cannot be read (it is then not half-opened). */
530
+ const serveRoot = (res, root) => {
531
+ const out = addRoot(root);
532
+ if ('error' in out) {
533
+ sendJson(res, 422, { error: out.error });
534
+ return null;
535
+ }
536
+ return out;
577
537
  };
578
538
  const handleProjectAdd = (req, res) => {
579
539
  if (!writeAllowed(req, res))
@@ -596,34 +556,29 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
596
556
  });
597
557
  });
598
558
  };
599
- // ---- a new project (BL-PM-003): what `init` does in <parent>/<name>, then served like an opened folder
600
- const handleProjectNewGet = (res) => {
601
- try {
602
- sendJson(res, 200, (0, specSetup_1.newProjectQuestions)());
603
- }
604
- catch (err) {
605
- sendJson(res, 422, { error: `The OS username could not be read: ${err.message}` });
606
- }
607
- };
608
- const handleProjectNew = (req, res) => {
609
- if (!writeAllowed(req, res, exports.MAX_SETUP_BODY))
559
+ // ---- the Setup view's pending path (BL-103, SEC-004.26): where a new project may be made, checked, nothing
560
+ // created; one slot for the run, replaced by the next registration, never written anywhere.
561
+ let pendingTarget = null;
562
+ const handlePending = (req, res) => {
563
+ if (!writeAllowed(req, res))
610
564
  return;
611
565
  readJson(req, res, body => {
612
- const problem = (0, specSetup_1.newProjectShapeError)(body);
566
+ const problem = (0, specSetup_1.pendingShapeError)(body);
613
567
  if (problem)
614
568
  return sendJson(res, 422, { error: problem });
615
- const { parent, name, ...answers } = body;
616
- underLock(res, async () => {
569
+ const { parent, name } = body;
570
+ underLock(res, () => {
617
571
  if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
618
- return sendJson(res, 409, { error: TOO_MANY_PROJECTS }); // before anything is created
619
- const out = await (0, specSetup_1.createProject)(parent, name, answers, roots, home, cloningTarget);
620
- if (out.status !== 200)
572
+ return sendJson(res, 409, { error: TOO_MANY_PROJECTS });
573
+ const out = (0, specSetup_1.checkTarget)(parent, name, roots, home, cloningTarget);
574
+ if ('status' in out)
575
+ pendingTarget = null; // a refusal leaves no path writable that the page no longer shows (BL-104)
576
+ if ('status' in out)
621
577
  return sendJson(res, out.status, out.project === undefined ? { error: out.error } : { error: out.error, project: out.project });
622
- const body200 = serveRoot(res, out.root);
623
- if (body200)
624
- sendJson(res, 200, { ...body200, kept: out.kept, notice: out.notice });
578
+ pendingTarget = out.target;
579
+ sendJson(res, 200, { target: out.target });
625
580
  });
626
- }, exports.MAX_SETUP_BODY);
581
+ });
627
582
  };
628
583
  // ---- clone a repository (BL-PM-002): the user's git fills <parent>/<name>, then served like an opened folder.
629
584
  // One at a time, outside the write lock: the lock covers the checks and the mkdir, and serving the folder.
@@ -712,6 +667,44 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
712
667
  });
713
668
  });
714
669
  };
670
+ // ---- browse for a folder (BL-PM-011): the system's dialog, its answer returned as text for the Folder path field.
671
+ // Nothing comes from the request, nothing is read or written, so no lock; one dialog at a time.
672
+ let browseAbort = null;
673
+ let browseDone = Promise.resolve();
674
+ const handleBrowse = (req, res) => {
675
+ if (!writeAllowed(req, res))
676
+ return;
677
+ readJson(req, res, body => {
678
+ if (body === null || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length)
679
+ return sendJson(res, 422, { error: 'Send an empty JSON object.' });
680
+ if (closing)
681
+ return sendJson(res, 503, { error: 'The server is stopping.' });
682
+ if (browseAbort)
683
+ return sendJson(res, 409, { error: 'A folder dialog is already open.' });
684
+ const abort = new AbortController();
685
+ browseAbort = abort;
686
+ const gone = () => {
687
+ if (!res.writableEnded)
688
+ abort.abort(); // the sheet was closed or the page went away: close the dialog
689
+ };
690
+ res.on('close', gone);
691
+ browseDone = (0, folderPicker_1.pickFolder)(home, { timeoutMs: opts.browseTimeoutMs, signal: abort.signal })
692
+ .then(out => {
693
+ if (!abort.signal.aborted)
694
+ sendJson(res, 'error' in out ? 422 : 200, out);
695
+ })
696
+ .catch(() => {
697
+ if (!res.headersSent)
698
+ sendJson(res, 500, { error: 'The server could not finish this request.' });
699
+ })
700
+ .then(() => {
701
+ res.off('close', gone);
702
+ if (!res.writableEnded)
703
+ res.destroy();
704
+ browseAbort = null;
705
+ });
706
+ });
707
+ };
715
708
  const handleProjectRemove = (req, res) => {
716
709
  if (!writeAllowed(req, res))
717
710
  return;
@@ -732,7 +725,7 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
732
725
  [taskMover_1.STALE_ERROR]: 'planning/tasks.md changed on disk since you last read it. The move was not made.',
733
726
  [taskMover_1.NEW_STALE_ERROR]: 'planning/tasks.md changed on disk since you last read it, so the task was not added. Call specpilot_list_tasks for the current sha256, then try again.',
734
727
  };
735
- const mcpTools = mcpLocal_1.MCP_TOOLS.filter(t => token || !t.writes); // --read-only: no write tools
728
+ const mcpTools = mcpLocal_1.MCP_TOOLS.filter(t => token || (!t.writes && !t.setup)); // --read-only: no write tools, no setup tools (D3)
736
729
  const mcpProject = (args) => {
737
730
  const n = args.project ?? 0;
738
731
  if (!Number.isInteger(n) || n < 0 || n >= roots.length)
@@ -760,7 +753,135 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
760
753
  }
761
754
  return out;
762
755
  };
756
+ const BACKFILL = (p) => `${p} already has .specs/. To add missing SpecPilot sections there, run specpilot backfill.`;
757
+ /** D2: a served root named or opened from the page without .specs/, or exactly the pending target. Run on every call and again under the lock. */
758
+ const setupTarget = (path) => {
759
+ if (typeof path !== 'string' || !path.trim() || path.includes('\0'))
760
+ throw new mcpLocal_1.ToolRefusal('path is required: the folder as the SpecPilot page shows it.');
761
+ const expanded = path === '~' ? home : path.startsWith('~/') ? (0, path_1.join)(home, path.slice(2)) : path;
762
+ const abs = (0, path_1.resolve)(expanded);
763
+ let norm = abs;
764
+ try {
765
+ norm = (0, fs_1.existsSync)(abs) ? (0, fs_1.realpathSync)(abs) : (0, path_1.join)((0, fs_1.realpathSync)((0, path_1.dirname)(abs)), (0, path_1.basename)(abs));
766
+ }
767
+ catch {
768
+ /* a parent that is gone: compared as given */
769
+ }
770
+ // A served root as given or by its real path (the command line's roots are real paths already).
771
+ const real = (r) => {
772
+ try {
773
+ return (0, fs_1.realpathSync)(r);
774
+ }
775
+ catch {
776
+ return r;
777
+ }
778
+ };
779
+ const index = roots.findIndex(r => r === norm || real(r) === norm);
780
+ if (index >= 0 && namedFlags[index]) {
781
+ if (!(0, specSetup_1.specsMissing)(roots[index]))
782
+ throw new mcpLocal_1.ToolRefusal(BACKFILL(norm));
783
+ return { kind: 'existing', root: roots[index], index };
784
+ }
785
+ if (pendingTarget !== null && norm === pendingTarget && (0, path_1.isAbsolute)(norm)) {
786
+ if ((0, fs_1.existsSync)(norm) && !(0, specSetup_1.specsMissing)(norm))
787
+ throw new mcpLocal_1.ToolRefusal(BACKFILL(norm));
788
+ return { kind: 'new', target: norm };
789
+ }
790
+ throw new mcpLocal_1.ToolRefusal(`${norm} is not a folder this SpecPilot page is setting up. Open it in the page (Open a Project Folder, Clone, or Start a New Project) first.`);
791
+ };
792
+ /** `event: setup` to every open stream: state and counts only, never a path (SEC-004.9). */
793
+ const emitSetup = (t, data) => {
794
+ const line = JSON.stringify({ ...(t.kind === 'existing' ? { project: t.index } : { pending: true }), ...data });
795
+ allStreams().forEach(st => st.write(`event: setup\ndata: ${line}\n\n`));
796
+ };
797
+ /** The questions for a target: the CLI's, then the 23 optional fields with the chat core's wording, labels and options. */
798
+ const setupQuestionList = async (t) => {
799
+ let q;
800
+ try {
801
+ q = t.kind === 'existing' ? await (0, specSetup_1.setupQuestions)(t.root) : (0, specSetup_1.newProjectQuestions)();
802
+ }
803
+ catch (err) {
804
+ throw new mcpLocal_1.ToolRefusal(t.kind === 'existing' ? `This folder could not be read: ${err.message}` : `The OS username could not be read: ${err.message}`);
805
+ }
806
+ const mode = t.kind === 'existing' ? 'setup' : 'new';
807
+ // Answers that open every optional field's question: databases and realtime follow a REST or GraphQL API, sync
808
+ // follows an offline store, constraint detail follows a technical constraint. The agent answers what applies.
809
+ const open = { apiParadigm: 'rest', localDatabases: ['SQLite'], technicalConstraints: ['Budget cap'] };
810
+ const core = (0, chatFlow_1.chatQuestions)(q.questions, flowQuestions(q, {}, []), open, mode, q.files.outside);
811
+ const cli = q.questions.map(x => ({
812
+ key: x.key, label: x.label ?? x.key, question: x.message, required: !!x.required,
813
+ ...(x.choices ? { choices: x.choices.map(c => ({ value: c.value, text: c.name })) } : {}),
814
+ ...(x.key === 'framework' && !x.choices && q.frameworks ? { choicesByLanguage: q.frameworks } : {}),
815
+ ...(x.when ? { when: x.when } : {}),
816
+ }));
817
+ const fields = core.filter(c => c.core && c.key in chatFlow_1.OPTIONAL_FIELD_LIMITS).map(c => ({
818
+ 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,
819
+ ...(c.options?.length ? { options: c.options.filter(o => !o.todo).map(o => o.label) } : {}),
820
+ ...(c.categories ? { categories: c.categories.map(k => ({ id: k.id, label: k.label, options: k.options })) } : {}),
821
+ }));
822
+ const detected = 'detected' in q && q.detected ? q.detected.rows.map(r => ({ label: r.label, value: r.value })) : [];
823
+ 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));
824
+ return { questions: [...cli, ...fields], detected, name };
825
+ };
826
+ const setupProjectTool = async (args) => {
827
+ const first = setupTarget(args.path);
828
+ const answers = args.answers;
829
+ if (!answers || typeof answers !== 'object' || Array.isArray(answers))
830
+ throw new mcpLocal_1.ToolRefusal('answers must be an object: one value per question key from specpilot_setup_questions.');
831
+ if (args.asked !== undefined && (!Array.isArray(args.asked) || args.asked.some(k => typeof k !== 'string')))
832
+ throw new mcpLocal_1.ToolRefusal('asked must be a list of answer keys.');
833
+ const a = answers;
834
+ if (first.kind === 'new' && ('parent' in a || 'name' in a))
835
+ throw new mcpLocal_1.ToolRefusal('"parent" and "name" come from the path; leave them out of answers.');
836
+ const problem = first.kind === 'existing' ? (0, specSetup_1.answersShapeError)(a) : (0, specSetup_1.newProjectShapeError)({ parent: (0, path_1.dirname)(first.target), name: (0, path_1.basename)(first.target), ...a });
837
+ if (problem)
838
+ throw new mcpLocal_1.ToolRefusal(problem);
839
+ const labels = new Map((await setupQuestionList(first)).questions.map(x => [x.key, x.label]));
840
+ const asked = [...new Set(args.asked ?? [])].filter(k => k in a);
841
+ const counts = { fromCode: Object.keys(a).length - asked.length, fromUser: asked.length, topics: asked.flatMap(k => (labels.has(k) ? [labels.get(k)] : [])) };
842
+ const written = await locked(async () => {
843
+ const t = setupTarget(args.path); // again under the lock: the folder may have changed since (SEC-004.27)
844
+ if (t.kind !== first.kind)
845
+ throw new mcpLocal_1.ToolRefusal(`${t.kind === 'new' ? t.target : t.root} changed while it was being set up. Call specpilot_setup_questions again.`);
846
+ emitSetup(t, { row: 'questions', state: 'done', ...counts });
847
+ emitSetup(t, { row: 'write', state: 'running' });
848
+ let out;
849
+ if (t.kind === 'existing')
850
+ out = await (0, specSetup_1.setupProject)(t.root, a);
851
+ else if (roots.length + (cloningTarget ? 1 : 0) >= projectRegistry_1.MAX_PROJECTS)
852
+ out = { status: 409, error: TOO_MANY_PROJECTS };
853
+ else
854
+ out = await (0, specSetup_1.createProject)((0, path_1.dirname)(t.target), (0, path_1.basename)(t.target), a, roots, home, cloningTarget);
855
+ if (out.status !== 200) {
856
+ emitSetup(t, { row: 'write', state: 'idle' });
857
+ throw new mcpLocal_1.ToolRefusal(out.error);
858
+ }
859
+ emitSetup(t, { row: 'write', state: 'done', files: out.written.length });
860
+ if (t.kind === 'existing')
861
+ return { t, root: t.root, project: t.index, out };
862
+ pendingTarget = null;
863
+ const served = addRoot(t.target);
864
+ if ('error' in served)
865
+ throw new mcpLocal_1.ToolRefusal(`${t.target} was set up, but it could not be read to be served (${served.error}). Open it with Open a Project Folder. Written: ${out.written.join(', ')}`);
866
+ return { t, root: t.target, project: served.project, out };
867
+ });
868
+ emitSetup(written.t, { row: 'validate', state: 'running' });
869
+ const r = await new specValidator_1.SpecValidator().validate(written.root, { fix: false, verbose: false });
870
+ emitSetup(written.t, { row: 'validate', state: 'done', errors: r.errors.length, warnings: r.warnings.length, ...(written.t.kind === 'new' ? { project: written.project } : {}) });
871
+ const { out } = written;
872
+ return asJson({ path: written.root, project: written.project, written: out.written, kept: out.kept, notice: out.notice, validate: { errors: r.errors, warnings: r.warnings } });
873
+ };
763
874
  const callTool = async (name, args) => {
875
+ if (name === 'specpilot_setup_questions') {
876
+ const t = setupTarget(args.path);
877
+ emitSetup(t, { row: 'read', state: 'running' });
878
+ const list = await setupQuestionList(t);
879
+ emitSetup(t, { row: 'read', state: 'done', detected: list.detected.length });
880
+ emitSetup(t, { row: 'questions', state: 'running' });
881
+ return asJson({ mode: t.kind, path: t.kind === 'existing' ? t.root : t.target, name: list.name, detected: list.detected, questions: list.questions });
882
+ }
883
+ if (name === 'specpilot_setup_project')
884
+ return setupProjectTool(args);
764
885
  if (name === 'specpilot_list_projects') {
765
886
  return asJson({
766
887
  projects: roots.map((root, n) => {
@@ -811,6 +932,13 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
811
932
  return regenerateReport(new specBackfiller_1.SpecBackfiller().backfillSlashCommands(roots[i], false));
812
933
  }));
813
934
  };
935
+ /** An answered client (BL-103): kept for /api/specs, and sent as `event: mcp` to every open stream when it changes. */
936
+ const seeClient = (name) => {
937
+ if (mcpClient?.name === name)
938
+ return;
939
+ mcpClient = { name };
940
+ allStreams().forEach(st => st.write(`event: mcp\ndata: ${JSON.stringify({ client: mcpClient })}\n\n`));
941
+ };
814
942
  /** POST /mcp: the page's write checks in the same order, but Origin may be absent. A bad token is 403 too, never 401,
815
943
  * which Claude Code takes for an OAuth challenge (SEC-004.20). */
816
944
  const handleMcp = (req, res) => {
@@ -828,9 +956,12 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
828
956
  }
829
957
  if (!/^application\/json\s*(;|$)/i.test(req.headers['content-type'] ?? ''))
830
958
  return sendJson(res, 415, (0, mcpLocal_1.rpcError)(null, -32000, 'Send JSON-RPC as application/json.'));
831
- if (Number(req.headers['content-length'] ?? 0) > exports.MAX_MOVE_BODY)
959
+ if (Number(req.headers['content-length'] ?? 0) > exports.MAX_MCP_BODY)
832
960
  return sendJson(res, 413, (0, mcpLocal_1.rpcError)(null, -32000, 'The request is too large.'));
833
961
  readJson(req, res, body => (0, mcpLocal_1.answerMcp)(body, (0, mcpLocal_1.mirroredHeaders)(req.rawHeaders), mcpTools, specpilotVersion, callTool).then(reply => {
962
+ const name = (0, mcpLocal_1.mcpClientName)(body);
963
+ if (name !== undefined && reply.status === 200 && 'result' in reply.body)
964
+ seeClient(name);
834
965
  if (reply.status !== 202)
835
966
  return sendJson(res, reply.status, reply.body);
836
967
  res.writeHead(202, SECURITY_HEADERS);
@@ -838,7 +969,20 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
838
969
  }, () => {
839
970
  if (!res.headersSent)
840
971
  sendJson(res, 500, (0, mcpLocal_1.rpcError)(null, -32603, 'The server could not finish this request.'));
841
- }), exports.MAX_MOVE_BODY, () => sendJson(res, 400, (0, mcpLocal_1.rpcError)(null, -32700, 'Parse error: the body is not valid JSON.')));
972
+ }), exports.MAX_MCP_BODY, () => sendJson(res, 400, (0, mcpLocal_1.rpcError)(null, -32700, 'Parse error: the body is not valid JSON.')));
973
+ };
974
+ /** POST /api/quit (BL-098): 202, then the command's stop once the answer has gone out. */
975
+ let quitting = false;
976
+ const handleQuit = (req, res) => {
977
+ if (!writeAllowed(req, res))
978
+ return;
979
+ res.writeHead(202, { 'Content-Type': 'application/json; charset=utf-8', ...SECURITY_HEADERS });
980
+ res.end(JSON.stringify({ stopping: true }), () => {
981
+ if (quitting)
982
+ return;
983
+ quitting = true;
984
+ opts.onQuit?.();
985
+ });
842
986
  };
843
987
  const server = (0, http_1.createServer)((req, res) => {
844
988
  try {
@@ -856,12 +1000,10 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
856
1000
  res.setHeader('Allow', registry ? 'GET, POST' : '');
857
1001
  return send(res, 405, TEXT, 'Method Not Allowed\n');
858
1002
  }
859
- if (url.pathname === '/api/projects/new') {
860
- if (registry && req.method === 'GET')
861
- return handleProjectNewGet(res);
1003
+ if (url.pathname === '/api/projects/pending') {
862
1004
  if (registry && req.method === 'POST')
863
- return handleProjectNew(req, res);
864
- res.setHeader('Allow', registry ? 'GET, POST' : '');
1005
+ return handlePending(req, res);
1006
+ res.setHeader('Allow', registry ? 'POST' : '');
865
1007
  return send(res, 405, TEXT, 'Method Not Allowed\n');
866
1008
  }
867
1009
  if (url.pathname === '/api/projects/clone') {
@@ -870,12 +1012,24 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
870
1012
  res.setHeader('Allow', registry ? 'POST' : '');
871
1013
  return send(res, 405, TEXT, 'Method Not Allowed\n');
872
1014
  }
1015
+ if (url.pathname === '/api/projects/browse') {
1016
+ if (registry && req.method === 'POST')
1017
+ return handleBrowse(req, res);
1018
+ res.setHeader('Allow', registry ? 'POST' : '');
1019
+ return send(res, 405, TEXT, 'Method Not Allowed\n');
1020
+ }
873
1021
  if (url.pathname === '/api/projects/remove') {
874
1022
  if (registry && req.method === 'POST')
875
1023
  return handleProjectRemove(req, res);
876
1024
  res.setHeader('Allow', registry ? 'POST' : '');
877
1025
  return send(res, 405, TEXT, 'Method Not Allowed\n');
878
1026
  }
1027
+ if (url.pathname === '/api/quit') {
1028
+ if (token && req.method === 'POST')
1029
+ return handleQuit(req, res);
1030
+ res.setHeader('Allow', token ? 'POST' : '');
1031
+ return send(res, 405, TEXT, 'Method Not Allowed\n');
1032
+ }
879
1033
  if (url.pathname === '/api/tasks/move') {
880
1034
  if (req.method === 'POST' && token)
881
1035
  return handleMove(req, res, url);
@@ -894,20 +1048,6 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
894
1048
  res.setHeader('Allow', token ? 'POST' : '');
895
1049
  return send(res, 405, TEXT, 'Method Not Allowed\n');
896
1050
  }
897
- if (url.pathname === '/api/preview') {
898
- if (token && req.method === 'POST')
899
- return handlePreview(req, res, url);
900
- res.setHeader('Allow', token ? 'POST' : '');
901
- return send(res, 405, TEXT, 'Method Not Allowed\n');
902
- }
903
- if (url.pathname === '/api/setup') {
904
- if (token && req.method === 'GET')
905
- return handleSetupGet(res, url);
906
- if (token && req.method === 'POST')
907
- return handleSetupPost(req, res, url);
908
- res.setHeader('Allow', token ? 'GET, POST' : '');
909
- return send(res, 405, TEXT, 'Method Not Allowed\n');
910
- }
911
1051
  if (req.method !== 'GET') {
912
1052
  res.setHeader('Allow', 'GET');
913
1053
  return send(res, 405, TEXT, 'Method Not Allowed\n');
@@ -917,8 +1057,6 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
917
1057
  const mcpMeta = token && mcpToken ? `<meta name="specpilot-mcp" content="${opts.mcpToken ? 'env' : 'page'}">` : '';
918
1058
  return send(res, 200, UI_ROUTES['/'][1], page.replace(TOKEN_SLOT, token ? `<meta name="specpilot-token" content="${token}">` : '').replace(MCP_SLOT, mcpMeta));
919
1059
  }
920
- if (url.pathname === '/assets/chat-core.js')
921
- return send(res, 200, 'text/javascript; charset=utf-8', chatCoreScript((0, fs_1.readFileSync)(CHAT_CORE, 'utf-8')));
922
1060
  const ui = UI_ROUTES[url.pathname];
923
1061
  if (ui)
924
1062
  return send(res, 200, ui[1], (0, fs_1.readFileSync)((0, path_1.join)(UI_DIR, ui[0])));
@@ -943,12 +1081,14 @@ function createSpecServer(initialRoots, specpilotVersion, opts = {}) {
943
1081
  const stopClone = () => {
944
1082
  closing = true;
945
1083
  cloneAbort?.abort();
946
- return cloneDone;
1084
+ browseAbort?.abort();
1085
+ return Promise.all([cloneDone, browseDone]).then(() => undefined);
947
1086
  };
948
1087
  return {
949
1088
  server,
950
1089
  mcpToken,
951
1090
  streams: () => allStreams().length,
1091
+ pending: () => pendingTarget,
952
1092
  stopClone,
953
1093
  close: async () => {
954
1094
  await stopClone();