claude-code-session-manager 0.141.0 → 0.143.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,477 @@
1
+ // @ts-check
2
+ /**
3
+ * siteFeedbackService — the ONE implementation of every website-feedback widget setting and
4
+ * inbox action. The desktop UI (IPC) and the Feedback MCP (admin routes) both call these
5
+ * functions, so the two can never disagree. Data path:
6
+ * session-manager-operations/architecture/site-feedback.md.
7
+ *
8
+ * Widgets (sealed drop boxes on the bilko.run relay):
9
+ * createWidget / listWidgets / updateWidget / deleteWidget / getSnippet
10
+ * - createWidget generates the box key pair (feedbackSeal), registers the box on the relay
11
+ * (feedbackRelayClient) and only then stores the private key (feedbackBoxKeys).
12
+ * - Relay error codes are passed through verbatim as `error`, with a one-line `message`.
13
+ * getIdentitySecret / rotateIdentitySecret — the box's reporter-signing HMAC secret, local
14
+ * keystore only (never the relay, never the widget); the site owner pastes it into their backend.
15
+ * Inbox (decrypted reports in <project>/session-manager-operations/feedback-inbox/):
16
+ * listItems / getItem / getImage / setStatus / linkEpic delegate to siteFeedbackInbox;
17
+ * drainNow / startDrainLoop delegate to feedbackBoxDrain.
18
+ *
19
+ * Every function resolves `{ ok: true, ... }` or `{ ok: false, error, message }` and never
20
+ * throws. Nothing here logs report text, image bytes, a private key or the device token.
21
+ */
22
+ 'use strict';
23
+
24
+ const fsp = require('node:fs/promises');
25
+
26
+ const WIDGET_SCRIPT_URL = 'https://bilko.run/projects/session-manager/widget/v1/feedback.js';
27
+ const KEY_PREFIX = 'fbk1_';
28
+ const MAX_ORIGINS = 10;
29
+ const MAX_LABEL = 80;
30
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
31
+ const GONE_HINT = 'This widget no longer exists on bilko.run - create a new one';
32
+
33
+ /** One-line human explanations for the relay codes the UI and MCP pass through verbatim. */
34
+ const RELAY_ERROR_MESSAGES = Object.freeze({
35
+ not_linked: 'This desktop is not paired with bilko.run yet - pair it in App Settings > Phone remote first',
36
+ not_enabled: 'Website feedback is not enabled for this bilko.run account yet',
37
+ box_limit_reached: 'This bilko.run account already has the most feedback widgets it may have - delete one first',
38
+ device_token_required: 'Only the paired desktop can do this - the request did not carry its device token',
39
+ rate_limited: 'bilko.run is rate limiting these requests - wait a minute and try again',
40
+ });
41
+
42
+ /**
43
+ * @typedef {{ ok: false, error: string, message: string, status?: number, retryAfterSec?: number }} Failure
44
+ * @typedef {{ ok: false, status: number, error: string, retryAfterSec?: number }} RelayFailure
45
+ * @typedef {{ boxId: string, label?: string, allowedOrigins?: string[], state?: string, pending?: number }} RelayBox
46
+ * @typedef {{
47
+ * createBox: (input: { label: string, publicKey: string, allowedOrigins: string[] }) => Promise<{ ok: true, boxId: string, state?: string, createdAt?: string } | RelayFailure>,
48
+ * listBoxes: () => Promise<{ ok: true, boxes: RelayBox[] } | RelayFailure>,
49
+ * patchBox: (boxId: string, patch: { label?: string, allowedOrigins?: string[], state?: 'open'|'paused' }) => Promise<{ ok: true, box: RelayBox } | RelayFailure>,
50
+ * deleteBox: (boxId: string) => Promise<{ ok: true } | RelayFailure>,
51
+ * listEnvelopes: (boxId: string, limit?: number) => Promise<any>,
52
+ * getEnvelope: (boxId: string, envelopeId: string) => Promise<any>,
53
+ * ackEnvelope: (boxId: string, envelopeId: string) => Promise<any>,
54
+ * }} ServiceRelay
55
+ * @typedef {import('./feedbackBoxKeys.cjs')} ServiceKeystore
56
+ * @typedef {import('./siteFeedbackInbox.cjs')} ServiceInbox
57
+ * @typedef {'open'|'in_progress'|'resolved'|'wontfix'} InboxStatus
58
+ * @typedef {{ drainOnce: (deps?: any) => Promise<any>, startDrainLoop: (opts?: any) => { drainNow: () => Promise<any>, stop: () => void } }} ServiceDrain
59
+ * @typedef {{ relay?: ServiceRelay, keystore?: ServiceKeystore, inbox?: ServiceInbox, drain?: ServiceDrain,
60
+ * seal?: { generateBoxKeypair: () => { publicKey: string, privateKeyJwk: object }, keyFingerprint: (pk: string) => string } }} ServiceDeps
61
+ */
62
+
63
+ /**
64
+ * @param {string} error
65
+ * @param {string} [message]
66
+ * @returns {Failure}
67
+ */
68
+ function failure(error, message) {
69
+ return { ok: false, error, message: message || RELAY_ERROR_MESSAGES[/** @type {keyof typeof RELAY_ERROR_MESSAGES} */ (error)] || `bilko.run refused the request (${error})` };
70
+ }
71
+
72
+ /**
73
+ * A relay failure passed through verbatim, with its one-line explanation.
74
+ * @param {RelayFailure} r
75
+ * @returns {Failure}
76
+ */
77
+ function relayFailure(r) {
78
+ /** @type {Failure} */
79
+ const out = { ...failure(r.error), status: r.status };
80
+ return typeof r.retryAfterSec === 'number' ? { ...out, retryAfterSec: r.retryAfterSec } : out;
81
+ }
82
+
83
+ /** @param {unknown} e */
84
+ function errMessage(e) {
85
+ return e instanceof Error ? e.message : String(e);
86
+ }
87
+
88
+ /** @param {unknown} v @returns {v is string} */
89
+ function nonEmpty(v) {
90
+ return typeof v === 'string' && v.length > 0;
91
+ }
92
+
93
+ /**
94
+ * Normalise each origin to new URL(o).origin and drop duplicates. Only https:, or
95
+ * http://localhost / http://127.0.0.1, and 1-10 entries.
96
+ * @param {unknown} origins
97
+ * @returns {{ ok: true, origins: string[] } | Failure}
98
+ */
99
+ function normalizeOrigins(origins) {
100
+ if (!Array.isArray(origins)) return failure('invalid_allowed_origins', 'allowedOrigins must be a list of 1-10 origins');
101
+ /** @type {string[]} */
102
+ const out = [];
103
+ for (const o of origins) {
104
+ if (typeof o !== 'string') return failure('invalid_allowed_origins', 'Every allowed origin must be a string');
105
+ /** @type {URL} */
106
+ let url;
107
+ try {
108
+ url = new URL(o.trim());
109
+ } catch {
110
+ return failure('invalid_allowed_origins', `Not a valid origin: ${o.slice(0, 200)}`);
111
+ }
112
+ const ok = url.protocol === 'https:'
113
+ || (url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1'));
114
+ if (!ok) {
115
+ return failure('invalid_allowed_origins', `Origin must be https, or http://localhost / http://127.0.0.1: ${o.slice(0, 200)}`);
116
+ }
117
+ if (!out.includes(url.origin)) out.push(url.origin);
118
+ }
119
+ if (out.length < 1 || out.length > MAX_ORIGINS) {
120
+ return failure('invalid_allowed_origins', `allowedOrigins must hold 1-${MAX_ORIGINS} distinct origins`);
121
+ }
122
+ return { ok: true, origins: out };
123
+ }
124
+
125
+ /** @param {unknown} label @returns {{ ok: true, label: string } | Failure} */
126
+ function normalizeLabel(label) {
127
+ const s = typeof label === 'string' ? label.trim() : '';
128
+ if (s.length < 1 || s.length > MAX_LABEL) return failure('invalid_label', `label must be 1-${MAX_LABEL} characters`);
129
+ return { ok: true, label: s };
130
+ }
131
+
132
+ /**
133
+ * The one-line embed for a box.
134
+ * @param {string} boxId
135
+ * @param {string} fingerprint
136
+ */
137
+ function snippetFor(boxId, fingerprint) {
138
+ return `<script src="${WIDGET_SCRIPT_URL}" data-key="${KEY_PREFIX}${boxId}.${fingerprint}" async></script>`;
139
+ }
140
+
141
+ /** @returns {ServiceRelay} */
142
+ function defaultRelay() {
143
+ const { createRelayClient } = require('./feedbackRelayClient.cjs');
144
+ return createRelayClient({
145
+ getDeviceToken: () => require('../../webRemote.cjs').getLinkedDeviceToken(),
146
+ });
147
+ }
148
+
149
+ /**
150
+ * A service instance. Every dependency is injectable (tests); the defaults are the real
151
+ * relay client (paired device token), keystore, inbox and drain.
152
+ * @param {ServiceDeps} [deps]
153
+ */
154
+ function createSiteFeedbackService(deps = {}) {
155
+ /** @type {ServiceRelay | null} */
156
+ let lazyRelay = deps.relay || null;
157
+ const relay = () => (lazyRelay = lazyRelay || defaultRelay());
158
+ const keystore = () => deps.keystore || require('./feedbackBoxKeys.cjs');
159
+ const inbox = () => deps.inbox || require('./siteFeedbackInbox.cjs');
160
+ const drain = () => deps.drain || require('./feedbackBoxDrain.cjs');
161
+ const seal = () => deps.seal || require('./feedbackSeal.cjs');
162
+ const drainDeps = () => ({ relay: relay(), keystore: keystore(), inbox: inbox() });
163
+ /** @type {{ drainNow: () => Promise<any>, stop: () => void } | null} */
164
+ let loop = null;
165
+
166
+ /** @param {string} boxId */
167
+ async function localBox(boxId) {
168
+ const all = await keystore().listBoxes();
169
+ return all.find((b) => b.boxId === boxId) || null;
170
+ }
171
+
172
+ /**
173
+ * @param {{ cwd: string, label: string, allowedOrigins: string[] }} p
174
+ */
175
+ async function createWidget(p) {
176
+ const { cwd, label, allowedOrigins } = p || /** @type {any} */ ({});
177
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
178
+ const l = normalizeLabel(label);
179
+ if (!l.ok) return l;
180
+ const o = normalizeOrigins(allowedOrigins);
181
+ if (!o.ok) return o;
182
+ try {
183
+ const kp = seal().generateBoxKeypair();
184
+ const fingerprint = seal().keyFingerprint(kp.publicKey);
185
+ const created = await relay().createBox({ label: l.label, publicKey: kp.publicKey, allowedOrigins: o.origins });
186
+ if (!created.ok) return relayFailure(created);
187
+ try {
188
+ await keystore().addBox({
189
+ boxId: created.boxId, projectCwd: cwd, label: l.label, publicKey: kp.publicKey,
190
+ fingerprint, privateKeyJwk: /** @type {Record<string, unknown>} */ (kp.privateKeyJwk),
191
+ });
192
+ } catch (e) {
193
+ // Without its private key the box could never be opened: take it back off the relay.
194
+ await relay().deleteBox(created.boxId).catch(() => {});
195
+ return failure('keystore_failed', `The widget key could not be saved: ${errMessage(e)}`);
196
+ }
197
+ return { ok: /** @type {const} */ (true), boxId: created.boxId, fingerprint, snippet: snippetFor(created.boxId, fingerprint) };
198
+ } catch (e) {
199
+ return failure('internal', errMessage(e));
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Local records merged with relay state. A local box the relay no longer lists is 'gone'.
205
+ * When the relay cannot be read, widgets carry state 'unknown' and `relayError` says why.
206
+ * @param {{ cwd?: string }} [p]
207
+ */
208
+ async function listWidgets(p = {}) {
209
+ try {
210
+ const cwd = p && nonEmpty(p.cwd) ? p.cwd : undefined;
211
+ const local = await keystore().listBoxes(cwd ? { projectCwd: cwd } : undefined);
212
+ const remote = await relay().listBoxes();
213
+ /** @type {Map<string, RelayBox>} */
214
+ const byId = new Map();
215
+ if (remote.ok) for (const b of remote.boxes) if (b && nonEmpty(b.boxId)) byId.set(b.boxId, b);
216
+ const widgets = local.map((b) => {
217
+ const r = byId.get(b.boxId);
218
+ const base = {
219
+ boxId: b.boxId,
220
+ projectCwd: b.projectCwd,
221
+ fingerprint: b.fingerprint,
222
+ createdAt: b.createdAt,
223
+ snippet: snippetFor(b.boxId, b.fingerprint),
224
+ };
225
+ if (!remote.ok) {
226
+ return { ...base, label: b.label, allowedOrigins: /** @type {string[]} */ ([]), state: 'unknown', pending: null, hint: null };
227
+ }
228
+ if (!r) {
229
+ return { ...base, label: b.label, allowedOrigins: /** @type {string[]} */ ([]), state: 'gone', pending: 0, hint: GONE_HINT };
230
+ }
231
+ return {
232
+ ...base,
233
+ label: typeof r.label === 'string' ? r.label : b.label,
234
+ allowedOrigins: Array.isArray(r.allowedOrigins) ? r.allowedOrigins : [],
235
+ state: typeof r.state === 'string' ? r.state : 'unknown',
236
+ pending: typeof r.pending === 'number' ? r.pending : 0,
237
+ hint: null,
238
+ };
239
+ });
240
+ return remote.ok
241
+ ? { ok: /** @type {const} */ (true), widgets }
242
+ : { ok: /** @type {const} */ (true), widgets, relayError: relayFailure(remote) };
243
+ } catch (e) {
244
+ return failure('internal', errMessage(e));
245
+ }
246
+ }
247
+
248
+ /**
249
+ * @param {{ boxId: string, label?: string, allowedOrigins?: string[], state?: 'open'|'paused' }} p
250
+ */
251
+ async function updateWidget(p) {
252
+ const { boxId, label, allowedOrigins, state } = p || /** @type {any} */ ({});
253
+ if (!nonEmpty(boxId)) return failure('invalid_input', 'boxId is required');
254
+ /** @type {{ label?: string, allowedOrigins?: string[], state?: 'open'|'paused' }} */
255
+ const patch = {};
256
+ if (label !== undefined) {
257
+ const l = normalizeLabel(label);
258
+ if (!l.ok) return l;
259
+ patch.label = l.label;
260
+ }
261
+ if (allowedOrigins !== undefined) {
262
+ const o = normalizeOrigins(allowedOrigins);
263
+ if (!o.ok) return o;
264
+ patch.allowedOrigins = o.origins;
265
+ }
266
+ if (state !== undefined) {
267
+ if (state !== 'open' && state !== 'paused') return failure('invalid_state', "state must be 'open' or 'paused'");
268
+ patch.state = state;
269
+ }
270
+ if (Object.keys(patch).length === 0) return failure('invalid_input', 'Nothing to update: give label, allowedOrigins or state');
271
+ try {
272
+ if (!(await localBox(boxId))) return failure('not_found', `No widget ${boxId} on this desktop`);
273
+ const r = await relay().patchBox(boxId, patch);
274
+ if (!r.ok) {
275
+ if (r.status === 404 && r.error === 'box_not_found') return { ...relayFailure(r), message: GONE_HINT };
276
+ return relayFailure(r);
277
+ }
278
+ const b = r.box || /** @type {RelayBox} */ ({ boxId });
279
+ return {
280
+ ok: /** @type {const} */ (true),
281
+ widget: { boxId, label: b.label, allowedOrigins: b.allowedOrigins, state: b.state, pending: b.pending },
282
+ };
283
+ } catch (e) {
284
+ return failure('internal', errMessage(e));
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Deletes on the relay, then locally. A box the relay no longer has is removed locally too.
290
+ * @param {{ boxId: string }} p
291
+ */
292
+ async function deleteWidget(p) {
293
+ const boxId = p && p.boxId;
294
+ if (!nonEmpty(boxId)) return failure('invalid_input', 'boxId is required');
295
+ try {
296
+ if (!(await localBox(boxId))) return failure('not_found', `No widget ${boxId} on this desktop`);
297
+ const r = await relay().deleteBox(boxId);
298
+ if (!r.ok && !(r.status === 404 && r.error === 'box_not_found')) return relayFailure(r);
299
+ await keystore().removeBox(boxId);
300
+ return { ok: /** @type {const} */ (true), boxId };
301
+ } catch (e) {
302
+ return failure('internal', errMessage(e));
303
+ }
304
+ }
305
+
306
+ /** @param {{ boxId: string }} p */
307
+ async function getSnippet(p) {
308
+ const boxId = p && p.boxId;
309
+ if (!nonEmpty(boxId)) return failure('invalid_input', 'boxId is required');
310
+ try {
311
+ const b = await localBox(boxId);
312
+ if (!b) return failure('not_found', `No widget ${boxId} on this desktop`);
313
+ return { ok: /** @type {const} */ (true), boxId, fingerprint: b.fingerprint, snippet: snippetFor(boxId, b.fingerprint) };
314
+ } catch (e) {
315
+ return failure('internal', errMessage(e));
316
+ }
317
+ }
318
+
319
+ /**
320
+ * @param {string | { boxId: string }} p
321
+ * @param {boolean} rotate
322
+ */
323
+ async function identitySecret(p, rotate) {
324
+ const boxId = typeof p === 'string' ? p : p && p.boxId;
325
+ if (!nonEmpty(boxId)) return failure('invalid_input', 'boxId is required');
326
+ try {
327
+ if (!(await localBox(boxId))) return failure('not_found', `No widget ${boxId} on this desktop`);
328
+ const ks = keystore();
329
+ const secret = rotate ? await ks.rotateIdentitySecret(boxId) : await ks.getIdentitySecret(boxId);
330
+ if (!secret) return failure('not_found', `No widget ${boxId} on this desktop`);
331
+ return { ok: /** @type {const} */ (true), boxId, identitySecret: secret };
332
+ } catch (e) {
333
+ return failure('internal', errMessage(e));
334
+ }
335
+ }
336
+
337
+ /**
338
+ * The box's reporter-signing secret, created on first request. Never logged, never sent to
339
+ * the relay; only the desktop UI asks for it, on an explicit user action.
340
+ * @param {string | { boxId: string }} p
341
+ */
342
+ function getIdentitySecret(p) {
343
+ return identitySecret(p, false);
344
+ }
345
+
346
+ /** Replace the box's reporter-signing secret. @param {string | { boxId: string }} p */
347
+ function rotateIdentitySecret(p) {
348
+ return identitySecret(p, true);
349
+ }
350
+
351
+ /** @param {{ cwd: string, status?: InboxStatus }} p */
352
+ async function listItems(p) {
353
+ const { cwd, status } = p || /** @type {any} */ ({});
354
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
355
+ try {
356
+ return { ok: /** @type {const} */ (true), items: await inbox().list(cwd, status ? { status } : {}) };
357
+ } catch (e) {
358
+ return failure('invalid_input', errMessage(e));
359
+ }
360
+ }
361
+
362
+ /** @param {{ cwd: string, hostId: string }} p */
363
+ async function getItem(p) {
364
+ const { cwd, hostId } = p || /** @type {any} */ ({});
365
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
366
+ try {
367
+ const item = await inbox().get(cwd, hostId);
368
+ if (!item) return failure('not_found', `No feedback item ${hostId}`);
369
+ return { ok: /** @type {const} */ (true), item };
370
+ } catch (e) {
371
+ return failure('invalid_input', errMessage(e));
372
+ }
373
+ }
374
+
375
+ /**
376
+ * One stored image as a data URL, only after its bytes sniff as PNG.
377
+ * @param {{ cwd: string, hostId: string, which?: 'screenshot'|'annotated' }} p
378
+ */
379
+ async function getImage(p) {
380
+ const { cwd, hostId, which = 'annotated' } = p || /** @type {any} */ ({});
381
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
382
+ if (which !== 'screenshot' && which !== 'annotated') return failure('invalid_input', "which must be 'screenshot' or 'annotated'");
383
+ try {
384
+ const item = await inbox().get(cwd, hostId);
385
+ if (!item) return failure('not_found', `No feedback item ${hostId}`);
386
+ const file = item.imagePaths[/** @type {'screenshot'|'annotated'} */ (which)];
387
+ if (!file) return failure('not_found', `Feedback item ${hostId} has no ${which} image`);
388
+ const buf = await fsp.readFile(file);
389
+ if (buf.length < PNG_SIGNATURE.length || !buf.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
390
+ return failure('not_png', `The stored ${which} image is not a PNG`);
391
+ }
392
+ return { ok: /** @type {const} */ (true), hostId, which, dataUrl: `data:image/png;base64,${buf.toString('base64')}` };
393
+ } catch (e) {
394
+ return failure('invalid_input', errMessage(e));
395
+ }
396
+ }
397
+
398
+ /** @param {{ cwd: string, hostId: string, status: InboxStatus, note?: string | null }} p */
399
+ async function setStatus(p) {
400
+ const { cwd, hostId, status, note } = p || /** @type {any} */ ({});
401
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
402
+ try {
403
+ return { ok: /** @type {const} */ (true), meta: await inbox().setStatus(cwd, hostId, status, note ?? null) };
404
+ } catch (e) {
405
+ const msg = errMessage(e);
406
+ return failure(/no item/.test(msg) ? 'not_found' : 'invalid_input', msg);
407
+ }
408
+ }
409
+
410
+ /** @param {{ cwd: string, hostId: string, epicId: string }} p */
411
+ async function linkEpic(p) {
412
+ const { cwd, hostId, epicId } = p || /** @type {any} */ ({});
413
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
414
+ try {
415
+ return { ok: /** @type {const} */ (true), meta: await inbox().linkEpic(cwd, hostId, epicId) };
416
+ } catch (e) {
417
+ const msg = errMessage(e);
418
+ return failure(/no item/.test(msg) ? 'not_found' : 'invalid_input', msg);
419
+ }
420
+ }
421
+
422
+ /** Delete one stored item (its report, images and meta). @param {{ cwd: string, hostId: string }} p */
423
+ async function removeItem(p) {
424
+ const { cwd, hostId } = p || /** @type {any} */ ({});
425
+ if (!nonEmpty(cwd)) return failure('invalid_input', 'cwd is required');
426
+ try {
427
+ const r = await inbox().remove(cwd, hostId);
428
+ if (!r.removed) return failure('not_found', `No feedback item ${hostId}`);
429
+ return { ok: /** @type {const} */ (true), hostId };
430
+ } catch (e) {
431
+ return failure('invalid_input', errMessage(e));
432
+ }
433
+ }
434
+
435
+ /** One drain pass now (shares a pass already running). */
436
+ async function drainNow() {
437
+ try {
438
+ const result = loop ? await loop.drainNow() : await drain().drainOnce(drainDeps());
439
+ return { ok: /** @type {const} */ (true), ...result };
440
+ } catch (e) {
441
+ return failure('internal', errMessage(e));
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Start the periodic drain once (idempotent).
447
+ * @param {{ intervalMs?: number }} [opts]
448
+ */
449
+ function startDrainLoop(opts = {}) {
450
+ if (!loop) loop = drain().startDrainLoop({ ...drainDeps(), ...(opts || {}) });
451
+ return loop;
452
+ }
453
+
454
+ function stopDrainLoop() {
455
+ if (loop) loop.stop();
456
+ loop = null;
457
+ }
458
+
459
+ return {
460
+ createWidget, listWidgets, updateWidget, deleteWidget, getSnippet,
461
+ getIdentitySecret, rotateIdentitySecret,
462
+ listItems, getItem, getImage, setStatus, linkEpic, removeItem, drainNow,
463
+ startDrainLoop, stopDrainLoop,
464
+ };
465
+ }
466
+
467
+ const defaultService = createSiteFeedbackService();
468
+
469
+ module.exports = {
470
+ ...defaultService,
471
+ createSiteFeedbackService,
472
+ normalizeOrigins,
473
+ snippetFor,
474
+ RELAY_ERROR_MESSAGES,
475
+ GONE_HINT,
476
+ WIDGET_SCRIPT_URL,
477
+ };
@@ -980,6 +980,14 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
980
980
  const epicDir = worktreeDirFor(kind, cwd, key);
981
981
  const epicBranch = branchNameFor(kind, key);
982
982
  if (fs.existsSync(epicDir) && await isRegisteredWorktreeOnBranch(cwd, epicDir, epicBranch)) {
983
+ // node_modules links are a snapshot from mint time: pick up packages main gained
984
+ // since (and drop links main lost). Best-effort — never fails the reuse.
985
+ try {
986
+ const sync = await require('./worktreeDeps.cjs').syncNodeModulesLinks({ mainCwd: cwd, worktreeCwd: epicDir });
987
+ if (sync && (sync.added || sync.removed)) console.log(`[gitWorktree] synced dep links: +${sync.added} -${sync.removed} -> ${epicDir}`);
988
+ } catch (err) {
989
+ console.warn(`[gitWorktree] dep link sync failed for ${epicDir}: ${(err && err.message) || err}`);
990
+ }
983
991
  return { ok: true, dir: epicDir, branch: epicBranch, baseCwd: cwd, reused: true };
984
992
  }
985
993
  }
@@ -34,6 +34,20 @@ async function findTrackedRuntimeState(projectRoot) {
34
34
  return out.split('\0').filter((p) => p && path.posix.basename(p) !== 'README.md');
35
35
  }
36
36
 
37
+ /**
38
+ * Untracked runtime paths (repo-relative, posix) that git can see — i.e. not
39
+ * ignored by any .gitignore. Each one is a namespace missing its self-ignore.
40
+ */
41
+ async function findVisibleRuntimeState(projectRoot) {
42
+ let out;
43
+ try {
44
+ out = await execGit(projectRoot, ['ls-files', '-z', '--others', '--exclude-standard', '--', ...nsPathspecs()], { maxBuffer: 64 * 1024 * 1024 });
45
+ } catch {
46
+ return [];
47
+ }
48
+ return out.split('\0').filter(Boolean);
49
+ }
50
+
37
51
  /** Sorted list of every file on disk under the runtime namespaces. */
38
52
  function listRuntimeFilesOnDisk(projectRoot) {
39
53
  const found = [];
@@ -121,4 +135,4 @@ async function untrackRuntimeState(projectRoot, opts = {}) {
121
135
  }
122
136
  }
123
137
 
124
- module.exports = { findTrackedRuntimeState, untrackRuntimeState, listRuntimeFilesOnDisk };
138
+ module.exports = { findTrackedRuntimeState, findVisibleRuntimeState, untrackRuntimeState, listRuntimeFilesOnDisk };