claude-code-session-manager 0.126.0 → 0.128.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/bin/cli.cjs +71 -9
- package/bin/supervise.cjs +84 -0
- package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
- package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
- package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
- package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
- package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
- package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
- package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
- package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
- package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
- package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
- package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
- package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
- package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
- package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
- package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
- package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
- package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
- package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
- package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
- package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
- package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
- package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
- package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
- package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
- package/dist/assets/index-DzY_GXYY.js +3081 -0
- package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
- package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +343 -341
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
- package/scripts/scheduler-mcp-server.cjs +209 -7
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +37 -4
- package/src/main/crashDiagnostics.cjs +83 -8
- package/src/main/health.cjs +16 -5
- package/src/main/index.cjs +46 -0
- package/src/main/ipcSchemas.cjs +107 -0
- package/src/main/lib/chatBootRecovery.cjs +136 -0
- package/src/main/lib/chatInflight.cjs +88 -0
- package/src/main/lib/claude/agentModelResolve.cjs +26 -7
- package/src/main/lib/claude/personaToolScope.cjs +40 -2
- package/src/main/lib/demo-video-kit/capture.cjs +113 -0
- package/src/main/lib/demo-video-kit/character.cjs +97 -0
- package/src/main/lib/demo-video-kit/checks.cjs +150 -0
- package/src/main/lib/demo-video-kit/frames.cjs +200 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
- package/src/main/lib/demo-video-kit/sound.cjs +312 -0
- package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
- package/src/main/lib/epic/epicValidationHook.cjs +31 -3
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
- package/src/main/lib/mcpToolCatalog.cjs +93 -14
- package/src/main/lib/opsOwnership.cjs +9 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
- package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
- package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
- package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
- package/src/main/lib/prd/prdCreate.cjs +17 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
- package/src/main/lib/process/childWithLog.cjs +38 -95
- package/src/main/lib/process/memoryScope.cjs +140 -0
- package/src/main/lib/process/ozonePlatform.cjs +15 -0
- package/src/main/lib/process/procIdentity.cjs +10 -3
- package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
- package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
- package/src/main/lib/project-pages/playerBridge.cjs +129 -0
- package/src/main/lib/scheduler/cpuSample.cjs +147 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
- package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
- package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
- package/src/main/lib/scheduler/loadGate.cjs +116 -45
- package/src/main/lib/scheduler/queueStore.cjs +5 -2
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
- package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
- package/src/main/lib/smfileHeaders.cjs +11 -3
- package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
- package/src/main/projectPages.cjs +107 -30
- package/src/main/promptSessionsIpc.cjs +131 -0
- package/src/main/scheduler/budget.cjs +31 -0
- package/src/main/scheduler/prdParser.cjs +2 -0
- package/src/main/scheduler/prdPaths.cjs +54 -0
- package/src/main/scheduler/reviewLadder.cjs +17 -0
- package/src/main/scheduler/starvation.cjs +22 -0
- package/src/main/scheduler.cjs +548 -77
- package/src/main/seedSchedulerMcp.cjs +10 -1
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/transcripts.cjs +8 -0
- package/src/main/usage.cjs +4 -2
- package/src/main/webRemote.cjs +3 -1
- package/src/preload/api.d.ts +113 -7
- package/src/preload/apiSurface.json +70 -0
- package/src/preload/index.cjs +13 -0
- package/src/seed/agents/demo-video-builder.md +141 -43
- package/src/seed/agents/project-home-builder.md +26 -13
- package/dist/assets/index-DgPUERhe.js +0 -3079
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot-time seeder for the demo-video kit.
|
|
3
|
+
*
|
|
4
|
+
* Copies the kit's runnable modules to a stable per-machine folder,
|
|
5
|
+
* `~/.claude/session-manager/demo-video-kit/`, so the demo-video persona can
|
|
6
|
+
* `require()` them from any project's cwd (the app's own install path changes
|
|
7
|
+
* with every npx hash dir). A `KIT_VERSION` stamp file records which kit
|
|
8
|
+
* version is installed; files are overwritten only when the stamp differs, so
|
|
9
|
+
* a normal boot is one small read. Bump KIT_VERSION whenever any kit file
|
|
10
|
+
* changes behaviour.
|
|
11
|
+
*
|
|
12
|
+
* Fire-and-forget from index.cjs: errors are logged, never thrown.
|
|
13
|
+
* Kill-switch: SM_SEED_DEMO_VIDEO_KIT_DISABLE=1.
|
|
14
|
+
*/
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
|
|
18
|
+
const { writeTextAtomic } = require('../util/atomicFs.cjs');
|
|
19
|
+
|
|
20
|
+
const KIT_VERSION = '1';
|
|
21
|
+
const KIT_FILES = ['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs'];
|
|
22
|
+
const STAMP_FILE = 'KIT_VERSION';
|
|
23
|
+
|
|
24
|
+
function kitDestDir() {
|
|
25
|
+
return path.join(schedulerHome(), 'demo-video-kit');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function seedDemoVideoKit({ logger = console, writeLog = () => {}, destDir = kitDestDir(), srcDir = __dirname, kitVersion = KIT_VERSION } = {}) {
|
|
29
|
+
if (process.env.SM_SEED_DEMO_VIDEO_KIT_DISABLE === '1') return { seeded: false, reason: 'disabled' };
|
|
30
|
+
try {
|
|
31
|
+
const stampPath = path.join(destDir, STAMP_FILE);
|
|
32
|
+
let installed = null;
|
|
33
|
+
try { installed = fs.readFileSync(stampPath, 'utf8').trim(); } catch { /* no stamp yet */ }
|
|
34
|
+
const filesPresent = KIT_FILES.every((f) => fs.existsSync(path.join(destDir, f)));
|
|
35
|
+
if (installed === String(kitVersion) && filesPresent) return { seeded: false, reason: 'current' };
|
|
36
|
+
|
|
37
|
+
fs.mkdirSync(destDir, { recursive: true });
|
|
38
|
+
for (const f of KIT_FILES) {
|
|
39
|
+
await writeTextAtomic(path.join(destDir, f), fs.readFileSync(path.join(srcDir, f), 'utf8'));
|
|
40
|
+
}
|
|
41
|
+
// Stamp last: a crash mid-copy leaves the old/no stamp, so the next boot retries.
|
|
42
|
+
await writeTextAtomic(stampPath, `${kitVersion}\n`);
|
|
43
|
+
logger.log?.(`[seedDemoVideoKit] installed kit v${kitVersion} at ${destDir}`);
|
|
44
|
+
return { seeded: true, reason: installed === null ? 'fresh' : 'updated' };
|
|
45
|
+
} catch (err) {
|
|
46
|
+
logger.warn?.('[seedDemoVideoKit] error:', err?.message ?? err);
|
|
47
|
+
writeLog({ scope: 'seed-demo-video-kit', level: 'error', message: 'seed error', meta: { error: err?.message ?? String(err) } });
|
|
48
|
+
return { seeded: false, reason: 'error' };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { seedDemoVideoKit, kitDestDir, KIT_VERSION, KIT_FILES };
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Demo-video kit sound helper: synthesized royalty-free music bed, small SFX set,
|
|
3
|
+
// ducked mix under narration, and two-pass ffmpeg loudnorm (-14 LUFS / -1.5 dBTP).
|
|
4
|
+
// Node builtins only; ffmpeg is spawned without a shell and every call has a timeout.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { spawnSync } = require('child_process');
|
|
8
|
+
|
|
9
|
+
const SR = 44100;
|
|
10
|
+
const FFMPEG = process.env.SM_FFMPEG || 'ffmpeg';
|
|
11
|
+
const FFMPEG_TIMEOUT_MS = 120000;
|
|
12
|
+
const TARGET = { I: -14, TP: -1.5, LRA: 11 };
|
|
13
|
+
const DUCK_DB = 4;
|
|
14
|
+
const BED_BASE_DB = -16; // bed level under silence, relative to full scale before loudnorm
|
|
15
|
+
|
|
16
|
+
// Style presets: tempo, root (Hz), chord progression as semitone triads, timbre, pulse.
|
|
17
|
+
const STYLES = {
|
|
18
|
+
Professional: { bpm: 84, root: 130.81, prog: [[0, 4, 7], [5, 9, 12], [7, 11, 14], [0, 4, 7]], pad: 0.5, bass: 0.35, pulse: 0, pluck: 0.15, bright: 0.2 },
|
|
19
|
+
Fun: { bpm: 118, root: 196.0, prog: [[0, 4, 7], [7, 11, 14], [9, 12, 16], [5, 9, 12]], pad: 0.25, bass: 0.35, pulse: 0.5, pluck: 0.45, bright: 0.6 },
|
|
20
|
+
'Animated whiteboard': { bpm: 100, root: 174.61, prog: [[0, 4, 7], [9, 12, 16], [5, 9, 12], [7, 11, 14]], pad: 0.3, bass: 0.3, pulse: 0.25, pluck: 0.5, bright: 0.45 },
|
|
21
|
+
'Kinetic typography': { bpm: 124, root: 146.83, prog: [[0, 3, 7], [8, 12, 15], [5, 8, 12], [10, 14, 17]], pad: 0.25, bass: 0.5, pulse: 0.6, pluck: 0.3, bright: 0.5 },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function mulberry32(seed) {
|
|
25
|
+
let a = (Number(seed) >>> 0) || 1;
|
|
26
|
+
return () => {
|
|
27
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
28
|
+
let t = a;
|
|
29
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
30
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
31
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const semi = (root, n) => root * Math.pow(2, n / 12);
|
|
36
|
+
const dbToGain = (db) => Math.pow(10, db / 20);
|
|
37
|
+
|
|
38
|
+
/** Wrap mono Float32 samples in a WAV (IEEE float, format 3). */
|
|
39
|
+
function encodeWav(samples, sr = SR) {
|
|
40
|
+
const dataBytes = samples.length * 4;
|
|
41
|
+
const buf = Buffer.alloc(44 + dataBytes);
|
|
42
|
+
buf.write('RIFF', 0, 'ascii');
|
|
43
|
+
buf.writeUInt32LE(36 + dataBytes, 4);
|
|
44
|
+
buf.write('WAVE', 8, 'ascii');
|
|
45
|
+
buf.write('fmt ', 12, 'ascii');
|
|
46
|
+
buf.writeUInt32LE(16, 16);
|
|
47
|
+
buf.writeUInt16LE(3, 20);
|
|
48
|
+
buf.writeUInt16LE(1, 22);
|
|
49
|
+
buf.writeUInt32LE(sr, 24);
|
|
50
|
+
buf.writeUInt32LE(sr * 4, 28);
|
|
51
|
+
buf.writeUInt16LE(4, 32);
|
|
52
|
+
buf.writeUInt16LE(32, 34);
|
|
53
|
+
buf.write('data', 36, 'ascii');
|
|
54
|
+
buf.writeUInt32LE(dataBytes, 40);
|
|
55
|
+
for (let i = 0; i < samples.length; i++) buf.writeFloatLE(samples[i], 44 + i * 4);
|
|
56
|
+
return buf;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Read a mono 32-bit float WAV into Float32Array. */
|
|
60
|
+
function decodeWavF32(buf) {
|
|
61
|
+
if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') throw new Error('not a WAV file');
|
|
62
|
+
let pos = 12;
|
|
63
|
+
let fmt = null;
|
|
64
|
+
while (pos + 8 <= buf.length) {
|
|
65
|
+
const id = buf.toString('ascii', pos, pos + 4);
|
|
66
|
+
let size = buf.readUInt32LE(pos + 4);
|
|
67
|
+
const body = pos + 8;
|
|
68
|
+
if (id === 'fmt ') fmt = { tag: buf.readUInt16LE(body), ch: buf.readUInt16LE(body + 2), sr: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };
|
|
69
|
+
if (id === 'data') {
|
|
70
|
+
if (!fmt || fmt.tag !== 3 || fmt.bits !== 32 || fmt.ch !== 1) throw new Error('expected mono float32 WAV');
|
|
71
|
+
size = Math.min(size, buf.length - body);
|
|
72
|
+
const n = Math.floor(size / 4);
|
|
73
|
+
const out = new Float32Array(n);
|
|
74
|
+
for (let i = 0; i < n; i++) out[i] = buf.readFloatLE(body + i * 4);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
pos = body + size + (size % 2);
|
|
78
|
+
}
|
|
79
|
+
throw new Error('WAV has no data chunk');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function softClipPeak(x, peak) {
|
|
83
|
+
let m = 0;
|
|
84
|
+
for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > m) m = a; }
|
|
85
|
+
if (m > 0) { const g = peak / m; for (let i = 0; i < x.length; i++) x[i] *= g; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function bedSamples({ style, lengthS, seed }) {
|
|
89
|
+
const p = STYLES[style];
|
|
90
|
+
if (!p) throw new Error(`unknown style: ${style} (expected one of ${Object.keys(STYLES).join(', ')})`);
|
|
91
|
+
const n = Math.max(1, Math.round(Number(lengthS) * SR));
|
|
92
|
+
const rnd = mulberry32(seed);
|
|
93
|
+
const out = new Float32Array(n);
|
|
94
|
+
const beat = 60 / p.bpm;
|
|
95
|
+
const barS = beat * 4;
|
|
96
|
+
// Seed picks a transposition and a pluck pattern so different seeds give different beds.
|
|
97
|
+
const transpose = Math.floor(rnd() * 5) - 2;
|
|
98
|
+
const pattern = Array.from({ length: 8 }, () => rnd() < 0.7);
|
|
99
|
+
const arpPick = Array.from({ length: 8 }, () => Math.floor(rnd() * 3));
|
|
100
|
+
const root = semi(p.root, transpose);
|
|
101
|
+
const TAU = 2 * Math.PI;
|
|
102
|
+
for (let i = 0; i < n; i++) {
|
|
103
|
+
const t = i / SR;
|
|
104
|
+
const bar = Math.floor(t / barS);
|
|
105
|
+
const chord = p.prog[bar % p.prog.length];
|
|
106
|
+
const tb = t - bar * barS; // time inside bar
|
|
107
|
+
// Pad: detuned sines with slow swell per bar.
|
|
108
|
+
const swell = Math.sin(Math.PI * Math.min(1, tb / barS)) ** 0.5;
|
|
109
|
+
let v = 0;
|
|
110
|
+
for (const st of chord) {
|
|
111
|
+
const f = semi(root, st);
|
|
112
|
+
v += p.pad * swell * (Math.sin(TAU * f * t) + Math.sin(TAU * f * 1.004 * t) * 0.6 + p.bright * 0.3 * Math.sin(TAU * f * 2 * t)) / 3;
|
|
113
|
+
}
|
|
114
|
+
// Bass on beats 1 and 3 of each bar.
|
|
115
|
+
const bf = semi(root, chord[0]) / 2;
|
|
116
|
+
const bt = tb % (beat * 2);
|
|
117
|
+
v += p.bass * Math.sin(TAU * bf * t) * Math.exp(-bt * 2.2) * 0.9;
|
|
118
|
+
// Eighth-note pluck arpeggio.
|
|
119
|
+
const eighth = beat / 2;
|
|
120
|
+
const step = Math.floor(tb / eighth);
|
|
121
|
+
if (p.pluck > 0 && pattern[step % 8]) {
|
|
122
|
+
const et = tb - step * eighth;
|
|
123
|
+
const pf = semi(root, chord[arpPick[step % 8]] + 12);
|
|
124
|
+
v += p.pluck * 0.5 * Math.sin(TAU * pf * t) * Math.exp(-et * 9);
|
|
125
|
+
}
|
|
126
|
+
// Soft pulse: kick-like thump on every beat.
|
|
127
|
+
if (p.pulse > 0) {
|
|
128
|
+
const kt = tb % beat;
|
|
129
|
+
v += p.pulse * 0.5 * Math.sin(TAU * (55 + 90 * Math.exp(-kt * 30)) * kt) * Math.exp(-kt * 10);
|
|
130
|
+
}
|
|
131
|
+
out[i] = v;
|
|
132
|
+
}
|
|
133
|
+
softClipPeak(out, 0.8);
|
|
134
|
+
// Fade in/out so the bed never clicks at the edges.
|
|
135
|
+
const fade = Math.min(Math.round(1.0 * SR), Math.floor(n / 2));
|
|
136
|
+
for (let i = 0; i < fade; i++) { const g = i / fade; out[i] *= g; out[n - 1 - i] *= g; }
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Deterministic Float32 PCM WAV (mono, 44.1 kHz) music bed. */
|
|
141
|
+
function buildMusicBed({ style, lengthS, seed = 1 }) {
|
|
142
|
+
return encodeWav(bedSamples({ style, lengthS, seed }));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const SFX_NAMES = ['whoosh', 'pop', 'chime', 'click'];
|
|
146
|
+
|
|
147
|
+
function sfxSamples(name) {
|
|
148
|
+
if (!SFX_NAMES.includes(name)) throw new Error(`unknown sfx: ${name} (expected one of ${SFX_NAMES.join(', ')})`);
|
|
149
|
+
const TAU = 2 * Math.PI;
|
|
150
|
+
const rnd = mulberry32(0x5f3759df);
|
|
151
|
+
let durS;
|
|
152
|
+
switch (name) {
|
|
153
|
+
case 'whoosh': durS = 0.6; break;
|
|
154
|
+
case 'pop': durS = 0.15; break;
|
|
155
|
+
case 'chime': durS = 1.2; break;
|
|
156
|
+
default: durS = 0.05;
|
|
157
|
+
}
|
|
158
|
+
const n = Math.round(durS * SR);
|
|
159
|
+
const out = new Float32Array(n);
|
|
160
|
+
let lp = 0;
|
|
161
|
+
for (let i = 0; i < n; i++) {
|
|
162
|
+
const t = i / SR;
|
|
163
|
+
const x = t / durS;
|
|
164
|
+
if (name === 'whoosh') {
|
|
165
|
+
// Noise through a sweeping one-pole low-pass, bell-shaped envelope.
|
|
166
|
+
const a = 0.02 + 0.5 * Math.sin(Math.PI * x);
|
|
167
|
+
lp += a * ((rnd() * 2 - 1) - lp);
|
|
168
|
+
out[i] = lp * Math.sin(Math.PI * x) ** 2 * 1.6;
|
|
169
|
+
} else if (name === 'pop') {
|
|
170
|
+
out[i] = Math.sin(TAU * (180 + 520 * Math.exp(-t * 60)) * t) * Math.exp(-t * 28);
|
|
171
|
+
} else if (name === 'chime') {
|
|
172
|
+
let v = 0;
|
|
173
|
+
[[880, 1], [1318.5, 0.5], [1760, 0.3], [2637, 0.12]].forEach(([f, amp]) => { v += amp * Math.sin(TAU * f * t); });
|
|
174
|
+
out[i] = v * Math.exp(-t * 4) * Math.min(1, t * 400) * 0.45;
|
|
175
|
+
} else {
|
|
176
|
+
out[i] = ((rnd() * 2 - 1) * 0.6 + Math.sin(TAU * 2400 * t) * 0.4) * Math.exp(-t * 110);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
softClipPeak(out, 0.7);
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** SFX as Float32 WAV. name: whoosh | pop | chime | click. */
|
|
184
|
+
function buildSfx(name) {
|
|
185
|
+
return encodeWav(sfxSamples(name));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function runFfmpeg(args) {
|
|
189
|
+
const r = spawnSync(FFMPEG, args, { encoding: 'utf8', timeout: FFMPEG_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, shell: false });
|
|
190
|
+
if (r.error) throw new Error(`ffmpeg failed to run: ${r.error.message}`);
|
|
191
|
+
if (r.status !== 0) throw new Error(`ffmpeg exited ${r.status}: ${String(r.stderr).slice(-600)}`);
|
|
192
|
+
return String(r.stderr || '');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Parse ffmpeg `ebur128=peak=true` summary into {lufs, truePeakDb}. */
|
|
196
|
+
function parseEbur128(text) {
|
|
197
|
+
const s = String(text);
|
|
198
|
+
const i = s.lastIndexOf('Summary:');
|
|
199
|
+
const tail = i >= 0 ? s.slice(i) : s;
|
|
200
|
+
const num = (m) => (m ? (m[1] === '-inf' ? -Infinity : Number(m[1])) : null);
|
|
201
|
+
const lufs = num(/Integrated loudness:\s*I:\s*(-?inf|-?[\d.]+)\s*LUFS/.exec(tail));
|
|
202
|
+
const truePeakDb = num(/True peak:\s*Peak:\s*(-?inf|-?[\d.]+)\s*dBFS/.exec(tail));
|
|
203
|
+
if (lufs === null || truePeakDb === null) throw new Error('could not parse ebur128 output');
|
|
204
|
+
return { lufs, truePeakDb };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Measure integrated loudness and true peak of an audio/video file. */
|
|
208
|
+
function measure(file) {
|
|
209
|
+
const err = runFfmpeg(['-hide_banner', '-nostats', '-i', file, '-vn', '-af', 'ebur128=peak=true', '-f', 'null', '-']);
|
|
210
|
+
return parseEbur128(err);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Two-pass loudnorm of `input` into `output` at I=-14 TP=-1.5 LRA=11. */
|
|
214
|
+
function loudnorm(input, output) {
|
|
215
|
+
const base = `loudnorm=I=${TARGET.I}:TP=${TARGET.TP}:LRA=${TARGET.LRA}`;
|
|
216
|
+
const err1 = runFfmpeg(['-hide_banner', '-nostats', '-i', input, '-af', `${base}:print_format=json`, '-f', 'null', '-']);
|
|
217
|
+
const j = err1.slice(err1.lastIndexOf('{'), err1.lastIndexOf('}') + 1);
|
|
218
|
+
let m;
|
|
219
|
+
try { m = JSON.parse(j); } catch { throw new Error('could not parse loudnorm pass-1 output'); }
|
|
220
|
+
const f = (k) => {
|
|
221
|
+
const v = Number(m[k]);
|
|
222
|
+
if (!Number.isFinite(v)) throw new Error(`loudnorm pass-1 missing ${k}`);
|
|
223
|
+
return v;
|
|
224
|
+
};
|
|
225
|
+
const pass2 = `${base}:measured_I=${f('input_i')}:measured_TP=${f('input_tp')}:measured_LRA=${f('input_lra')}:measured_thresh=${f('input_thresh')}:offset=${f('target_offset')}:linear=true:print_format=summary`;
|
|
226
|
+
const codec = /\.wav$/i.test(output) ? ['-c:a', 'pcm_s16le'] : [];
|
|
227
|
+
runFfmpeg(['-hide_banner', '-nostats', '-y', '-i', input, '-af', pass2, '-ar', String(SR), ...codec, output]);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Per-sample gain (1 → -DUCK_DB) following speech activity; returns {gain, speechS}. */
|
|
231
|
+
function duckEnvelope(narr) {
|
|
232
|
+
const win = Math.round(0.02 * SR);
|
|
233
|
+
const nWin = Math.ceil(narr.length / win);
|
|
234
|
+
const speech = new Uint8Array(nWin);
|
|
235
|
+
let active = 0;
|
|
236
|
+
for (let w = 0; w < nWin; w++) {
|
|
237
|
+
let e = 0;
|
|
238
|
+
const end = Math.min(narr.length, (w + 1) * win);
|
|
239
|
+
for (let i = w * win; i < end; i++) e += narr[i] * narr[i];
|
|
240
|
+
const rms = Math.sqrt(e / Math.max(1, end - w * win));
|
|
241
|
+
if (rms > 0.01) { speech[w] = 1; active++; }
|
|
242
|
+
}
|
|
243
|
+
const hold = 15; // 300 ms hold bridges gaps between words
|
|
244
|
+
const target = new Float32Array(nWin).fill(1);
|
|
245
|
+
const low = dbToGain(-DUCK_DB);
|
|
246
|
+
let since = hold + 1;
|
|
247
|
+
for (let w = 0; w < nWin; w++) {
|
|
248
|
+
since = speech[w] ? 0 : since + 1;
|
|
249
|
+
if (since <= hold) target[w] = low;
|
|
250
|
+
}
|
|
251
|
+
const gain = new Float32Array(narr.length);
|
|
252
|
+
const atk = 1 - Math.exp(-1 / (0.05 * SR));
|
|
253
|
+
const rel = 1 - Math.exp(-1 / (0.3 * SR));
|
|
254
|
+
let g = 1;
|
|
255
|
+
for (let i = 0; i < narr.length; i++) {
|
|
256
|
+
const tg = target[Math.min(nWin - 1, Math.floor(i / win))];
|
|
257
|
+
g += (tg < g ? atk : rel) * (tg - g);
|
|
258
|
+
gain[i] = g;
|
|
259
|
+
}
|
|
260
|
+
return { gain, speechS: active * 0.02 };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Mix narration + ducked music bed + SFX cues, then loudnorm to -14 LUFS / -1.5 dBTP.
|
|
265
|
+
* cues: [{name, t}] (t in seconds; `at` also accepted). Output length is the longer of
|
|
266
|
+
* lengthS and the narration. Returns the measured {lufs, truePeakDb, speechS}.
|
|
267
|
+
*/
|
|
268
|
+
function mix({ narrationWav, cues = [], style, lengthS, out, seed = 1 }) {
|
|
269
|
+
const dir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'dvk-sound-'));
|
|
270
|
+
try {
|
|
271
|
+
const narrF32 = path.join(dir, 'narration.f32.wav');
|
|
272
|
+
runFfmpeg(['-hide_banner', '-nostats', '-y', '-i', narrationWav, '-vn', '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_f32le', narrF32]);
|
|
273
|
+
const narr = decodeWavF32(fs.readFileSync(narrF32));
|
|
274
|
+
const n = Math.max(narr.length, Math.round(Number(lengthS) * SR));
|
|
275
|
+
const bed = bedSamples({ style, lengthS: n / SR, seed });
|
|
276
|
+
const { gain, speechS } = duckEnvelope(narr);
|
|
277
|
+
const bedGain = dbToGain(BED_BASE_DB);
|
|
278
|
+
const mixed = new Float32Array(n);
|
|
279
|
+
for (let i = 0; i < n; i++) {
|
|
280
|
+
const g = i < gain.length ? gain[i] : 1;
|
|
281
|
+
mixed[i] = (i < narr.length ? narr[i] : 0) + bed[i] * bedGain * g;
|
|
282
|
+
}
|
|
283
|
+
const sfxGain = dbToGain(-10);
|
|
284
|
+
for (const cue of cues) {
|
|
285
|
+
const at = Math.round(Number(cue.t ?? cue.at ?? 0) * SR);
|
|
286
|
+
const s = sfxSamples(cue.name);
|
|
287
|
+
for (let i = 0; i < s.length && at + i < n; i++) if (at + i >= 0) mixed[at + i] += s[i] * sfxGain;
|
|
288
|
+
}
|
|
289
|
+
const pre = path.join(dir, 'premix.f32.wav');
|
|
290
|
+
fs.writeFileSync(pre, encodeWav(mixed));
|
|
291
|
+
fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
|
|
292
|
+
loudnorm(pre, out);
|
|
293
|
+
return { ...measure(out), speechS };
|
|
294
|
+
} finally {
|
|
295
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
module.exports = { buildMusicBed, buildSfx, mix, measure, parseEbur128, STYLES, SFX_NAMES, TARGET };
|
|
300
|
+
|
|
301
|
+
if (require.main === module) {
|
|
302
|
+
try {
|
|
303
|
+
const specPath = process.argv[2];
|
|
304
|
+
if (!specPath) throw new Error('usage: node sound.cjs <spec.json>');
|
|
305
|
+
const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
|
|
306
|
+
const r = mix(spec);
|
|
307
|
+
process.stdout.write(JSON.stringify({ lufs: r.lufs, truePeakDb: r.truePeakDb, speechS: r.speechS }) + '\n');
|
|
308
|
+
} catch (e) {
|
|
309
|
+
process.stderr.write(`${e.message}\n`);
|
|
310
|
+
process.exit(1);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
@@ -6,12 +6,38 @@
|
|
|
6
6
|
* checks the completed PRDs of a settled Epic that no validator has checked.
|
|
7
7
|
* Pure: no fs, no child_process. The caller decides when a sweep is needed and
|
|
8
8
|
* whether to create the PRD.
|
|
9
|
+
*
|
|
10
|
+
* Sizing: the sweep's kill budget must cover every gate running to its own
|
|
11
|
+
* timeout plus reading/writing time, because a kill loses every minute of
|
|
12
|
+
* evidence. Why these numbers: across 916 real validator runs the most
|
|
13
|
+
* non-gate time was 13.7 minutes, hence VALIDATOR_OVERHEAD_MS = 15 minutes;
|
|
14
|
+
* UNKNOWN_GATE_MS matches definitionOfDone's DEFAULT_GATE_TIMEOUT_MS; the plain
|
|
15
|
+
* sum with no dedupe follows the validator's rule to re-run every command in
|
|
16
|
+
* each PRD's gate. Real runs sit far under their timeouts (median 7%), so about
|
|
17
|
+
* 2.3% of sweeps (3 of 130) will split that strictly did not need it. An extra
|
|
18
|
+
* validator costs far less than a lost run, so that is accepted.
|
|
9
19
|
*/
|
|
10
20
|
|
|
11
21
|
const { bareSlug } = require('../prd/depSlugResolve.cjs');
|
|
22
|
+
const { JOB_BUDGET_FACTOR, JOB_BUDGET_CEILING_MS } = require('../scheduler/schedulerConfig.cjs');
|
|
12
23
|
|
|
13
24
|
const SWEEP_SLUG_PREFIX = 'validate-sweep';
|
|
14
25
|
const MAX_SWEEP_PRDS = 25;
|
|
26
|
+
const VALIDATOR_OVERHEAD_MS = 15 * 60_000;
|
|
27
|
+
const UNKNOWN_GATE_MS = 5 * 60_000;
|
|
28
|
+
const MIN_VALIDATOR_ESTIMATE_MINUTES = 10;
|
|
29
|
+
|
|
30
|
+
/** A value that is not a finite number >= 0 counts UNKNOWN_GATE_MS; 0 stays 0. */
|
|
31
|
+
function gateMsOrUnknown(v) {
|
|
32
|
+
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : UNKNOWN_GATE_MS;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** max(10, ceil((sum + overhead) / 60000 / factor)). */
|
|
36
|
+
function validatorEstimateMinutes(gateMsValues, { factor } = {}) {
|
|
37
|
+
const f = typeof factor === 'number' && factor > 0 ? factor : JOB_BUDGET_FACTOR;
|
|
38
|
+
const sum = (Array.isArray(gateMsValues) ? gateMsValues : []).reduce((a, v) => a + gateMsOrUnknown(v), 0);
|
|
39
|
+
return Math.max(MIN_VALIDATOR_ESTIMATE_MINUTES, Math.ceil((sum + VALIDATOR_OVERHEAD_MS) / 60_000 / f));
|
|
40
|
+
}
|
|
15
41
|
|
|
16
42
|
const PERSONA_LINE = 'Work as the validator persona — the procedure is your system prompt.';
|
|
17
43
|
|
|
@@ -27,14 +53,31 @@ function isSweepValidatorSlug(slug) {
|
|
|
27
53
|
* baseSha?: string | null, now: number | Date | string }} args
|
|
28
54
|
* @returns {{ input: object | null, carried: Array<object> }}
|
|
29
55
|
*/
|
|
30
|
-
function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
|
|
56
|
+
function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now, jobBudget }) {
|
|
31
57
|
if (!Array.isArray(uncovered) || uncovered.length === 0) return { input: null, carried: [] };
|
|
32
58
|
|
|
33
|
-
const
|
|
34
|
-
|
|
59
|
+
const factor = jobBudget && typeof jobBudget.factor === 'number' && jobBudget.factor > 0
|
|
60
|
+
? jobBudget.factor : JOB_BUDGET_FACTOR;
|
|
61
|
+
const ceilingMs = jobBudget && typeof jobBudget.ceilingMs === 'number' && jobBudget.ceilingMs > 0
|
|
62
|
+
? jobBudget.ceilingMs : JOB_BUDGET_CEILING_MS;
|
|
63
|
+
|
|
64
|
+
// First-fit in input order; the first entry always joins.
|
|
65
|
+
const covered = [];
|
|
66
|
+
const carried = [];
|
|
67
|
+
let workMs = VALIDATOR_OVERHEAD_MS;
|
|
68
|
+
for (const entry of uncovered) {
|
|
69
|
+
const g = gateMsOrUnknown(entry && entry.gateMs);
|
|
70
|
+
if (covered.length === 0 || (covered.length < MAX_SWEEP_PRDS && workMs + g <= ceilingMs)) {
|
|
71
|
+
covered.push(entry);
|
|
72
|
+
workMs += g;
|
|
73
|
+
} else {
|
|
74
|
+
carried.push(entry);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const budgetExempt = covered.length === 1 && workMs > ceilingMs;
|
|
35
78
|
const names = covered.map((entry) => entry.bareSlug || bareSlug(entry.slug));
|
|
36
79
|
|
|
37
|
-
const stamp = new Date(now).toISOString().replace(/\D/g, '').slice(0,
|
|
80
|
+
const stamp = new Date(now).toISOString().replace(/\D/g, '').slice(0, 14);
|
|
38
81
|
const slug = `${SWEEP_SLUG_PREFIX}-${stamp}`;
|
|
39
82
|
const recordPath = `session-manager-operations/reviews/validation/${epicId}/${slug}.md`;
|
|
40
83
|
|
|
@@ -60,7 +103,7 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
|
|
|
60
103
|
outOfScope: ['Editing product code', 'Queuing fix PRDs'],
|
|
61
104
|
gate: ['none'],
|
|
62
105
|
files: [recordPath],
|
|
63
|
-
estimateMinutes:
|
|
106
|
+
estimateMinutes: validatorEstimateMinutes(covered.map((e) => e.gateMs), { factor }),
|
|
64
107
|
agentType: 'validator',
|
|
65
108
|
tag: 'build',
|
|
66
109
|
sourcePromptId: epicId,
|
|
@@ -68,7 +111,18 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
|
|
|
68
111
|
dependsOn: names,
|
|
69
112
|
};
|
|
70
113
|
|
|
114
|
+
if (budgetExempt) input.budgetExempt = true;
|
|
115
|
+
|
|
71
116
|
return { input, carried };
|
|
72
117
|
}
|
|
73
118
|
|
|
74
|
-
module.exports = {
|
|
119
|
+
module.exports = {
|
|
120
|
+
SWEEP_SLUG_PREFIX,
|
|
121
|
+
MAX_SWEEP_PRDS,
|
|
122
|
+
VALIDATOR_OVERHEAD_MS,
|
|
123
|
+
UNKNOWN_GATE_MS,
|
|
124
|
+
MIN_VALIDATOR_ESTIMATE_MINUTES,
|
|
125
|
+
isSweepValidatorSlug,
|
|
126
|
+
validatorEstimateMinutes,
|
|
127
|
+
buildSweepValidatorInput,
|
|
128
|
+
};
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* Kill-switch: SM_EPIC_VALIDATION_DISABLE=1 turns the whole runner off.
|
|
12
12
|
* SM_EPIC_SETTLE_SECONDS sets the debounce before a settle run (default 120).
|
|
13
13
|
*
|
|
14
|
+
* A sweep covers what fits one budget; the rest go to the next settle.
|
|
15
|
+
*
|
|
14
16
|
* This module spawns NO process itself: the sweep validator is a PRD queued
|
|
15
17
|
* through the scheduler (which acquires a lib/scheduler/sessionSlots.cjs slot),
|
|
16
18
|
* and the digest goes through the chat queue's pump, which does the same.
|
|
@@ -108,6 +110,8 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
|
|
|
108
110
|
loadHistory = async () => [],
|
|
109
111
|
createPrd,
|
|
110
112
|
resolveBaseSha = async () => null,
|
|
113
|
+
readGateMs = async () => new Map(),
|
|
114
|
+
jobBudget,
|
|
111
115
|
sendPrompt,
|
|
112
116
|
appendResponseEvent,
|
|
113
117
|
now = Date.now,
|
|
@@ -128,6 +132,19 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
|
|
|
128
132
|
if (!settle.settled) return { action: 'none', reason: 'not-settled' };
|
|
129
133
|
if (!settle.hasContent) return { action: 'none', reason: 'no-content' };
|
|
130
134
|
|
|
135
|
+
// Macro builds (rows carrying macroId): the artifact check and gate are the
|
|
136
|
+
// done-check; no sweep validator, no digest chat turn.
|
|
137
|
+
const macroSlugs = new Set();
|
|
138
|
+
let epicRows = 0;
|
|
139
|
+
for (const r of [...jobs, ...history]) {
|
|
140
|
+
if (!_rowInEpic(r, epicId)) continue;
|
|
141
|
+
epicRows++;
|
|
142
|
+
if (typeof r.macroId === 'string' && r.macroId.trim()) macroSlugs.add(bareSlug(r.slug));
|
|
143
|
+
}
|
|
144
|
+
if (epicRows > 0 && [...jobs, ...history].every((r) => !_rowInEpic(r, epicId) || (typeof r.macroId === 'string' && r.macroId.trim()))) {
|
|
145
|
+
return { action: 'none', reason: 'macro-build' };
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
let newestDigest = null;
|
|
132
149
|
for (const e of events) if (e && e.outcome === 'digest') newestDigest = e;
|
|
133
150
|
if (newestDigest && newestDigest.digestKey === settle.digestKey) {
|
|
@@ -142,7 +159,10 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
|
|
|
142
159
|
if (!_rowInEpic(r, epicId) || !isSweepValidatorSlug(r.slug) || !Array.isArray(r.dependsOn)) continue;
|
|
143
160
|
for (const d of r.dependsOn) swept.add(bareSlug(d));
|
|
144
161
|
}
|
|
145
|
-
const candidates = settle.uncovered.filter((u) =>
|
|
162
|
+
const candidates = settle.uncovered.filter((u) => {
|
|
163
|
+
const b = u.bareSlug || bareSlug(u.slug);
|
|
164
|
+
return !swept.has(b) && !macroSlugs.has(b);
|
|
165
|
+
});
|
|
146
166
|
if (candidates.length) {
|
|
147
167
|
const byBare = new Map();
|
|
148
168
|
for (const h of history) {
|
|
@@ -158,14 +178,22 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
|
|
|
158
178
|
}
|
|
159
179
|
let baseSha = null;
|
|
160
180
|
try { baseSha = earliest ? await resolveBaseSha(cwd, earliest.landedCommit) : null; } catch { baseSha = null; }
|
|
161
|
-
|
|
181
|
+
let gateMap = new Map();
|
|
182
|
+
try {
|
|
183
|
+
const m = await readGateMs(cwd, epicId, candidates.map((c) => c.slug));
|
|
184
|
+
if (m instanceof Map) gateMap = m;
|
|
185
|
+
} catch (e) {
|
|
186
|
+
try { (log || console).error('[epicValidationHook] readGateMs failed', epicId, e); } catch { /* noop */ }
|
|
187
|
+
}
|
|
188
|
+
const sized = candidates.map((c) => ({ ...c, gateMs: gateMap.get(c.slug) }));
|
|
189
|
+
const { input, carried } = buildSweepValidatorInput({ epicId, cwd, uncovered: sized, baseSha, now: now(), jobBudget });
|
|
162
190
|
let res;
|
|
163
191
|
try {
|
|
164
192
|
res = await createPrd(input);
|
|
165
193
|
} catch (e) {
|
|
166
194
|
res = { ok: false, error: e && e.message ? e.message : String(e) };
|
|
167
195
|
}
|
|
168
|
-
if (res && res.ok) return { action: 'sweep-queued', slug: input.slug };
|
|
196
|
+
if (res && res.ok) return { action: 'sweep-queued', slug: input.slug, carried: carried.length };
|
|
169
197
|
notValidatedReason = `the validator persona could not be queued: ${(res && res.error) || 'unknown error'}`;
|
|
170
198
|
} else {
|
|
171
199
|
notValidatedReason = 'a sweep validator already ran and did not check them';
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* macroAdminRoutes.cjs — loopback admin HTTP routes so an agent session (via
|
|
3
|
-
* the scheduler MCP
|
|
3
|
+
* the scheduler MCP) can list, create/update and delete a HOT KEYS macro
|
|
4
4
|
* for its own project, through the existing macroLibrary.cjs store:
|
|
5
5
|
* GET /admin/macros?cwd=… -> { ok, macros }
|
|
6
6
|
* POST /admin/macros/save {cwd, id?, label, agentName, tag, prompt, inputs?}
|
|
7
|
+
* POST /admin/macros/delete {cwd, id, originClaudeSessionId?}
|
|
8
|
+
* -> { ok, deleted, macro }
|
|
9
|
+
* delete removes the macro from THIS project through
|
|
10
|
+
* macroLibrary.removeMacroFromProject (deleted:false when other projects still
|
|
11
|
+
* list it), fires onChanged once and appends one `admin_macro_delete` audit
|
|
12
|
+
* event on success; every refusal is a 400 with no onChanged and no audit.
|
|
7
13
|
*
|
|
8
14
|
* cwd resolution matches projectHomeAdminRoutes.cjs's resolveCwd exactly
|
|
9
15
|
* (reused, not copied). A create always stores `projects: [resolvedCwd]`,
|
|
@@ -20,6 +26,30 @@
|
|
|
20
26
|
const { readBody, sendJson } = require('./localAdminHttp.cjs');
|
|
21
27
|
const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
|
|
22
28
|
const macroLibrary = require('../persona-macro/macroLibrary.cjs');
|
|
29
|
+
const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
|
|
30
|
+
|
|
31
|
+
/** Read + parse a JSON object body; on failure sends the 400 and returns null. */
|
|
32
|
+
async function readJsonBody(req, res) {
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = await readBody(req);
|
|
36
|
+
} catch (e) {
|
|
37
|
+
sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
let body;
|
|
41
|
+
try {
|
|
42
|
+
body = raw ? JSON.parse(raw) : {};
|
|
43
|
+
} catch {
|
|
44
|
+
sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (body === null || typeof body !== 'object') {
|
|
48
|
+
sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return body;
|
|
52
|
+
}
|
|
23
53
|
|
|
24
54
|
function listHandler(onChanged, libOpts) {
|
|
25
55
|
return async (_req, res, query) => {
|
|
@@ -38,20 +68,8 @@ function listHandler(onChanged, libOpts) {
|
|
|
38
68
|
|
|
39
69
|
function saveHandler(onChanged, libOpts) {
|
|
40
70
|
return async (req, res) => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
raw = await readBody(req);
|
|
44
|
-
} catch (e) {
|
|
45
|
-
sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
let body;
|
|
49
|
-
try {
|
|
50
|
-
body = raw ? JSON.parse(raw) : {};
|
|
51
|
-
} catch {
|
|
52
|
-
sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
71
|
+
const body = await readJsonBody(req, res);
|
|
72
|
+
if (!body) return;
|
|
55
73
|
const resolved = resolveCwd(body.cwd);
|
|
56
74
|
if (!resolved.ok) {
|
|
57
75
|
sendJson(res, resolved.status, { ok: false, error: resolved.error });
|
|
@@ -101,10 +119,48 @@ function saveHandler(onChanged, libOpts) {
|
|
|
101
119
|
};
|
|
102
120
|
}
|
|
103
121
|
|
|
122
|
+
function deleteHandler(onChanged, libOpts) {
|
|
123
|
+
return async (req, res) => {
|
|
124
|
+
const body = await readJsonBody(req, res);
|
|
125
|
+
if (!body) return;
|
|
126
|
+
const resolved = resolveCwd(body.cwd);
|
|
127
|
+
if (!resolved.ok) {
|
|
128
|
+
sendJson(res, resolved.status, { ok: false, error: resolved.error });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (typeof body.id !== 'string' || !body.id) {
|
|
132
|
+
sendJson(res, 400, { ok: false, error: 'id is required' });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
let result;
|
|
136
|
+
try {
|
|
137
|
+
result = await macroLibrary.removeMacroFromProject({ id: body.id, cwd: resolved.cwd }, libOpts);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
sendJson(res, 400, { ok: false, error: e?.issues?.[0]?.message ?? e?.message ?? 'delete failed' });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (!result.ok) {
|
|
143
|
+
sendJson(res, 400, result);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const origin = body.originClaudeSessionId;
|
|
147
|
+
appendAuditEvent('admin_macro_delete', {
|
|
148
|
+
route: '/admin/macros/delete',
|
|
149
|
+
cwd: resolved.cwd,
|
|
150
|
+
deleted: result.deleted,
|
|
151
|
+
macro: result.macro,
|
|
152
|
+
originClaudeSessionId: typeof origin === 'string' && origin.length >= 1 && origin.length <= 128 ? origin : null,
|
|
153
|
+
});
|
|
154
|
+
if (onChanged) onChanged();
|
|
155
|
+
sendJson(res, 200, result);
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
104
159
|
function registerAdminRoute(adminHttp, { onChanged } = {}, opts = {}) {
|
|
105
160
|
const libOpts = opts.filePath ? { filePath: opts.filePath } : undefined;
|
|
106
161
|
adminHttp.registerRoute('GET', '/admin/macros', listHandler(onChanged, libOpts));
|
|
107
162
|
adminHttp.registerRoute('POST', '/admin/macros/save', saveHandler(onChanged, libOpts));
|
|
163
|
+
adminHttp.registerRoute('POST', '/admin/macros/delete', deleteHandler(onChanged, libOpts));
|
|
108
164
|
}
|
|
109
165
|
|
|
110
166
|
module.exports = {
|