claude-code-session-manager 0.75.3 → 0.77.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 (164) hide show
  1. package/dist/assets/{AgentLibrary-CzQqcObq.js → AgentLibrary-B2ie8bbw.js} +2 -2
  2. package/dist/assets/{DataModel-Bj_WlLz8.js → DataModel-BIJPYw32.js} +1 -1
  3. package/dist/assets/{History-DnSi_OHm.js → History-CeY6dk9S.js} +2 -2
  4. package/dist/assets/{Hooks-0BB0dp3S.js → Hooks-BFH2ocKg.js} +2 -2
  5. package/dist/assets/{HostBilko-DHpwwsLQ.js → HostBilko-36gj9wLz.js} +1 -1
  6. package/dist/assets/{Library-CaJVqVvi.js → Library-C-hBct39.js} +1 -1
  7. package/dist/assets/{ListDetail-C1W2HmC2.js → ListDetail-CNq64VWV.js} +1 -1
  8. package/dist/assets/{MarkdownEditor-5Ob9FW3z.js → MarkdownEditor-Bh3qt5-1.js} +1 -1
  9. package/dist/assets/{McpServers-JxCSfm1S.js → McpServers-DpGN0oyz.js} +1 -1
  10. package/dist/assets/{Memory-BDeqlqwH.js → Memory-D59hUjC4.js} +6 -6
  11. package/dist/assets/{Panel-Dh9ZHuEj.js → Panel-DCgbaoci.js} +1 -1
  12. package/dist/assets/{Permissions-DXy-CbEY.js → Permissions-DAmQ0DYV.js} +2 -2
  13. package/dist/assets/{Plugins-_n1Iuc8T.js → Plugins-Dyfgn6Is.js} +2 -2
  14. package/dist/assets/{ProvenanceBadge-BP_evfxE.js → ProvenanceBadge-BiYhPO1U.js} +1 -1
  15. package/dist/assets/SaveBar-RV7B6sOh.js +1 -0
  16. package/dist/assets/Scheduler-BPaNqx1b.js +14 -0
  17. package/dist/assets/{ScopeSwitcher-CAWzM6RI.js → ScopeSwitcher-P4mdLGNU.js} +1 -1
  18. package/dist/assets/{Settings-DRRozLyT.js → Settings-BL4vf5aX.js} +1 -1
  19. package/dist/assets/{SkillReferenceGraph-DGHDWlz4.js → SkillReferenceGraph-BRBDyi1_.js} +1 -1
  20. package/dist/assets/{Skills-D8L66eiX.js → Skills-BV08gDUH.js} +2 -2
  21. package/dist/assets/{SystemPrompt-CYtUsonD.js → SystemPrompt-CLftSsDw.js} +1 -1
  22. package/dist/assets/TagLibrary-Bp8jGsd5.js +1 -0
  23. package/dist/assets/{TiptapBody-B2hRgbPE.js → TiptapBody-jCpuB6E5.js} +1 -1
  24. package/dist/assets/{Toggle-BTwsbxam.js → Toggle-D2paA1xf.js} +1 -1
  25. package/dist/assets/{index-DijufvkJ.js → index-BDRSqBl3.js} +704 -704
  26. package/dist/assets/{index-CMLnzdZC.css → index-CYhdtisq.css} +1 -1
  27. package/dist/assets/{settingsSchema-D6wzxAi6.js → settingsSchema-6IOLjZZN.js} +1 -1
  28. package/dist/index.html +2 -2
  29. package/package.json +8 -2
  30. package/plugins/session-manager-dev/skills/develop/standards.md +1 -1
  31. package/scripts/lib/activeSessions.cjs +116 -6
  32. package/scripts/project-pages-logic/dist/logic.cjs +4709 -0
  33. package/scripts/render-project-pages/dist/renderer.cjs +18900 -0
  34. package/scripts/render-project-pages.cjs +70 -0
  35. package/scripts/scheduler-mcp-server.cjs +269 -96
  36. package/scripts/validate-project-pages-summary.cjs +62 -0
  37. package/src/main/__tests__/agentModelResolve.test.cjs +66 -0
  38. package/src/main/__tests__/epicStatusMirror.test.cjs +110 -0
  39. package/src/main/__tests__/health-delegation-chain.test.cjs +106 -0
  40. package/src/main/__tests__/prdAdminRoutes.test.cjs +295 -0
  41. package/src/main/__tests__/prdAgentType.test.cjs +103 -0
  42. package/src/main/__tests__/prdCreate.test.cjs +247 -0
  43. package/src/main/__tests__/prdFrontmatterAgentType.test.cjs +117 -0
  44. package/src/main/__tests__/prdFrontmatterQuietMachine.test.cjs +108 -0
  45. package/src/main/__tests__/projectHomeAdminRoutes.test.cjs +485 -0
  46. package/src/main/__tests__/projectPages.test.cjs +73 -1
  47. package/src/main/__tests__/rcaReport.test.cjs +54 -0
  48. package/src/main/__tests__/runVerify.test.cjs +94 -0
  49. package/src/main/__tests__/scheduler-autofix-select.test.cjs +58 -3
  50. package/src/main/__tests__/scheduler-bash-timeout-env.test.cjs +103 -0
  51. package/src/main/__tests__/scheduler-commit-guard-noop.test.cjs +41 -0
  52. package/src/main/__tests__/scheduler-effective-concurrency.test.cjs +10 -0
  53. package/src/main/__tests__/scheduler-foreign-wip-manifest.test.cjs +78 -0
  54. package/src/main/__tests__/scheduler-inplace-salvage.test.cjs +242 -0
  55. package/src/main/__tests__/scheduler-investigation-prompt.test.cjs +31 -0
  56. package/src/main/__tests__/scheduler-launch-failure.test.cjs +201 -0
  57. package/src/main/__tests__/scheduler-leftover-fields.test.cjs +52 -0
  58. package/src/main/__tests__/scheduler-looks-done.test.cjs +241 -0
  59. package/src/main/__tests__/scheduler-prd-persona-spawn.test.cjs +135 -0
  60. package/src/main/__tests__/scheduler-quiet-machine-lease.test.cjs +222 -0
  61. package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +207 -1
  62. package/src/main/__tests__/scheduler-shared-tree-guard.test.cjs +212 -0
  63. package/src/main/__tests__/scheduler-stranded-investigation.test.cjs +185 -0
  64. package/src/main/__tests__/scheduler-worktree-cap-defer.test.cjs +194 -0
  65. package/src/main/__tests__/seedAgentPersonas.test.cjs +75 -14
  66. package/src/main/__tests__/seedSchedulerMcp.test.cjs +66 -0
  67. package/src/main/__tests__/uniquePrdNumbers.test.cjs +14 -5
  68. package/src/main/bilkoHost.cjs +4 -3
  69. package/src/main/chatRunner.cjs +6 -1
  70. package/src/main/config.cjs +25 -33
  71. package/src/main/health.cjs +153 -2
  72. package/src/main/index.cjs +64 -5
  73. package/src/main/ipcSchemas.cjs +69 -1
  74. package/src/main/lib/__tests__/activeIndexRebuild.test.cjs +179 -0
  75. package/src/main/lib/__tests__/childWithLog.test.cjs +141 -0
  76. package/src/main/lib/__tests__/delegationReadiness.test.cjs +391 -42
  77. package/src/main/lib/__tests__/ephemeralCwd.test.cjs +91 -0
  78. package/src/main/lib/__tests__/epicWorktreeMint.test.cjs +5 -3
  79. package/src/main/lib/__tests__/fixChainDepth.test.cjs +40 -0
  80. package/src/main/lib/__tests__/gitWorktree.test.cjs +290 -5
  81. package/src/main/lib/__tests__/gitWorktreeSalvage.test.cjs +107 -0
  82. package/src/main/lib/__tests__/gitWorktreeSalvageDelta.test.cjs +153 -0
  83. package/src/main/lib/__tests__/jobWorktree.test.cjs +6 -4
  84. package/src/main/lib/__tests__/landedSinceRun.test.cjs +73 -0
  85. package/src/main/lib/__tests__/launchFailure.test.cjs +220 -0
  86. package/src/main/lib/__tests__/loadGate.test.cjs +159 -0
  87. package/src/main/lib/__tests__/mcpToolCatalog.test.cjs +102 -0
  88. package/src/main/lib/__tests__/opsOwnership.test.cjs +7 -0
  89. package/src/main/lib/__tests__/opsRootAbsoluteCwd.test.cjs +151 -0
  90. package/src/main/lib/__tests__/opsRootResolve.test.cjs +149 -0
  91. package/src/main/lib/__tests__/prdDeclaredPaths.test.cjs +82 -0
  92. package/src/main/lib/__tests__/projectRootResolve.test.cjs +148 -0
  93. package/src/main/lib/__tests__/queueHealth.test.cjs +58 -0
  94. package/src/main/lib/__tests__/quietMachineLease.test.cjs +39 -0
  95. package/src/main/lib/__tests__/reaperHelpers.test.cjs +133 -0
  96. package/src/main/lib/__tests__/schedulerBatchDepends.test.cjs +19 -9
  97. package/src/main/lib/__tests__/schedulerBatchFairness.test.cjs +213 -0
  98. package/src/main/lib/__tests__/schedulerBatchLaunchHold.test.cjs +125 -0
  99. package/src/main/lib/__tests__/schedulerBatchProjectCap.test.cjs +127 -0
  100. package/src/main/lib/__tests__/schedulerBatchQuietMachine.test.cjs +109 -0
  101. package/src/main/lib/__tests__/schedulerMcpServerHeadlessRefusal.test.cjs +71 -0
  102. package/src/main/lib/__tests__/schedulerMcpServerHelp.test.cjs +217 -0
  103. package/src/main/lib/__tests__/schedulerMcpServerProjectHome.test.cjs +350 -0
  104. package/src/main/lib/activeIndexMerge.cjs +15 -0
  105. package/src/main/lib/activeIndexRebuild.cjs +133 -0
  106. package/src/main/lib/agentModelResolve.cjs +58 -0
  107. package/src/main/lib/buildTarget.cjs +3 -2
  108. package/src/main/lib/childWithLog.cjs +69 -2
  109. package/src/main/lib/claudeBin.cjs +54 -1
  110. package/src/main/lib/crossProjectFeedback.cjs +8 -1
  111. package/src/main/lib/definitionOfDone.cjs +3 -2
  112. package/src/main/lib/delegationReadiness.cjs +514 -26
  113. package/src/main/lib/ephemeralCwd.cjs +78 -0
  114. package/src/main/lib/epicDelegationStats.cjs +2 -1
  115. package/src/main/lib/epicMint.cjs +17 -1
  116. package/src/main/lib/epicStatusMirror.cjs +95 -0
  117. package/src/main/lib/epicValidationHook.cjs +2 -1
  118. package/src/main/lib/epicWorktreeMint.cjs +5 -2
  119. package/src/main/lib/fixChainDepth.cjs +45 -0
  120. package/src/main/lib/gitWorktree.cjs +520 -21
  121. package/src/main/lib/jobWorktree.cjs +2 -0
  122. package/src/main/lib/landedSinceRun.cjs +55 -0
  123. package/src/main/lib/launchFailure.cjs +357 -0
  124. package/src/main/lib/loadGate.cjs +134 -0
  125. package/src/main/lib/mcpToolCatalog.cjs +370 -0
  126. package/src/main/lib/opsErrorLog.cjs +12 -1
  127. package/src/main/lib/opsOwnership.cjs +106 -0
  128. package/src/main/lib/prdAdminRoutes.cjs +43 -3
  129. package/src/main/lib/prdAgentType.cjs +84 -0
  130. package/src/main/lib/prdCreate.cjs +103 -15
  131. package/src/main/lib/prdDeclaredPaths.cjs +70 -0
  132. package/src/main/lib/prdFrontmatter.cjs +17 -3
  133. package/src/main/lib/prdLocations.cjs +13 -6
  134. package/src/main/lib/projectHomeAdminRoutes.cjs +402 -0
  135. package/src/main/lib/projectPageSummarySchema.cjs +181 -0
  136. package/src/main/lib/projectRootResolve.cjs +134 -0
  137. package/src/main/lib/promptSessionSchema.cjs +7 -0
  138. package/src/main/lib/queueHealth.cjs +38 -0
  139. package/src/main/lib/queueStore.cjs +40 -7
  140. package/src/main/lib/quietMachineLease.cjs +48 -0
  141. package/src/main/lib/rcaReport.cjs +54 -4
  142. package/src/main/lib/reaperHelpers.cjs +64 -1
  143. package/src/main/lib/scheduleJobSchema.cjs +31 -0
  144. package/src/main/lib/scheduleJobTransitions.cjs +6 -2
  145. package/src/main/lib/schedulerBatch.cjs +301 -55
  146. package/src/main/lib/schedulerConfig.cjs +99 -0
  147. package/src/main/projectBrief.cjs +3 -2
  148. package/src/main/projectPages.cjs +162 -3
  149. package/src/main/promptSessionTranscript.cjs +0 -0
  150. package/src/main/pty.cjs +5 -0
  151. package/src/main/queueOps.cjs +15 -8
  152. package/src/main/runVerify.cjs +50 -9
  153. package/src/main/scheduler/prdParser.cjs +18 -1
  154. package/src/main/scheduler.cjs +1701 -130
  155. package/src/main/seedAgentPersonas.cjs +62 -21
  156. package/src/main/seedSchedulerMcp.cjs +58 -4
  157. package/src/main/templates/project-pages-catalog.json +741 -0
  158. package/src/main/templates/project-pages-pipeline.md +417 -0
  159. package/src/preload/api.d.ts +187 -3
  160. package/src/preload/index.cjs +9 -0
  161. package/src/seed/agents/project-home-builder.md +59 -0
  162. package/dist/assets/SaveBar-D-gCUx4n.js +0 -1
  163. package/dist/assets/Scheduler-Bpd4OGju.js +0 -14
  164. package/dist/assets/TagLibrary-E5CLeuVk.js +0 -1
@@ -0,0 +1,402 @@
1
+ /**
2
+ * projectHomeAdminRoutes.cjs — the app-side half of "the generating session
3
+ * needs zero repo knowledge to build a Project Home page" (PRD:
4
+ * project-home-admin-routes). Before this file, the project-home-builder
5
+ * Epic had to know session-manager's own repo layout (where the catalog
6
+ * lives, how to invoke the validator/renderer CLIs, which build step to run
7
+ * first) — which is exactly why generation silently hung on a foreign
8
+ * machine with no repo checked out. These four routes make the app itself
9
+ * the authority on paths/schema/catalog/rendering, reusing the shipped
10
+ * assets PRD 1088 put in the npm tarball (scripts/render-project-pages/dist/
11
+ * renderer.cjs, scripts/project-pages-logic/dist/logic.cjs,
12
+ * src/main/templates/project-pages-catalog.json,
13
+ * src/main/templates/project-pages-pipeline.md) rather than reimplementing
14
+ * any of them.
15
+ *
16
+ * Registered against the same injected localAdminHttp.cjs transport as
17
+ * prdAdminRoutes.cjs — see that file's header for the transport contract
18
+ * (`registerRoute(method, url, handler)`, handlers get
19
+ * `(req, res, query: URLSearchParams)`).
20
+ *
21
+ * The MCP tool surface that calls these routes is the NEXT PRD in this
22
+ * chain — this file only exposes the HTTP contract.
23
+ */
24
+ 'use strict';
25
+
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const { readBody, sendJson } = require('./localAdminHttp.cjs');
29
+ const { resolveProjectContext } = require('./projectRootResolve.cjs');
30
+ const { opsPath, OPS_ROOT_DIR } = require('./opsOwnership.cjs');
31
+ const { PROJECT_PAGE_SUMMARY_JSON_SCHEMA, PROJECT_PAGE_PICKS_JSON_SCHEMA } = require('./projectPageSummarySchema.cjs');
32
+ const config = require('../config.cjs');
33
+ const { schemas } = require('../ipcSchemas.cjs');
34
+
35
+ const LENSES = ['home', 'marketing', 'feature', 'architecture', 'brief'];
36
+
37
+ // Shipped, build-time assets — fixed app-relative paths, read once and
38
+ // cached in-process, same pattern as projectPages.cjs's
39
+ // cachedDefaultHomeHtml (this file never changes at runtime; a repo edit
40
+ // requires an app restart to pick up during dev, same as that module).
41
+ const CATALOG_PATH = path.join(__dirname, '..', 'templates', 'project-pages-catalog.json');
42
+ const SPEC_PATH = path.join(__dirname, '..', 'templates', 'project-pages-pipeline.md');
43
+ const RENDERER_BUNDLE_PATH = path.join(__dirname, '..', '..', '..', 'scripts', 'render-project-pages', 'dist', 'renderer.cjs');
44
+ const LOGIC_BUNDLE_PATH = path.join(__dirname, '..', '..', '..', 'scripts', 'project-pages-logic', 'dist', 'logic.cjs');
45
+
46
+ let cachedCatalog = null;
47
+ function loadCatalog() {
48
+ if (!cachedCatalog) {
49
+ const raw = fs.readFileSync(CATALOG_PATH, 'utf8');
50
+ const parsed = JSON.parse(raw);
51
+ // Drop $comment — it names the repo-relative source files the catalog
52
+ // was generated from (build-tooling provenance), which would violate
53
+ // this route's "never point the caller at a repo-relative path"
54
+ // contract if echoed back verbatim.
55
+ cachedCatalog = { lenses: parsed.lenses };
56
+ }
57
+ return cachedCatalog;
58
+ }
59
+
60
+ let cachedSpecText = null;
61
+ function loadSpecText() {
62
+ if (cachedSpecText === null) {
63
+ cachedSpecText = fs.readFileSync(SPEC_PATH, 'utf8');
64
+ }
65
+ return cachedSpecText;
66
+ }
67
+
68
+ let cachedRenderer = null;
69
+ function loadRenderer() {
70
+ if (!cachedRenderer) {
71
+ ({ renderProjectPages: cachedRenderer } = require(RENDERER_BUNDLE_PATH));
72
+ }
73
+ return cachedRenderer;
74
+ }
75
+
76
+ let cachedValidator = null;
77
+ function loadValidator() {
78
+ if (!cachedValidator) {
79
+ ({ validateProjectPageSummary: cachedValidator } = require(LOGIC_BUNDLE_PATH));
80
+ }
81
+ return cachedValidator;
82
+ }
83
+
84
+ /** Same definition crossProjectFeedback.cjs uses for "is this a Session
85
+ * Manager project": it already has an operations root. Deliberately does
86
+ * NOT require project-pages/ specifically to exist — a project that has
87
+ * never generated a Project Home page yet is still a Session Manager
88
+ * project (see the "no output dir yet" edge case on /status and /render). */
89
+ function isSessionManagerProject(cwd) {
90
+ try {
91
+ return fs.statSync(path.join(cwd, OPS_ROOT_DIR)).isDirectory();
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ function projectPagesPaths(cwd) {
98
+ const dir = opsPath(cwd, 'project-pages');
99
+ return {
100
+ summaryPath: path.join(dir, 'summary.json'),
101
+ picksPath: path.join(dir, 'picks.json'),
102
+ outputDir: path.join(dir, 'output'),
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Resolve+validate a caller-supplied cwd into a real Session Manager
108
+ * project root. Never throws — returns a structured verdict so every route
109
+ * can turn a bad cwd into a JSON error instead of an unhandled throw (this
110
+ * PRD's edge-case requirement).
111
+ *
112
+ * Deliberately does NOT call config.addAllowedRoot here — that widens
113
+ * config.cjs's process-lifetime write boundary and belongs only on an
114
+ * actual write path (the render route calls it itself, right before
115
+ * writing), not on every GET this function also gates.
116
+ */
117
+ function resolveCwd(rawCwd) {
118
+ if (!rawCwd || typeof rawCwd !== 'string') {
119
+ return { ok: false, status: 400, error: 'cwd is required' };
120
+ }
121
+ if (!path.isAbsolute(rawCwd)) {
122
+ return { ok: false, status: 400, error: 'cwd must be an absolute path' };
123
+ }
124
+ // Normalizes a worktree/ops-internal cwd to its real project root (see
125
+ // projectRootResolve.cjs's header) so a headless job running inside an
126
+ // Epic's worktree still targets the right project.
127
+ const resolved = resolveProjectContext({ cwd: rawCwd });
128
+ const candidate = resolved.cwd || rawCwd;
129
+ let realCwd;
130
+ try {
131
+ realCwd = config.validatePath(candidate);
132
+ } catch (e) {
133
+ return { ok: false, status: 400, error: `cwd rejected: ${e?.message ?? 'outside allowed roots'}` };
134
+ }
135
+ if (!isSessionManagerProject(realCwd)) {
136
+ return {
137
+ ok: false,
138
+ status: 400,
139
+ error: `${realCwd} is not a Session Manager project — it has no ${OPS_ROOT_DIR}/ directory`,
140
+ };
141
+ }
142
+ return { ok: true, cwd: realCwd };
143
+ }
144
+
145
+ /** Each validateProjectPageSummary error string is "<field.path> must ...".
146
+ * Split it into { field, message } for the route's documented response
147
+ * shape — the validator itself only returns flat strings. */
148
+ function toFieldErrors(errors) {
149
+ return errors.map((message) => {
150
+ const m = /^([\w.]+)\s/.exec(message);
151
+ return { field: m ? m[1] : 'summary', message };
152
+ });
153
+ }
154
+
155
+ /**
156
+ * Structural check for ProjectPagePicks (lensId -> slotId -> variantId) —
157
+ * the shipped validator only covers `summary`, so this is the one guard
158
+ * against handing the renderer bundle a shape it doesn't expect. Returns
159
+ * "<field> must ..." strings in the same format toFieldErrors expects, so
160
+ * both routes can share one error-shape.
161
+ */
162
+ function validatePicksShape(picks) {
163
+ if (picks === null || typeof picks !== 'object' || Array.isArray(picks)) {
164
+ return ['picks must be an object'];
165
+ }
166
+ const errors = [];
167
+ for (const [lensId, slotMap] of Object.entries(picks)) {
168
+ if (slotMap === null || typeof slotMap !== 'object' || Array.isArray(slotMap)) {
169
+ errors.push(`picks.${lensId} must be an object`);
170
+ continue;
171
+ }
172
+ for (const [slotId, variantId] of Object.entries(slotMap)) {
173
+ if (typeof variantId !== 'string' || variantId.length === 0) {
174
+ errors.push(`picks.${lensId}.${slotId} must be a non-empty string`);
175
+ }
176
+ }
177
+ }
178
+ return errors;
179
+ }
180
+
181
+ /** Shared readBody -> JSON.parse -> zod-schema.parse pipeline for the two
182
+ * POST routes — collapses the 3-step try/catch chain that was previously
183
+ * duplicated in both handlers into one call. Returns either
184
+ * { ok: true, input } or { ok: false, status, error, details }. */
185
+ async function parseJsonBody(req, schema) {
186
+ const raw = await readBody(req);
187
+ let body;
188
+ try {
189
+ body = raw ? JSON.parse(raw) : {};
190
+ } catch {
191
+ return { ok: false, status: 400, error: 'invalid JSON body' };
192
+ }
193
+ try {
194
+ return { ok: true, input: schema.parse(body) };
195
+ } catch (e) {
196
+ return { ok: false, status: 400, error: 'invalid payload', details: e?.issues ?? e?.message };
197
+ }
198
+ }
199
+
200
+ function buildProtocol() {
201
+ return [
202
+ 'Call GET /admin/project-home/status?cwd=<abs> to see what already exists for this project (summary.json, picks.json, and any prior output).',
203
+ 'Compose a ProjectPageSummary object matching the schema in this response\'s "summarySchema" field. Never fabricate content — every field must trace to something concrete about this project (an Epic goal, a source file/dir, a convention, a git log entry). Omit "brief" entirely if this project has no generated brief.json yet; omit "quotes" entries rather than inventing a testimonial.',
204
+ 'For each lens in this response\'s "catalog.lenses", and for each of that lens\'s slots, pick exactly one variant id by judging the candidate variants\' "note" text against the summary content you composed. Assemble the picks into a ProjectPagePicks object (lensId -> slotId -> variantId) matching "picksSchema".',
205
+ 'POST /admin/project-home/validate-summary with {cwd, summary}. If "valid" is false, fix every listed {field, message} error and re-validate before continuing.',
206
+ 'POST /admin/project-home/render with {cwd, summary, picks}. This re-validates the summary server-side (rejecting with no writes on failure), renders all 5 lenses, and writes summary.json, picks.json, and output/{home,marketing,feature,architecture,brief}.html + output/manifest.json at the absolute paths in this response\'s "paths" field.',
207
+ 'Optionally call GET /admin/project-home/status again to confirm the new files landed and to read manifest.json\'s generatedAt.',
208
+ ];
209
+ }
210
+
211
+ function registerAdminRoute(adminHttp) {
212
+ // GET /admin/project-home/contract?cwd=<abs> — the self-sufficient
213
+ // contract: protocol, schema, catalog, absolute paths, spec. Nothing in
214
+ // this response should require the caller to read a repo-relative path.
215
+ adminHttp.registerRoute('GET', '/admin/project-home/contract', async (req, res, query) => {
216
+ let input;
217
+ try {
218
+ input = schemas.projectHomeAdminCwdQuery.parse(Object.fromEntries(query ?? []));
219
+ } catch (e) {
220
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
221
+ return;
222
+ }
223
+ const resolved = resolveCwd(input.cwd);
224
+ if (!resolved.ok) {
225
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
226
+ return;
227
+ }
228
+ // projectPagesPaths()->opsPath() can throw for a cwd resolveCwd accepted
229
+ // but opsPath's own (separate) ephemeral-root check refuses — keep this
230
+ // route's "never an unhandled throw" contract even on that edge.
231
+ try {
232
+ const { summaryPath, picksPath, outputDir } = projectPagesPaths(resolved.cwd);
233
+ sendJson(res, 200, {
234
+ ok: true,
235
+ protocol: buildProtocol(),
236
+ summarySchema: PROJECT_PAGE_SUMMARY_JSON_SCHEMA,
237
+ picksSchema: PROJECT_PAGE_PICKS_JSON_SCHEMA,
238
+ catalog: loadCatalog(),
239
+ paths: { summaryPath, picksPath, outputDir },
240
+ spec: { text: loadSpecText(), path: SPEC_PATH },
241
+ });
242
+ } catch (e) {
243
+ sendJson(res, 400, { ok: false, error: e?.message ?? 'failed to resolve project-pages paths' });
244
+ }
245
+ });
246
+
247
+ // POST /admin/project-home/validate-summary {cwd, summary}
248
+ adminHttp.registerRoute('POST', '/admin/project-home/validate-summary', async (req, res) => {
249
+ const parsed = await parseJsonBody(req, schemas.projectHomeAdminValidateSummaryBody);
250
+ if (!parsed.ok) {
251
+ sendJson(res, parsed.status, { ok: false, error: parsed.error, details: parsed.details });
252
+ return;
253
+ }
254
+ const { input } = parsed;
255
+ const resolved = resolveCwd(input.cwd);
256
+ if (!resolved.ok) {
257
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
258
+ return;
259
+ }
260
+ const validateProjectPageSummary = loadValidator();
261
+ const result = validateProjectPageSummary(input.summary);
262
+ if (!result.ok) {
263
+ sendJson(res, 200, { ok: true, valid: false, errors: toFieldErrors(result.errors) });
264
+ return;
265
+ }
266
+ sendJson(res, 200, { ok: true, valid: true, errors: [] });
267
+ });
268
+
269
+ // POST /admin/project-home/render {cwd, summary, picks}
270
+ adminHttp.registerRoute('POST', '/admin/project-home/render', async (req, res) => {
271
+ const parsed = await parseJsonBody(req, schemas.projectHomeAdminRenderBody);
272
+ if (!parsed.ok) {
273
+ sendJson(res, parsed.status, { ok: false, error: parsed.error, details: parsed.details });
274
+ return;
275
+ }
276
+ const { input } = parsed;
277
+ const resolved = resolveCwd(input.cwd);
278
+ if (!resolved.ok) {
279
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
280
+ return;
281
+ }
282
+ const validateProjectPageSummary = loadValidator();
283
+ const validation = validateProjectPageSummary(input.summary);
284
+ const picksErrors = validatePicksShape(input.picks);
285
+ if (!validation.ok || picksErrors.length > 0) {
286
+ sendJson(res, 400, {
287
+ ok: false,
288
+ valid: false,
289
+ errors: [...toFieldErrors(validation.ok ? [] : validation.errors), ...toFieldErrors(picksErrors)],
290
+ });
291
+ return;
292
+ }
293
+
294
+ // Only a route that is actually about to write registers the cwd as a
295
+ // write-allowed root — see resolveCwd's header for why this must not
296
+ // happen on the GET routes above.
297
+ config.addAllowedRoot(resolved.cwd);
298
+ try {
299
+ const result = await serializedPerCwd(resolved.cwd, () => doRender(resolved.cwd, input.summary, input.picks));
300
+ sendJson(res, 200, { ok: true, ...result });
301
+ } catch (e) {
302
+ sendJson(res, 500, { ok: false, error: e?.message ?? 'render failed' });
303
+ }
304
+ });
305
+
306
+ // GET /admin/project-home/status?cwd=<abs>
307
+ adminHttp.registerRoute('GET', '/admin/project-home/status', async (req, res, query) => {
308
+ let input;
309
+ try {
310
+ input = schemas.projectHomeAdminCwdQuery.parse(Object.fromEntries(query ?? []));
311
+ } catch (e) {
312
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
313
+ return;
314
+ }
315
+ const resolved = resolveCwd(input.cwd);
316
+ if (!resolved.ok) {
317
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
318
+ return;
319
+ }
320
+ try {
321
+ const status = await getStatus(resolved.cwd);
322
+ sendJson(res, 200, { ok: true, ...status });
323
+ } catch (e) {
324
+ sendJson(res, 400, { ok: false, error: e?.message ?? 'failed to read project-pages status' });
325
+ }
326
+ });
327
+ }
328
+
329
+ // Per-cwd in-process promise chain — the render route's only concurrency
330
+ // guard. Sufficient because this admin HTTP server is a single Node
331
+ // process (Electron main) with no worker pool for these routes; a second
332
+ // concurrent render for the SAME cwd simply waits for the first to finish
333
+ // writing before it starts, so output/ is never observed half-written by
334
+ // two overlapping /render calls (it does NOT defend against a
335
+ // project-home-builder Epic's own separate Write-tool calls racing this
336
+ // route from a different OS process — see project-pages/README.md's
337
+ // concurrency section). Entries are evicted once their chain settles so
338
+ // this Map doesn't grow for the life of the process across many cwds.
339
+ const renderChains = new Map();
340
+ function serializedPerCwd(cwd, fn) {
341
+ const prev = renderChains.get(cwd) || Promise.resolve();
342
+ const next = prev.catch(() => {}).then(fn);
343
+ const settled = next.catch(() => {});
344
+ renderChains.set(cwd, settled);
345
+ settled.finally(() => {
346
+ if (renderChains.get(cwd) === settled) renderChains.delete(cwd);
347
+ });
348
+ return next;
349
+ }
350
+
351
+ async function doRender(cwd, summary, picks) {
352
+ const renderProjectPages = loadRenderer();
353
+ const pages = renderProjectPages(summary, picks);
354
+ const generatedAt = new Date().toISOString();
355
+ const { summaryPath, picksPath, outputDir } = projectPagesPaths(cwd);
356
+
357
+ // The 5 lens files plus summary.json/picks.json have no ordering
358
+ // dependency on each other — only manifest.json's presence is the
359
+ // "generation complete" signal getStatus() relies on, so it's written
360
+ // last, after everything else has landed.
361
+ const lensWrites = LENSES.map((lens) => {
362
+ const lensPath = path.join(outputDir, `${lens}.html`);
363
+ return config.writeTextAtomic(lensPath, pages[lens], { writer: 'project-home' }).then(() => lensPath);
364
+ });
365
+ const [, , ...lensPaths] = await Promise.all([
366
+ config.writeJson(summaryPath, summary, { writer: 'project-home' }).then(() => summaryPath),
367
+ config.writeJson(picksPath, picks, { writer: 'project-home' }).then(() => picksPath),
368
+ ...lensWrites,
369
+ ]);
370
+ const manifestPath = path.join(outputDir, 'manifest.json');
371
+ await config.writeJson(manifestPath, { generatedAt }, { writer: 'project-home' });
372
+
373
+ return { filesWritten: [summaryPath, picksPath, ...lensPaths, manifestPath], generatedAt };
374
+ }
375
+
376
+ async function getStatus(cwd) {
377
+ const { summaryPath, picksPath, outputDir } = projectPagesPaths(cwd);
378
+ const [summaryRes, picksRes, manifestRes, ...lensRes] = await Promise.all([
379
+ config.readJson(summaryPath),
380
+ config.readJson(picksPath),
381
+ config.readJson(path.join(outputDir, 'manifest.json')),
382
+ ...LENSES.map((lens) => config.readText(path.join(outputDir, `${lens}.html`))),
383
+ ]);
384
+
385
+ const output = {};
386
+ LENSES.forEach((lens, i) => {
387
+ const r = lensRes[i];
388
+ output[lens] = { exists: r.exists, mtimeMs: r.exists ? r.mtimeMs : null };
389
+ });
390
+
391
+ return {
392
+ summary: { exists: summaryRes.exists, mtimeMs: summaryRes.exists ? summaryRes.mtimeMs : null },
393
+ picks: { exists: picksRes.exists, mtimeMs: picksRes.exists ? picksRes.mtimeMs : null },
394
+ output,
395
+ manifest: {
396
+ exists: manifestRes.exists,
397
+ generatedAt: manifestRes.exists && manifestRes.data ? (manifestRes.data.generatedAt ?? null) : null,
398
+ },
399
+ };
400
+ }
401
+
402
+ module.exports = { registerAdminRoute };
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * projectPageSummarySchema.cjs — hand-authored JSON Schema description of
5
+ * `ProjectPageSummary` (src/renderer/lib/projectPages/summaryType.ts), for
6
+ * the /admin/project-home/contract route (PRD: project-home-admin-routes).
7
+ *
8
+ * This schema is DESCRIPTIVE, not the enforcement mechanism — the actual
9
+ * gate a posted summary must pass is `validateProjectPageSummary` (shipped
10
+ * in scripts/project-pages-logic/dist/logic.cjs, called by
11
+ * /admin/project-home/validate-summary and /admin/project-home/render).
12
+ * Kept hand-written rather than derived at runtime so the contract route
13
+ * never needs to load the TypeScript source; if summaryType.ts's shape
14
+ * changes, update this alongside it (same discipline as any other
15
+ * TS-type-mirrored constant in this codebase).
16
+ */
17
+
18
+ const PROJECT_PAGE_SUMMARY_JSON_SCHEMA = Object.freeze({
19
+ $schema: 'http://json-schema.org/draft-07/schema#',
20
+ title: 'ProjectPageSummary',
21
+ type: 'object',
22
+ required: ['identity', 'stats', 'pillars', 'feature', 'architecture', 'quotes'],
23
+ properties: {
24
+ identity: {
25
+ type: 'object',
26
+ required: ['name', 'tag', 'version', 'oneLine', 'claim', 'sub', 'audience', 'install'],
27
+ properties: {
28
+ name: { type: 'string' },
29
+ tag: { type: 'string' },
30
+ version: { type: 'string' },
31
+ oneLine: { type: 'string' },
32
+ claim: { type: 'string' },
33
+ sub: { type: 'string' },
34
+ audience: { type: 'string' },
35
+ install: { type: 'string' },
36
+ },
37
+ description: 'Every string field must be non-empty and must not be the literal "TODO".',
38
+ },
39
+ stats: {
40
+ type: 'array',
41
+ items: {
42
+ type: 'object',
43
+ required: ['v', 'k', 'n'],
44
+ properties: { v: { type: 'string' }, k: { type: 'string' }, n: { type: 'string' } },
45
+ },
46
+ },
47
+ pillars: {
48
+ type: 'array',
49
+ items: {
50
+ type: 'object',
51
+ required: ['t', 'd', 'k'],
52
+ properties: { t: { type: 'string' }, d: { type: 'string' }, k: { type: 'string' } },
53
+ },
54
+ },
55
+ quotes: {
56
+ type: 'array',
57
+ description: 'Never fabricate testimonials — omit entirely rather than invent a quote.',
58
+ items: {
59
+ type: 'object',
60
+ required: ['q', 'a', 'r'],
61
+ properties: { q: { type: 'string' }, a: { type: 'string' }, r: { type: 'string' } },
62
+ },
63
+ },
64
+ feature: {
65
+ type: 'object',
66
+ required: ['name', 'kicker', 'status', 'owner', 'oneLine', 'problem', 'solution', 'steps', 'rules', 'specs', 'faq', 'timeline'],
67
+ properties: {
68
+ name: { type: 'string' },
69
+ kicker: { type: 'string' },
70
+ status: { type: 'string' },
71
+ owner: { type: 'string' },
72
+ oneLine: { type: 'string' },
73
+ problem: { type: 'string' },
74
+ solution: { type: 'string' },
75
+ steps: { type: 'array', items: { type: 'object', required: ['t', 'd'], properties: { t: { type: 'string' }, d: { type: 'string' } } } },
76
+ rules: { type: 'array', items: { type: 'object', required: ['t', 'd'], properties: { t: { type: 'string' }, d: { type: 'string' } } } },
77
+ specs: { type: 'array', items: { type: 'array', description: '[label, value, note]', items: { type: 'string' }, minItems: 3, maxItems: 3 } },
78
+ faq: { type: 'array', items: { type: 'object', required: ['q', 'a'], properties: { q: { type: 'string' }, a: { type: 'string' } } } },
79
+ timeline: {
80
+ type: 'array',
81
+ items: {
82
+ type: 'object',
83
+ required: ['w', 't', 's'],
84
+ properties: { w: { type: 'string' }, t: { type: 'string' }, s: { type: 'string', enum: ['done', 'next', 'idea'] } },
85
+ },
86
+ },
87
+ },
88
+ },
89
+ architecture: {
90
+ type: 'object',
91
+ required: ['summary', 'principles', 'layers', 'modules', 'flow', 'decisions', 'risks'],
92
+ properties: {
93
+ summary: { type: 'string' },
94
+ principles: { type: 'array', items: { type: 'object', required: ['t', 'd'], properties: { t: { type: 'string' }, d: { type: 'string' } } } },
95
+ layers: {
96
+ type: 'array',
97
+ items: {
98
+ type: 'object',
99
+ required: ['n', 'd', 'f', 'tone'],
100
+ properties: { n: { type: 'string' }, d: { type: 'string' }, f: { type: 'string' }, tone: { type: 'string', enum: ['accent', 'butter', 'sage', 'mute'] } },
101
+ },
102
+ },
103
+ modules: {
104
+ type: 'array',
105
+ items: {
106
+ type: 'object',
107
+ required: ['n', 'd', 'f', 'dep', 'heat'],
108
+ properties: { n: { type: 'string' }, d: { type: 'string' }, f: { type: 'number' }, dep: { type: 'array', items: { type: 'string' } }, heat: { type: 'number' } },
109
+ },
110
+ },
111
+ flow: {
112
+ type: 'array',
113
+ items: {
114
+ type: 'object',
115
+ required: ['a', 'b', 't', 'n'],
116
+ properties: { a: { type: 'string' }, b: { type: 'string' }, t: { type: 'string' }, n: { type: 'string' } },
117
+ },
118
+ },
119
+ decisions: {
120
+ type: 'array',
121
+ items: {
122
+ type: 'object',
123
+ required: ['id', 't', 'w', 's'],
124
+ properties: { id: { type: 'string' }, t: { type: 'string' }, w: { type: 'string' }, s: { type: 'string', enum: ['accepted', 'proposed', 'superseded'] } },
125
+ },
126
+ },
127
+ risks: {
128
+ type: 'array',
129
+ description: 'No clean source in the Brief — leave empty rather than invent.',
130
+ items: {
131
+ type: 'object',
132
+ required: ['t', 'd', 's'],
133
+ properties: { t: { type: 'string' }, d: { type: 'string' }, s: { type: 'string', enum: ['open', 'watching', 'mitigated'] } },
134
+ },
135
+ },
136
+ },
137
+ },
138
+ brief: {
139
+ type: 'object',
140
+ description: 'OPTIONAL — omit entirely when this project has no generated brief.json yet.',
141
+ required: ['purpose', 'what', 'areas', 'scope', 'conventions'],
142
+ properties: {
143
+ purpose: { type: 'string' },
144
+ what: { type: 'array', items: { type: 'string' } },
145
+ areas: {
146
+ type: 'array',
147
+ items: {
148
+ type: 'object',
149
+ required: ['name', 'files', 'note', 'epic', 'heat'],
150
+ properties: { name: { type: 'string' }, files: { type: 'number' }, note: { type: 'string' }, epic: { type: ['string', 'null'] }, heat: { type: 'number' } },
151
+ },
152
+ },
153
+ scope: {
154
+ type: 'array',
155
+ items: {
156
+ type: 'object',
157
+ required: ['when', 'kind', 'text', 'src'],
158
+ properties: { when: { type: 'string' }, kind: { type: 'string', enum: ['added', 'narrowed', 'decided'] }, text: { type: 'string' }, src: { type: 'string' } },
159
+ },
160
+ },
161
+ conventions: { type: 'array', items: { type: 'string' } },
162
+ },
163
+ },
164
+ },
165
+ });
166
+
167
+ // ProjectPagePicks — Record<lensId, Record<slotId, variantId>>. Matched
168
+ // against each lens's own catalog.slots[].variants[].id at render time by
169
+ // the renderer bundle itself, so this schema only bounds the wire shape.
170
+ const PROJECT_PAGE_PICKS_JSON_SCHEMA = Object.freeze({
171
+ $schema: 'http://json-schema.org/draft-07/schema#',
172
+ title: 'ProjectPagePicks',
173
+ type: 'object',
174
+ additionalProperties: {
175
+ type: 'object',
176
+ additionalProperties: { type: 'string' },
177
+ },
178
+ description: 'lensId -> slotId -> variantId. Every lensId/slotId/variantId must match one from the catalog.',
179
+ });
180
+
181
+ module.exports = { PROJECT_PAGE_SUMMARY_JSON_SCHEMA, PROJECT_PAGE_PICKS_JSON_SCHEMA };