claude-code-session-manager 0.125.1 → 0.127.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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +71 -9
  3. package/bin/supervise.cjs +84 -0
  4. package/dist/assets/{AgentLibrary-DjEH5SoY.js → AgentLibrary-DKQznr7o.js} +1 -1
  5. package/dist/assets/{Button-B8NLivk-.js → Button-CZXqmIiM.js} +1 -1
  6. package/dist/assets/{DataModel-CHiBk8m_.js → DataModel-piyV33To.js} +1 -1
  7. package/dist/assets/{History-DttgrJO0.js → History-BxwtrKF2.js} +1 -1
  8. package/dist/assets/{Hooks-Bvy0BH1u.js → Hooks-DogeSPII.js} +1 -1
  9. package/dist/assets/{Library-UbBOgkkP.js → Library-BDt6EeQQ.js} +1 -1
  10. package/dist/assets/{ListDetail-xOyOpVZX.js → ListDetail-CwS-LKar.js} +1 -1
  11. package/dist/assets/{McpServers-CoGL0ddv.js → McpServers-D2HVljgS.js} +1 -1
  12. package/dist/assets/{Memory-Cise856d.js → Memory-hNzuOGn8.js} +1 -1
  13. package/dist/assets/{Panel-Cj72VO5s.js → Panel-BLDrsUeq.js} +1 -1
  14. package/dist/assets/{Permissions-BoJ9AB-G.js → Permissions-DzZ5vaJW.js} +1 -1
  15. package/dist/assets/{Plugins-DfT24sAZ.js → Plugins-Cz9yaxzG.js} +2 -2
  16. package/dist/assets/{ProvenanceBadge-ChkIslT4.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  17. package/dist/assets/{SaveBar-RCXr0jey.js → SaveBar-Shmn699J.js} +1 -1
  18. package/dist/assets/{Scheduler-B70tknnx.js → Scheduler-Bqr0WHNd.js} +1 -1
  19. package/dist/assets/{ScopeSwitcher-p_tgO5Sa.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  20. package/dist/assets/{Settings-wHiAxTfI.js → Settings-Ci8in-yF.js} +1 -1
  21. package/dist/assets/{SkillReferenceGraph-D_Pt35vb.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  22. package/dist/assets/{Skills-DUvOrgw9.js → Skills-BON6o-c4.js} +1 -1
  23. package/dist/assets/{SystemPrompt-BrNIdy68.js → SystemPrompt-D5epIYYs.js} +1 -1
  24. package/dist/assets/{TagLibrary-CDRatxXG.js → TagLibrary-C2qDZROJ.js} +1 -1
  25. package/dist/assets/{TiptapBody-BF8PxUDj.js → TiptapBody-SZhI3-bW.js} +1 -1
  26. package/dist/assets/{Toggle-CQH8NGXW.js → Toggle-C_qFDG0g.js} +1 -1
  27. package/dist/assets/{ViewTabs-DwnxqCVs.js → ViewTabs-C9q5WCEd.js} +1 -1
  28. package/dist/assets/{historyTotals-KINLTHQ4.js → historyTotals-BCl7IOhY.js} +1 -1
  29. package/dist/assets/{index-CfR3NU2t.js → index-CMIYLbPb.js} +581 -581
  30. package/dist/assets/{settingsSchema-BUcHqLnt.js → settingsSchema-BBrRBrBr.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BwwkyuMD.js → skillFrontmatter-B01qJk6N.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Coem9Wg-.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/dist-web/{assets/app.js → app.js} +351 -351
  35. package/dist-web/index.html +2 -2
  36. package/package.json +2 -2
  37. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  38. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  39. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  40. package/scripts/scheduler-mcp-server.cjs +56 -5
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +73 -6
  43. package/src/main/crashDiagnostics.cjs +83 -8
  44. package/src/main/health.cjs +16 -5
  45. package/src/main/index.cjs +32 -0
  46. package/src/main/lib/chatBootRecovery.cjs +136 -0
  47. package/src/main/lib/chatInflight.cjs +88 -0
  48. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  49. package/src/main/lib/epic/epicMint.cjs +6 -0
  50. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  51. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  52. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  53. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  54. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  56. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  57. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  58. package/src/main/lib/git/gitExec.cjs +11 -1
  59. package/src/main/lib/git/gitWorktree.cjs +255 -9
  60. package/src/main/lib/git/jobWorktree.cjs +5 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +27 -5
  62. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  63. package/src/main/lib/persona-macro/macroLibrary.cjs +78 -3
  64. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  65. package/src/main/lib/prd/prdCreate.cjs +5 -1
  66. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  67. package/src/main/lib/process/childWithLog.cjs +38 -95
  68. package/src/main/lib/process/memoryScope.cjs +140 -0
  69. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  70. package/src/main/lib/process/procIdentity.cjs +10 -3
  71. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  72. package/src/main/lib/promptSessionSchema.cjs +6 -1
  73. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  74. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  75. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  76. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  78. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  79. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  80. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  81. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  82. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  83. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  84. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  85. package/src/main/runVerify.cjs +59 -110
  86. package/src/main/scheduler/budget.cjs +31 -0
  87. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  88. package/src/main/scheduler/prdPaths.cjs +54 -0
  89. package/src/main/scheduler/reviewLadder.cjs +28 -5
  90. package/src/main/scheduler/starvation.cjs +22 -0
  91. package/src/main/scheduler.cjs +662 -90
  92. package/src/main/templates/PRD_AUTHORING.md +10 -3
  93. package/src/main/usage.cjs +4 -2
  94. package/src/main/webRemote.cjs +3 -0
  95. package/src/preload/api.d.ts +19 -3
  96. package/src/seed/agents/demo-video-builder.md +62 -14
  97. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -47,6 +47,14 @@
47
47
  * is told to approve-and-start it through its normal approveProposed path.
48
48
  * Anything unverifiable degrades to the ordinary proposal.
49
49
  *
50
+ * A SECOND GROUND — the MACRO. A session a human launched from a saved macro
51
+ * (its Epic is source.producer 'new-epic-ui' with a source.macroId) may
52
+ * auto-start bug/feature work in a target the macro's autoStartTargets names:
53
+ * the human pressed that macro and listed the target, so no quote or autoStart
54
+ * flag is needed. The sender Epic is resolved ONLY from originClaudeSessionId
55
+ * (never from the agent-supplied fromEpicId), is capped at MAX_MACRO_AUTO_STARTS
56
+ * grants, and anything denied stays an ordinary proposal.
57
+ *
50
58
  * Guards, all fail-closed:
51
59
  * - both cwds go through config.cjs's validatePath (allowedRoots = home)
52
60
  * - both must be real, existing directories
@@ -460,6 +468,23 @@ function defaultNotifyRenderer(payload) {
460
468
  } catch { /* not running under Electron */ }
461
469
  }
462
470
 
471
+ /**
472
+ * quoteNamesTarget(quote, toCwd) → boolean. The quote itself (not the wider
473
+ * prompt) must name the receiving project: folder name on non-alphanumeric
474
+ * boundaries ('-'/'_' read as spaces, case-insensitive), or the full path.
475
+ */
476
+ function quoteNamesTarget(quote, toCwd) {
477
+ const norm = (x) => String(x || '').toLowerCase().replace(/[-_]/g, ' ');
478
+ const q = norm(quote);
479
+ const base = norm(path.basename(String(toCwd || '')));
480
+ if (base.trim()) {
481
+ const esc = base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
482
+ if (new RegExp(`(^|[^a-z0-9])${esc}($|[^a-z0-9])`).test(q)) return true;
483
+ }
484
+ const full = norm(toCwd);
485
+ return full.trim() !== '' && q.includes(full);
486
+ }
487
+
463
488
  /**
464
489
  * verifyAutoStart(v, originClaudeSessionId) → { granted: true, quote } | { granted: false, reason }
465
490
  *
@@ -477,14 +502,67 @@ function verifyAutoStart(v, originClaudeSessionId) {
477
502
  if (!found) {
478
503
  return { granted: false, reason: 'humanRequestQuote was not found in a prompt the human typed in this chat session' };
479
504
  }
480
- const prompt = found.text.toLowerCase();
481
- const base = path.basename(v.toCwd).toLowerCase();
482
- if (!(base && prompt.includes(base)) && !prompt.includes(v.toCwd.toLowerCase())) {
483
- return { granted: false, reason: `the human's prompt does not name the receiving project (${path.basename(v.toCwd)})` };
505
+ if (!quoteNamesTarget(v.humanRequestQuote, v.toCwd)) {
506
+ return { granted: false, reason: `the human's quote does not name the receiving project (${path.basename(v.toCwd)})` };
484
507
  }
485
508
  return { granted: true, quote: v.humanRequestQuote };
486
509
  }
487
510
 
511
+ const MAX_MACRO_AUTO_STARTS = 5;
512
+ const AUTO_START_TAGS = Object.freeze(['bug', 'feature']);
513
+
514
+ // Grants per sender Epic id. In memory, so a restart resets it — accepted
515
+ // because each press of a macro is a human act.
516
+ const macroGrantCounts = new Map();
517
+
518
+ /**
519
+ * verifyMacroAutoStart(v, originClaudeSessionId, deps) →
520
+ * null (sender Epic has no macro: fall through to verifyAutoStart)
521
+ * | { granted: true, ground:'macro', macroId, macroLabel, senderEpicId }
522
+ * | { granted: false, reason }
523
+ *
524
+ * Does NOT reserve the count; the caller does that via reserveMacroGrant so a
525
+ * failed mint can release it.
526
+ */
527
+ async function verifyMacroAutoStart(v, originClaudeSessionId, deps = {}) {
528
+ if (!originClaudeSessionId) return null;
529
+ let senderEpicId = null;
530
+ let source = null;
531
+ try {
532
+ const { resolveSourcePromptIdFromClaudeSession } = require('../prd/prdCreate.cjs');
533
+ senderEpicId = resolveSourcePromptIdFromClaudeSession(v.fromCwd, originClaudeSessionId) || null;
534
+ if (senderEpicId) {
535
+ const epic = readActiveIndex(v.fromCwd).sessions[senderEpicId];
536
+ source = (epic && epic.source) || null;
537
+ }
538
+ } catch { return null; }
539
+ if (!senderEpicId || !source || source.producer !== 'new-epic-ui' || !source.macroId) return null;
540
+
541
+ let macro = null;
542
+ try {
543
+ const listMacros = deps.listMacros || require('../persona-macro/macroLibrary.cjs').listMacros;
544
+ macro = ((await listMacros()) || []).find((m) => m && m.id === source.macroId) || null;
545
+ } catch { /* unreadable library → denied below */ }
546
+ if (!macro) return { granted: false, reason: `macro ${source.macroId} no longer exists` };
547
+ const { macroAllowsAutoStart } = require('../persona-macro/macroLibrary.cjs');
548
+ if (!macroAllowsAutoStart(macro, v.toCwd)) {
549
+ return { granted: false, reason: `macro ${macro.id} does not allow auto-start in ${path.basename(v.toCwd)}` };
550
+ }
551
+ if (!AUTO_START_TAGS.includes(v.tag)) {
552
+ return { granted: false, reason: `macro auto-start covers bug and feature work only (tag was ${v.tag})` };
553
+ }
554
+ if ((macroGrantCounts.get(senderEpicId) || 0) >= MAX_MACRO_AUTO_STARTS) {
555
+ return { granted: false, reason: `macro auto-start limit of ${MAX_MACRO_AUTO_STARTS} reached for this session` };
556
+ }
557
+ return {
558
+ granted: true,
559
+ ground: 'macro',
560
+ macroId: macro.id,
561
+ macroLabel: macro.label || macro.id,
562
+ senderEpicId,
563
+ };
564
+ }
565
+
488
566
  /**
489
567
  * openFeedbackSession(input, deps?) → { ok, status?, error?, epicId, toCwd, ... }
490
568
  *
@@ -516,7 +594,23 @@ async function openFeedbackSession(input, deps = {}) {
516
594
  typeof input.originClaudeSessionId === 'string' && input.originClaudeSessionId
517
595
  ? input.originClaudeSessionId
518
596
  : null;
519
- const auto = verifyAutoStart(v, originClaudeSessionId);
597
+ const macroAuto = await verifyMacroAutoStart(v, originClaudeSessionId, deps);
598
+ let auto = macroAuto && macroAuto.granted ? macroAuto : verifyAutoStart(v, originClaudeSessionId);
599
+ // A macro denial is the more specific reason when verifyAutoStart (no
600
+ // autoStart flag) would only say "not requested".
601
+ if (!auto.granted && macroAuto && !macroAuto.granted) auto = macroAuto;
602
+ const isMacro = auto.granted && auto.ground === 'macro';
603
+ // Reserve at grant time (re-checked after the verify's await so concurrent
604
+ // sends cannot overshoot the cap); released below if the mint throws.
605
+ if (isMacro) {
606
+ const used = macroGrantCounts.get(auto.senderEpicId) || 0;
607
+ if (used >= MAX_MACRO_AUTO_STARTS) {
608
+ auto = { granted: false, reason: `macro auto-start limit of ${MAX_MACRO_AUTO_STARTS} reached for this session` };
609
+ } else {
610
+ macroGrantCounts.set(auto.senderEpicId, used + 1);
611
+ }
612
+ }
613
+ const macroGranted = auto.granted && auto.ground === 'macro';
520
614
  const verifiedAt = new Date().toISOString();
521
615
 
522
616
  // The MCP client can't know its own Epic id — it only inherits the claude
@@ -566,12 +660,20 @@ async function openFeedbackSession(input, deps = {}) {
566
660
  ...(v.fromEpicId ? { fromEpicId: v.fromEpicId } : {}),
567
661
  ...(auto.granted
568
662
  ? {
569
- autoApprove: {
570
- requestedBy: 'human',
571
- quote: auto.quote,
572
- verifiedAt,
573
- fromClaudeSessionId: originClaudeSessionId,
574
- },
663
+ autoApprove: macroGranted
664
+ ? {
665
+ requestedBy: 'macro',
666
+ macroId: auto.macroId,
667
+ macroLabel: auto.macroLabel,
668
+ verifiedAt,
669
+ fromClaudeSessionId: originClaudeSessionId,
670
+ }
671
+ : {
672
+ requestedBy: 'human',
673
+ quote: auto.quote,
674
+ verifiedAt,
675
+ fromClaudeSessionId: originClaudeSessionId,
676
+ },
575
677
  }
576
678
  : {}),
577
679
  proposal: {
@@ -586,6 +688,10 @@ async function openFeedbackSession(input, deps = {}) {
586
688
  mintAuthority: MINT_AUTHORITY_CROSS_PROJECT_FEEDBACK,
587
689
  });
588
690
  } catch (e) {
691
+ if (macroGranted) {
692
+ const n = (macroGrantCounts.get(auto.senderEpicId) || 1) - 1;
693
+ if (n > 0) macroGrantCounts.set(auto.senderEpicId, n); else macroGrantCounts.delete(auto.senderEpicId);
694
+ }
589
695
  return { ok: false, status: 500, error: `could not open the feedback session: ${e.message}` };
590
696
  }
591
697
 
@@ -598,7 +704,7 @@ async function openFeedbackSession(input, deps = {}) {
598
704
  title: v.title,
599
705
  series: v.series,
600
706
  autoStartGranted: auto.granted,
601
- autoStartReason: auto.granted ? 'verified human request' : auto.reason,
707
+ autoStartReason: auto.granted ? (macroGranted ? `macro grant ${auto.macroId}` : 'verified human request') : auto.reason,
602
708
  });
603
709
 
604
710
  if (auto.granted) {
@@ -617,7 +723,9 @@ async function openFeedbackSession(input, deps = {}) {
617
723
  + (v.series ? ` [${seriesLine(v.series)}]` : '')
618
724
  + '. '
619
725
  + (auto.granted
620
- ? 'It was auto-approved at the human\'s explicit request and is starting in that project.'
726
+ ? (macroGranted
727
+ ? `It was auto-approved by the "${auto.macroLabel}" macro (${auto.macroId}) and is starting in that project.`
728
+ : 'It was auto-approved at the human\'s explicit request and is starting in that project.')
621
729
  : 'It will not run until a human in that project approves it.'),
622
730
  );
623
731
  } catch {
@@ -632,11 +740,15 @@ async function openFeedbackSession(input, deps = {}) {
632
740
  fromCwd: v.fromCwd,
633
741
  tag: v.tag,
634
742
  status: auto.granted ? 'auto-approved' : 'proposed',
635
- ...(v.autoStart ? { autoStart: auto.granted ? { granted: true } : { granted: false, reason: auto.reason } } : {}),
743
+ ...(v.autoStart || macroAuto ? { autoStart: auto.granted ? { granted: true } : { granted: false, reason: auto.reason } } : {}),
636
744
  receiptOnOriginEpic,
637
745
  // Say plainly what did NOT happen, same posture as create-prd's
638
746
  // `enqueued: false` — never let a caller report this as "work started".
639
- note: auto.granted
747
+ note: macroGranted
748
+ ? `Auto-approved by the "${auto.macroLabel}" macro (${auto.macroId}), which the human launched this session `
749
+ + 'from and which allows auto-start in this project: the session is starting in the receiving project. '
750
+ + 'There is no callback: if you need an answer, ask the human to follow up.'
751
+ : auto.granted
640
752
  ? 'Auto-approved at the human\'s explicit request (verified against their chat prompt): the session '
641
753
  + 'is starting in the receiving project. There is no callback: if you need an answer, ask the human '
642
754
  + 'to follow up.'
@@ -783,6 +895,9 @@ module.exports = {
783
895
  MAX_TITLE_CHARS,
784
896
  MAX_BODY_CHARS,
785
897
  MAX_REFERENCES,
898
+ MAX_MACRO_AUTO_STARTS,
899
+ verifyMacroAutoStart,
900
+ quoteNamesTarget,
786
901
  PROJECTS_DIR,
787
902
  resolveProjectsDir,
788
903
  isSessionManagerProject,
@@ -1,9 +1,15 @@
1
1
  /**
2
2
  * macroAdminRoutes.cjs — loopback admin HTTP routes so an agent session (via
3
- * the scheduler MCP, next PRD) can list and create/update a HOT KEYS macro
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
- let raw;
42
- try {
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 = {
@@ -92,7 +92,31 @@ function readAsset(name) {
92
92
  };
93
93
  }
94
94
 
95
+ /**
96
+ * Basenames of local stylesheet/script references in dist-web/index.html that the manifest
97
+ * cannot serve (e.g. nested under assets/). ['index.html'] when the root or index.html is absent.
98
+ */
99
+ function missingEntryFiles() {
100
+ let html;
101
+ try { html = fs.readFileSync(path.join(webRoot(), 'index.html'), 'utf8'); } catch { return ['index.html']; }
102
+ const served = new Set(assetManifest().files.map((f) => f.name));
103
+ const refs = [];
104
+ for (const m of html.matchAll(/<script\b[^>]*?\bsrc\s*=\s*["']([^"']+)["']/gi)) refs.push(m[1]);
105
+ for (const m of html.matchAll(/<link\b[^>]*>/gi)) {
106
+ if (!/\brel\s*=\s*["']?stylesheet/i.test(m[0])) continue;
107
+ const h = /\bhref\s*=\s*["']([^"']+)["']/i.exec(m[0]);
108
+ if (h) refs.push(h[1]);
109
+ }
110
+ const missing = [];
111
+ for (const ref of refs) {
112
+ if (/^(https?:)?\/\//i.test(ref) || /^[a-z][a-z0-9+.-]*:/i.test(ref)) continue;
113
+ const name = path.basename(ref.split(/[?#]/)[0]);
114
+ if (name && !served.has(name) && !missing.includes(name)) missing.push(name);
115
+ }
116
+ return missing;
117
+ }
118
+
95
119
  module.exports = {
96
- assetManifest, readAsset, MAX_ASSET_BYTES,
120
+ assetManifest, readAsset, missingEntryFiles, MAX_ASSET_BYTES,
97
121
  __test: { setRoot: (p) => { _rootOverride = p; } },
98
122
  };
@@ -185,11 +185,22 @@ function chunkFrames(value, maxBytes = DEFAULT_FRAME_BYTES) {
185
185
  const json = JSON.stringify(value === undefined ? null : value)
186
186
  const buf = Buffer.from(json, 'utf8')
187
187
  if (buf.length > MAX_VALUE_BYTES) return { ok: false, reason: 'too_large' }
188
- const limit = Math.max(4, maxBytes - 1)
188
+ // Budget is the JSON-escaped size of each slice (quotes/backslashes double,
189
+ // control bytes become \\n or \\u00XX) because the frame is re-stringified
190
+ // and then base64url-encoded inside an e2e:box.
191
+ const limit = Math.max(12, maxBytes - 1)
189
192
  const slices = []
190
193
  let start = 0
191
194
  while (start < buf.length) {
192
- let end = Math.min(start + limit, buf.length)
195
+ let end = start
196
+ let cost = 0
197
+ while (end < buf.length) {
198
+ const b = buf[end]
199
+ const c = b === 0x22 || b === 0x5c ? 2 : b < 0x20 ? (b === 0x0a || b === 0x0d || b === 0x09 || b === 0x08 || b === 0x0c ? 2 : 6) : 1
200
+ if (cost + c > limit) break
201
+ cost += c
202
+ end++
203
+ }
193
204
  if (end < buf.length) {
194
205
  while (end > start && (buf[end] & 0xc0) === 0x80) end--
195
206
  }
@@ -66,4 +66,14 @@ function parseWorktreePorcelain(text) {
66
66
  return entries;
67
67
  }
68
68
 
69
- module.exports = { execGit, parseWorktreePorcelain };
69
+ /**
70
+ * Namespace for durable pins on commits a checkout holds but no branch does
71
+ * (a job that left its branch via `git checkout HEAD~0` then committed).
72
+ * Deliberately NOT under refs/heads/sm-job: branchSweep.cjs merges that
73
+ * namespace forward and deletes it, which would silently drop the pin. A
74
+ * ref outside refs/heads, refs/tags and refs/remotes is still a GC root but
75
+ * invisible to branch listings and sweeps.
76
+ */
77
+ const STRANDED_REF_PREFIX = 'refs/sm-stranded/';
78
+
79
+ module.exports = { execGit, parseWorktreePorcelain, STRANDED_REF_PREFIX };