claude-code-session-manager 0.130.3 → 0.132.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 (78) hide show
  1. package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-C09MlPFx.js} +2 -2
  2. package/dist/assets/AppSettings-DvDKsCnD.js +2 -0
  3. package/dist/assets/{Button-UUr5giu8.js → Button-BzG_KdBC.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-fm6zsnLM.js} +1 -1
  5. package/dist/assets/Extensions-DgxKT_OZ.js +2 -0
  6. package/dist/assets/{History-Bndupj87.js → History-Nd3bKjBq.js} +2 -2
  7. package/dist/assets/{Library-DFn0YPIW.js → Library-R71t6VAB.js} +12 -12
  8. package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-CG50Ul7c.js} +1 -1
  9. package/dist/assets/{Panel-CIvb-XXN.js → Panel-C7EFG4eU.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-J92iNEGC.js} +7 -7
  11. package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-C3KB3ILO.js} +1 -1
  12. package/dist/assets/Scheduler-DeYBA7uc.js +16 -0
  13. package/dist/assets/{Settings-DqxUna06.js → Settings-B6r7N4v-.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-D7bt3fyB.js} +1 -1
  15. package/dist/assets/Skills-GpxtUrFP.js +29 -0
  16. package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-uyVMCZc7.js} +1 -1
  17. package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-Cv25uFSM.js} +1 -1
  18. package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-uP8fJkbM.js} +1 -1
  19. package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DRs80cX-.js} +1 -1
  20. package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-BDkvvzJ8.js} +1 -1
  21. package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-Cmtz2sQt.js} +1 -1
  22. package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-DHwAXunq.js} +1 -1
  23. package/dist/assets/index-CBCdyHbZ.js +3097 -0
  24. package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +414 -390
  28. package/package.json +1 -1
  29. package/scripts/scheduler-mcp-server.cjs +83 -4
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/index.cjs +11 -0
  32. package/src/main/ipcSchemas.cjs +28 -1
  33. package/src/main/lib/epic/epicMint.cjs +61 -6
  34. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  35. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  36. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  37. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
  38. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  39. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  40. package/src/main/lib/git/branchSweep.cjs +9 -3
  41. package/src/main/lib/git/gitExec.cjs +8 -1
  42. package/src/main/lib/git/gitWorktree.cjs +564 -62
  43. package/src/main/lib/git/jobWorktree.cjs +3 -0
  44. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  45. package/src/main/lib/mcpToolCatalog.cjs +43 -6
  46. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  47. package/src/main/lib/persona-macro/builtinMacros.cjs +33 -0
  48. package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
  49. package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
  50. package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
  51. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  52. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  53. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  54. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  55. package/src/main/lib/promptSessionSchema.cjs +5 -0
  56. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  57. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  58. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  59. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  60. package/src/main/projectPages.cjs +25 -2
  61. package/src/main/promptSessionEvents.cjs +10 -6
  62. package/src/main/runVerify.cjs +8 -3
  63. package/src/main/scheduler/budget.cjs +146 -7
  64. package/src/main/scheduler/gitTreeGuard.cjs +10 -11
  65. package/src/main/scheduler/reviewLadder.cjs +60 -0
  66. package/src/main/scheduler.cjs +461 -48
  67. package/src/main/seedAgentPersonas.cjs +1 -1
  68. package/src/preload/api.d.ts +162 -2
  69. package/src/preload/apiSurface.json +21 -0
  70. package/src/preload/index.cjs +5 -0
  71. package/src/seed/agents/competitive-analyst.md +69 -0
  72. package/src/seed/agents/competitive-researcher.md +75 -0
  73. package/src/seed/agents/validator.md +2 -2
  74. package/dist/assets/AppSettings-Cs4POznd.js +0 -2
  75. package/dist/assets/Extensions-B9QdiNOV.js +0 -2
  76. package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
  77. package/dist/assets/Skills-DTXehVS7.js +0 -12
  78. package/dist/assets/index-C9w-dVzo.js +0 -3090
@@ -91,6 +91,39 @@ const BUILTIN_MACROS = Object.freeze([
91
91
  prompt:
92
92
  "Use the session-manager-dev:maintaining-md-network skill to review this project's markdown network. Scope: {{scope}}. Mode: {{mode}}.",
93
93
  }),
94
+ Object.freeze({
95
+ id: 'builtin-competitor-matrix',
96
+ label: 'Competitor matrix',
97
+ agentName: 'competitive-analyst',
98
+ tag: 'project-home-builder',
99
+ surface: 'project-home',
100
+ projects: ['*'],
101
+ builtinVersion: 1,
102
+ job: Object.freeze({
103
+ estimateMinutes: 90,
104
+ artifactPaths: Object.freeze(['session-manager-operations/project-pages/matrix/matrix.json']),
105
+ }),
106
+ priorPrompts: Object.freeze([]),
107
+ prompt:
108
+ "Build this project's competitor feature matrix: how this product compares to its top 4 competitors. The competitors are named on a 'Competitors:' line in the additional instructions — up to 4 semicolon-separated slots, each a product name or 'auto' (an 'auto' slot means pick the most popular remaining competitor in this product's category, with cited popularity evidence); with no Competitors line, reuse the saved matrix's competitors, or make 4 auto picks when there is no saved matrix. Warm-start first: call project_matrix_read and, when a matrix exists, keep its feature, group and competitor ids stable and research only what is new since its last run plus unknown cells. Then fan out Haiku competitive-researcher subagents, one per competitor plus one user-voice sweep, collecting official announcements, dev blogs, changelogs, docs and what users rave about or ask for, with a source URL for every claim. Compare their findings against this repository's real features (read from the README, docs, manifest, source tree and git log, each backed by a path) and merge everything into 6-12 logical feature groups; for every feature record a stable id, title, detailed description, support per product (yes/partial/no/unknown with evidence), user sentiment, priority, rationale, and a ready-to-run sessionGoal where this project lacks or only partly has it. Append a runs[] entry and save the whole matrix with one project_matrix_write call.",
109
+ }),
110
+ Object.freeze({
111
+ id: 'builtin-cpu-audit',
112
+ label: 'CPU audit & fixes',
113
+ agentName: 'architect',
114
+ tag: 'feature',
115
+ surface: 'project-home',
116
+ projects: ['*'],
117
+ builtinVersion: 1,
118
+ inputs: Object.freeze([
119
+ Object.freeze({ name: 'scope', label: 'Scope', default: 'the whole project', required: true }),
120
+ Object.freeze({ name: 'scenario', label: 'Run scenario', default: 'idle, then its typical everyday load', required: true }),
121
+ ]),
122
+ supersedes: Object.freeze(['cpu-audit-fixes-8bd5d1']),
123
+ priorPrompts: Object.freeze([]),
124
+ prompt:
125
+ "Critically evaluate how much CPU this project uses while it runs, then get the recommended changes built. Primary goal: it consumes fewer resources while it runs — CPU first, then memory, disk I/O, network and process count. Secondary goal: it gets faster. Behavior stays the same. Scope: {{scope}}. Run scenario to measure: {{scenario}}. The project's CLAUDE.md and AGENTS.md laws override this prompt.\n\n1. Learn how it really runs. Read the README, manifests and start scripts. List every long-running process and everything it starts: workers, child CLIs, MCP servers, file watchers, timers, cron entries. If the project has no long-running process (a library, CLI or static site), measure its main commands instead (build, test, a typical run).\n\n2. Measure a baseline before you look for fixes. If the project is already running on this machine, measure that instance; never start a second copy beside a live one (ports, locks and shared state clash). Put a hard timeout on every command. Measure each state of the run scenario over a fixed window of at least 5 minutes. Record per process: average and peak CPU %, RSS, threads, child processes started per minute, and wakeups or syscalls where you can (pidstat, ps, top -b, /proc/<pid>/stat deltas, strace -c -f). Then profile the top consumers so cost is attributed to functions, not guessed: attach a sampling profiler to the running process where the runtime allows it (perf, py-spy, the Node inspector, DevTools for renderer processes), and restart a process under a profiler only when nothing live depends on it. Save the exact commands so the after-measurement repeats them.\n\n3. Review the code critically, starting from the hottest profiled paths. Look for: polling and timers that fire while nothing changes (idle should be near 0% CPU); busy loops; full rescans or re-parses of large files and directories; recursive watchers on big trees; a process spawned per tick or per request; unbounded concurrency; work redone on every request or render instead of cached; UI re-render storms and animations running while hidden; sync I/O on hot paths; chatty logging; large JSON stringify/parse; retries without backoff; over-frequent heartbeats; leaks (listeners, intervals, caches that only grow). For each one, first ask whether the work needs to run at all, then how to make it cheaper. Prefer structural fixes (event-driven instead of polling, incremental instead of full rescans, one shared process instead of many) over micro-tuning.\n\n4. Rank findings by measured cost × confidence ÷ risk, and drop anything without a measurable cost. Show them as a table: rank | where (file:line) | what burns the resource | measured cost (CPU share, RSS, spawns/min) | recommended change | expected saving | risk or tradeoff. Name every tradeoff plainly, such as a slower refresh. If the project is already lean, say so with the numbers and stop; do not invent work.\n\n5. Build the changes through /develop, highest impact first. Each PRD carries its measured evidence, the change, and acceptance criteria a headless run can check: deterministic tests (fake timers proving nothing polls while idle, call or spawn counts, bounded work per tick) or a bounded micro-benchmark with a before number and a target. Never use \"launch the app and watch top\" as a criterion. Every fix gets a regression guard so the waste cannot quietly return, and existing tests stay green.\n\n6. Track the PRDs to a validated finish, then re-measure live with the same commands, window and scenario. Report a before/after table per process: average and peak CPU, RSS, spawns/min. If the running copy is an installed or released build rather than this tree, the after-measurement waits for that release: say exactly what has landed but is not live yet, and never claim a saving from tests alone.",
126
+ }),
94
127
  ]);
95
128
 
96
129
  module.exports = { BUILTIN_MACROS };
@@ -27,12 +27,20 @@ const PAGE_IDS = { 'how it works': 'how-it-works', faq: 'faq', overview: 'overvi
27
27
  // Same rule as ENTRY_ID_RE in ipcSchemas.cjs. The id becomes a path segment in
28
28
  // artifactPaths, so an id taken from free text must pass it first.
29
29
  const ENTRY_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
30
+ // Reserved for the Competitor matrix snapshot; projectHomeAdminRoutes.cjs
31
+ // buildPage refuses it with the same constant. A builder page gets this instead.
32
+ const MATRIX_PAGE_ID = 'competitive-matrix';
33
+ const unreserve = (id) => (id === MATRIX_PAGE_ID ? `${MATRIX_PAGE_ID}-page` : id);
30
34
 
31
35
  // Entry id: a valid 'Replace entry: <id>' line in the extra instructions
32
36
  // (Regenerate) rebuilds that entry in place, for either kind; an invalid one
33
37
  // is ignored. Otherwise videos get a fresh id per press and knowledge pages
34
38
  // are named by a 'Page: <name>' line (default 'overview').
35
39
  function entryIdFor(kind, extra, t) {
40
+ return kind === 'video' ? rawEntryIdFor(kind, extra, t) : unreserve(rawEntryIdFor(kind, extra, t));
41
+ }
42
+
43
+ function rawEntryIdFor(kind, extra, t) {
36
44
  const replace = /^\s*Replace entry:\s*(\S+)\s*$/im.exec(extra || '');
37
45
  if (replace && ENTRY_ID_RE.test(replace[1])) return replace[1];
38
46
  if (kind === 'video') return `vid-${t.toString(36)}${Math.random().toString(36).slice(2, 5).padEnd(3, '0')}`;
@@ -6,17 +6,48 @@
6
6
  * injected (index.cjs passes the real scheduler, createPrd and archive).
7
7
  *
8
8
  * deps: { schemas, validatePath, readActiveIndex, createPrd, loadJobs,
9
- * archivePrd, dispatchMacroJob?, macroJobStatuses?, readHistoryTail? }
9
+ * archivePrd, appendResponseEventWithReason?, dispatchMacroJob?,
10
+ * macroJobStatuses?, readHistoryTail?, builtins? }
11
+ *
12
+ * When a dispatch returns ok:false for an Epic that exists in the cwd's
13
+ * active-index.json (and no build is already running for it — `activeSlug`),
14
+ * one durable 'response' event marked `notice: 'job-not-queued'` is appended
15
+ * to that Epic naming the macro, the error and the retry path (PRD 2950), so
16
+ * a job-macro Epic whose build never queued cannot read as a silently running
17
+ * session. The append is best effort: it never changes the returned result.
10
18
  * `createPrd` is called as `chat:create-prd` calls it, so its own
11
19
  * remote.requestReconcile() queues the row at once — no second rescan here.
12
20
  */
13
21
 
14
22
  const { dispatchMacroJob: realDispatch } = require('./macroJobDispatch.cjs');
15
23
  const { macroJobStatuses: realStatuses } = require('./macroJobStatus.cjs');
24
+ const { BUILTIN_MACROS } = require('./builtinMacros.cjs');
25
+
26
+ const JOB_NOT_QUEUED_NOTICE = 'job-not-queued';
27
+
28
+ function noticeText(label, error) {
29
+ return `${label} background build was not queued: ${error} — press it again in Project Home ▸ Tools to retry.`;
30
+ }
16
31
 
17
32
  function registerMacroJobIpc(ipcMain, deps = {}) {
18
33
  const dispatch = deps.dispatchMacroJob || realDispatch;
19
34
  const statuses = deps.macroJobStatuses || realStatuses;
35
+ const builtins = deps.builtins || BUILTIN_MACROS;
36
+
37
+ async function appendNotice(cwd, macroId, epicId, error) {
38
+ if (typeof deps.appendResponseEventWithReason !== 'function') return;
39
+ try {
40
+ const macro = (builtins || []).find((m) => m && m.id === macroId);
41
+ const label = (macro && macro.label) || macroId;
42
+ const res = await deps.appendResponseEventWithReason(
43
+ cwd, epicId, noticeText(label, error),
44
+ { notice: JOB_NOT_QUEUED_NOTICE, allowInactive: true },
45
+ );
46
+ if (res && res.ok === false) console.warn('[macroJobIpc] job-not-queued notice not appended', epicId, res.reason);
47
+ } catch (e) {
48
+ console.warn('[macroJobIpc] job-not-queued notice append failed', epicId, e?.message ?? e);
49
+ }
50
+ }
20
51
 
21
52
  ipcMain.handle('macros:dispatch-job', async (_event, rawPayload) => {
22
53
  const payload = deps.schemas.macrosDispatchJob.parse(rawPayload);
@@ -24,17 +55,32 @@ function registerMacroJobIpc(ipcMain, deps = {}) {
24
55
  const index = deps.readActiveIndex(cwd);
25
56
  const sessions = index && index.sessions ? index.sessions : {};
26
57
  const entry = Object.prototype.hasOwnProperty.call(sessions, payload.epicId) ? sessions[payload.epicId] : null;
27
- if (!entry || entry.status !== 'active') {
58
+ if (!entry) {
28
59
  return { ok: false, error: `epic ${payload.epicId} is not an active session in this project` };
29
60
  }
30
- return dispatch(
31
- { cwd, macroId: payload.macroId, epicId: payload.epicId, extraInstructions: payload.extraInstructions },
32
- {
33
- createPrd: deps.createPrd,
34
- listRows: async () => deps.loadJobs(),
35
- archivePrd: (slug, rowCwd) => deps.archivePrd(slug, rowCwd),
36
- },
37
- );
61
+ if (entry.status !== 'active') {
62
+ const refused = { ok: false, error: `epic ${payload.epicId} is not an active session in this project` };
63
+ await appendNotice(cwd, payload.macroId, payload.epicId, refused.error);
64
+ return refused;
65
+ }
66
+ let result;
67
+ try {
68
+ result = await dispatch(
69
+ { cwd, macroId: payload.macroId, epicId: payload.epicId, extraInstructions: payload.extraInstructions },
70
+ {
71
+ createPrd: deps.createPrd,
72
+ listRows: async () => deps.loadJobs(),
73
+ archivePrd: (slug, rowCwd) => deps.archivePrd(slug, rowCwd),
74
+ },
75
+ );
76
+ } catch (e) {
77
+ await appendNotice(cwd, payload.macroId, payload.epicId, e?.message ?? String(e));
78
+ throw e;
79
+ }
80
+ if (result && result.ok === false && !result.activeSlug) {
81
+ await appendNotice(cwd, payload.macroId, payload.epicId, result.error || 'unknown error');
82
+ }
83
+ return result;
38
84
  });
39
85
 
40
86
  ipcMain.handle('macros:job-status', async (_event, rawPayload) => {
@@ -47,4 +93,4 @@ function registerMacroJobIpc(ipcMain, deps = {}) {
47
93
  });
48
94
  }
49
95
 
50
- module.exports = { registerMacroJobIpc };
96
+ module.exports = { registerMacroJobIpc, JOB_NOT_QUEUED_NOTICE };
@@ -31,6 +31,10 @@
31
31
  * project). setMacroProject cannot narrow a '*' macro: it returns
32
32
  * `{ ok: false, error: 'macro is shown in every project' }`.
33
33
  *
34
+ * A surface 'project-home' macro is shown in every project (only its generated
35
+ * artifacts are per project); this module enforces that on load (a narrowed
36
+ * stored entry is widened to ['*']) and on save (projects forced to ['*']).
37
+ *
34
38
  * Plain Node, no Electron imports.
35
39
  */
36
40
 
@@ -394,16 +398,35 @@ function ensureBuiltins(macros, builtins) {
394
398
  return { macros: next, changed, retired };
395
399
  }
396
400
 
397
- /** Apply builtin seeding/upgrades, writing only when something changed. */
401
+ /**
402
+ * Pure. A 'project-home' macro is shown in every project, so any such entry
403
+ * whose `projects` is not exactly ['*'] comes back with ['*']. Every other
404
+ * field — notably `updatedAt` — is left as is: ensureBuiltins reads
405
+ * `updatedAt !== createdAt` as a human edit and would freeze a built-in.
406
+ * Returns `{ macros, changed }`.
407
+ */
408
+ function widenProjectHomeScope(macros) {
409
+ let changed = false;
410
+ const next = macros.map((m) => {
411
+ if (m.surface !== 'project-home') return m;
412
+ if (m.projects.length === 1 && m.projects[0] === ALL_PROJECTS) return m;
413
+ changed = true;
414
+ return { ...m, projects: [ALL_PROJECTS] };
415
+ });
416
+ return { macros: changed ? next : macros, changed };
417
+ }
418
+
419
+ /** Apply project-home widening + builtin seeding/upgrades, writing only when something changed. */
398
420
  async function applyBuiltins(filePath, macros, opts) {
399
421
  const builtins = resolveBuiltins(opts);
400
- const { macros: next, changed, retired } = ensureBuiltins(macros, builtins);
401
- if (!changed) return { macros, failed: false };
422
+ const widened = widenProjectHomeScope(macros);
423
+ const { macros: next, changed: builtinsChanged, retired } = ensureBuiltins(widened.macros, builtins);
424
+ if (!builtinsChanged && !widened.changed) return { macros, failed: false };
402
425
  try {
403
426
  await writeStore(filePath, next);
404
427
  } catch (err) {
405
- console.warn('[macroLibrary] could not persist built-in macro seeding:', err && err.message);
406
- return { macros, failed: false };
428
+ console.warn('[macroLibrary] could not persist built-in macro seeding / project-home widening:', err && err.message);
429
+ return { macros: widened.macros, failed: false };
407
430
  }
408
431
  for (const id of retired) {
409
432
  const by = (builtins || []).find((b) => Array.isArray(b.supersedes) && b.supersedes.includes(id));
@@ -528,7 +551,7 @@ async function listMacrosRaw(opts) {
528
551
  const first = await readStore(filePath);
529
552
  if (first.state === 'ok') {
530
553
  const { changed } = ensureBuiltins(first.macros, resolveBuiltins(opts));
531
- if (!changed) return first.macros;
554
+ if (!changed && !widenProjectHomeScope(first.macros).changed) return first.macros;
532
555
  }
533
556
  // Missing/corrupt/needs-seeding: repair inside the write chain so racing callers don't double-seed.
534
557
  return serialize(async () => (await loadStore(filePath, opts)).macros);
@@ -566,7 +589,10 @@ async function saveMacro(input, opts = {}) {
566
589
  if (macros[idx].builtin && parsed.surface !== undefined && parsed.surface !== macros[idx].surface) {
567
590
  throw new Error('built-in macro surface cannot be changed');
568
591
  }
569
- const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : macros[idx].projects;
592
+ const surface = parsed.surface ?? macros[idx].surface;
593
+ const projects = surface === 'project-home'
594
+ ? [ALL_PROJECTS]
595
+ : parsed.projects !== undefined ? normalizeProjects(parsed.projects) : macros[idx].projects;
570
596
  saved = {
571
597
  ...macros[idx],
572
598
  label: parsed.label,
@@ -574,7 +600,7 @@ async function saveMacro(input, opts = {}) {
574
600
  tag: parsed.tag,
575
601
  prompt: parsed.prompt,
576
602
  projects,
577
- surface: parsed.surface ?? macros[idx].surface,
603
+ surface,
578
604
  updatedAt: now,
579
605
  };
580
606
  if (parsed.inputs === undefined) {
@@ -594,7 +620,10 @@ async function saveMacro(input, opts = {}) {
594
620
  assertPlaceholdersDeclared(saved);
595
621
  macros[idx] = saved;
596
622
  } else {
597
- const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : [];
623
+ const surface = parsed.surface ?? 'sessions';
624
+ const projects = surface === 'project-home'
625
+ ? [ALL_PROJECTS]
626
+ : parsed.projects !== undefined ? normalizeProjects(parsed.projects) : [];
598
627
  saved = {
599
628
  id: newId(parsed.label, new Set(macros.map((m) => m.id))),
600
629
  label: parsed.label,
@@ -602,7 +631,7 @@ async function saveMacro(input, opts = {}) {
602
631
  tag: parsed.tag,
603
632
  prompt: parsed.prompt,
604
633
  projects,
605
- surface: parsed.surface ?? 'sessions',
634
+ surface,
606
635
  createdAt: now,
607
636
  updatedAt: now,
608
637
  };
@@ -718,4 +747,5 @@ module.exports = {
718
747
  removeMacroFromProject,
719
748
  defaultFilePath,
720
749
  ensureBuiltins,
750
+ widenProjectHomeScope,
721
751
  };
@@ -343,6 +343,17 @@ const SHIPPED_PERSONA_SEEDS = deepFreeze({
343
343
  tools: "Read, Grep, Glob, Bash",
344
344
  },
345
345
  },
346
+ {
347
+ commit: "ca493932",
348
+ bodySha256: "5f81ad780f052adbcd6b64125b6447dcc9927c576bba81f5ff8fb9d58a06174a",
349
+ fm: {
350
+ description: "Validates a finished PLAN (the PRDs its validate PRD lists) once, after its last PRD lands — re-runs each PRD's gate, checks every acceptance criterion against the real tree, reviews the plan's combined diff, and reports one VERIFIED/REFUTED verdict per PRD via sentinel lines. Runs headless as a scheduled PRD (agentType: validator); never edits product code and never queues work.",
351
+ executorOnly: "true",
352
+ model: "sonnet",
353
+ title: "Engineering — Plan Validator",
354
+ tools: "Read, Grep, Glob, Bash",
355
+ },
356
+ },
346
357
  ],
347
358
  "demo-video-builder": [
348
359
  {
@@ -504,6 +515,33 @@ const SHIPPED_PERSONA_SEEDS = deepFreeze({
504
515
  },
505
516
  },
506
517
  ],
518
+ "competitive-researcher": [
519
+ {
520
+ commit: "seed-v1",
521
+ bodySha256: "4c6df5cb5a6486ea507fd6f985f324c9bd2557f1aed50ebd30dd666662267fda",
522
+ fm: {
523
+ description: "The Haiku collector for the Competitor matrix — run as a subagent by competitive-analyst, it researches ONE product's official announcements, dev blogs, changelogs and docs plus what users rave about or ask for, and writes cited JSON findings to the path it is given.",
524
+ tools: "WebSearch, WebFetch, Read, Write",
525
+ title: "Research — Competitor collector",
526
+ model: "haiku",
527
+ effort: "low",
528
+ },
529
+ },
530
+ ],
531
+ "competitive-analyst": [
532
+ {
533
+ commit: "seed-v1",
534
+ bodySha256: "8e72237e9b743bb8c26cc701d3ebd6c65212ebf777de37f9eb5f40aeaf224fae",
535
+ fm: {
536
+ description: "The Opus analyst and executor of the Competitor matrix macro — warm-starts from the saved matrix, settles 1..4 competitors, inventories this project's real features, fans out Haiku competitive-researcher subagents, then merges everything into a grouped feature matrix with sentiment and prioritized recommendations and saves it once with project_matrix_write.",
537
+ tools: "Read, Grep, Glob, Bash, Write, WebSearch, WebFetch, Agent, mcp__session-manager-scheduler__project_matrix_read, mcp__session-manager-scheduler__project_matrix_write",
538
+ title: "Research — Competitor analyst",
539
+ model: "opus",
540
+ effort: "high",
541
+ tags: "project-home-builder",
542
+ },
543
+ },
544
+ ],
507
545
  });
508
546
 
509
547
  module.exports = { SHIPPED_PERSONA_SEEDS };
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * competitiveMatrix.cjs — data model for the Project Home "Competitor matrix"
5
+ * tool. The matrix is a local, schema-checked JSON file
6
+ * (`project-pages/matrix/matrix.json`) that the research macro reads at the
7
+ * start of every run so it never starts cold: my product ('self') + 1..4
8
+ * competitors, logical feature groups, features with per-product support,
9
+ * user sentiment and a recommendation, cited sources, and run history.
10
+ *
11
+ * This module is read-only: schema, referential validation, derived JSON
12
+ * Schema, path helpers, a never-throwing reader and a missing-features helper.
13
+ * Writing lives elsewhere (matrixStore.cjs, writer 'project-home').
14
+ */
15
+
16
+ const fsp = require('node:fs/promises');
17
+ const { z } = require('zod/v4');
18
+ const { opsPath } = require('../opsOwnership.cjs');
19
+
20
+ const MAX_MATRIX_BYTES = 1048576;
21
+ const SCHEMA_ID = 'session-manager/competitive-matrix.v1';
22
+ const ERROR_MAX = 300;
23
+
24
+ const ID = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/);
25
+ const Status = z.enum(['yes', 'partial', 'no', 'unknown']);
26
+ const HttpsUrl = z.string().max(500).url()
27
+ .refine((s) => s.startsWith('https://'), { message: 'URL must start with https://' });
28
+ const DateTime = z.iso.datetime();
29
+ const SourceIds = z.array(ID).max(20);
30
+
31
+ const ProductSchema = z.object({
32
+ id: z.literal('self'),
33
+ name: z.string().min(1).max(80),
34
+ summary: z.string().max(600),
35
+ }).strict();
36
+
37
+ const CompetitorSchema = z.object({
38
+ id: ID,
39
+ name: z.string().min(1).max(80),
40
+ url: HttpsUrl.optional(),
41
+ category: z.string().max(60),
42
+ chosenBy: z.enum(['user', 'auto']),
43
+ why: z.string().max(600),
44
+ }).strict();
45
+
46
+ const GroupSchema = z.object({
47
+ id: ID,
48
+ title: z.string().min(1).max(80),
49
+ description: z.string().max(400),
50
+ }).strict();
51
+
52
+ const SupportSchema = z.object({
53
+ status: Status,
54
+ note: z.string().max(400),
55
+ sourceIds: SourceIds,
56
+ }).strict();
57
+
58
+ const PRIORITIES = ['P0', 'P1', 'P2', 'P3', 'none'];
59
+
60
+ const FeatureSchema = z.object({
61
+ id: ID,
62
+ groupId: ID,
63
+ title: z.string().min(1).max(120),
64
+ description: z.string().min(1).max(2000),
65
+ sentiment: z.object({
66
+ signal: z.enum(['loved', 'requested', 'mixed', 'complained', 'none']),
67
+ summary: z.string().max(600),
68
+ sourceIds: SourceIds,
69
+ }).strict(),
70
+ support: z.record(ID, SupportSchema),
71
+ recommendation: z.object({
72
+ priority: z.enum(PRIORITIES),
73
+ rationale: z.string().max(1000),
74
+ sessionGoal: z.string().max(2000),
75
+ }).strict(),
76
+ firstSeenAt: DateTime,
77
+ updatedAt: DateTime,
78
+ }).strict();
79
+
80
+ const SourceSchema = z.object({
81
+ id: ID,
82
+ url: HttpsUrl,
83
+ title: z.string().min(1).max(200),
84
+ publisher: z.string().max(80),
85
+ publishedAt: z.string().max(40).nullable(),
86
+ retrievedAt: DateTime,
87
+ kind: z.enum(['announcement', 'blog', 'docs', 'changelog', 'forum', 'review', 'social', 'repo']),
88
+ }).strict();
89
+
90
+ const RunSchema = z.object({
91
+ at: DateTime,
92
+ model: z.string().max(60),
93
+ competitors: z.array(z.string().max(80)).max(4),
94
+ added: z.array(ID).max(300),
95
+ changed: z.array(ID).max(300),
96
+ notes: z.string().max(1000),
97
+ }).strict();
98
+
99
+ const CompetitiveMatrixSchema = z.object({
100
+ schemaVersion: z.literal(1),
101
+ product: ProductSchema,
102
+ competitors: z.array(CompetitorSchema).min(1).max(4),
103
+ groups: z.array(GroupSchema).min(1).max(30),
104
+ features: z.array(FeatureSchema).max(300),
105
+ sources: z.array(SourceSchema).max(600),
106
+ runs: z.array(RunSchema).min(1).max(200),
107
+ updatedAt: DateTime,
108
+ }).strict();
109
+
110
+ function fail(pathStr, message) {
111
+ const text = `${pathStr || '(root)'}: ${message}`.replace(/\s+/g, ' ').trim();
112
+ return { ok: false, error: text.slice(0, ERROR_MAX) };
113
+ }
114
+
115
+ function fmtPath(parts) {
116
+ return parts.reduce((acc, p) => (typeof p === 'number' ? `${acc}[${p}]` : acc ? `${acc}.${String(p)}` : String(p)), '');
117
+ }
118
+
119
+ function dupId(list, name) {
120
+ const seen = new Set();
121
+ for (let i = 0; i < list.length; i++) {
122
+ const id = list[i].id;
123
+ if (seen.has(id)) return fail(`${name}[${i}].id`, `duplicate id '${id}'`);
124
+ seen.add(id);
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /** Cross-reference checks the zod shape cannot express. */
130
+ function referentialError(m) {
131
+ for (const name of ['competitors', 'groups', 'features', 'sources']) {
132
+ const err = dupId(m[name], name);
133
+ if (err) return err;
134
+ }
135
+ for (let i = 0; i < m.competitors.length; i++) {
136
+ if (m.competitors[i].id === 'self') {
137
+ return fail(`competitors[${i}].id`, "'self' is reserved for the product");
138
+ }
139
+ }
140
+ const groupIds = new Set(m.groups.map((g) => g.id));
141
+ const sourceIds = new Set(m.sources.map((s) => s.id));
142
+ const expectedKeys = ['self', ...m.competitors.map((c) => c.id)].sort();
143
+ const checkSources = (ids, at) => {
144
+ for (let k = 0; k < ids.length; k++) {
145
+ if (!sourceIds.has(ids[k])) return fail(`${at}.sourceIds[${k}]`, `unknown source '${ids[k]}'`);
146
+ }
147
+ return null;
148
+ };
149
+ for (let i = 0; i < m.features.length; i++) {
150
+ const f = m.features[i];
151
+ const at = `features[${i}]`;
152
+ if (!groupIds.has(f.groupId)) return fail(`${at}.groupId`, `unknown group '${f.groupId}'`);
153
+ const keys = Object.keys(f.support).sort();
154
+ if (keys.length !== expectedKeys.length || keys.some((k, j) => k !== expectedKeys[j])) {
155
+ const missing = expectedKeys.filter((k) => !keys.includes(k));
156
+ const extra = keys.filter((k) => !expectedKeys.includes(k));
157
+ return fail(`${at}.support`, `keys must be exactly [${expectedKeys.join(', ')}]`
158
+ + (missing.length ? `; missing ${missing.join(', ')}` : '')
159
+ + (extra.length ? `; unexpected ${extra.join(', ')}` : ''));
160
+ }
161
+ let err = checkSources(f.sentiment.sourceIds, `${at}.sentiment`);
162
+ if (err) return err;
163
+ for (const key of keys) {
164
+ err = checkSources(f.support[key].sourceIds, `${at}.support.${key}`);
165
+ if (err) return err;
166
+ }
167
+ }
168
+ return null;
169
+ }
170
+
171
+ /** validateMatrix(value) → { ok: true, matrix } | { ok: false, error }. Never throws. */
172
+ function validateMatrix(value) {
173
+ let json;
174
+ try {
175
+ json = JSON.stringify(value);
176
+ } catch (e) {
177
+ return fail('(root)', `not serializable: ${e && e.message ? e.message : e}`);
178
+ }
179
+ if (json === undefined) return fail('(root)', 'expected an object');
180
+ const bytes = Buffer.byteLength(json, 'utf8');
181
+ if (bytes > MAX_MATRIX_BYTES) {
182
+ return fail('(root)', `matrix is ${bytes} bytes, over the ${MAX_MATRIX_BYTES}-byte cap`);
183
+ }
184
+ const parsed = CompetitiveMatrixSchema.safeParse(value);
185
+ if (!parsed.success) {
186
+ const issue = parsed.error.issues[0];
187
+ return fail(fmtPath(issue.path), issue.message);
188
+ }
189
+ const err = referentialError(parsed.data);
190
+ if (err) return err;
191
+ return { ok: true, matrix: parsed.data };
192
+ }
193
+
194
+ /** JSON Schema for the matrix, written beside it so the macro can read the contract. */
195
+ function matrixJsonSchema() {
196
+ return { $id: SCHEMA_ID, ...z.toJSONSchema(CompetitiveMatrixSchema) };
197
+ }
198
+
199
+ /** Features my product lacks or only partly has — P0..P3, none, then title. */
200
+ function missingFeatures(matrix) {
201
+ const rank = (f) => PRIORITIES.indexOf(f.recommendation.priority);
202
+ return matrix.features
203
+ .filter((f) => f.support.self && (f.support.self.status === 'no' || f.support.self.status === 'partial'))
204
+ .sort((a, b) => (rank(a) - rank(b)) || a.title.localeCompare(b.title));
205
+ }
206
+
207
+ /** Paths under project-pages/matrix/, or null for an ephemeral cwd. */
208
+ function matrixPaths(realCwd) {
209
+ try {
210
+ return {
211
+ dir: opsPath(realCwd, 'project-pages', 'matrix'),
212
+ matrix: opsPath(realCwd, 'project-pages', 'matrix', 'matrix.json'),
213
+ schema: opsPath(realCwd, 'project-pages', 'matrix', 'matrix.schema.json'),
214
+ history: opsPath(realCwd, 'project-pages', 'matrix', 'history'),
215
+ };
216
+ } catch (e) {
217
+ if (e && e.ephemeral) return null;
218
+ throw e;
219
+ }
220
+ }
221
+
222
+ /** readMatrix(realCwd) → { matrix, error, path }. Never throws. */
223
+ async function readMatrix(realCwd) {
224
+ let paths;
225
+ try {
226
+ paths = matrixPaths(realCwd);
227
+ } catch (e) {
228
+ return { matrix: null, error: fail('(cwd)', e && e.message ? e.message : String(e)).error, path: null };
229
+ }
230
+ if (!paths) return { matrix: null, error: null, path: null };
231
+ const file = paths.matrix;
232
+ let text;
233
+ try {
234
+ text = await fsp.readFile(file, 'utf8');
235
+ } catch (e) {
236
+ if (e && e.code === 'ENOENT') return { matrix: null, error: null, path: file };
237
+ return { matrix: null, error: fail('matrix.json', `unreadable: ${e && e.message ? e.message : e}`).error, path: file };
238
+ }
239
+ let value;
240
+ try {
241
+ value = JSON.parse(text);
242
+ } catch (e) {
243
+ return { matrix: null, error: fail('matrix.json', `invalid JSON: ${e && e.message ? e.message : e}`).error, path: file };
244
+ }
245
+ const v = validateMatrix(value);
246
+ if (!v.ok) return { matrix: null, error: v.error, path: file };
247
+ return { matrix: v.matrix, error: null, path: file };
248
+ }
249
+
250
+ module.exports = {
251
+ CompetitiveMatrixSchema,
252
+ validateMatrix,
253
+ matrixJsonSchema,
254
+ missingFeatures,
255
+ matrixPaths,
256
+ readMatrix,
257
+ MAX_MATRIX_BYTES,
258
+ };