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.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +76 -153
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
- package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
- package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
- package/dist/assets/Scheduler-CNLjn90m.js +16 -0
- package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
- package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
- package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
- package/dist/assets/Toggle-CYajnSdx.js +1 -0
- package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
- package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
- package/dist/assets/index-CdTppjKR.js +3133 -0
- package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +496 -484
- package/package.json +6 -4
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/hooks/hooks.json +15 -0
- package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
- package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +5 -1
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
- package/scripts/scheduler-mcp-server.cjs +1032 -112
- package/src/main/adminRouteRegistry.cjs +69 -0
- package/src/main/agentLibrary.cjs +72 -4
- package/src/main/agentsIpc.cjs +3 -2
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +336 -23
- package/src/main/config.cjs +35 -1
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +129 -2
- package/src/main/index.cjs +110 -52
- package/src/main/ipcSchemas.cjs +172 -8
- package/src/main/lib/AGENTS.md +1 -1
- package/src/main/lib/chatBootRecovery.cjs +2 -0
- package/src/main/lib/claude/agentModelResolve.cjs +51 -25
- package/src/main/lib/claude/agentSnapshot.cjs +186 -0
- package/src/main/lib/claude/environmentProfiles.cjs +242 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
- package/src/main/lib/claude/personaToolScope.cjs +82 -31
- package/src/main/lib/claude/runClaudeP.cjs +4 -2
- package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
- package/src/main/lib/claude/usageCircuit.cjs +49 -21
- package/src/main/lib/claude/vaultRefs.cjs +277 -0
- package/src/main/lib/demo-video-kit/capture.cjs +282 -12
- package/src/main/lib/demo-video-kit/cast.md +52 -0
- package/src/main/lib/demo-video-kit/character.cjs +778 -30
- package/src/main/lib/demo-video-kit/checks.cjs +120 -1
- package/src/main/lib/demo-video-kit/export.cjs +218 -0
- package/src/main/lib/demo-video-kit/frames.cjs +104 -9
- package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
- package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
- package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
- package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
- package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
- package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
- package/src/main/lib/demo-video-kit/sound.cjs +166 -9
- package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
- package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
- package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
- package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
- package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
- package/src/main/lib/epic/artifactIpc.cjs +153 -0
- package/src/main/lib/epic/artifactNotice.cjs +72 -0
- package/src/main/lib/epic/artifactRetention.cjs +356 -0
- package/src/main/lib/epic/artifactStore.cjs +435 -0
- package/src/main/lib/epic/delegationReadiness.cjs +83 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +258 -0
- package/src/main/lib/epic/epicMint.cjs +43 -1
- package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
- package/src/main/lib/epic/epicOutsideState.cjs +18 -4
- package/src/main/lib/epic/epicPurge.cjs +347 -0
- package/src/main/lib/epic/epicReopen.cjs +5 -2
- package/src/main/lib/epic/epicSettle.cjs +4 -13
- package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
- package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
- package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
- package/src/main/lib/epic/epicTransitions.cjs +139 -0
- package/src/main/lib/epic/epicValidationHook.cjs +94 -4
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +48 -4
- package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
- package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
- package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
- package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
- package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
- package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
- package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
- package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
- package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
- package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
- package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
- package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
- package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
- package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
- package/src/main/lib/git/gitWorktree.cjs +8 -0
- package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
- package/src/main/lib/git/worktreeDeps.cjs +182 -4
- package/src/main/lib/mcpToolCatalog.cjs +399 -29
- package/src/main/lib/opsOwnership.cjs +141 -28
- package/src/main/lib/opsRetentionSettings.cjs +27 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
- package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
- package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
- package/src/main/lib/phaseProjection.cjs +103 -0
- package/src/main/lib/prd/depSlugResolve.cjs +4 -13
- package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
- package/src/main/lib/prd/prdCreate.cjs +387 -228
- package/src/main/lib/prd/prdCriteria.cjs +228 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
- package/src/main/lib/prd/prdGateFiles.cjs +125 -49
- package/src/main/lib/prd/prdSizing.cjs +3 -1
- package/src/main/lib/process/cleanEnv.cjs +52 -1
- package/src/main/lib/process/leftoverRenice.cjs +178 -0
- package/src/main/lib/process/memoryScope.cjs +31 -3
- package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
- package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
- package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
- package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
- package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
- package/src/main/lib/project-pages/voicePreview.cjs +196 -0
- package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
- package/src/main/lib/scheduler/cpuSample.cjs +133 -42
- package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
- package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
- package/src/main/lib/scheduler/queueStore.cjs +16 -0
- package/src/main/lib/scheduler/rcaReport.cjs +79 -15
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
- package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
- package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
- package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
- package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
- package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
- package/src/main/lib/tasks/mitigationReview.cjs +314 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
- package/src/main/lib/tasks/taskIpc.cjs +22 -18
- package/src/main/lib/tasks/taskLedger.cjs +147 -25
- package/src/main/lib/tasks/taskRun.cjs +186 -17
- package/src/main/lib/tasks/taskSwitch.cjs +85 -12
- package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
- package/src/main/lib/telemetry/auditEvents.cjs +204 -6
- package/src/main/lib/telemetry/auditLog.cjs +6 -2
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
- package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
- package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
- package/src/main/lib/toolUseClassify.cjs +181 -0
- package/src/main/lib/util/atomicFs.cjs +2 -2
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +21 -1
- package/src/main/pty.cjs +77 -0
- package/src/main/queueOps.cjs +33 -14
- package/src/main/runVerify.cjs +74 -9
- package/src/main/scheduler/AGENTS.md +1 -0
- package/src/main/scheduler/budget.cjs +6 -5
- package/src/main/scheduler/prdParser.cjs +46 -13
- package/src/main/scheduler/reviewLadder.cjs +9 -25
- package/src/main/scheduler/utilizationHold.cjs +191 -0
- package/src/main/scheduler.cjs +1932 -213
- package/src/main/templates/PRD_AUTHORING.md +11 -3
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +576 -39
- package/src/preload/apiSurface.json +223 -7
- package/src/preload/index.cjs +48 -1
- package/src/seed/agents/architect.md +6 -1
- package/src/seed/agents/blender-artist.md +2 -1
- package/src/seed/agents/competitive-analyst.md +3 -1
- package/src/seed/agents/competitive-researcher.md +2 -1
- package/src/seed/agents/demo-video-builder.md +98 -87
- package/src/seed/agents/dev-lead.md +3 -3
- package/src/seed/agents/project-home-builder.md +9 -31
- package/src/seed/agents/validator.md +23 -23
- package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
- package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
- package/dist/assets/Scheduler-cyr61UAC.js +0 -16
- package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
- package/dist/assets/index-B2TQz3nd.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* through customerFeedbackInbox.cjs:
|
|
6
6
|
* GET /admin/customer-feedback/inbox?pull=1&includeHidden=1 -> { ok, items, pulled? }
|
|
7
7
|
* POST /admin/customer-feedback/status {id, status, note?} -> { ok, item }
|
|
8
|
-
* POST /admin/customer-feedback/submit {title, body, tag, imagePaths?} -> { ok, item, warning? } | { ok:false, error }
|
|
8
|
+
* POST /admin/customer-feedback/submit {title, body, tag, imagePaths?, context?} -> { ok, item, warning? } | { ok:false, error }
|
|
9
9
|
*
|
|
10
10
|
* submit is the customer path (no owner token needed): it runs the exact
|
|
11
11
|
* submit the Feedback panel's customerFeedback:submit IPC uses
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* item + receipt land in the same local mirror. os.homedir() is replaced with
|
|
14
14
|
* `~` in title and body first; the body text is never echoed or logged.
|
|
15
15
|
* imagePaths (absolute only) are prepared by submitFeedback; image bytes are
|
|
16
|
-
* never logged or echoed.
|
|
16
|
+
* never logged or echoed. context (the widget's page/marks/console/network) is validated by
|
|
17
|
+
* feedbackReport.parseContext (Report v1 rules, <= 262144 bytes) and forwarded unchanged.
|
|
17
18
|
*
|
|
18
19
|
* Deliberately NO route that mints an Epic (SINGLE-CREATOR LAW, epicMint.cjs).
|
|
19
20
|
* Responses never carry the owner token — the inbox lib redacts it from errors.
|
|
@@ -22,6 +23,7 @@
|
|
|
22
23
|
|
|
23
24
|
const path = require('path');
|
|
24
25
|
const { readBody, sendJson } = require('./localAdminHttp.cjs');
|
|
26
|
+
const feedbackReport = require('./feedbackReport.cjs');
|
|
25
27
|
|
|
26
28
|
/** @param {any} dep */
|
|
27
29
|
function getInbox(dep) {
|
|
@@ -131,9 +133,20 @@ function submitHandler(submitDep) {
|
|
|
131
133
|
sendJson(res, 400, { ok: false, error: 'imagePaths must be absolute paths' });
|
|
132
134
|
return;
|
|
133
135
|
}
|
|
136
|
+
/** @type {import('./feedbackReport.cjs').FeedbackContext | undefined} */
|
|
137
|
+
let context;
|
|
138
|
+
if (body.context !== undefined && body.context !== null) {
|
|
139
|
+
const c = feedbackReport.parseContext(body.context);
|
|
140
|
+
if (!c.ok) {
|
|
141
|
+
sendJson(res, 400, { ok: false, error: `invalid submission: ${c.error}` });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
context = c.context;
|
|
145
|
+
}
|
|
134
146
|
const result = await submit({
|
|
135
147
|
title: redactHome(title), body: redactHome(text), tag,
|
|
136
148
|
...(imagePaths && imagePaths.length ? { imagePaths } : {}),
|
|
149
|
+
...(context ? { context } : {}),
|
|
137
150
|
});
|
|
138
151
|
if (!result || !result.ok) {
|
|
139
152
|
sendJson(res, 502, { ok: false, error: result && typeof result.error === 'string' ? result.error : 'submit failed' });
|
|
@@ -148,7 +161,7 @@ function submitHandler(submitDep) {
|
|
|
148
161
|
|
|
149
162
|
/**
|
|
150
163
|
* @param {any} adminHttp
|
|
151
|
-
* @param {{ inbox?: any, submit?: (p: { title: string, body: string, tag: string, imagePaths?: string[] }) => Promise<any> }} [opts] test seams
|
|
164
|
+
* @param {{ inbox?: any, submit?: (p: { title: string, body: string, tag: string, imagePaths?: string[], context?: import('./feedbackReport.cjs').FeedbackContext }) => Promise<any> }} [opts] test seams
|
|
152
165
|
*/
|
|
153
166
|
function registerAdminRoute(adminHttp, opts = {}) {
|
|
154
167
|
adminHttp.registerRoute('GET', '/admin/customer-feedback/inbox', inboxHandler(opts.inbox));
|
|
@@ -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 =
|
|
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[]
|
|
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({
|
|
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
|
+
};
|