claude-code-session-manager 0.141.0 → 0.142.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 (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -15,12 +15,13 @@
15
15
  const path = require('node:path');
16
16
  const fsp = require('node:fs/promises');
17
17
  const atomicFs = require('../util/atomicFs.cjs');
18
+ const { parseContext } = require('./feedbackReport.cjs');
18
19
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
19
20
 
20
21
  const FEEDBACK_SLUG = 'session-manager';
21
22
  const TAGS = /** @type {const} */ (['bug', 'feature', 'discussion']);
22
23
  const MAX_TITLE = 120;
23
- const MAX_BODY = 4000;
24
+ const MAX_BODY = 5000;
24
25
  const MAX_ITEMS = 500;
25
26
  const MAX_LOOKUP = 100;
26
27
  const TIMEOUT_MS = 15000;
@@ -75,8 +76,8 @@ function validateImages(raw) {
75
76
  }
76
77
 
77
78
  /**
78
- * @param {{ title?: unknown, body?: unknown, tag?: unknown, images?: unknown }} input
79
- * @returns {{ ok: true, value: { title: string, body: string, tag: string, images: FeedbackImage[] } } | { ok: false, error: string }}
79
+ * @param {{ title?: unknown, body?: unknown, tag?: unknown, images?: unknown, context?: unknown }} input
80
+ * @returns {{ ok: true, value: { title: string, body: string, tag: string, images: FeedbackImage[], context?: import('./feedbackReport.cjs').FeedbackContext } } | { ok: false, error: string }}
80
81
  */
81
82
  function validateSubmission(input) {
82
83
  const src = input || {};
@@ -92,7 +93,10 @@ function validateSubmission(input) {
92
93
  }
93
94
  const imgs = validateImages(src.images);
94
95
  if (!imgs.ok) return imgs;
95
- return { ok: true, value: { title, body, tag, images: imgs.images } };
96
+ if (src.context === undefined || src.context === null) return { ok: true, value: { title, body, tag, images: imgs.images } };
97
+ const c = parseContext(src.context);
98
+ if (!c.ok) return { ok: false, error: `Invalid feedback context — ${c.error}` };
99
+ return { ok: true, value: { title, body, tag, images: imgs.images, context: c.context } };
96
100
  }
97
101
 
98
102
  function defaultStoreFile() {
@@ -174,7 +178,7 @@ function imageWarning(acked, sent) {
174
178
  }
175
179
 
176
180
  /**
177
- * @param {{ title?: unknown, body?: unknown, tag?: unknown, images?: unknown }} input
181
+ * @param {{ title?: unknown, body?: unknown, tag?: unknown, images?: unknown, context?: unknown }} input
178
182
  * @param {Deps} [deps]
179
183
  * @returns {Promise<{ ok: true, item: FeedbackItem, warning?: string } | { ok: false, error: string }>}
180
184
  */
@@ -182,7 +186,7 @@ async function submit(input, deps) {
182
186
  const v = validateSubmission(input);
183
187
  if (!v.ok) return v;
184
188
  const c = ctx(deps);
185
- const { title, body, tag, images } = v.value;
189
+ const { title, body, tag, images, context } = v.value;
186
190
  try {
187
191
  const res = await c.fetchImpl(`${resolveFeedbackBase()}/api/projects/${FEEDBACK_SLUG}/feedback`, {
188
192
  method: 'POST',
@@ -194,6 +198,7 @@ async function submit(input, deps) {
194
198
  description: body,
195
199
  client: { app: 'session-manager', version: c.appVersion, platform: process.platform },
196
200
  ...(images.length > 0 ? { images } : {}),
201
+ ...(context ? { context } : {}),
197
202
  }),
198
203
  signal: AbortSignal.timeout(TIMEOUT_MS),
199
204
  });
@@ -16,6 +16,8 @@ const atomicFs = require('../util/atomicFs.cjs');
16
16
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
17
17
  const { resolveFeedbackBase, fromWireType, FEEDBACK_SLUG } = require('./customerFeedbackClient.cjs');
18
18
  const { ATTACHMENT_MIMES, sniffImageMime } = require('../epic/epicAttachments.cjs');
19
+ /** Host stores the widget context opaquely up to MAX_CONTEXT_BYTES of JSON (Bilko 76e88612). */
20
+ const { MAX_CONTEXT_BYTES } = require('./feedbackReport.cjs');
19
21
 
20
22
  const STATUSES = /** @type {const} */ (['open', 'in_progress', 'resolved', 'wontfix']);
21
23
  const MAX_NOTE = 500;
@@ -38,7 +40,8 @@ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
38
40
  * @typedef {{ mime: string, bytes: number, path: string|null }} InboxImage
39
41
  * @typedef {{ id: string, receivedAt: string|number|null, tag: string, title: string, body: string,
40
42
  * clientVersion: string|null, clientPlatform: string|null, moderation: string|null, status: string,
41
- * statusNote: string|null, statusAt: string|number|null, epicId: string|null, images?: InboxImage[] }} InboxItem
43
+ * statusNote: string|null, statusAt: string|number|null, epicId: string|null, images?: InboxImage[],
44
+ * context?: Record<string, unknown>|null }} InboxItem
42
45
  * @typedef {{ items: InboxItem[], nextSince: string|null, nextModeratedSince: string|null }} Store
43
46
  * @typedef {{ fetchImpl?: typeof fetch, storeFile?: string, ownerFile?: string, imagesDir?: string,
44
47
  * env?: Record<string, string|undefined>, now?: () => number }} Deps
@@ -163,9 +166,31 @@ function toItem(w, prev) {
163
166
  statusAt: st ? (st.at ?? null) : null,
164
167
  epicId: prev && prev.epicId ? prev.epicId : null,
165
168
  images: toImages(w.images, prev),
169
+ context: toContext(w, prev),
166
170
  };
167
171
  }
168
172
 
173
+ /**
174
+ * The host's opaque widget context (page/marks/console/network). A wire item with no `context`
175
+ * key (e.g. a status/moderation delta) keeps the stored one; a non-object or one over
176
+ * MAX_CONTEXT_BYTES of JSON is stored as null.
177
+ * @param {any} w @param {InboxItem|undefined} prev @returns {Record<string, unknown>|null}
178
+ */
179
+ function toContext(w, prev) {
180
+ if (!w || !Object.prototype.hasOwnProperty.call(w, 'context') || w.context === undefined) {
181
+ return prev && prev.context && typeof prev.context === 'object' ? prev.context : null;
182
+ }
183
+ const v = w.context;
184
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return null;
185
+ try {
186
+ const json = JSON.stringify(v);
187
+ if (typeof json !== 'string' || Buffer.byteLength(json, 'utf8') > MAX_CONTEXT_BYTES) return null;
188
+ return JSON.parse(json);
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+
169
194
  /** @param {unknown} wireImages @param {InboxItem|undefined} prev @returns {InboxImage[]} */
170
195
  function toImages(wireImages, prev) {
171
196
  if (!Array.isArray(wireImages)) return [];
@@ -19,7 +19,7 @@ function getClient() {
19
19
  * feedbackImages.prepareFeedbackImages, then calls client.submit. A prepare
20
20
  * error resolves { ok: false, error } without submitting; otherwise the
21
21
  * client's result (including any `warning`) is returned unchanged.
22
- * @param {{ title: string, body: string, tag: string, images?: { dataUrl: string }[], imagePaths?: string[] }} p
22
+ * @param {{ title: string, body: string, tag: string, images?: { dataUrl: string }[], imagePaths?: string[], context?: unknown }} p
23
23
  * @param {any} [client]
24
24
  * @param {(inputs: { dataUrl?: string, path?: string }[]) => Promise<any>} [prepare]
25
25
  */
@@ -32,7 +32,10 @@ async function submitFeedback(p, client = getClient(), prepare = require('./feed
32
32
  if (!prepared || !prepared.ok) {
33
33
  return { ok: false, error: prepared && typeof prepared.error === 'string' ? prepared.error : 'Images could not be prepared.' };
34
34
  }
35
- return client.submit({ title: p.title, body: p.body, tag: p.tag, images: prepared.images });
35
+ return client.submit({
36
+ title: p.title, body: p.body, tag: p.tag, images: prepared.images,
37
+ ...(p.context !== undefined && p.context !== null ? { context: p.context } : {}),
38
+ });
36
39
  }
37
40
 
38
41
  /**
@@ -0,0 +1,409 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackBoxDrain — moves every waiting website-widget envelope from the bilko.run relay into its
4
+ * project's feedback-inbox/ and only then acks it (the host deletes acked envelopes).
5
+ * Data path: session-manager-operations/architecture/site-feedback.md.
6
+ *
7
+ * Per local box (feedbackBoxKeys): list envelopes (limit 20, repeat until empty), download, open
8
+ * (feedbackEnvelope.openReportEnvelope), write (siteFeedbackInbox.writeItem), ack.
9
+ * - open failure (any ok:false code) -> one rejected.jsonl line (no content), then ack.
10
+ * - writeItem refuses the hostId as stored for another report (code host_id_clash) -> one
11
+ * rejected.jsonl line with code host_id_clash, then ack (it would never succeed: a poison
12
+ * envelope must not stall its box).
13
+ * - network error / 5xx / 429 / any other relay failure -> stop that box for this pass, no ack;
14
+ * 429 also defers the box by Retry-After.
15
+ * - 404 box_not_found -> box is gone (deleted, or re-paired under another account): reported in
16
+ * goneBoxes and skipped until its keystore record is removed.
17
+ * - projectCwd missing -> box held (not drained, nothing acked), reported in heldBoxes.
18
+ *
19
+ * - any throw -> box stopped for this pass, logged with a fixed code from classifyError
20
+ * (write_denied, io_error, relay_error, open_failed, keystore_error).
21
+ *
22
+ * Verified reporter (site-feedback.md#verified-reporter): before the write, a report whose user
23
+ * carries a string `sig` is checked against the box's identity secret (keystore.peekIdentitySecret — read-only, never mints):
24
+ * HMAC-SHA256(secret, 'v1|id|email|exp') as base64url, compared with crypto.timingSafeEqual, and
25
+ * exp (epoch seconds) not earlier than createdAt minus 5 minutes. The result is stored as
26
+ * meta.reporterVerified: true (valid), false (sig present but invalid, expired, or no secret) or
27
+ * null (no sig). Neither the secret nor the sig is ever logged.
28
+ *
29
+ * Retention: once per project per 24 h (per drain instance) the drain calls
30
+ * inbox.prune(cwd, feedbackInboxDays) with the days from opsRetentionSettings.read().
31
+ *
32
+ * Nothing logged ever carries report text, image bytes, a private key or the device token: log
33
+ * lines name only box ids and fixed codes.
34
+ */
35
+ 'use strict';
36
+
37
+ const fs = require('node:fs');
38
+ const crypto = require('node:crypto');
39
+ const { openReportEnvelope } = require('./feedbackEnvelope.cjs');
40
+
41
+ const PAGE_LIMIT = 20;
42
+ const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
43
+ const DEFAULT_RETRY_AFTER_SEC = 60;
44
+ const MAX_PAGES_PER_BOX = 100;
45
+ const HOST_ID_RE = /^FB-[0-9A-Z]{5}$/;
46
+ const HOST_ID_CLASH = 'host_id_clash';
47
+ const PRUNE_EVERY_MS = 24 * 60 * 60 * 1000;
48
+ /** Clock skew allowed between the site's signer and the visitor's createdAt. */
49
+ const REPORTER_EXP_SKEW_MS = 5 * 60 * 1000;
50
+
51
+ /**
52
+ * @typedef {{ ok: false, status: number, error: string, retryAfterSec?: number }} RelayFailure
53
+ * @typedef {{ envelopeId: string, hostId: string, clientReportId?: string, receivedAt: string,
54
+ * origin: string, bytes?: number }} EnvelopeListing
55
+ * @typedef {{
56
+ * listEnvelopes: (boxId: string, limit?: number) => Promise<{ ok: true, envelopes: EnvelopeListing[] } | RelayFailure>,
57
+ * getEnvelope: (boxId: string, envelopeId: string) => Promise<{ ok: true, body: Buffer } | RelayFailure>,
58
+ * ackEnvelope: (boxId: string, envelopeId: string) => Promise<{ ok: true } | RelayFailure>,
59
+ * }} DrainRelay
60
+ * @typedef {{ boxId: string, projectCwd: string }} DrainBox
61
+ * @typedef {{
62
+ * listBoxes: () => Promise<DrainBox[]>,
63
+ * getPrivateKey: (boxId: string) => Promise<Record<string, unknown> | null>,
64
+ * peekIdentitySecret?: (boxId: string) => Promise<string | null>,
65
+ * }} DrainKeystore
66
+ * @typedef {{
67
+ * writeItem: (args: any) => Promise<{ duplicate: boolean, hostId: string }>,
68
+ * appendRejected: (args: { cwd: string, at: string, boxId: string, hostId: string, code: string, bytes: number }) => Promise<void>,
69
+ * prune: (cwd: string, days: number) => Promise<string[]>,
70
+ * }} DrainInbox
71
+ * @typedef {{ relay?: DrainRelay, keystore?: DrainKeystore, inbox?: DrainInbox,
72
+ * now?: () => number, cwdExists?: (cwd: string) => boolean,
73
+ * feedbackInboxDays?: () => number,
74
+ * log?: (msg: string) => void }} DrainDeps
75
+ * @typedef {{ stored: number, duplicates: number, rejected: number,
76
+ * goneBoxes: string[], heldBoxes: string[] }} DrainResult
77
+ */
78
+
79
+ /** @param {string} cwd */
80
+ function defaultCwdExists(cwd) {
81
+ try {
82
+ return fs.statSync(cwd).isDirectory();
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ /** @param {string} msg */
89
+ function defaultLog(msg) {
90
+ console.warn(`[feedbackBoxDrain] ${msg}`);
91
+ }
92
+
93
+ /** @returns {DrainRelay} */
94
+ function defaultRelay() {
95
+ const { createRelayClient } = require('./feedbackRelayClient.cjs');
96
+ return createRelayClient({
97
+ getDeviceToken: () => require('../../webRemote.cjs').getLinkedDeviceToken(),
98
+ });
99
+ }
100
+
101
+ /** @returns {number} */
102
+ function defaultFeedbackInboxDays() {
103
+ return require('../opsRetentionSettings.cjs').read().feedbackInboxDays;
104
+ }
105
+
106
+ /** @param {unknown} e */
107
+ function isHostIdClash(e) {
108
+ return !!e && typeof e === 'object' && /** @type {any} */ (e).code === HOST_ID_CLASH;
109
+ }
110
+
111
+ /** @param {unknown} code */
112
+ function safeCode(code) {
113
+ return typeof code === 'string' && /^[a-z0-9_]{1,64}$/i.test(code) ? code : 'unknown';
114
+ }
115
+
116
+ /**
117
+ * Does the report's user carry a signature, and does it verify? Pure: the caller supplies the secret.
118
+ * @param {unknown} report the opened Report v1
119
+ * @param {string | null} secret the box's identity secret (null = the box has none)
120
+ * @returns {boolean | null} null when the user carries no sig
121
+ */
122
+ function verifyReporter(report, secret) {
123
+ const r = /** @type {any} */ (report);
124
+ const u = r && typeof r === 'object' && r.user && typeof r.user === 'object' ? r.user : null;
125
+ if (!u || typeof u.sig !== 'string' || u.sig.length === 0) return null;
126
+ if (typeof secret !== 'string' || secret.length === 0) return false;
127
+ const { id, email, exp, sig } = u;
128
+ if (typeof id !== 'string' || !Number.isSafeInteger(exp)) return false;
129
+ if (email !== undefined && email !== null && typeof email !== 'string') return false;
130
+ const createdMs = typeof r.createdAt === 'string' ? Date.parse(r.createdAt) : NaN;
131
+ if (!Number.isFinite(createdMs) || exp * 1000 < createdMs - REPORTER_EXP_SKEW_MS) return false;
132
+ const expected = crypto.createHmac('sha256', secret)
133
+ .update(`v1|${id}|${typeof email === 'string' ? email : ''}|${exp}`)
134
+ .digest();
135
+ const given = Buffer.from(sig, 'utf8');
136
+ const want = Buffer.from(expected.toString('base64url'), 'utf8');
137
+ if (given.length !== want.length) return false;
138
+ return crypto.timingSafeEqual(given, want);
139
+ }
140
+
141
+ /** @typedef {'keystore' | 'relay' | 'open' | 'write'} DrainStage */
142
+
143
+ const DENIED_CODES = new Set(['EACCES', 'EPERM', 'EROFS']);
144
+
145
+ /**
146
+ * Map an error thrown mid-box to a fixed, content-free code for the log line. A write-stage
147
+ * error without a system errno is a boundary/ownership refusal (config.cjs validateWrite,
148
+ * opsOwnership assertOpsWrite, siteFeedbackInbox's own cwd checks): write_denied.
149
+ * @param {DrainStage} stage
150
+ * @param {unknown} e
151
+ * @returns {string}
152
+ */
153
+ function classifyError(stage, e) {
154
+ const code = e && typeof e === 'object' ? /** @type {any} */ (e).code : undefined;
155
+ if (stage === 'write') {
156
+ if (typeof code !== 'string' || DENIED_CODES.has(code)) return 'write_denied';
157
+ return 'io_error';
158
+ }
159
+ if (stage === 'relay') return 'relay_error';
160
+ if (stage === 'open') return 'open_failed';
161
+ return 'keystore_error';
162
+ }
163
+
164
+ /**
165
+ * A drain instance: its own single-flight promise, gone set and 429 deferrals.
166
+ * @param {DrainDeps} [defaults]
167
+ */
168
+ function createDrain(defaults = {}) {
169
+ /** @type {Promise<DrainResult> | null} */
170
+ let inFlight = null;
171
+ /** @type {Set<string>} */
172
+ const gone = new Set();
173
+ /** @type {Map<string, number>} boxId -> epoch ms before which the box is not polled */
174
+ const deferredUntil = new Map();
175
+ /** @type {DrainRelay | null} */
176
+ let lazyRelay = null;
177
+ /** @type {Map<string, number>} projectCwd -> epoch ms of the last prune attempt */
178
+ const lastPruneAt = new Map();
179
+
180
+ /** @param {DrainDeps} deps */
181
+ function resolveDeps(deps) {
182
+ const d = { ...defaults, ...(deps || {}) };
183
+ const relay = d.relay || (lazyRelay = lazyRelay || defaultRelay());
184
+ return {
185
+ relay,
186
+ keystore: d.keystore || /** @type {DrainKeystore} */ (require('./feedbackBoxKeys.cjs')),
187
+ inbox: d.inbox || /** @type {DrainInbox} */ (require('./siteFeedbackInbox.cjs')),
188
+ now: d.now || Date.now,
189
+ cwdExists: d.cwdExists || defaultCwdExists,
190
+ feedbackInboxDays: d.feedbackInboxDays || defaultFeedbackInboxDays,
191
+ log: d.log || defaultLog,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Classify a relay failure. Returns 'gone' for 404 box_not_found, else 'stop'.
197
+ * @param {string} boxId
198
+ * @param {RelayFailure} fail
199
+ * @param {ReturnType<typeof resolveDeps>} d
200
+ * @returns {'gone' | 'stop'}
201
+ */
202
+ function onRelayFailure(boxId, fail, d) {
203
+ if (fail.status === 404 && fail.error === 'box_not_found') {
204
+ gone.add(boxId);
205
+ d.log(`box ${boxId} is gone on the relay (box_not_found)`);
206
+ return 'gone';
207
+ }
208
+ if (fail.status === 429) {
209
+ const sec = typeof fail.retryAfterSec === 'number' && fail.retryAfterSec >= 0
210
+ ? fail.retryAfterSec : DEFAULT_RETRY_AFTER_SEC;
211
+ deferredUntil.set(boxId, d.now() + sec * 1000);
212
+ d.log(`box ${boxId} rate limited; deferred ${sec}s`);
213
+ return 'stop';
214
+ }
215
+ d.log(`box ${boxId} stopped for this pass (${fail.status} ${safeCode(fail.error)})`);
216
+ return 'stop';
217
+ }
218
+
219
+ /**
220
+ * @param {DrainBox} box
221
+ * @param {Record<string, unknown>} privateKeyJwk
222
+ * @param {ReturnType<typeof resolveDeps>} d
223
+ * @param {DrainResult} result
224
+ * @param {{ stage: DrainStage }} ctx updated before each step so a throw can be classified
225
+ */
226
+ async function drainBox(box, privateKeyJwk, d, result, ctx) {
227
+ const { boxId, projectCwd: cwd } = box;
228
+ /** @type {Set<string>} */
229
+ const handled = new Set();
230
+ for (let page = 0; page < MAX_PAGES_PER_BOX; page++) {
231
+ ctx.stage = 'relay';
232
+ const listed = await d.relay.listEnvelopes(boxId, PAGE_LIMIT);
233
+ if (!listed.ok) {
234
+ if (onRelayFailure(boxId, listed, d) === 'gone') result.goneBoxes.push(boxId);
235
+ return;
236
+ }
237
+ const fresh = listed.envelopes.filter((e) => e && typeof e.envelopeId === 'string' && !handled.has(e.envelopeId));
238
+ if (fresh.length === 0) return;
239
+ for (const env of fresh) {
240
+ handled.add(env.envelopeId);
241
+ ctx.stage = 'relay';
242
+ const got = await d.relay.getEnvelope(boxId, env.envelopeId);
243
+ if (!got.ok) {
244
+ if (got.status === 404 && got.error === 'envelope_not_found') continue;
245
+ if (onRelayFailure(boxId, got, d) === 'gone') result.goneBoxes.push(boxId);
246
+ return;
247
+ }
248
+ const bytes = got.body.length;
249
+ const hostId = typeof env.hostId === 'string' ? env.hostId : '';
250
+ const metaOk = HOST_ID_RE.test(hostId)
251
+ && typeof env.receivedAt === 'string' && env.receivedAt.length > 0
252
+ && typeof env.origin === 'string' && env.origin.length > 0;
253
+ ctx.stage = 'open';
254
+ const opened = metaOk
255
+ ? await openReportEnvelope(got.body, { privateKeyJwk, boxId })
256
+ : /** @type {const} */ ({ ok: false, code: 'bad_metadata' });
257
+ ctx.stage = 'write';
258
+ if (!opened.ok) {
259
+ await d.inbox.appendRejected({ cwd, at: new Date(d.now()).toISOString(), boxId, hostId, code: opened.code, bytes });
260
+ result.rejected += 1;
261
+ d.log(`box ${boxId} rejected ${hostId || '(no host id)'} (${opened.code})`);
262
+ } else {
263
+ /** @type {{ duplicate: boolean, hostId: string } | null} */
264
+ let w = null;
265
+ let reporterVerified = verifyReporter(opened.report, null);
266
+ if (reporterVerified !== null) {
267
+ ctx.stage = 'keystore';
268
+ const secret = d.keystore.peekIdentitySecret ? await d.keystore.peekIdentitySecret(boxId) : null;
269
+ reporterVerified = verifyReporter(opened.report, secret);
270
+ ctx.stage = 'write';
271
+ }
272
+ try {
273
+ w = await d.inbox.writeItem({
274
+ cwd, hostId, boxId, receivedAt: env.receivedAt, origin: env.origin,
275
+ report: opened.report, screenshot: opened.screenshot, annotated: opened.annotated,
276
+ reporterVerified,
277
+ });
278
+ } catch (e) {
279
+ if (!isHostIdClash(e)) throw e;
280
+ }
281
+ if (!w) {
282
+ await d.inbox.appendRejected({ cwd, at: new Date(d.now()).toISOString(), boxId, hostId, code: HOST_ID_CLASH, bytes });
283
+ result.rejected += 1;
284
+ d.log(`box ${boxId} rejected ${hostId} (${HOST_ID_CLASH})`);
285
+ } else if (w.duplicate) result.duplicates += 1;
286
+ else result.stored += 1;
287
+ }
288
+ ctx.stage = 'relay';
289
+ const acked = await d.relay.ackEnvelope(boxId, env.envelopeId);
290
+ if (!acked.ok) {
291
+ if (acked.status === 404 && acked.error === 'envelope_not_found') continue;
292
+ if (onRelayFailure(boxId, acked, d) === 'gone') result.goneBoxes.push(boxId);
293
+ return;
294
+ }
295
+ }
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Prune the project's feedback-inbox at most once per PRUNE_EVERY_MS. A failure is logged with
301
+ * a fixed code and not retried until the next window.
302
+ * @param {string} cwd
303
+ * @param {ReturnType<typeof resolveDeps>} d
304
+ */
305
+ async function maybePrune(cwd, d) {
306
+ const now = d.now();
307
+ const last = lastPruneAt.get(cwd);
308
+ if (last !== undefined && now - last < PRUNE_EVERY_MS) return;
309
+ lastPruneAt.set(cwd, now);
310
+ try {
311
+ await d.inbox.prune(cwd, d.feedbackInboxDays());
312
+ } catch {
313
+ d.log('feedback-inbox prune failed (prune_failed)');
314
+ }
315
+ }
316
+
317
+ /**
318
+ * @param {DrainDeps} deps
319
+ * @returns {Promise<DrainResult>}
320
+ */
321
+ async function runPass(deps) {
322
+ const d = resolveDeps(deps);
323
+ /** @type {DrainResult} */
324
+ const result = { stored: 0, duplicates: 0, rejected: 0, goneBoxes: [], heldBoxes: [] };
325
+ /** @type {DrainBox[]} */
326
+ let boxes;
327
+ try {
328
+ boxes = await d.keystore.listBoxes();
329
+ } catch {
330
+ d.log('could not read the box keystore');
331
+ return result;
332
+ }
333
+ const known = new Set(boxes.map((b) => b.boxId));
334
+ for (const id of [...gone]) if (!known.has(id)) gone.delete(id);
335
+ for (const id of [...deferredUntil.keys()]) if (!known.has(id)) deferredUntil.delete(id);
336
+
337
+ for (const box of boxes) {
338
+ if (gone.has(box.boxId)) {
339
+ result.goneBoxes.push(box.boxId);
340
+ continue;
341
+ }
342
+ const until = deferredUntil.get(box.boxId);
343
+ if (until !== undefined) {
344
+ if (d.now() < until) continue;
345
+ deferredUntil.delete(box.boxId);
346
+ }
347
+ if (!d.cwdExists(box.projectCwd)) {
348
+ result.heldBoxes.push(box.boxId);
349
+ continue;
350
+ }
351
+ /** @type {{ stage: DrainStage }} */
352
+ const ctx = { stage: 'keystore' };
353
+ try {
354
+ const key = await d.keystore.getPrivateKey(box.boxId);
355
+ if (!key) continue;
356
+ await drainBox(box, key, d, result, ctx);
357
+ } catch (e) {
358
+ d.log(`box ${box.boxId} stopped for this pass (${classifyError(ctx.stage, e)})`);
359
+ }
360
+ await maybePrune(box.projectCwd, d);
361
+ }
362
+ return result;
363
+ }
364
+
365
+ /**
366
+ * One drain pass; concurrent callers share the pass already running.
367
+ * @param {DrainDeps} [deps]
368
+ * @returns {Promise<DrainResult>}
369
+ */
370
+ function drainOnce(deps = {}) {
371
+ if (inFlight) return inFlight;
372
+ const p = runPass(deps).finally(() => {
373
+ inFlight = null;
374
+ });
375
+ inFlight = p;
376
+ return p;
377
+ }
378
+
379
+ /**
380
+ * Run drainOnce every intervalMs on an unref'd timer.
381
+ * @param {DrainDeps & { intervalMs?: number }} [opts]
382
+ */
383
+ function startDrainLoop(opts = {}) {
384
+ const { intervalMs = DEFAULT_INTERVAL_MS, ...deps } = opts;
385
+ const tick = () => {
386
+ drainOnce(deps).catch(() => { /* a pass never rejects; belt and braces for the timer */ });
387
+ };
388
+ const timer = setInterval(tick, intervalMs);
389
+ if (typeof timer.unref === 'function') timer.unref();
390
+ return {
391
+ drainNow: () => drainOnce(deps),
392
+ stop: () => clearInterval(timer),
393
+ };
394
+ }
395
+
396
+ return { drainOnce, startDrainLoop };
397
+ }
398
+
399
+ const defaultDrain = createDrain();
400
+
401
+ module.exports = {
402
+ createDrain,
403
+ drainOnce: defaultDrain.drainOnce,
404
+ startDrainLoop: defaultDrain.startDrainLoop,
405
+ PAGE_LIMIT,
406
+ DEFAULT_INTERVAL_MS,
407
+ PRUNE_EVERY_MS,
408
+ verifyReporter,
409
+ };