claude-code-session-manager 0.125.0 → 0.126.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 (67) hide show
  1. package/.claude-plugin/marketplace.json +4 -3
  2. package/dist/assets/{AgentLibrary-CcnnJg8P.js → AgentLibrary-bzeuZN4F.js} +1 -1
  3. package/dist/assets/{Button-sA4lqAao.js → Button-8dWfDDuQ.js} +1 -1
  4. package/dist/assets/{DataModel-BSTejIBU.js → DataModel-D4ybBPZN.js} +1 -1
  5. package/dist/assets/{History-DuwlZsQ5.js → History-hsztE6yh.js} +1 -1
  6. package/dist/assets/{Hooks-DHDSoDJ_.js → Hooks-CRmZMQaW.js} +1 -1
  7. package/dist/assets/{Library-XA9osRfi.js → Library-Czt3Bojd.js} +1 -1
  8. package/dist/assets/{ListDetail-B3goE3Wc.js → ListDetail-Cr6Ct_WX.js} +1 -1
  9. package/dist/assets/{McpServers-cMZTsPS6.js → McpServers-CeXJ2bng.js} +1 -1
  10. package/dist/assets/{Memory-D6qntpZ0.js → Memory-caujO8O3.js} +1 -1
  11. package/dist/assets/{Panel-DIyJXHfp.js → Panel-D64i9tGz.js} +1 -1
  12. package/dist/assets/{Permissions-DJda4Aii.js → Permissions-DpWOIrvr.js} +1 -1
  13. package/dist/assets/{Plugins-DcdRVBnU.js → Plugins-Bd1ekP5P.js} +2 -2
  14. package/dist/assets/{ProvenanceBadge-BSI_2wAv.js → ProvenanceBadge-B96A_uZf.js} +1 -1
  15. package/dist/assets/{SaveBar-CeL4vXRp.js → SaveBar-D0Y2t-Ao.js} +1 -1
  16. package/dist/assets/{Scheduler-CTd19y5U.js → Scheduler-Y5_YbNrC.js} +1 -1
  17. package/dist/assets/{ScopeSwitcher-BMiHySnz.js → ScopeSwitcher-BmWA_dP9.js} +1 -1
  18. package/dist/assets/{Settings-D-oIEKZy.js → Settings-Bcf65bpL.js} +1 -1
  19. package/dist/assets/{SkillReferenceGraph-B_7WfFjn.js → SkillReferenceGraph-BeSNXloA.js} +1 -1
  20. package/dist/assets/{Skills-CKpgxhSS.js → Skills-DwnQKJVc.js} +1 -1
  21. package/dist/assets/{SystemPrompt-BjJPTx_a.js → SystemPrompt-Dih6SCmL.js} +1 -1
  22. package/dist/assets/{TagLibrary-DJBB4gL0.js → TagLibrary-BZ-Kp10P.js} +1 -1
  23. package/dist/assets/{TiptapBody-C9Cu2GBL.js → TiptapBody-C2nEUmF7.js} +1 -1
  24. package/dist/assets/{Toggle-DbIRTOix.js → Toggle-Dw8-zNQo.js} +1 -1
  25. package/dist/assets/{ViewTabs-BDpHur6l.js → ViewTabs-CoYPKGN-.js} +1 -1
  26. package/dist/assets/{historyTotals-WCJHsBMq.js → historyTotals-BbKcNpV7.js} +1 -1
  27. package/dist/assets/{index-BD0ufZqe.js → index-DgPUERhe.js} +581 -581
  28. package/dist/assets/{settingsSchema-DmjBj3q7.js → settingsSchema-6doG_61l.js} +1 -1
  29. package/dist/assets/{skillFrontmatter-Tn_XHajE.js → skillFrontmatter-BYMYWDfb.js} +1 -1
  30. package/dist/assets/{useAgentsDirWatch-Vz2iXtsQ.js → useAgentsDirWatch-Cqabjieh.js} +1 -1
  31. package/dist/index.html +1 -1
  32. package/dist-web/{assets/app.js → app.js} +350 -350
  33. package/dist-web/index.html +2 -2
  34. package/package.json +4 -2
  35. package/plugins/session-manager-dev/.claude-plugin/plugin.json +4 -3
  36. package/plugins/session-manager-dev/skills/develop/SKILL.md +2 -1
  37. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  38. package/scripts/README.md +3 -1
  39. package/scripts/scheduler-mcp-server.cjs +17 -4
  40. package/src/main/build-info.json +4 -4
  41. package/src/main/chatRunner.cjs +36 -2
  42. package/src/main/lib/epic/epicMint.cjs +6 -0
  43. package/src/main/lib/epic/epicSweepValidator.cjs +1 -1
  44. package/src/main/lib/epic/epicValidationHook.cjs +1 -1
  45. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  47. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  48. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  49. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  50. package/src/main/lib/git/gitExec.cjs +11 -1
  51. package/src/main/lib/git/gitWorktree.cjs +255 -9
  52. package/src/main/lib/git/jobWorktree.cjs +5 -0
  53. package/src/main/lib/mcpToolCatalog.cjs +9 -3
  54. package/src/main/lib/persona-macro/macroLibrary.cjs +21 -0
  55. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  56. package/src/main/lib/promptSessionSchema.cjs +6 -1
  57. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  58. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  59. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  60. package/src/main/runVerify.cjs +59 -110
  61. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  62. package/src/main/scheduler/reviewLadder.cjs +11 -5
  63. package/src/main/scheduler.cjs +140 -22
  64. package/src/main/templates/PRD_AUTHORING.md +6 -2
  65. package/src/main/webRemote.cjs +9 -0
  66. package/src/preload/api.d.ts +7 -1
  67. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -7,8 +7,8 @@
7
7
  <link rel="preconnect" href="https://fonts.googleapis.com">
8
8
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
9
  <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;0,6..72,700;1,6..72,400&family=Geist:wght@300;400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
10
- <script type="module" crossorigin src="./assets/app.js"></script>
11
- <link rel="stylesheet" crossorigin href="./assets/app.css">
10
+ <script type="module" crossorigin src="./app.js"></script>
11
+ <link rel="stylesheet" crossorigin href="./app.css">
12
12
  </head>
13
13
  <body class="bg-bg text-fg font-sans antialiased">
14
14
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.125.0",
3
+ "version": "0.126.0",
4
4
  "description": "Local cockpit for the Claude Code CLI — multi-tab terminal, full config surface, scheduler, voice dictation, and live observability.",
5
5
  "type": "module",
6
6
  "main": "src/main/index.cjs",
@@ -37,7 +37,7 @@
37
37
  "dev": "concurrently -k -n vite,electron -c magenta,cyan \"npm:dev:renderer\" \"npm:dev:electron\"",
38
38
  "dev:renderer": "vite",
39
39
  "dev:electron": "wait-on http://localhost:5173 && SM_DEV=1 electron .",
40
- "build": "vite build && vite build --config vite.web.config.ts",
40
+ "build": "vite build && vite build --config vite.web.config.ts && node scripts/check-dist-web.cjs",
41
41
  "build:web": "vite build --config vite.web.config.ts",
42
42
  "dist:stage": "npm run build && node scripts/package/stage.cjs",
43
43
  "dist:mac": "npm run dist:stage && electron-builder --config electron-builder.yml --mac --publish never",
@@ -63,6 +63,8 @@
63
63
  "manual:build": "node web/manual/build.mjs",
64
64
  "manual:figures": "xvfb-run -a node web/manual/capture-figures.mjs",
65
65
  "lint:selectors": "node scripts/check-unstable-selectors.cjs",
66
+ "hooks:install": "bash scripts/install-git-hooks.sh",
67
+ "identity:scan": "bash scripts/identity-guard.sh tree",
66
68
  "lint:hooks": "node scripts/check-conditional-hooks.cjs",
67
69
  "lint:docs": "node scripts/check-doc-hierarchy.cjs",
68
70
  "lint:paths": "node scripts/check-ops-path-literals.cjs",
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "session-manager-dev",
3
3
  "description": "The default end-to-end development skillset for the Claude Code Session Manager: decompose work into scheduler PRDs and track them to a validated finish (/develop), publish releases to npm (/builder), and hand a finding to another project on this machine (/send-feedback). Together with the session-manager scheduler these form a develop → queue → validate → release loop.",
4
- "version": "0.2.1",
4
+ "version": "0.2.3",
5
5
  "author": {
6
- "name": "Stanislav Georgiev",
7
- "url": "https://github.com/StanislavBG"
6
+ "name": "Bilko Bibitkov",
7
+ "email": "BilkoBibitkov2000@gmail.com",
8
+ "url": "https://bilko.run"
8
9
  },
9
10
  "homepage": "https://github.com/StanislavBG/claude-code-session-manager",
10
11
  "keywords": [
@@ -222,7 +222,8 @@ End every plan with exactly one validate PRD:
222
222
  (under `$SM_PROJECT_ROOT/session-manager-operations/scheduler/epics/<epic-id>/`; find it by
223
223
  slug under prds/ or prds-archived/, possibly a timestamped subfolder. Why: `session-manager-operations/scheduler/` is gitignored, so it is never in
224
224
  the validator's job worktree. The last: write and commit
225
- `session-manager-operations/reviews/validation/<epic-id>/<validate-slug>.md`.
225
+ `session-manager-operations/reviews/validation/<epic-id>/<validate-slug>.md`, relative to the repository root
226
+ (`git rev-parse --show-toplevel`), not to any subdirectory you `cd`'d into to run a gate.
226
227
  5. Notes: "Work as the validator persona — the procedure is your system prompt." and a line
227
228
  `Base: <sha>`, the SHA from step 11.
228
229
  6. `gate: ["none"]`; `files`: the record path. Why: the validator re-runs each PRD's gate
@@ -148,6 +148,14 @@ stays a plain proposal. If the quote cannot be verified, the call silently falls
148
148
  back to a normal `proposed` session (the result note gives the reason), so
149
149
  report it as a proposal in that case.
150
150
 
151
+ **Auto-start from a macro.** If the human started THIS session by pressing a
152
+ macro whose auto-start setting allows the target project, bug and feature
153
+ proposals there start without any quote: pass no `autoStart` flag and no
154
+ `humanRequestQuote`, and do not try to set the setting yourself (it is edited
155
+ only in the macro editor). It reaches only that one hop, at most 5 times per
156
+ session, and `discussion` or other tags stay plain proposals. The result status
157
+ tells you which happened.
158
+
151
159
  `fromEpicId` is filled in automatically from your running session; pass it
152
160
  explicitly only if you know it and the auto-fill failed. When it resolves, a
153
161
  receipt is chained onto your own session's event log so your transcript records
@@ -161,8 +169,8 @@ human sees the motivation, plan and acceptance criteria on the proposal before
161
169
  approving.
162
170
 
163
171
  If the result status is `auto-approved`, say instead that the session was
164
- auto-approved on the human's request and is starting in `<toCwd>` — not that it
165
- is done.
172
+ auto-approved (on the human's request, or by the macro they pressed) and is
173
+ starting in `<toCwd>` — not that it is done.
166
174
 
167
175
  Do **not** say the other project has been notified-and-is-working-on-it, that
168
176
  the bug is filed/fixed/assigned, or that you'll follow up when they respond.
package/scripts/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # scripts/
2
2
 
3
- Five invocation mechanisms live here: npm scripts, a systemd timer, `.claude/settings.json` hooks, plugin skills, and manual one-shots. This is the index.
3
+ Six invocation mechanisms live here: npm scripts, a systemd timer, `.claude/settings.json` hooks, git hooks, plugin skills, and manual one-shots. This is the index.
4
4
 
5
5
  scripts/lib was moved into src/main/lib (2026-09); nothing under src/ may require from scripts/.
6
6
 
@@ -9,6 +9,8 @@ scripts/lib was moved into src/main/lib (2026-09); nothing under src/ may requir
9
9
  | script | invoked by | shipped on npm |
10
10
  | --- | --- | --- |
11
11
  | audit-ops-hygiene.cjs | manual | yes |
12
+ | identity-guard.sh | `npm run identity:scan` (CI `ci` job) and the git hooks from install-git-hooks.sh; rule in `session-manager-operations/architecture/identity-boundary.md` | no |
13
+ | install-git-hooks.sh | `npm run hooks:install`, manual, once per clone and after any guard change | no |
12
14
  | bench/main-bench.cjs | `npm run bench` (main-process micro-benches, plain Node); renderer half is `npm run bench:renderer` (`tests/bench/`, `vitest.bench.config.ts`, not in `test:unit`) | no |
13
15
  | page-surface.cjs | manual and by the page steward personas `.claude/agents/page-*.md`; derives a page's owned/shared files, window.api methods, main handlers and tests | no |
14
16
  | check-page-stewards.cjs | `npm run lint:page-stewards` (in `lint`) — every nav page has a valid `.claude/agents/page-<key>.md` steward persona; ratchets PENDING | no |
@@ -200,6 +200,15 @@ const CREATE_PRD_ITEM_SCHEMA = {
200
200
  type: 'string',
201
201
  description: 'Optional: WHO executes this PRD — the persona name (a file at ~/.claude/agents/<name>.md, e.g. "dev-lead") the executor should adopt. Distinct from `tag` (what kind of work); this is who does it. Defaults to "dev-lead" when omitted. Rejected at write time if the name does not resolve to a readable persona file.',
202
202
  },
203
+ deliverable: {
204
+ type: 'string',
205
+ enum: ['artifact'],
206
+ description: 'Optional: set to "artifact" ONLY when this PRD truthfully lands no commit (publish, live migration, probe) and instead writes git-excluded output files during the run. Requires artifactPaths. A no-commit PRD with no declaration parks in needs_review.',
207
+ },
208
+ artifactPaths: {
209
+ type: 'array', items: { type: 'string' },
210
+ description: 'Required with deliverable: "artifact" (and refused without it): every git-excluded file this PRD writes during the run, e.g. a built file in a gitignored folder. Relative paths, never containing "..", no commas or brackets. Each must be non-empty and freshly written.',
211
+ },
203
212
  quietMachine: {
204
213
  type: 'boolean',
205
214
  description: 'Optional: set true only when this PRD\'s acceptance criteria are wall-clock/timing measurements (frame time, performance fences) that CPU contention from concurrent jobs would invalidate. The scheduler dispatches it only once zero other jobs are running machine-wide, and holds every other job off the whole slot pool for its run — a whole-machine exclusive lease, not a per-project one. If the machine never goes quiet within the configured wait window (default 30 minutes), it dispatches anyway and is marked degraded. Opt-in only; omit for ordinary PRDs.',
@@ -454,7 +463,7 @@ const TOOLS = [
454
463
  },
455
464
  humanRequestQuote: {
456
465
  type: 'string',
457
- description: "Required with autoStart. Copy VERBATIM from the human's own message in this conversation; that message must name the target project. Do not paraphrase or write it yourself.",
466
+ description: "Required with autoStart. Copy VERBATIM from the human's own message in this conversation; the quoted words themselves must name the target project. Do not paraphrase or write it yourself.",
458
467
  },
459
468
  },
460
469
  required: ['toCwd', 'fromCwd', 'title', 'motivation', 'acceptanceCriteria', 'body'],
@@ -777,7 +786,11 @@ async function handleCallTool(request) {
777
786
  // Epic and chain a receipt onto it. Never invents an Epic — an
778
787
  // unresolvable id just means no receipt.
779
788
  const payload = { ...args };
780
- if (!payload.fromEpicId && process.env.SM_CHAT_SESSION_ID) {
789
+ // payload starts as a copy of args: drop any caller-supplied identity so
790
+ // only this process's own env can vouch for the session (a scheduled PRD
791
+ // job has no SM_CHAT_SESSION_ID and so cannot claim one).
792
+ delete payload.originClaudeSessionId;
793
+ if (process.env.SM_CHAT_SESSION_ID) {
781
794
  payload.originClaudeSessionId = process.env.SM_CHAT_SESSION_ID;
782
795
  }
783
796
  // See scheduler_create_prd's own SM_PROJECT_ROOT forwarding above.
@@ -792,10 +805,10 @@ async function handleCallTool(request) {
792
805
  let note = '';
793
806
  if (result?.ok !== false) {
794
807
  if (result?.status === 'auto-approved') {
795
- note = ' — auto-approved on the human\'s explicit request; the session is starting in the receiving project. No reply channel; the work is not done yet.';
808
+ note = ' — the session was auto-approved and is starting in the receiving project. No reply channel; the work is not done yet.';
796
809
  } else {
797
810
  note = ' — delivered as a PROPOSED session in the receiving project; it runs only if a human there presses Approve & start. No reply channel.';
798
- if (args.autoStart && result?.autoStart && result.autoStart.granted !== true && result.autoStart.reason) {
811
+ if (result?.autoStart && result.autoStart.granted === false && result.autoStart.reason) {
799
812
  note += ` Auto-start was requested but not granted: ${result.autoStart.reason}`;
800
813
  }
801
814
  }
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.125.0",
3
- "gitSha": "3b39163b6942d4b5b636b06dc2d737366b1d78e2",
4
- "gitShortSha": "3b39163b",
2
+ "version": "0.126.0",
3
+ "gitSha": "52a58ff337bbb86c0de1841f70b2220fce04877a",
4
+ "gitShortSha": "52a58ff3",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-10-27T02:44:41.942Z",
6
+ "builtAt": "2026-10-31T16:13:41.329Z",
7
7
  "dirty": false
8
8
  }
@@ -269,6 +269,29 @@ const SCHEDULER_TURN_INSTRUCTION =
269
269
  `Make the safest reasonable choice for anything left open, and end with a short report ` +
270
270
  `of what you did.\n\n`;
271
271
 
272
+ /**
273
+ * Picks the instruction block that opens a turn: scheduler turns and
274
+ * auto-started inbound Epics have no human watching, so they never ask.
275
+ */
276
+ /** Only the first (inbound-proposal) turn earns a follow-up; scheduler turns never chain. */
277
+ function shouldFollowUp(origin) {
278
+ return origin === 'inbound-proposal';
279
+ }
280
+
281
+ function turnInstructionFor(origin, cwd, sessionId) {
282
+ if (origin === 'scheduler') {
283
+ // An auto-started Epic with no PRDs needs /develop Phase 1 (plan), not Phase 2.
284
+ const auto = require('./lib/feedback-remote/autoStartedSession.cjs');
285
+ if (auto.autoStartNeedsPlan(cwd, sessionId)) return auto.autoStartTurnInstruction(STOP_SENTINEL);
286
+ return SCHEDULER_TURN_INSTRUCTION;
287
+ }
288
+ if (origin === 'inbound-proposal') {
289
+ const auto = require('./lib/feedback-remote/autoStartedSession.cjs');
290
+ if (auto.isAutoStartedEpic(cwd, sessionId)) return auto.autoStartTurnInstruction(STOP_SENTINEL);
291
+ }
292
+ return STOP_SIGNAL_INSTRUCTION;
293
+ }
294
+
272
295
  // tab+prompt keys of scheduler-originated prompts awaiting their run() (consumed once).
273
296
  const schedulerPrompts = new Map();
274
297
  const SCHEDULER_PROMPT_TTL_MS = 6 * 60 * 60 * 1000;
@@ -581,7 +604,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
581
604
 
582
605
  // Prepend the stop-signal protocol instruction and the chat-mode truth
583
606
  // instruction to every prompt
584
- const fullPrompt = (origin === 'scheduler' ? SCHEDULER_TURN_INSTRUCTION : STOP_SIGNAL_INSTRUCTION)
607
+ const fullPrompt = turnInstructionFor(origin, cwd, sessionId)
585
608
  + CHAT_MODE_TRUTH_INSTRUCTION + prompt;
586
609
 
587
610
  // sessionId is the Epic's claudeSessionId for an Epic-backed tab (see
@@ -830,6 +853,15 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
830
853
  console.error('[chatRunner] recordExchange failed:', err?.message ?? err);
831
854
  });
832
855
  }
856
+ if (shouldFollowUp(origin)) {
857
+ try {
858
+ require('./lib/feedback-remote/autoStartedSession.cjs').autoStartFollowUp({
859
+ cwd, tabId, sessionId, send: enqueueExternalPrompt,
860
+ });
861
+ } catch (err) {
862
+ console.error('[chatRunner] auto-start follow-up failed:', err?.message ?? err);
863
+ }
864
+ }
833
865
  }
834
866
  } else {
835
867
  emitTerminal('chat:run:error', {
@@ -1113,7 +1145,7 @@ function registerChatHandlers() {
1113
1145
  // A user send is always accepted now (queued behind the tab's live run if
1114
1146
  // one holds it), but the renderer gets the truth either way rather than a
1115
1147
  // success it can't verify.
1116
- const outcome = run({ tabId, sessionId, prompt, cwd, resume: !!resume, promptId });
1148
+ const outcome = run({ tabId, sessionId, prompt, cwd, resume: !!resume, promptId, origin });
1117
1149
  return { ok: outcome.accepted !== false, queued: !!outcome.queued, reason: outcome.reason };
1118
1150
  }));
1119
1151
 
@@ -1144,6 +1176,8 @@ module.exports = {
1144
1176
  attachWindow,
1145
1177
  registerChatHandlers,
1146
1178
  noteChatRunOrigin,
1179
+ turnInstructionFor,
1180
+ shouldFollowUp,
1147
1181
  parseStopSignal,
1148
1182
  splitStopSignal,
1149
1183
  parseContextUsageMarkdown,
@@ -69,6 +69,12 @@ const MINT_AUTHORITY_NEW_EPIC_UI = 'new-epic-ui';
69
69
  // that is all it may do. The removed channel let an agent file work into the
70
70
  // project it was already running in, which is what /develop-inside-your-own-
71
71
  // Epic replaced and which stays refused.
72
+ //
73
+ // Two grounds can stamp source.autoApprove on a cross-project Epic (it is
74
+ // still minted 'proposed'; the receiving renderer approves it): a verified
75
+ // human request quote, or a MACRO ground — the sender Epic was launched by a
76
+ // human pressing a macro whose autoStartTargets names the target project
77
+ // (bug/feature only, capped per sender Epic). Anything else stays a proposal.
72
78
  const MINT_AUTHORITY_CROSS_PROJECT_FEEDBACK = 'cross-project-feedback';
73
79
 
74
80
  const MINT_AUTHORITIES = Object.freeze([
@@ -41,7 +41,7 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now }) {
41
41
  const acceptanceCriteria = names.map(
42
42
  (name) => `${name} verified against its PRD file (find it by slug under $SM_PROJECT_ROOT/session-manager-operations/scheduler/epics/${epicId}/prds/ or prds-archived/, possibly in a timestamped subfolder)`,
43
43
  );
44
- acceptanceCriteria.push(`Record written and committed at ${recordPath}`);
44
+ acceptanceCriteria.push(`Record written and committed at ${recordPath}, relative to the repository root (git rev-parse --show-toplevel), never relative to a subdirectory you cd'd into`);
45
45
 
46
46
  const base = baseSha
47
47
  ? `Base: ${baseSha}`
@@ -56,7 +56,7 @@ function buildSettledDigest(settle, { epicId, notValidatedReason } = {}) {
56
56
  const notValidated = (s.uncovered || []).map((u) => (typeof u === 'string' ? u : u.slug));
57
57
  const lines = [
58
58
  `PLAN SETTLED — no PRD of this session is pending or running. This is ONE digest, not a per-PRD request.`,
59
- `Validation record folder: session-manager-operations/reviews/validation/${epicId}/`,
59
+ `Validation record folder (relative to the repository root): session-manager-operations/reviews/validation/${epicId}/`,
60
60
  'Do NOT re-verify VERIFIED PRDs — a validator already checked them.',
61
61
  ];
62
62
  if (verified.length) {
@@ -25,7 +25,7 @@
25
25
  * them from the command line.
26
26
  */
27
27
 
28
- const { integrateEpicBranch, cleanupEpicWorktree } = require('../git/gitWorktree.cjs');
28
+ const { integrateEpicBranch, cleanupEpicWorktree, reconcileWorktreeHead } = require('../git/gitWorktree.cjs');
29
29
  const { validatePath } = require('../../config.cjs');
30
30
 
31
31
  /**
@@ -40,6 +40,14 @@ const { validatePath } = require('../../config.cjs');
40
40
  */
41
41
  async function mergeEpicToMainViaIpc(cwd, epicId, branch, dir, carriedPaths) {
42
42
  validatePath(cwd);
43
+ if (dir) {
44
+ const rec = await reconcileWorktreeHead({ cwd, dir, branch, key: epicId });
45
+ if (rec && rec.action === 'diverged') {
46
+ const reason = `worktree HEAD ${rec.finalHead} is not on ${branch}; commit pinned at ${rec.pinnedRef || 'no ref'} — resolve manually`;
47
+ console.log(`[epicWorktreeMerge] ${epicId}: needs manual resolution (${reason})`);
48
+ return { ok: false, status: 'needs_merge_resolution', reason };
49
+ }
50
+ }
43
51
  const outcome = await integrateEpicBranch({ cwd, branch, epicId, carriedPaths });
44
52
  if (!outcome.ok) {
45
53
  console.log(`[epicWorktreeMerge] ${epicId}: needs manual resolution (${outcome.reason})`);
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ /**
7
+ * autoStartedSession.cjs — recognises an Epic that cross-project feedback
8
+ * auto-started (nobody watching its first turn) and supplies the no-ask turn
9
+ * instruction for it. Takes the stop sentinel as an argument so it never
10
+ * requires chatRunner.cjs. See epicMint.cjs for the autoApprove stamp.
11
+ */
12
+
13
+ /** Finds the Epic by claude session id → { epicId, session } or null. Never throws. */
14
+ function findEpic(cwd, claudeSessionId) {
15
+ try {
16
+ if (!cwd || !claudeSessionId) return null;
17
+ const { readActiveIndex } = require('../epic/epicMint.cjs');
18
+ const { sessions } = readActiveIndex(cwd);
19
+ for (const [key, session] of Object.entries(sessions)) {
20
+ if (session && session.claudeSessionId === claudeSessionId) {
21
+ return { epicId: session.id || key, session };
22
+ }
23
+ }
24
+ return null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ function stampedAutoStart(session) {
31
+ const source = session && session.source;
32
+ return !!(source && source.producer === 'cross-project-feedback' && source.autoApprove);
33
+ }
34
+
35
+ /** True only for an Epic stamped producer 'cross-project-feedback' + autoApprove. Never throws. */
36
+ function isAutoStartedEpic(cwd, claudeSessionId) {
37
+ const found = findEpic(cwd, claudeSessionId);
38
+ return !!found && stampedAutoStart(found.session);
39
+ }
40
+
41
+ function hasMarkdown(dir) {
42
+ try {
43
+ const entries = fs.readdirSync(dir, { recursive: true });
44
+ return entries.some((e) => String(e).toLowerCase().endsWith('.md'));
45
+ } catch {
46
+ return false; // missing folder = empty
47
+ }
48
+ }
49
+
50
+ /**
51
+ * True when the Epic is auto-started, tagged bug or feature, and has no PRD
52
+ * file under prds/ or prds-archived/ (timestamped subfolders included). Never throws.
53
+ */
54
+ function autoStartNeedsPlan(cwd, claudeSessionId) {
55
+ try {
56
+ const found = findEpic(cwd, claudeSessionId);
57
+ if (!found || !stampedAutoStart(found.session)) return false;
58
+ const tag = found.session.tag;
59
+ if (tag !== 'bug' && tag !== 'feature') return false;
60
+ const { resolveEpicPrdWriteDir } = require('../prd/prdLocations.cjs');
61
+ const prds = resolveEpicPrdWriteDir(cwd, found.epicId);
62
+ const archived = path.join(path.dirname(prds), 'prds-archived');
63
+ return !hasMarkdown(prds) && !hasMarkdown(archived);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ const AUTO_START_FOLLOW_UP_PROMPT =
70
+ 'Your first turn ended with nothing queued. Queue the plan now with the /develop skill. ' +
71
+ 'If nothing needs building, say why and stop.';
72
+
73
+ /** Sends one automatic follow-up turn when the first turn left no plan. Never throws. */
74
+ function autoStartFollowUp({ cwd, tabId, sessionId, send }) {
75
+ try {
76
+ if (typeof send !== 'function') return false;
77
+ if (!autoStartNeedsPlan(cwd, sessionId)) return false;
78
+ const r = send(tabId, AUTO_START_FOLLOW_UP_PROMPT, { origin: 'scheduler', sessionId, cwd });
79
+ if (r && typeof r.catch === 'function') r.catch(() => {});
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ function autoStartTurnInstruction(stopSentinel) {
87
+ return (
88
+ `IMPORTANT: This session was started automatically and nobody is watching. ` +
89
+ `Never ask questions and never print ${stopSentinel}. First check the report below ` +
90
+ `against this codebase. If it holds and the Mission is to plan or fix, finish the plan ` +
91
+ `in this turn and queue it with the /develop skill. If it does not hold, say why and ` +
92
+ `stop. End with a short report.\n\n`
93
+ );
94
+ }
95
+
96
+ module.exports = {
97
+ isAutoStartedEpic,
98
+ autoStartNeedsPlan,
99
+ autoStartFollowUp,
100
+ autoStartTurnInstruction,
101
+ AUTO_START_FOLLOW_UP_PROMPT,
102
+ };
@@ -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,