claude-code-session-manager 0.130.2 → 0.131.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 (88) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-CYXre0J-.js +2 -0
  4. package/dist/assets/{AppSettings-Bpwynea4.js → AppSettings-xNSfCj8e.js} +2 -2
  5. package/dist/assets/{Button-DSoqrxCB.js → Button-BWljh5IK.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-FUC2hZlp.js +1 -0
  7. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  8. package/dist/assets/{History-DzMo9Otn.js → History-BvNmY9OQ.js} +2 -2
  9. package/dist/assets/{Library-C5wKMTSn.js → Library-DVXk77zA.js} +12 -12
  10. package/dist/assets/{ListDetail-DDQ1S0yu.js → ListDetail-DAAx__24.js} +1 -1
  11. package/dist/assets/{Panel-B-3NWUlv.js → Panel-g2D-e-RM.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BDuHJwaO.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-CUChwz4Z.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  14. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  15. package/dist/assets/Settings-B23RsRfm.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-C6JEdypC.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  17. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  18. package/dist/assets/{SourceChip-DcBNYYhe.js → SourceChip-jrC0vjfw.js} +1 -1
  19. package/dist/assets/SystemPrompt-hHoBEnYb.js +1 -0
  20. package/dist/assets/{TiptapBody-DiVYC-_O.js → TiptapBody-FkUqxO9u.js} +1 -1
  21. package/dist/assets/{Toggle-Cs3k6I96.js → Toggle-DQMNWZKT.js} +1 -1
  22. package/dist/assets/ViewTabs-DGU0ZuxB.js +1 -0
  23. package/dist/assets/{VoiceButton-C3NLotUZ.js → VoiceButton-BPPvDllh.js} +1 -1
  24. package/dist/assets/{historyTotals-f-E0L9Xw.js → historyTotals-D8Oc3wUK.js} +1 -1
  25. package/dist/assets/index-9ajPMXBg.js +3097 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-oXqzajWV.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +455 -427
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/scripts/scheduler-mcp-server.cjs +71 -0
  35. package/src/main/agentLibrary.cjs +81 -29
  36. package/src/main/agentsIpc.cjs +21 -16
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/index.cjs +9 -0
  39. package/src/main/ipcSchemas.cjs +35 -2
  40. package/src/main/lib/epic/epicMint.cjs +61 -6
  41. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  42. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  43. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  44. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  45. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  46. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +4 -0
  47. package/src/main/lib/git/branchSweep.cjs +9 -3
  48. package/src/main/lib/git/gitExec.cjs +8 -1
  49. package/src/main/lib/git/gitWorktree.cjs +771 -96
  50. package/src/main/lib/git/jobWorktree.cjs +3 -0
  51. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  52. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  53. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  54. package/src/main/lib/mdNetworkScan.cjs +555 -0
  55. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +22 -4
  57. package/src/main/lib/persona-macro/macroJobDispatch.cjs +17 -2
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  59. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  60. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  61. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  62. package/src/main/lib/promptSessionSchema.cjs +5 -0
  63. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  64. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  65. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  66. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  67. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  68. package/src/main/projectPages.cjs +51 -7
  69. package/src/main/runVerify.cjs +8 -3
  70. package/src/main/scheduler/budget.cjs +146 -7
  71. package/src/main/scheduler/gitTreeGuard.cjs +92 -20
  72. package/src/main/scheduler/reviewLadder.cjs +60 -0
  73. package/src/main/scheduler.cjs +477 -53
  74. package/src/main/seedAgentPersonas.cjs +1 -1
  75. package/src/preload/api.d.ts +250 -7
  76. package/src/preload/apiSurface.json +28 -0
  77. package/src/preload/index.cjs +6 -0
  78. package/src/seed/agents/competitive-analyst.md +69 -0
  79. package/src/seed/agents/competitive-researcher.md +75 -0
  80. package/src/seed/agents/validator.md +2 -2
  81. package/dist/assets/AgentLibrary-Bfj862qf.js +0 -2
  82. package/dist/assets/Extensions-BziIutWV.js +0 -13
  83. package/dist/assets/Memory-Bq5T33d2.js +0 -25
  84. package/dist/assets/Scheduler-CkGHMXvo.js +0 -16
  85. package/dist/assets/Settings-DGxvyajs.js +0 -2
  86. package/dist/assets/SystemPrompt-CfozyVQx.js +0 -1
  87. package/dist/assets/ViewTabs-DFXH03tb.js +0 -1
  88. package/dist/assets/index-CuAfFXNd.js +0 -3086
@@ -31,7 +31,7 @@ const BUILTIN_MACROS = Object.freeze([
31
31
  tag: 'project-home-builder',
32
32
  surface: 'project-home',
33
33
  projects: ['*'],
34
- builtinVersion: 2,
34
+ builtinVersion: 3,
35
35
  job: Object.freeze({
36
36
  estimateMinutes: 20,
37
37
  entryKind: 'knowledge',
@@ -39,9 +39,10 @@ const BUILTIN_MACROS = Object.freeze([
39
39
  }),
40
40
  priorPrompts: Object.freeze([
41
41
  "Generate this project's Project Home page: one self-contained HTML overview (what it is, who it is for, key features, structure, how to run it, key commands), grounded only in what you read in the repository. Save it with a single project_home_write call.",
42
+ "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
42
43
  ]),
43
44
  prompt:
44
- "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
45
+ "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). A 'Page: Overview' line means the same as no Page line. Write for the reader named on an 'Audience:' line: Newcomers (new to the project: plain words, every term explained), Users (people who use it: what it does for them and how to use it) or Contributors (people who work on its code: name the real files and modules); with no Audience line, write for Newcomers. Size the page to a 'Length:' line: Brief (only the essentials), Standard (the usual depth) or In-depth (thorough, with more sections and more detail); with no Length line, write a Standard page. Read only the sources named on a 'Read from:' line — README & docs, Source tree (the code, its manifest and directory layout) or Git log — and ground every claim in those alone; with 'Read from: nothing selected' or no Read from line, read any of the three. Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
45
46
  }),
46
47
  Object.freeze({
47
48
  id: 'builtin-demo-video',
@@ -50,7 +51,7 @@ const BUILTIN_MACROS = Object.freeze([
50
51
  tag: 'project-home-builder',
51
52
  surface: 'project-home',
52
53
  projects: ['*'],
53
- builtinVersion: 6,
54
+ builtinVersion: 7,
54
55
  job: Object.freeze({
55
56
  estimateMinutes: 60,
56
57
  entryKind: 'video',
@@ -62,9 +63,10 @@ const BUILTIN_MACROS = Object.freeze([
62
63
  'Generate a 30-second demo video for this project as one self-contained HTML/JavaScript animation that presents its main goals and key features, grounded only in what you read in the repository, with a matching on-device narration track: narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.',
63
64
  "Generate a character and cute animated JavaScript video: a 30-second demo of this project as one self-contained HTML/JavaScript animation. Ground everything in what you read in the repository — invent an original mascot character whose look, name and personality match the project's theme and purpose, and tell the project's real goals and key features through it. The character, story and visuals must match the project's theme and purpose as read from the repository. Write the narration script first (hook, problem, solution, three features, call to action), then build every scene to match its line, with fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits the project. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.",
64
65
  "Generate a character and cute animated JavaScript video: a demo of this project as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. Ground everything in what you read in the repository — invent an original mascot character whose look, name and personality match the project's theme and purpose, and tell the project's real goals and key features through it. The character, story and visuals must match the project's theme and purpose as read from the repository. Write the narration script first (hook, problem, solution, key features, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits the project. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.",
66
+ "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
65
67
  ]),
66
68
  prompt:
67
- "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
69
+ "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise; a 'Video length: 30' line means 30 seconds. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. A 'Video kind: Project demo' line means that same whole-project demo. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. A 'Character: off' line means no mascot: make a type-led animation in the chosen style that tells the same real story through moving type and shapes, skip the character wherever the persona uses one (design, _character, project_character_write, lip-sync, the character self-check) and save meta.character as null; a 'Character: on' line or no Character line keeps the mascot. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. A 'Video style: Auto' line means the same: pick the style that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
68
70
  }),
69
71
  Object.freeze({
70
72
  id: 'builtin-review-md-network',
@@ -89,6 +91,22 @@ const BUILTIN_MACROS = Object.freeze([
89
91
  prompt:
90
92
  "Use the session-manager-dev:maintaining-md-network skill to review this project's markdown network. Scope: {{scope}}. Mode: {{mode}}.",
91
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
+ }),
92
110
  ]);
93
111
 
94
112
  module.exports = { BUILTIN_MACROS };
@@ -24,10 +24,25 @@ function buildGate(absPath, nowMs) {
24
24
  }
25
25
 
26
26
  const PAGE_IDS = { 'how it works': 'how-it-works', faq: 'faq', overview: 'overview' };
27
+ // Same rule as ENTRY_ID_RE in ipcSchemas.cjs. The id becomes a path segment in
28
+ // artifactPaths, so an id taken from free text must pass it first.
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);
27
34
 
28
- // Entry id: videos get a fresh one per press; knowledge pages are named by a
29
- // 'Page: <name>' line in the extra instructions (default 'overview').
35
+ // Entry id: a valid 'Replace entry: <id>' line in the extra instructions
36
+ // (Regenerate) rebuilds that entry in place, for either kind; an invalid one
37
+ // is ignored. Otherwise videos get a fresh id per press and knowledge pages
38
+ // are named by a 'Page: <name>' line (default 'overview').
30
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) {
44
+ const replace = /^\s*Replace entry:\s*(\S+)\s*$/im.exec(extra || '');
45
+ if (replace && ENTRY_ID_RE.test(replace[1])) return replace[1];
31
46
  if (kind === 'video') return `vid-${t.toString(36)}${Math.random().toString(36).slice(2, 5).padEnd(3, '0')}`;
32
47
  const m = /^\s*Page:\s*(.+?)\s*$/im.exec(extra || '');
33
48
  if (!m) return 'overview';
@@ -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
+ };
@@ -0,0 +1,239 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * matrixHtml.cjs — renders a valid CompetitiveMatrix (competitiveMatrix.cjs)
5
+ * into one self-contained, read-only HTML page for the Project Home Pages
6
+ * library. Pure: no I/O. No <script>, no href=/src= attributes, no CSS url(),
7
+ * so the page passes validateHomeHtml and never reaches the network.
8
+ *
9
+ * Every matrix string comes from web research, so every one of them goes
10
+ * through escapeHtml before it reaches the document.
11
+ */
12
+
13
+ const { missingFeatures } = require('./competitiveMatrix.cjs');
14
+
15
+ const PRIORITIES = ['P0', 'P1', 'P2', 'P3', 'none'];
16
+
17
+ const STATUS = {
18
+ yes: { symbol: '✓', label: 'Has it' },
19
+ partial: { symbol: '◐', label: 'Partial' },
20
+ no: { symbol: '✗', label: 'Missing' },
21
+ unknown: { symbol: '?', label: 'Unknown' },
22
+ };
23
+
24
+ const ESCAPES = {
25
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '@': '&#64;', '(': '&#40;',
26
+ };
27
+
28
+ /**
29
+ * Escape & < > " ' for text and attribute contexts, plus @ and ( so research
30
+ * text like "@import url(https://…)" or "eval(" never trips validateHomeHtml's
31
+ * literal pattern checks.
32
+ */
33
+ function escapeHtml(s) {
34
+ return String(s == null ? '' : s).replace(/[&<>"'@(]/g, (c) => ESCAPES[c]);
35
+ }
36
+
37
+ const CSS = `
38
+ :root{--bg:#ffffff;--fg:#1f2328;--muted:#656d76;--border:#d0d7de;--head:#f6f8fa;
39
+ --yes-bg:#dafbe1;--yes-fg:#116329;--partial-bg:#fff8c5;--partial-fg:#7d4e00;
40
+ --no-bg:#ffebe9;--no-fg:#a40e26;--unknown-bg:#eaeef2;--unknown-fg:#57606a;--accent:#0969da}
41
+ @media (prefers-color-scheme: dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#8d96a0;--border:#30363d;--head:#161b22;
42
+ --yes-bg:#0f2e1a;--yes-fg:#56d364;--partial-bg:#2e2508;--partial-fg:#e3b341;
43
+ --no-bg:#3a1118;--no-fg:#ff7b72;--unknown-bg:#21262d;--unknown-fg:#8d96a0;--accent:#4493f8}}
44
+ *{box-sizing:border-box}
45
+ body{margin:0;padding:24px;background:var(--bg);color:var(--fg);
46
+ font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif}
47
+ h1{font-size:22px;margin:0 0 4px}
48
+ h2{font-size:17px;margin:28px 0 8px;border-bottom:1px solid var(--border);padding-bottom:4px}
49
+ h3{font-size:15px;margin:18px 0 6px}
50
+ .meta,.muted{color:var(--muted)}
51
+ .meta{margin:0 0 8px}
52
+ .vs{font-weight:400;color:var(--muted)}
53
+ .empty{padding:16px;border:1px dashed var(--border);border-radius:6px;color:var(--muted)}
54
+ .scroll{overflow-x:auto;border:1px solid var(--border);border-radius:6px;margin-bottom:8px}
55
+ table{border-collapse:separate;border-spacing:0;width:100%;font-size:13px}
56
+ th,td{padding:6px 8px;border-bottom:1px solid var(--border);text-align:left;vertical-align:top}
57
+ thead th{background:var(--head);font-weight:600;white-space:nowrap}
58
+ th.feat{position:sticky;left:0;z-index:1;background:var(--head);min-width:180px;max-width:280px}
59
+ tbody th.feat{background:var(--bg);font-weight:500}
60
+ tr:last-child th,tr:last-child td{border-bottom:none}
61
+ .chip{display:inline-block;padding:1px 7px;border-radius:10px;font-weight:600;font-size:12px;white-space:nowrap}
62
+ .s-yes{background:var(--yes-bg);color:var(--yes-fg)}
63
+ .s-partial{background:var(--partial-bg);color:var(--partial-fg)}
64
+ .s-no{background:var(--no-bg);color:var(--no-fg)}
65
+ .s-unknown{background:var(--unknown-bg);color:var(--unknown-fg)}
66
+ .note{display:block;color:var(--muted);font-size:12px;margin-top:2px}
67
+ .prio{display:inline-block;min-width:34px;text-align:center;padding:1px 6px;border-radius:4px;
68
+ border:1px solid var(--border);font-weight:700;font-size:12px;margin-right:6px}
69
+ .p-P0{color:var(--no-fg);border-color:var(--no-fg)}
70
+ .p-P1{color:var(--partial-fg);border-color:var(--partial-fg)}
71
+ ol,ul{padding-left:20px}
72
+ li{margin:4px 0}
73
+ .feature{border:1px solid var(--border);border-radius:6px;padding:10px 12px;margin:8px 0}
74
+ .feature h3{margin:0 0 4px}
75
+ .url{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;word-break:break-all;color:var(--accent)}
76
+ `;
77
+
78
+ function rank(f) {
79
+ return PRIORITIES.indexOf(f.recommendation.priority);
80
+ }
81
+
82
+ function byPriorityThenTitle(a, b) {
83
+ return (rank(a) - rank(b)) || a.title.localeCompare(b.title);
84
+ }
85
+
86
+ function dateOf(iso) {
87
+ return escapeHtml(String(iso || '').slice(0, 10));
88
+ }
89
+
90
+ function chip(status) {
91
+ const s = STATUS[status] || STATUS.unknown;
92
+ const key = STATUS[status] ? status : 'unknown';
93
+ return `<span class="chip s-${key}">${s.symbol} ${s.label}</span>`;
94
+ }
95
+
96
+ function renderHeader(matrix) {
97
+ const names = matrix.competitors.map((c) => escapeHtml(c.name)).join(', ');
98
+ const runs = matrix.runs.length;
99
+ return [
100
+ '<header>',
101
+ `<h1>${escapeHtml(matrix.product.name)} <span class="vs">vs ${names}</span></h1>`,
102
+ `<p class="meta">Updated ${dateOf(matrix.updatedAt)} · ${runs} run${runs === 1 ? '' : 's'}`
103
+ + ` · ${matrix.features.length} feature${matrix.features.length === 1 ? '' : 's'}</p>`,
104
+ matrix.product.summary ? `<p class="muted">${escapeHtml(matrix.product.summary)}</p>` : '',
105
+ '</header>',
106
+ ].join('\n');
107
+ }
108
+
109
+ function renderGroupTable(group, features, products) {
110
+ const out = [];
111
+ out.push(`<h3>${escapeHtml(group.title)}</h3>`);
112
+ if (group.description) out.push(`<p class="muted">${escapeHtml(group.description)}</p>`);
113
+ out.push('<div class="scroll"><table><thead><tr><th class="feat">Feature</th>');
114
+ for (const p of products) out.push(`<th>${escapeHtml(p.name)}</th>`);
115
+ out.push('</tr></thead><tbody>');
116
+ for (const f of features) {
117
+ out.push(`<tr><th class="feat">${escapeHtml(f.title)}</th>`);
118
+ for (const p of products) {
119
+ const s = f.support[p.id] || { status: 'unknown', note: '' };
120
+ const note = s.note ? `<span class="note">${escapeHtml(s.note)}</span>` : '';
121
+ out.push(`<td>${chip(s.status)}${note}</td>`);
122
+ }
123
+ out.push('</tr>');
124
+ }
125
+ out.push('</tbody></table></div>');
126
+ return out.join('');
127
+ }
128
+
129
+ function renderMatrixSection(matrix) {
130
+ const out = ['<section>', '<h2>Feature matrix</h2>'];
131
+ if (matrix.features.length === 0) {
132
+ out.push('<p class="empty">No features yet</p>', '</section>');
133
+ return out.join('\n');
134
+ }
135
+ const products = [{ id: 'self', name: matrix.product.name }, ...matrix.competitors];
136
+ for (const g of matrix.groups) {
137
+ const features = matrix.features.filter((f) => f.groupId === g.id).sort(byPriorityThenTitle);
138
+ if (features.length === 0) continue;
139
+ out.push(renderGroupTable(g, features, products));
140
+ }
141
+ out.push('</section>');
142
+ return out.join('\n');
143
+ }
144
+
145
+ function renderRecommendations(matrix) {
146
+ const missing = missingFeatures(matrix);
147
+ const out = ['<section>', '<h2>Recommendations</h2>'];
148
+ if (missing.length === 0) {
149
+ out.push('<p class="muted">Nothing missing — every tracked feature is covered.</p>');
150
+ } else {
151
+ out.push('<ol>');
152
+ for (const f of missing) {
153
+ const p = f.recommendation.priority;
154
+ out.push(`<li><span class="prio p-${escapeHtml(p)}">${escapeHtml(p)}</span>`
155
+ + `<strong>${escapeHtml(f.title)}</strong> ${chip(f.support.self.status)}`
156
+ + (f.recommendation.rationale ? `<span class="note">${escapeHtml(f.recommendation.rationale)}</span>` : '')
157
+ + '</li>');
158
+ }
159
+ out.push('</ol>');
160
+ }
161
+ out.push('</section>');
162
+ return out.join('\n');
163
+ }
164
+
165
+ function renderDetails(matrix) {
166
+ if (matrix.features.length === 0) return '';
167
+ const groupTitle = new Map(matrix.groups.map((g) => [g.id, g.title]));
168
+ const groupOrder = new Map(matrix.groups.map((g, i) => [g.id, i]));
169
+ const features = matrix.features.slice().sort((a, b) =>
170
+ (groupOrder.get(a.groupId) - groupOrder.get(b.groupId)) || byPriorityThenTitle(a, b));
171
+ const out = ['<section>', '<h2>Feature details</h2>'];
172
+ for (const f of features) {
173
+ out.push('<div class="feature">',
174
+ `<h3>${escapeHtml(f.title)} <span class="vs">· ${escapeHtml(groupTitle.get(f.groupId) || f.groupId)}</span></h3>`,
175
+ `<p>${escapeHtml(f.description)}</p>`,
176
+ `<p class="muted">Sentiment: <strong>${escapeHtml(f.sentiment.signal)}</strong>`
177
+ + (f.sentiment.summary ? ` — ${escapeHtml(f.sentiment.summary)}` : '') + '</p>',
178
+ '</div>');
179
+ }
180
+ out.push('</section>');
181
+ return out.join('\n');
182
+ }
183
+
184
+ function renderSources(matrix) {
185
+ const out = ['<section>', '<h2>Sources</h2>'];
186
+ if (matrix.sources.length === 0) {
187
+ out.push('<p class="muted">No sources yet</p>');
188
+ } else {
189
+ out.push('<ul>');
190
+ for (const s of matrix.sources) {
191
+ const bits = [s.publisher, s.publishedAt].filter(Boolean).map(escapeHtml).join(' · ');
192
+ out.push(`<li><strong>${escapeHtml(s.title)}</strong>`
193
+ + (bits ? ` <span class="muted">${bits}</span>` : '')
194
+ + `<span class="note url">${escapeHtml(s.url)}</span></li>`);
195
+ }
196
+ out.push('</ul>');
197
+ }
198
+ out.push('</section>');
199
+ return out.join('\n');
200
+ }
201
+
202
+ function renderRuns(matrix) {
203
+ const runs = matrix.runs.slice().sort((a, b) => String(b.at).localeCompare(String(a.at)));
204
+ const out = ['<section>', '<h2>Run history</h2>', '<ul>'];
205
+ for (const r of runs) {
206
+ out.push(`<li><strong>${escapeHtml(String(r.at).replace('T', ' ').slice(0, 16))}</strong>`
207
+ + ` <span class="muted">${escapeHtml(r.model)} · ${r.added.length} added · ${r.changed.length} changed`
208
+ + (r.competitors.length ? ` · vs ${r.competitors.map(escapeHtml).join(', ')}` : '') + '</span>'
209
+ + (r.notes ? `<span class="note">${escapeHtml(r.notes)}</span>` : '') + '</li>');
210
+ }
211
+ out.push('</ul>', '</section>');
212
+ return out.join('\n');
213
+ }
214
+
215
+ /** renderMatrixHtml(matrix) → complete self-contained HTML document string. */
216
+ function renderMatrixHtml(matrix) {
217
+ return [
218
+ '<!DOCTYPE html>',
219
+ '<html lang="en">',
220
+ '<head>',
221
+ '<meta charset="utf-8">',
222
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
223
+ `<title>${escapeHtml(matrix.product.name)} — Competitor matrix</title>`,
224
+ `<style>${CSS}</style>`,
225
+ '</head>',
226
+ '<body>',
227
+ renderHeader(matrix),
228
+ renderMatrixSection(matrix),
229
+ renderRecommendations(matrix),
230
+ renderDetails(matrix),
231
+ renderSources(matrix),
232
+ renderRuns(matrix),
233
+ '</body>',
234
+ '</html>',
235
+ '',
236
+ ].join('\n');
237
+ }
238
+
239
+ module.exports = { renderMatrixHtml, escapeHtml };