claude-code-session-manager 0.138.0 → 0.140.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +352 -79
  3. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  4. package/dist/assets/History--JwsFnbn.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
  8. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  10. package/dist/assets/Skills-DtRzghn5.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
  12. package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
  15. package/dist/assets/index-CtxruO1L.js +3121 -0
  16. package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +467 -451
  20. package/package.json +17 -6
  21. package/plugins/AGENTS.md +60 -0
  22. package/plugins/CLAUDE.md +1 -60
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  25. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  26. package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  36. package/scripts/README.md +2 -0
  37. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  38. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  39. package/scripts/ops-sweep.cjs +53 -23
  40. package/scripts/scheduler-mcp-server.cjs +360 -35
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +2 -2
  43. package/src/main/config.cjs +112 -8
  44. package/src/main/docEdit.cjs +6 -1
  45. package/src/main/exchanges.cjs +70 -5
  46. package/src/main/files.cjs +7 -27
  47. package/src/main/health.cjs +48 -15
  48. package/src/main/historyAggregator.cjs +172 -63
  49. package/src/main/historyDashboard.cjs +87 -17
  50. package/src/main/index.cjs +78 -4
  51. package/src/main/ipcSchemas.cjs +233 -20
  52. package/src/main/lib/AGENTS.md +54 -0
  53. package/src/main/lib/CLAUDE.md +1 -54
  54. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  55. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  56. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  57. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  58. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  59. package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
  60. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  61. package/src/main/lib/claude/modelPricing.cjs +148 -0
  62. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  63. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  64. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  65. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  66. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  67. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  68. package/src/main/lib/ephemeralCwd.cjs +37 -2
  69. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  70. package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
  71. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  72. package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
  73. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  74. package/src/main/lib/epic/epicSettle.cjs +1 -1
  75. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  76. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  77. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  78. package/src/main/lib/epic/externalRef.cjs +37 -0
  79. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  80. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  81. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  82. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  83. package/src/main/lib/externalContract.cjs +137 -0
  84. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  90. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  91. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  92. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
  93. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  94. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  95. package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
  96. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  97. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  98. package/src/main/lib/git/branchSweep.cjs +209 -4
  99. package/src/main/lib/git/gitWorktree.cjs +41 -5
  100. package/src/main/lib/guardShims.cjs +1 -1
  101. package/src/main/lib/historyRollup.cjs +58 -5
  102. package/src/main/lib/insideHome.cjs +27 -1
  103. package/src/main/lib/mcpToolCatalog.cjs +232 -25
  104. package/src/main/lib/mdDocCensus.cjs +59 -78
  105. package/src/main/lib/mdDocRefs.cjs +71 -93
  106. package/src/main/lib/mdNetworkScan.cjs +245 -250
  107. package/src/main/lib/mdReviewRecord.cjs +22 -9
  108. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  109. package/src/main/lib/opsOwnership.cjs +18 -2
  110. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  111. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  112. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  113. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  114. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  115. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  116. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  117. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  118. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  119. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  120. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  121. package/src/main/lib/prd/prdCreate.cjs +351 -23
  122. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  123. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  124. package/src/main/lib/process/loginItem.cjs +171 -0
  125. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  126. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  127. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  128. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  129. package/src/main/lib/promptSessionSchema.cjs +4 -0
  130. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  131. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  132. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  133. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  134. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  135. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  136. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  137. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  138. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  139. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  140. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  141. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  142. package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
  143. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  144. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  145. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  146. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  147. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  148. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  149. package/src/main/lib/tasks/taskRun.cjs +313 -0
  150. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  151. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  152. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  153. package/src/main/loginItemIpc.cjs +35 -0
  154. package/src/main/loopEfficiencyHandlers.cjs +11 -2
  155. package/src/main/projectPages.cjs +6 -15
  156. package/src/main/promptSessionEvents.cjs +9 -1
  157. package/src/main/queueOps.cjs +260 -3
  158. package/src/main/runVerify.cjs +53 -25
  159. package/src/main/scheduler/AGENTS.md +26 -0
  160. package/src/main/scheduler/CLAUDE.md +1 -26
  161. package/src/main/scheduler/budget.cjs +239 -9
  162. package/src/main/scheduler/cancelDependents.cjs +154 -0
  163. package/src/main/scheduler/prdParser.cjs +4 -1
  164. package/src/main/scheduler/starvation.cjs +20 -18
  165. package/src/main/scheduler.cjs +774 -64
  166. package/src/main/supervisor.cjs +5 -1
  167. package/src/main/templates/PRD_AUTHORING.md +7 -1
  168. package/src/main/transcripts.cjs +62 -7
  169. package/src/main/validationQualityHandlers.cjs +199 -0
  170. package/src/main/webRemote.cjs +132 -20
  171. package/src/preload/api.d.ts +434 -28
  172. package/src/preload/apiSurface.cjs +7 -0
  173. package/src/preload/apiSurface.json +485 -81
  174. package/src/preload/index.cjs +38 -5
  175. package/src/seed/agents/validator.md +19 -8
  176. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  177. package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
  178. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  179. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  180. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  181. package/dist/assets/History-BwO3coo4.js +0 -2
  182. package/dist/assets/Library-BDV69fSe.js +0 -32
  183. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  184. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  185. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  186. package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
  187. package/dist/assets/Settings-COT34hBF.js +0 -2
  188. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  189. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  190. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  191. package/dist/assets/Toggle-CENi19iK.js +0 -1
  192. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  193. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  194. package/dist/assets/index-CgCxpunJ.js +0 -3116
@@ -0,0 +1,285 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * needsYouStore.cjs — machine-level store of "Needs you" items: questions an
5
+ * outside app on this machine needs the owner to decide, so they can show in
6
+ * the Dashboard's Needs you list instead of one inbox per app.
7
+ *
8
+ * File: schedulerHome()/needs-you.json = { version: 1, items }.
9
+ * Writes are atomic (writeJsonAtomic) and serialized through one queue.
10
+ * A missing or corrupt file reads as empty; a corrupt file is set aside as
11
+ * `needs-you.json.corrupt-<ms>` at the next write. Answered or withdrawn items
12
+ * older than 14 days are dropped at the next write.
13
+ */
14
+
15
+ const fsp = require('node:fs/promises');
16
+ const { z } = require('zod');
17
+ const { writeJsonAtomic } = require('../util/atomicFs.cjs');
18
+ const { needsYouPath } = require('../scheduler/schedulerPaths.cjs');
19
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
20
+
21
+ const STORE_VERSION = 1;
22
+ const MAX_OPEN_PER_APP = 10;
23
+ const MAX_OPEN_TOTAL = 50;
24
+ const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
25
+ const STATUSES = /** @type {const} */ (['open', 'answered', 'withdrawn']);
26
+
27
+ const AppSchema = z.string().regex(/^[A-Za-z0-9._-]{1,40}$/, 'app must be 1 to 40 letters, digits, . _ or -');
28
+
29
+ /**
30
+ * Runs a value through normalizeExternalRef; `required` refuses absent values.
31
+ * The input is `.optional()` so zod 4 lets a missing key reach the transform
32
+ * (a bare z.unknown().transform() rejects it as "expected nonoptional").
33
+ */
34
+ function refSchema(label, required) {
35
+ return z.unknown().optional().transform((v, ctx) => {
36
+ if (required && (v === undefined || v === null)) {
37
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} is required.` });
38
+ return z.NEVER;
39
+ }
40
+ const r = normalizeExternalRef(v);
41
+ if (!r.ok) {
42
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: r.error.replace(/^externalRef/, label) });
43
+ return z.NEVER;
44
+ }
45
+ return r.value;
46
+ });
47
+ }
48
+
49
+ const TitleSchema = z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), 'title must be one line');
50
+ const WhySchema = z.string().max(1000);
51
+ const LinkSchema = z.string().max(2000).regex(/^https?:\/\//, 'link must start with http:// or https://');
52
+ const OptionsSchema = z.array(z.string().min(1).max(80)).min(2).max(5)
53
+ .refine((opts) => new Set(opts).size === opts.length, 'options must be distinct');
54
+
55
+ const NeedsYouPostSchema = z.object({
56
+ app: AppSchema,
57
+ id: refSchema('id', true),
58
+ title: TitleSchema,
59
+ why: WhySchema.optional(),
60
+ link: LinkSchema.optional(),
61
+ options: OptionsSchema.optional(),
62
+ externalRef: refSchema('externalRef', false),
63
+ });
64
+
65
+ const KeySchema = z.object({ app: AppSchema, id: refSchema('id', true) });
66
+
67
+ const StoredItemSchema = z.object({
68
+ app: AppSchema,
69
+ id: z.string().min(1),
70
+ title: TitleSchema,
71
+ why: z.string(),
72
+ link: LinkSchema.nullable(),
73
+ options: OptionsSchema.nullable(),
74
+ externalRef: z.string().nullable(),
75
+ status: z.enum(STATUSES),
76
+ answer: z.string().nullable(),
77
+ createdAt: z.string(),
78
+ updatedAt: z.string(),
79
+ answeredAt: z.string().nullable(),
80
+ });
81
+
82
+ /** @typedef {z.infer<typeof StoredItemSchema>} NeedsYouItem */
83
+
84
+ // --- serialized writes ------------------------------------------------------
85
+
86
+ let writeChain = Promise.resolve();
87
+ /** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */
88
+ function serialize(fn) {
89
+ const run = writeChain.then(fn, fn);
90
+ writeChain = run.then(() => undefined, () => undefined);
91
+ return run;
92
+ }
93
+
94
+ // --- read / write -----------------------------------------------------------
95
+
96
+ /** Returns { state: 'missing'|'corrupt'|'unreadable'|'ok', items }. Never throws. */
97
+ async function readStore(filePath) {
98
+ let text;
99
+ try {
100
+ text = await fsp.readFile(filePath, 'utf8');
101
+ } catch (err) {
102
+ if (err && err.code === 'ENOENT') return { state: 'missing', items: [] };
103
+ console.warn(`[needsYouStore] cannot read ${filePath}:`, err && err.message);
104
+ return { state: 'unreadable', items: [] };
105
+ }
106
+ let raw;
107
+ try {
108
+ raw = JSON.parse(text);
109
+ } catch {
110
+ return { state: 'corrupt', items: [] };
111
+ }
112
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { state: 'corrupt', items: [] };
113
+ const list = Array.isArray(raw.items) ? raw.items : [];
114
+ const items = [];
115
+ const seen = new Set();
116
+ let dropped = 0;
117
+ for (const entry of list) {
118
+ const r = StoredItemSchema.safeParse(entry);
119
+ const key = r.success ? `${r.data.app}\u0000${r.data.id}` : '';
120
+ if (r.success && !seen.has(key)) {
121
+ seen.add(key);
122
+ items.push(r.data);
123
+ } else {
124
+ dropped++;
125
+ }
126
+ }
127
+ if (dropped > 0) console.warn(`[needsYouStore] dropped ${dropped} invalid item(s) from ${filePath}`);
128
+ return { state: 'ok', items };
129
+ }
130
+
131
+ /** Load for a write. MUST run inside serialize. Sets a corrupt file aside. */
132
+ async function loadForWrite(filePath) {
133
+ const cur = await readStore(filePath);
134
+ if (cur.state === 'unreadable') throw new Error(`needs-you store is unreadable: ${filePath}`);
135
+ if (cur.state === 'corrupt') {
136
+ const quarantine = `${filePath}.corrupt-${Date.now()}`;
137
+ await fsp.rename(filePath, quarantine);
138
+ console.warn(`[needsYouStore] ${filePath} is unparseable; preserved as ${quarantine}`);
139
+ }
140
+ return cur.items;
141
+ }
142
+
143
+ function prune(items, nowMs) {
144
+ return items.filter((it) => {
145
+ if (it.status === 'open') return true;
146
+ const closedAt = Date.parse(it.answeredAt || it.updatedAt);
147
+ return !(Number.isFinite(closedAt) && nowMs - closedAt > RETENTION_MS);
148
+ });
149
+ }
150
+
151
+ async function writeStore(filePath, items) {
152
+ await writeJsonAtomic(filePath, { version: STORE_VERSION, items: prune(items, Date.now()) });
153
+ }
154
+
155
+ function limitError(message) {
156
+ const err = /** @type {Error & { code: string }} */ (new Error(message));
157
+ err.code = 'NEEDS_YOU_LIMIT';
158
+ return err;
159
+ }
160
+
161
+ // --- public API ---------------------------------------------------------------
162
+
163
+ /**
164
+ * @param {{ app?: string, status?: string }} [filter]
165
+ * @returns {Promise<NeedsYouItem[]>}
166
+ */
167
+ async function listNeedsYou(filter = {}) {
168
+ const { app, status } = filter || {};
169
+ const { items } = await readStore(needsYouPath());
170
+ return items.filter((it) => (app === undefined || it.app === app) && (status === undefined || it.status === status));
171
+ }
172
+
173
+ /** The caller fields a post may set on an open item. */
174
+ function callerKey(item) {
175
+ return JSON.stringify([item.title, item.why, item.link, item.options, item.externalRef]);
176
+ }
177
+
178
+ /**
179
+ * Create an open item, or replace title/why/link/options/externalRef of an
180
+ * existing open item with the same app + id (a left-out field is cleared).
181
+ * A closed item is returned unchanged. `changed` is decided inside the write
182
+ * queue: true on create or when a stored field differs; an identical re-post
183
+ * writes nothing and keeps updatedAt.
184
+ * @param {unknown} input
185
+ * @returns {Promise<{ item: NeedsYouItem, created: boolean, changed: boolean }>}
186
+ */
187
+ async function postNeedsYou(input) {
188
+ const data = NeedsYouPostSchema.parse(input);
189
+ const filePath = needsYouPath();
190
+ return serialize(async () => {
191
+ const items = await loadForWrite(filePath);
192
+ const now = new Date().toISOString();
193
+ const existing = items.find((it) => it.app === data.app && it.id === data.id);
194
+ if (existing) {
195
+ if (existing.status !== 'open') return { item: existing, created: false, changed: false };
196
+ const before = callerKey(existing);
197
+ existing.title = data.title;
198
+ existing.why = data.why ?? '';
199
+ existing.link = data.link ?? null;
200
+ existing.options = data.options ?? null;
201
+ existing.externalRef = data.externalRef ?? null;
202
+ if (callerKey(existing) === before) return { item: existing, created: false, changed: false };
203
+ existing.updatedAt = now;
204
+ await writeStore(filePath, items);
205
+ return { item: existing, created: false, changed: true };
206
+ }
207
+ const open = items.filter((it) => it.status === 'open');
208
+ if (open.filter((it) => it.app === data.app).length >= MAX_OPEN_PER_APP) {
209
+ throw limitError(`${data.app} already has ${MAX_OPEN_PER_APP} open Needs you items.`);
210
+ }
211
+ if (open.length >= MAX_OPEN_TOTAL) {
212
+ throw limitError(`There are already ${MAX_OPEN_TOTAL} open Needs you items.`);
213
+ }
214
+ /** @type {NeedsYouItem} */
215
+ const item = {
216
+ app: data.app,
217
+ id: /** @type {string} */ (data.id),
218
+ title: data.title,
219
+ why: data.why ?? '',
220
+ link: data.link ?? null,
221
+ options: data.options ?? null,
222
+ externalRef: data.externalRef ?? null,
223
+ status: 'open',
224
+ answer: null,
225
+ createdAt: now,
226
+ updatedAt: now,
227
+ answeredAt: null,
228
+ };
229
+ items.push(item);
230
+ await writeStore(filePath, items);
231
+ return { item, created: true, changed: true };
232
+ });
233
+ }
234
+
235
+ /** Apply `mutate` to the open item app+id; returns it, or null when none / mutate refuses. */
236
+ async function updateOpen(app, id, mutate) {
237
+ const key = KeySchema.parse({ app, id });
238
+ const filePath = needsYouPath();
239
+ return serialize(async () => {
240
+ const items = await loadForWrite(filePath);
241
+ const item = items.find((it) => it.app === key.app && it.id === key.id);
242
+ if (!item || item.status !== 'open') return null;
243
+ const now = new Date().toISOString();
244
+ if (!mutate(item, now)) return null;
245
+ item.updatedAt = now;
246
+ await writeStore(filePath, items);
247
+ return item;
248
+ });
249
+ }
250
+
251
+ /**
252
+ * @param {{ app: string, id: string }} args
253
+ * @returns {Promise<NeedsYouItem | null>}
254
+ */
255
+ async function withdrawNeedsYou({ app, id }) {
256
+ return updateOpen(app, id, (item) => {
257
+ item.status = 'withdrawn';
258
+ return true;
259
+ });
260
+ }
261
+
262
+ /**
263
+ * @param {{ app: string, id: string, answer: string }} args
264
+ * @returns {Promise<NeedsYouItem | null>}
265
+ */
266
+ async function answerNeedsYou({ app, id, answer }) {
267
+ return updateOpen(app, id, (item, now) => {
268
+ if (!item.options || typeof answer !== 'string' || !item.options.includes(answer)) return false;
269
+ item.status = 'answered';
270
+ item.answer = answer;
271
+ item.answeredAt = now;
272
+ return true;
273
+ });
274
+ }
275
+
276
+ module.exports = {
277
+ NeedsYouPostSchema,
278
+ listNeedsYou,
279
+ postNeedsYou,
280
+ withdrawNeedsYou,
281
+ answerNeedsYou,
282
+ MAX_OPEN_PER_APP,
283
+ MAX_OPEN_TOTAL,
284
+ RETENTION_MS,
285
+ };
@@ -6,6 +6,9 @@
6
6
  * POST /admin/project-home/demo-video/write alias: {cwd, html} -> a new videos/vid-<id>/ project-demo entry
7
7
  * POST /admin/project-home/matrix/read {cwd} -> project-pages/matrix/matrix.json (+ its JSON Schema)
8
8
  * POST /admin/project-home/matrix/write {cwd, matrix, model?} -> matrixStore.writeMatrix
9
+ * POST /admin/project-home/videos/review/write {cwd, videoId, text, images:[{base64}]} -> videoReview.writeMaterial
10
+ * (review material only; there is deliberately no route that decides, approves or retries —
11
+ * only the human buttons in the app record a decision)
9
12
  * all owned by writer 'project-home' (see opsOwnership.cjs). Registered
10
13
  * against the same injected localAdminHttp.cjs transport as
11
14
  * prdAdminRoutes.cjs.
@@ -36,9 +39,14 @@ const { checkHtmlLimits } = require('../demo-video-kit/checks.cjs');
36
39
  const { injectPlayerBridge } = require('../project-pages/playerBridge.cjs');
37
40
  const { readMatrix, matrixJsonSchema, MAX_MATRIX_BYTES } = require('../project-pages/competitiveMatrix.cjs');
38
41
  const { writeMatrix } = require('../project-pages/matrixStore.cjs');
42
+ const videoReview = require('../project-pages/videoReview.cjs');
39
43
 
40
44
  const MAX_HTML_BYTES = 1024 * 1024;
41
45
  const MAX_DEMO_VIDEO_BYTES = 2 * 1024 * 1024;
46
+ /** Review write body cap: 6 base64 images of 2 MiB (16 MiB) + a 32000-char text and JSON overhead. */
47
+ const REVIEW_WRITE_BODY_MAX = 18 * 1024 * 1024;
48
+ const REVIEW_DECISION_KEYS = Object.freeze(['decision', 'status', 'approved', 'approvedAt']);
49
+ const REVIEW_DECISION_REFUSAL = 'review decisions are made only by a human in the app';
42
50
 
43
51
  // Each detector is a linear regex scan; the input is capped first.
44
52
  const REMOTE_REFERENCE_CHECKS = [
@@ -79,6 +87,23 @@ const NETWORK_CHECKS = [
79
87
  { re: /<a\b[^>]*\bhref\s*=\s*["']?\s*(?:https?:|\/\/|javascript:)/i, message: '<a href="http(s):|//|javascript:…"> is not allowed' },
80
88
  ];
81
89
 
90
+ // <meta name="sm-demo-aspect" content="..."> in any attribute order, either quote style.
91
+ const META_TAG_RE = /<meta\b[^>]*>/gi;
92
+ const ASPECT_NAME_RE = /\bname\s*=\s*(["'])\s*sm-demo-aspect\s*\1/i;
93
+ const CONTENT_ATTR_RE = /\bcontent\s*=\s*(["'])(.*?)\1/i;
94
+ const VIDEO_ASPECTS = ['16:9', '9:16'];
95
+
96
+ /** The document's declared aspect: '16:9' when no tag, an error for any other value. */
97
+ function readAspect(html) {
98
+ for (const tag of html.match(META_TAG_RE) ?? []) {
99
+ if (!ASPECT_NAME_RE.test(tag)) continue;
100
+ const content = (tag.match(CONTENT_ATTR_RE)?.[2] ?? '').trim();
101
+ if (VIDEO_ASPECTS.includes(content)) return { aspect: content };
102
+ return { error: `sm-demo-aspect content must be '16:9' or '9:16' (got '${content.slice(0, 40)}')` };
103
+ }
104
+ return { aspect: '16:9' };
105
+ }
106
+
82
107
  const DURATION_META_RE = /<meta\b[^>]*\bname\s*=\s*["']sm-demo-duration["'][^>]*\bcontent\s*=\s*["'](\d+)["'][^>]*>/i;
83
108
  const MIN_DEMO_DURATION_S = 5;
84
109
  const MAX_DEMO_DURATION_S = 60;
@@ -220,7 +245,7 @@ function makeWriteHandler({ schema, bodyLimit, build }) {
220
245
  const abs = path.join(dir, 'index.html');
221
246
  await config.writeTextAtomic(abs, built.html, { writer: 'project-home' });
222
247
  await config.writeTextAtomic(path.join(dir, 'meta.json'), JSON.stringify(built.meta, null, 2) + '\n', { writer: 'project-home' });
223
- sendJson(res, 200, { ok: true, path: abs, bytes: Buffer.byteLength(built.html, 'utf8'), id: built.meta.id });
248
+ sendJson(res, 200, { ok: true, path: abs, bytes: Buffer.byteLength(built.html, 'utf8'), id: built.meta.id, meta: built.meta });
224
249
  } catch (e) {
225
250
  sendJson(res, 500, { ok: false, error: e?.message ?? 'write failed' });
226
251
  }
@@ -257,6 +282,9 @@ function buildVideo(input, { videoId, title, kind, lengthS, meta }) {
257
282
  if (rejection) return { error: rejection };
258
283
  const declared = Number(input.html.match(DURATION_META_RE)[1]);
259
284
  if (declared !== lengthS) return { error: `sm-demo-duration (${declared}) must equal lengthS (${lengthS})` };
285
+ // The document's tag is the one source; a caller-supplied meta.aspect is ignored.
286
+ const declaredAspect = readAspect(input.html);
287
+ if (declaredAspect.error) return { error: declaredAspect.error };
260
288
  const html = injectPlayerBridge(injectCsp(input.html));
261
289
  const bytes = Buffer.byteLength(html, 'utf8');
262
290
  return {
@@ -268,6 +296,7 @@ function buildVideo(input, { videoId, title, kind, lengthS, meta }) {
268
296
  title,
269
297
  kind,
270
298
  lengthS,
299
+ aspect: declaredAspect.aspect,
271
300
  createdAt: new Date().toISOString(),
272
301
  report: { ...meta.report, bytes },
273
302
  }),
@@ -338,6 +367,9 @@ function registerAdminRoute(adminHttp) {
338
367
  },
339
368
  }));
340
369
 
370
+ // POST /admin/project-home/videos/review/write {cwd, videoId, text, images:[{base64}]} -> review/material.json
371
+ adminHttp.registerRoute('POST', '/admin/project-home/videos/review/write', reviewWriteHandler);
372
+
341
373
  // POST /admin/project-home/character/write {cwd, json, js, replace?} -> videos/_character/
342
374
  adminHttp.registerRoute('POST', '/admin/project-home/character/write', characterWriteHandler);
343
375
 
@@ -393,6 +425,70 @@ function makeMatrixHandler(run) {
393
425
  };
394
426
  }
395
427
 
428
+ /**
429
+ * Saves review material for one review-stage video entry. Never records a
430
+ * decision: a body carrying any decision-shaped key is refused outright.
431
+ */
432
+ async function reviewWriteHandler(req, res) {
433
+ let raw;
434
+ try {
435
+ raw = await readBody(req, REVIEW_WRITE_BODY_MAX);
436
+ } catch (e) {
437
+ sendJson(res, 413, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'} (limit is ${REVIEW_WRITE_BODY_MAX} bytes)` });
438
+ return;
439
+ }
440
+ let body;
441
+ try {
442
+ body = raw ? JSON.parse(raw) : {};
443
+ } catch {
444
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
445
+ return;
446
+ }
447
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
448
+ sendJson(res, 400, { ok: false, error: 'invalid payload' });
449
+ return;
450
+ }
451
+ if (REVIEW_DECISION_KEYS.some((k) => Object.prototype.hasOwnProperty.call(body, k))) {
452
+ sendJson(res, 400, { ok: false, error: REVIEW_DECISION_REFUSAL });
453
+ return;
454
+ }
455
+ const { videoId, text, images } = body;
456
+ if (typeof videoId !== 'string' || !ENTRY_ID_RE.test(videoId)) {
457
+ sendJson(res, 400, { ok: false, error: 'invalid videoId' });
458
+ return;
459
+ }
460
+ if (!Array.isArray(images)) {
461
+ sendJson(res, 400, { ok: false, error: 'images must be an array of { base64 }' });
462
+ return;
463
+ }
464
+ const decoded = [];
465
+ for (let i = 0; i < images.length; i++) {
466
+ const b64 = images[i] && images[i].base64;
467
+ if (typeof b64 !== 'string' || !b64) {
468
+ sendJson(res, 400, { ok: false, error: `image ${i + 1}: base64 must be a non-empty string` });
469
+ return;
470
+ }
471
+ decoded.push({ bytes: Buffer.from(b64, 'base64') });
472
+ }
473
+ const resolved = resolveCwd(body.cwd);
474
+ if (!resolved.ok) {
475
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
476
+ return;
477
+ }
478
+ config.addAllowedRoot(resolved.cwd);
479
+ try {
480
+ const r = await videoReview.writeMaterial(resolved.cwd, videoId, { text, images: decoded });
481
+ if (!r.ok) {
482
+ sendJson(res, 400, { ok: false, error: r.error });
483
+ return;
484
+ }
485
+ const review = await videoReview.readReview(resolved.cwd, videoId);
486
+ sendJson(res, 200, { ok: true, entryId: videoId, status: review ? review.status : 'waiting' });
487
+ } catch (e) {
488
+ sendJson(res, 500, { ok: false, error: e?.message ?? 'review write failed' });
489
+ }
490
+ }
491
+
396
492
  async function characterWriteHandler(req, res) {
397
493
  let raw;
398
494
  try {
@@ -455,5 +551,6 @@ module.exports = {
455
551
  DEMO_VIDEO_CSP,
456
552
  MAX_HTML_BYTES,
457
553
  MAX_DEMO_VIDEO_BYTES,
554
+ REVIEW_WRITE_BODY_MAX,
458
555
  resolveCwd,
459
556
  };
@@ -68,6 +68,11 @@ const PATH_FENCED_CHANNELS = Object.freeze({
68
68
  'project-pages:matrix': { field: 'cwd', mode: 'root' },
69
69
  // Epic Changes view (main/lib/epic/epicChanges.cjs): diffs a repo, so cwd must sit inside a registered root.
70
70
  'epicChanges:get': { field: 'cwd', mode: 'root' },
71
+ // Scheduler Tasks section reads (main/lib/tasks/taskIpc.cjs): cwd inside a registered root.
72
+ // tasks:set-switch is not here — its apiSurface row is 'deny', so it never reaches the relay.
73
+ 'tasks:list': { field: 'cwd', mode: 'root' },
74
+ 'tasks:get': { field: 'cwd', mode: 'root' },
75
+ 'tasks:get-switch': { field: 'cwd', mode: 'root' },
71
76
  })
72
77
 
73
78
  const SECRET_DIRS = new Set(['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.password-store', '.azure', '.terraform.d'])