claude-code-session-manager 0.144.0 → 0.146.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 (66) hide show
  1. package/dist/assets/{AppSettings-Z68gQiVE.js → AppSettings-BXfkoKQq.js} +2 -2
  2. package/dist/assets/{History-C3E6y_7t.js → History-l7pBt_vO.js} +1 -1
  3. package/dist/assets/HomeClaudeConfig-DtFwZxTx.js +5 -0
  4. package/dist/assets/{Panel-CnfWs46Z.js → Panel-C5hihgUD.js} +1 -1
  5. package/dist/assets/{ProjectClaudeConfig-CP0Wsg-H.js → ProjectClaudeConfig-B3pODrM-.js} +1 -1
  6. package/dist/assets/{Scheduler-D8un7N3B.js → Scheduler-IU9wo8_u.js} +1 -1
  7. package/dist/assets/{SkillReferenceGraph-DRtZV1Al.js → SkillReferenceGraph-Bmen0OOC.js} +1 -1
  8. package/dist/assets/{Skills-Bg5O2Hyn.js → Skills-jYVxqJr2.js} +1 -1
  9. package/dist/assets/{TiptapBody-BdzoBmqu.js → TiptapBody-Dp2gtbb-.js} +1 -1
  10. package/dist/assets/{Toggle-Dt5K1OXt.js → Toggle-C_0yUCS5.js} +1 -1
  11. package/dist/assets/{VoiceButton-CTLyRgdF.js → VoiceButton-BRPzqDa-.js} +1 -1
  12. package/dist/assets/{historyTotals-B2_KWBga.js → historyTotals-pAv-MFnY.js} +1 -1
  13. package/dist/assets/{index-446b69rr.js → index-C6nhp7m_.js} +496 -496
  14. package/dist/index.html +1 -1
  15. package/dist-web/app.js +427 -427
  16. package/package.json +1 -1
  17. package/plugins/session-manager-dev/skills/develop/SKILL.md +11 -6
  18. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +1 -1
  19. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +8 -4
  20. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +13 -8
  21. package/scripts/scheduler-mcp-server.cjs +4 -3
  22. package/src/main/adminRouteRegistry.cjs +1 -1
  23. package/src/main/build-info.json +4 -4
  24. package/src/main/chatRunner.cjs +35 -5
  25. package/src/main/config.cjs +12 -0
  26. package/src/main/index.cjs +2 -2
  27. package/src/main/ipcSchemas.cjs +5 -0
  28. package/src/main/lib/claude/claudeJsonApproval.cjs +129 -0
  29. package/src/main/lib/claude/headlessMcpServers.cjs +1 -1
  30. package/src/main/lib/claude/personaToolScope.cjs +23 -8
  31. package/src/main/lib/demo-video-kit/resumableRun.cjs +36 -15
  32. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  33. package/src/main/lib/epic/epicOutsideRead.cjs +43 -8
  34. package/src/main/lib/epic/epicSpawnCwd.cjs +1 -0
  35. package/src/main/lib/epic/planReviewInput.cjs +5 -6
  36. package/src/main/lib/epic/scriptStartedBy.cjs +19 -4
  37. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +219 -48
  38. package/src/main/lib/feedback-remote/localAdminHttp.cjs +5 -1
  39. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +6 -3
  40. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +23 -3
  41. package/src/main/lib/feedback-remote/servicePairings.cjs +48 -0
  42. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +11 -6
  43. package/src/main/lib/git/gitWorktree.cjs +17 -0
  44. package/src/main/lib/mcpToolCatalog.cjs +6 -3
  45. package/src/main/lib/opsOwnership.cjs +2 -0
  46. package/src/main/lib/prd/prdCreate.cjs +2 -1
  47. package/src/main/lib/prd/prdMcpReachWarnings.cjs +3 -1
  48. package/src/main/lib/prd/prdSandboxWarnings.cjs +1 -1
  49. package/src/main/lib/scheduler/planReleaseRoute.cjs +53 -5
  50. package/src/main/lib/scheduler/planReviewStore.cjs +24 -2
  51. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  52. package/src/main/lib/scheduler/reviewNotice.cjs +3 -1
  53. package/src/main/lib/scheduler/terminalRunOutcome.cjs +1 -0
  54. package/src/main/lib/tasks/memoryConsolidation.cjs +21 -12
  55. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +131 -11
  56. package/src/main/runVerify.cjs +107 -3
  57. package/src/main/scheduler/gitTreeGuard.cjs +6 -0
  58. package/src/main/scheduler/planReviewHold.cjs +11 -5
  59. package/src/main/scheduler/prdPaths.cjs +10 -1
  60. package/src/main/scheduler.cjs +230 -27
  61. package/src/main/templates/PRD_AUTHORING.md +2 -2
  62. package/src/main/webRemote.cjs +22 -0
  63. package/src/preload/api.d.ts +8 -0
  64. package/src/preload/apiSurface.json +11 -0
  65. package/src/preload/index.cjs +2 -0
  66. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +0 -5
@@ -218,23 +218,58 @@ function startedByOf(raw) {
218
218
  return r.success ? r.data : null;
219
219
  }
220
220
 
221
- /** fixes[] ({ prd, missKind }) from this Epic's PRD files (prds/ and prds-archived/); [] on any failure. */
221
+ let MAX_FIX_FILES = 2000;
222
+ let MAX_FIX_CACHE = 5000;
223
+ /** Test seam: override the per-call file cap and the total cache bound. */
224
+ function _setFixesCapsForTests(files, cache) {
225
+ MAX_FIX_FILES = files == null ? 2000 : files;
226
+ MAX_FIX_CACHE = cache == null ? 5000 : cache;
227
+ }
228
+ /** Leading PRD number of a file name; -1 when it has none. */
229
+ function prdNN(name) {
230
+ const m = /^(\d+)/.exec(name);
231
+ return m ? Number(m[1]) : -1;
232
+ }
233
+ /** abs path -> { mtimeMs, size, fixes } — a repeat read re-parses only files whose stat changed. */
234
+ const fixesCache = new Map();
235
+
236
+ /** fixes[] ({ prd, missKind }) from this Epic's PRD files (prds/ and prds-archived/); [] on any failure. At most MAX_FIX_FILES files per call (the newest by name are kept). */
222
237
  function readEpicFixes(cwd, epicId) {
223
238
  const out = [];
224
239
  try {
225
240
  if (!isSafeEpicId(epicId)) return out;
226
241
  const base = path.join(opsPath(cwd, 'scheduler', 'epics'), epicId);
242
+ let files = [];
227
243
  for (const sub of ['prds', 'prds-archived']) {
228
244
  let names;
229
245
  try { names = fs.readdirSync(path.join(base, sub)); } catch { continue; }
230
- for (const n of names.filter((x) => x.endsWith('.md')).sort()) {
231
- try {
232
- const { fm } = splitFrontmatter(fs.readFileSync(path.join(base, sub, n), 'utf8'));
246
+ for (const n of names) if (n.endsWith('.md')) files.push({ n, p: path.join(base, sub, n) });
247
+ }
248
+ files.sort((x, y) => prdNN(x.n) - prdNN(y.n) || (x.n < y.n ? -1 : x.n > y.n ? 1 : x.p < y.p ? -1 : x.p > y.p ? 1 : 0));
249
+ files = files.map((f) => f.p);
250
+ if (files.length > MAX_FIX_FILES) files = files.slice(-MAX_FIX_FILES);
251
+ const seen = new Set(files);
252
+ for (const file of files) {
253
+ try {
254
+ const st = fs.statSync(file);
255
+ let hit = fixesCache.get(file);
256
+ if (!hit || hit.mtimeMs !== st.mtimeMs || hit.size !== st.size) {
257
+ const { fm } = splitFrontmatter(fs.readFileSync(file, 'utf8'));
233
258
  const list = typeof fm.fixes === 'string' ? parseFixes(fm.fixes) : null;
234
- for (const f of list || []) out.push({ prd: f.prd, missKind: f.missKind });
235
- } catch { /* skip unreadable PRD */ }
236
- }
259
+ hit = { mtimeMs: st.mtimeMs, size: st.size, fixes: (list || []).map((f) => ({ prd: f.prd, missKind: f.missKind })) };
260
+ fixesCache.set(file, hit);
261
+ } else {
262
+ // LRU: a hit moves the entry to the back so eviction drops the least recently used.
263
+ fixesCache.delete(file);
264
+ fixesCache.set(file, hit);
265
+ }
266
+ while (fixesCache.size > MAX_FIX_CACHE) fixesCache.delete(fixesCache.keys().next().value);
267
+ for (const f of hit.fixes) out.push({ prd: f.prd, missKind: f.missKind });
268
+ } catch { fixesCache.delete(file); /* skip unreadable or deleted PRD */ }
237
269
  }
270
+ // Drop deleted/out-of-scope files of this Epic from the cache.
271
+ const prefix = base + path.sep;
272
+ for (const k of fixesCache.keys()) if (k.startsWith(prefix) && !seen.has(k)) fixesCache.delete(k);
238
273
  } catch { /* none */ }
239
274
  return out;
240
275
  }
@@ -458,4 +493,4 @@ async function listOpenEpicRecords(cwd, opts = {}) {
458
493
  }
459
494
  }
460
495
 
461
- module.exports = { readVerdictFiles, listOpenEpicRecords, getEpicRecord, findEpicProject };
496
+ module.exports = { readEpicFixes, _setFixesCapsForTests, _fixesCacheSizeForTests: () => fixesCache.size, get MAX_FIX_FILES() { return MAX_FIX_FILES; }, get MAX_FIX_CACHE() { return MAX_FIX_CACHE; }, readVerdictFiles, listOpenEpicRecords, getEpicRecord, findEpicProject };
@@ -77,6 +77,7 @@ function restoreEpicWorktree({ dir, branch, baseCwd }) {
77
77
  const run = (args) => execFileSync('git', args, { cwd: baseCwd, stdio: 'ignore', timeout: 15_000 });
78
78
  run(['worktree', 'prune']);
79
79
  run(['worktree', 'add', dir, branch]);
80
+ require('../claude/claudeJsonApproval.cjs').copyExternalIncludeApprovalSync({ fromPath: baseCwd, toPath: dir });
80
81
  return isUsableDir(dir, fs.statSync);
81
82
  } catch {
82
83
  return false;
@@ -72,15 +72,14 @@ function buildPlanReviewInput({ epicId, cwd, epicGoal, validateSlug, members, ba
72
72
  const list = Array.isArray(members) ? members : [];
73
73
  const bare = bareSlug(validateSlug);
74
74
  const slug = `plan-review-${bare}${round && round >= 2 ? `-r${round}` : ''}`;
75
- const recordPath = `session-manager-operations/plan-records/${epicId}/${validateSlug}.plan-review.md`;
76
-
77
75
  const acceptanceCriteria = list.map((m) => `Review ${m.slug}`);
78
- acceptanceCriteria.push(`Record written at ${recordPath}, relative to the job worktree's repository root (git rev-parse --show-toplevel), never relative to a subdirectory you cd'd into. Do not git add or commit it — the scheduler copies it to the main checkout`);
76
+ acceptanceCriteria.push(`Return the review as the structured output object only; write no file — the scheduler saves the record (${validateSlug}.plan-review.json) from it`);
79
77
 
80
78
  const lines = [
81
79
  PERSONA_LINE,
82
80
  `Epic goal: ${epicGoal || 'unknown'}`,
83
81
  baseSha ? `Base: ${baseSha}` : 'Base: unknown',
82
+ 'Deliverable: the structured output object (PLAN_REVIEW_SCHEMA) only. Write no file; the scheduler saves the review.',
84
83
  '',
85
84
  'Plan members:',
86
85
  ];
@@ -110,12 +109,12 @@ function buildPlanReviewInput({ epicId, cwd, epicGoal, validateSlug, members, ba
110
109
  implementationNotes: lines.join('\n'),
111
110
  outOfScope: ['Editing product code', 'Queuing fix PRDs'],
112
111
  gate: ['none'],
113
- files: [recordPath],
114
- deliverable: 'artifact',
115
- artifactPaths: [recordPath],
112
+ // No `files`: the reviewer edits nothing (validateFiles refuses an empty list).
116
113
  agentType: 'plan-reviewer',
117
114
  tag: 'build',
118
115
  sourcePromptId: epicId,
116
+ // The plan's own PRDs are incomplete; without a disposition prdCreate refuses.
117
+ disposition: 'new-head',
119
118
  cwd,
120
119
  };
121
120
  }
@@ -2,7 +2,8 @@
2
2
 
3
3
  /**
4
4
  * scriptStartedBy.cjs — how a script-started Epic records who started it.
5
- * EpicSource.startedBy = { kind: 'script', route, caller?, fromCwd?, fromEpicId? };
5
+ * EpicSource.startedBy = { kind: 'script', route, caller?, fromCwd?, fromEpicId? }
6
+ * | { kind: 'service', serviceId, name } (a paired service under an owner grant);
6
7
  * absent for every human press. 'new-epic-ui' stays the mint authority
7
8
  * (epicMint.cjs); startedBy sits next to it. The stored shape is lenient
8
9
  * (promptSessionSchema.cjs); this is the strict entry-point validator.
@@ -17,7 +18,7 @@ const CallerSchema = z.object({
17
18
  attempt: z.number().int().min(0).optional(),
18
19
  }).strict();
19
20
 
20
- const StartedBySchema = z.object({
21
+ const ScriptStartedBySchema = z.object({
21
22
  kind: z.literal('script'),
22
23
  route: z.string().min(1).max(200),
23
24
  caller: CallerSchema.optional(),
@@ -25,6 +26,20 @@ const StartedBySchema = z.object({
25
26
  fromEpicId: z.string().max(200).optional(),
26
27
  }).strict();
27
28
 
29
+ /** A paired service started it under an owner startWork grant. */
30
+ const ServiceStartedBySchema = z.object({
31
+ kind: z.literal('service'),
32
+ serviceId: z.string().min(1).max(200),
33
+ name: z.string().min(1).max(200),
34
+ }).strict();
35
+
36
+ const StartedBySchema = z.discriminatedUnion('kind', [ScriptStartedBySchema, ServiceStartedBySchema]);
37
+
38
+ /** @param {{ serviceId: string, name: string }} args */
39
+ function buildServiceStartedBy({ serviceId, name }) {
40
+ return ServiceStartedBySchema.parse({ kind: 'service', serviceId, name });
41
+ }
42
+
28
43
  /**
29
44
  * Build a StartedBySchema-valid object, omitting absent/empty keys.
30
45
  * @param {{ route: string, caller?: object, fromCwd?: string, fromEpicId?: string }} args
@@ -40,7 +55,7 @@ function buildStartedBy({ route, caller, fromCwd, fromEpicId } = {}) {
40
55
  }
41
56
  if (typeof fromCwd === 'string' && fromCwd) out.fromCwd = fromCwd;
42
57
  if (typeof fromEpicId === 'string' && fromEpicId) out.fromEpicId = fromEpicId;
43
- return StartedBySchema.parse(out);
58
+ return ScriptStartedBySchema.parse(out);
44
59
  }
45
60
 
46
61
  /**
@@ -68,4 +83,4 @@ async function startedByFromRequest({ route, caller, socket } = {}, deps = {}) {
68
83
  return buildStartedBy({ route, caller, fromCwd, fromEpicId });
69
84
  }
70
85
 
71
- module.exports = { CallerSchema, StartedBySchema, buildStartedBy, startedByFromRequest };
86
+ module.exports = { CallerSchema, StartedBySchema, ScriptStartedBySchema, ServiceStartedBySchema, buildStartedBy, buildServiceStartedBy, startedByFromRequest };
@@ -86,6 +86,7 @@ const {
86
86
  MINT_AUTHORITY_CROSS_PROJECT_FEEDBACK,
87
87
  } = require('../epic/epicMint.cjs');
88
88
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
89
+ const { buildServiceStartedBy } = require('../epic/scriptStartedBy.cjs');
89
90
  const { normalizeExternalRef } = require('../epic/externalRef.cjs');
90
91
  const { recordExternalRef, findEpicByExternalRef, withExternalRefLock } = require('../epic/externalRefIndex.cjs');
91
92
  const { OPS_ROOT_DIR, opsPath } = require('../opsOwnership.cjs');
@@ -118,12 +119,23 @@ const MAX_ORIGIN_ASK_CHARS = 300;
118
119
  const MAX_HUMAN_QUOTE_CHARS = 2000;
119
120
  const KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
120
121
 
121
- /** Bound on how many `~/.claude/projects/` folders listFeedbackTargets will
122
- * resolve. That directory accumulates one folder per path the CLI was ever
123
- * launched from (thousands here — see CLAUDE.md's knownProjectAggregate
124
- * note), so the scan is capped at the most recently active folders and
125
- * reports the truncation rather than silently covering a subset. */
126
- const TARGET_SCAN_LIMIT = 300;
122
+ /** Page size for listFeedbackTargets. The scan itself is NEVER capped — every
123
+ * `~/.claude/projects/` folder is resolved (see the folder memo below) — so a
124
+ * quiet project can't fall off the list; only the returned page is bounded.
125
+ * The old 300-most-recent-folders scan cap silently dropped real projects
126
+ * (2026-11-27: /home/bilko/Projects/3PMahjong missing, 14k folders on disk). */
127
+ const TARGET_PAGE_DEFAULT = 200;
128
+ const TARGET_PAGE_MAX = 1000;
129
+ /** How many transcript folders are resolved concurrently on a cold scan. */
130
+ const TARGET_SCAN_CONCURRENCY = 32;
131
+ /** full folder path -> { mtimeMs, cwd }: the resolved main-checkout cwd (or
132
+ * null) for a transcript folder at that folder mtime. A folder's mtime bumps
133
+ * when a transcript file is added, which is the only thing that can change
134
+ * which file's head names its cwd, so an unchanged mtime means an unchanged
135
+ * answer. Makes every scan after the first a stat pass (14k folders cold
136
+ * ~20 s, warm well under 1 s). Bounded by the folder count on disk; entries
137
+ * for vanished folders are pruned per scan of their root. */
138
+ const targetFolderMemo = new Map();
127
139
 
128
140
  const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
129
141
 
@@ -583,8 +595,32 @@ function verifyAutoStart(v, originClaudeSessionId) {
583
595
  }
584
596
 
585
597
  const MAX_MACRO_AUTO_STARTS = 5;
598
+ /** Request-object key the in-process invoke() sets for a paired service call. */
599
+ const TRUSTED_SERVICE = Symbol.for('sm.trustedService');
586
600
  const AUTO_START_TAGS = Object.freeze(['bug', 'feature']);
587
601
 
602
+ /**
603
+ * verifyServiceAutoStart(v, service) → { granted: true, ground:'service', serviceId, serviceName }
604
+ * | { granted: false, reason }
605
+ * `service` is the paired-service record RE-READ from the store at decision time
606
+ * (null when revoked). Its identity never comes from the request body.
607
+ */
608
+ function verifyServiceAutoStart(v, service) {
609
+ if (!service) return { granted: false, reason: 'the paired service is no longer paired' };
610
+ const { startWorkAllows } = require('./servicePairings.cjs');
611
+ if (!v.autoStart) return { granted: false, reason: 'autoStart was not requested' };
612
+ if (!service.startWork || !service.startWork.targets || service.startWork.targets.length === 0) {
613
+ return { granted: false, reason: `the ${service.name} service has no start-work grant` };
614
+ }
615
+ if (!startWorkAllows(service, v.toCwd)) {
616
+ return { granted: false, reason: `the ${service.name} service's start-work grant does not cover ${path.basename(v.toCwd)}` };
617
+ }
618
+ if (!AUTO_START_TAGS.includes(v.tag)) {
619
+ return { granted: false, reason: `service auto-start covers bug and feature work only (tag was ${v.tag})` };
620
+ }
621
+ return { granted: true, ground: 'service', serviceId: service.serviceId, serviceName: service.name };
622
+ }
623
+
588
624
  // Grants per sender Epic id. In memory, so a restart resets it — accepted
589
625
  // because each press of a macro is a human act.
590
626
  const macroGrantCounts = new Map();
@@ -739,11 +775,25 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
739
775
  typeof input.originClaudeSessionId === 'string' && input.originClaudeSessionId
740
776
  ? input.originClaudeSessionId
741
777
  : null;
742
- const macroAuto = await verifyMacroAutoStart(v, originClaudeSessionId, deps);
743
- let auto = macroAuto && macroAuto.granted ? macroAuto : verifyAutoStart(v, originClaudeSessionId);
744
- // A macro denial is the more specific reason when verifyAutoStart (no
745
- // autoStart flag) would only say "not requested".
746
- if (!auto.granted && macroAuto && !macroAuto.granted) auto = macroAuto;
778
+ // A call from a paired service (identity set only by the in-process invoke
779
+ // channel, never the body) is judged on the service ground alone: a service
780
+ // has no chat to quote and no macro.
781
+ const trustedServiceId = typeof deps.trustedServiceId === 'string' && deps.trustedServiceId ? deps.trustedServiceId : null;
782
+ let serviceAuto = null;
783
+ let macroAuto = null;
784
+ let auto;
785
+ if (trustedServiceId) {
786
+ let service = null;
787
+ try { service = deps.findService ? deps.findService(trustedServiceId) : null; } catch { service = null; }
788
+ serviceAuto = verifyServiceAutoStart(v, service);
789
+ auto = serviceAuto;
790
+ } else {
791
+ macroAuto = await verifyMacroAutoStart(v, originClaudeSessionId, deps);
792
+ auto = macroAuto && macroAuto.granted ? macroAuto : verifyAutoStart(v, originClaudeSessionId);
793
+ // A macro denial is the more specific reason when verifyAutoStart (no
794
+ // autoStart flag) would only say "not requested".
795
+ if (!auto.granted && macroAuto && !macroAuto.granted) auto = macroAuto;
796
+ }
747
797
  const isMacro = auto.granted && auto.ground === 'macro';
748
798
  // Reserve at grant time (re-checked after the verify's await so concurrent
749
799
  // sends cannot overshoot the cap); released below if the mint throws.
@@ -756,6 +806,7 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
756
806
  }
757
807
  }
758
808
  const macroGranted = auto.granted && auto.ground === 'macro';
809
+ const serviceGranted = auto.granted && auto.ground === 'service';
759
810
  const verifiedAt = new Date().toISOString();
760
811
 
761
812
  // The MCP client can't know its own Epic id — it only inherits the claude
@@ -809,7 +860,15 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
809
860
  ...(replyTo ? { replyTo } : {}),
810
861
  ...(auto.granted
811
862
  ? {
812
- autoApprove: macroGranted
863
+ autoApprove: serviceGranted
864
+ ? {
865
+ requestedBy: 'service',
866
+ serviceId: auto.serviceId,
867
+ serviceName: auto.serviceName,
868
+ verifiedAt,
869
+ fromClaudeSessionId: null,
870
+ }
871
+ : macroGranted
813
872
  ? {
814
873
  requestedBy: 'macro',
815
874
  macroId: auto.macroId,
@@ -825,6 +884,7 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
825
884
  },
826
885
  }
827
886
  : {}),
887
+ ...(serviceGranted ? { startedBy: buildServiceStartedBy({ serviceId: auto.serviceId, name: auto.serviceName }) } : {}),
828
888
  proposal: {
829
889
  motivation: v.motivation,
830
890
  originAsk,
@@ -853,7 +913,10 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
853
913
  title: v.title,
854
914
  series: v.series,
855
915
  autoStartGranted: auto.granted,
856
- autoStartReason: auto.granted ? (macroGranted ? `macro grant ${auto.macroId}` : 'verified human request') : auto.reason,
916
+ autoStartReason: auto.granted
917
+ ? (serviceGranted ? `service grant ${auto.serviceId}` : macroGranted ? `macro grant ${auto.macroId}` : 'verified human request')
918
+ : auto.reason,
919
+ ...(serviceGranted ? { serviceId: auto.serviceId, serviceName: auto.serviceName } : {}),
857
920
  });
858
921
 
859
922
  if (auto.granted) {
@@ -872,7 +935,9 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
872
935
  + (v.series ? ` [${seriesLine(v.series)}]` : '')
873
936
  + '. '
874
937
  + (auto.granted
875
- ? (macroGranted
938
+ ? (serviceGranted
939
+ ? `It was auto-approved by the ${auto.serviceName} service grant and is starting in that project.`
940
+ : macroGranted
876
941
  ? `It was auto-approved by the "${auto.macroLabel}" macro (${auto.macroId}) and is starting in that project.`
877
942
  : 'It was auto-approved at the human\'s explicit request and is starting in that project.')
878
943
  : 'It will not run until a human in that project approves it.'),
@@ -890,7 +955,7 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
890
955
  tag: v.tag,
891
956
  ...(v.externalRef ? { externalRef: v.externalRef } : {}),
892
957
  status: auto.granted ? 'auto-approved' : 'proposed',
893
- ...(v.autoStart || macroAuto ? { autoStart: auto.granted ? { granted: true } : { granted: false, reason: auto.reason } } : {}),
958
+ ...(v.autoStart || macroAuto || serviceAuto ? { autoStart: auto.granted ? { granted: true } : { granted: false, reason: auto.reason } } : {}),
894
959
  receiptOnOriginEpic,
895
960
  // True only when source.replyTo was stamped — the MCP note keys its
896
961
  // feedback_reply promise off this, never off the delivery alone.
@@ -899,7 +964,13 @@ async function mintFeedbackSession(v, input, deps, { mint, appendReceipt, notify
899
964
  replyMode: v.replyMode,
900
965
  // Say plainly what did NOT happen, same posture as create-prd's
901
966
  // `enqueued: false` — never let a caller report this as "work started".
902
- note: (macroGranted
967
+ note: (serviceGranted
968
+ ? `Delivered auto-approved by the ${auto.serviceName} service grant (set by the owner for this project): `
969
+ + 'the session is starting in the receiving project. '
970
+ : serviceAuto && !auto.granted
971
+ ? `Delivered as a PROPOSED session (not auto-approved: ${auto.reason}). Nothing runs and no `
972
+ + 'tokens are spent until a human in that project presses Approve & start. '
973
+ : macroGranted
903
974
  ? `Auto-approved by the "${auto.macroLabel}" macro (${auto.macroId}), which the human launched this session `
904
975
  + 'from and which allows auto-start in this project: the session is starting in the receiving project. '
905
976
  : auto.granted
@@ -1120,7 +1191,9 @@ async function openReplyFallbackSession(input = {}, deps = {}) {
1120
1191
  }
1121
1192
 
1122
1193
  /**
1123
- * listFeedbackTargets() → { projects: [{ cwd, lastActivity }], scanned, truncated }
1194
+ * listFeedbackTargets({ limit?, offset?, cwd? }) →
1195
+ * { projects: [{ cwd, lastActivity }], total, offset, limit, hasMore, scanned }
1196
+ * or, with `cwd`: { lookup: { cwd, canReceive, reason } }
1124
1197
  *
1125
1198
  * Which projects can receive feedback. Resolved the same way CLAUDE.md
1126
1199
  * requires everywhere else: a PROJECT IS A CWD, resolved from transcript
@@ -1128,7 +1201,9 @@ async function openReplyFallbackSession(input = {}, deps = {}) {
1128
1201
  * into a path. A folder whose cwd cannot be resolved is DROPPED, not guessed.
1129
1202
  *
1130
1203
  * Two sources:
1131
- * 1. transcript folders under `~/.claude/projects/` (above);
1204
+ * 1. EVERY transcript folder under `~/.claude/projects/` (no recency cap —
1205
+ * `scanned` is how many folders were read; resolution is memoized per
1206
+ * folder mtime in targetFolderMemo);
1132
1207
  * 2. the created-projects ledger (`createdProjects.cjs`, injectable as
1133
1208
  * `createdProjects`, default `getCreatedProjects()`), so a folder made by
1134
1209
  * project_create is a target before anyone has worked in it. Ledger cwds
@@ -1137,9 +1212,18 @@ async function openReplyFallbackSession(input = {}, deps = {}) {
1137
1212
  * cwd in both sources is listed once.
1138
1213
  * Results are then filtered to directories that still exist AND already carry
1139
1214
  * an operations root — exactly `openFeedbackSession`'s own precondition, so
1140
- * this list can't offer a target that would then be refused.
1215
+ * this list can't offer a target that would then be refused. Sorted newest
1216
+ * activity first, then paged by `offset`/`limit` (default 200, max 1000);
1217
+ * `total` counts every target and `hasMore` says another page exists.
1218
+ *
1219
+ * `cwd` is the authoritative yes/no for one path, independent of transcripts:
1220
+ * it runs openFeedbackSession's own toCwd checks (validatePath, existing
1221
+ * directory, operations root), so a project that was never chatted in — or
1222
+ * whose transcripts were deleted — still answers yes when it can receive.
1141
1223
  */
1142
- async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir, createdProjects } = {}) {
1224
+ async function listFeedbackTargets({ limit = TARGET_PAGE_DEFAULT, offset = 0, cwd, projectsDir, createdProjects } = {}) {
1225
+ if (cwd !== undefined) return { lookup: lookupFeedbackTarget(cwd) };
1226
+
1143
1227
  const root = resolveProjectsDir(projectsDir);
1144
1228
  let entries;
1145
1229
  try {
@@ -1147,32 +1231,24 @@ async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir, cre
1147
1231
  } catch {
1148
1232
  entries = [];
1149
1233
  }
1150
- const dirs = entries.filter((e) => e.isDirectory());
1234
+ const dirs = entries.filter((e) => e.isDirectory()).map((d) => path.join(root, d.name));
1151
1235
 
1152
- // Newest-first by folder mtime, so the cap keeps the projects actually in
1153
- // use rather than an arbitrary alphabetical slice.
1154
- const stamped = [];
1155
- for (const d of dirs) {
1156
- const full = path.join(root, d.name);
1157
- try {
1158
- stamped.push({ full, mtimeMs: (await fsp.stat(full)).mtimeMs });
1159
- } catch { /* raced away */ }
1236
+ const resolved = [];
1237
+ for (let i = 0; i < dirs.length; i += TARGET_SCAN_CONCURRENCY) {
1238
+ const batch = await Promise.all(dirs.slice(i, i + TARGET_SCAN_CONCURRENCY).map(resolveTargetFolder));
1239
+ for (const r of batch) if (r) resolved.push(r);
1240
+ }
1241
+ // Prune memo entries for folders under this root that no longer exist.
1242
+ const live = new Set(dirs);
1243
+ for (const key of targetFolderMemo.keys()) {
1244
+ if (path.dirname(key) === root && !live.has(key)) targetFolderMemo.delete(key);
1160
1245
  }
1161
- stamped.sort((a, b) => b.mtimeMs - a.mtimeMs);
1162
- const scanned = stamped.slice(0, limit);
1163
1246
 
1164
1247
  const byCwd = new Map();
1165
- for (const { full, mtimeMs } of scanned) {
1166
- const rawCwd = await resolveCwdFromTranscriptDir(full);
1167
- if (!rawCwd) continue;
1168
- // Job/Epic worktrees carry a tracked operations root too, so each would
1169
- // list as a project. Collapse to the main checkout (same resolver the
1170
- // admin routes use); a worktree whose main checkout can't be proven
1171
- // stays ephemeral/worktree-shaped and is dropped, never listed.
1172
- const cwd = resolveProjectContext({ cwd: rawCwd }).cwd;
1173
- if (!cwd || isEphemeralCwd(cwd)) continue;
1174
- const prior = byCwd.get(cwd);
1175
- if (!prior || prior.lastActivity < mtimeMs) byCwd.set(cwd, { cwd, lastActivity: mtimeMs });
1248
+ for (const { cwd: c, mtimeMs } of resolved) {
1249
+ if (!c) continue;
1250
+ const prior = byCwd.get(c);
1251
+ if (!prior || prior.lastActivity < mtimeMs) byCwd.set(c, { cwd: c, lastActivity: mtimeMs });
1176
1252
  }
1177
1253
 
1178
1254
  // Second source: the created-projects ledger. A broken ledger never hides
@@ -1188,12 +1264,83 @@ async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir, cre
1188
1264
  if (!prior || prior.lastActivity < e.createdAt) byCwd.set(e.cwd, { cwd: e.cwd, lastActivity: e.createdAt });
1189
1265
  }
1190
1266
 
1191
- const projects = [...byCwd.values()]
1267
+ const all = [...byCwd.values()]
1192
1268
  .filter((p) => isDirectory(p.cwd) && isSessionManagerProject(p.cwd))
1193
- .sort((a, b) => b.lastActivity - a.lastActivity)
1269
+ .sort((a, b) => b.lastActivity - a.lastActivity);
1270
+
1271
+ const pageLimit = clampInt(limit, 1, TARGET_PAGE_MAX, TARGET_PAGE_DEFAULT);
1272
+ const pageOffset = clampInt(offset, 0, Number.MAX_SAFE_INTEGER, 0);
1273
+ const projects = all
1274
+ .slice(pageOffset, pageOffset + pageLimit)
1194
1275
  .map((p) => ({ cwd: p.cwd, lastActivity: new Date(p.lastActivity).toISOString() }));
1195
1276
 
1196
- return { projects, scanned: scanned.length, truncated: Math.max(0, stamped.length - scanned.length) };
1277
+ return {
1278
+ projects,
1279
+ total: all.length,
1280
+ offset: pageOffset,
1281
+ limit: pageLimit,
1282
+ hasMore: pageOffset + projects.length < all.length,
1283
+ scanned: dirs.length,
1284
+ };
1285
+ }
1286
+
1287
+ function clampInt(v, min, max, fallback) {
1288
+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
1289
+ if (typeof n !== 'number' || !Number.isFinite(n)) return fallback;
1290
+ return Math.min(max, Math.max(min, Math.floor(n)));
1291
+ }
1292
+
1293
+ /** One transcript folder → { cwd, mtimeMs } (cwd null when unresolvable or a
1294
+ * worktree/ephemeral path), or null when the folder raced away. Memoized by
1295
+ * folder mtime. */
1296
+ async function resolveTargetFolder(full) {
1297
+ let mtimeMs;
1298
+ try {
1299
+ mtimeMs = (await fsp.stat(full)).mtimeMs;
1300
+ } catch {
1301
+ targetFolderMemo.delete(full);
1302
+ return null;
1303
+ }
1304
+ const hit = targetFolderMemo.get(full);
1305
+ if (hit && hit.mtimeMs === mtimeMs) return hit;
1306
+ const rawCwd = await resolveCwdFromTranscriptDir(full);
1307
+ let cwd = null;
1308
+ if (rawCwd) {
1309
+ // Job/Epic worktrees carry a tracked operations root too, so each would
1310
+ // list as a project. Collapse to the main checkout (same resolver the
1311
+ // admin routes use); a worktree whose main checkout can't be proven
1312
+ // stays ephemeral/worktree-shaped and is dropped, never listed.
1313
+ const c = resolveProjectContext({ cwd: rawCwd }).cwd;
1314
+ if (c && !isEphemeralCwd(c)) cwd = c;
1315
+ }
1316
+ const rec = { mtimeMs, cwd };
1317
+ targetFolderMemo.set(full, rec);
1318
+ return rec;
1319
+ }
1320
+
1321
+ /**
1322
+ * lookupFeedbackTarget(cwd) → { cwd, canReceive, reason }
1323
+ *
1324
+ * The exact toCwd checks openFeedbackSession runs, minus the same-project
1325
+ * check (no fromCwd here). `reason` is null on yes, else one of
1326
+ * 'invalid' | 'rejected' | 'not-a-directory' | 'no-operations-root'.
1327
+ */
1328
+ function lookupFeedbackTarget(cwd) {
1329
+ if (typeof cwd !== 'string' || !cwd.trim()) return { cwd: null, canReceive: false, reason: 'invalid' };
1330
+ let resolved;
1331
+ try {
1332
+ resolved = config.validatePath(path.resolve(cwd));
1333
+ } catch {
1334
+ return { cwd: path.resolve(cwd), canReceive: false, reason: 'rejected' };
1335
+ }
1336
+ if (!isDirectory(resolved)) return { cwd: resolved, canReceive: false, reason: 'not-a-directory' };
1337
+ if (!isSessionManagerProject(resolved)) return { cwd: resolved, canReceive: false, reason: 'no-operations-root' };
1338
+ return { cwd: resolved, canReceive: true, reason: null };
1339
+ }
1340
+
1341
+ /** Test isolation: forget every memoized folder resolution. */
1342
+ function __resetFeedbackTargetMemoForTests() {
1343
+ targetFolderMemo.clear();
1197
1344
  }
1198
1345
 
1199
1346
  /** Read the `cwd` field off the first JSON line of the newest .jsonl in a
@@ -1241,7 +1388,14 @@ async function resolveCwdFromTranscriptDir(dir) {
1241
1388
 
1242
1389
  /** Registers both routes on the injected loopback admin transport. Mirrors
1243
1390
  * prdCreate.cjs's registerAdminRoute — auth is the transport's job. */
1244
- function registerAdminRoute(adminHttp) {
1391
+ function registerAdminRoute(adminHttp, { getServiceStore, warmTargetsAfterMs = null } = {}) {
1392
+ // Optional deferred warm-up of the target-folder memo, so the first
1393
+ // feedback_list_projects after boot doesn't pay the cold scan (seconds over
1394
+ // ~14k transcript folders). Opt-in: tests register routes without it.
1395
+ if (Number.isFinite(warmTargetsAfterMs)) {
1396
+ const t = setTimeout(() => { listFeedbackTargets({}).catch(() => {}); }, warmTargetsAfterMs);
1397
+ if (typeof t.unref === 'function') t.unref();
1398
+ }
1245
1399
  adminHttp.registerRoute('POST', '/admin/feedback/open-session', async (req, res) => {
1246
1400
  const raw = await readBody(req);
1247
1401
  let parsed;
@@ -1251,7 +1405,17 @@ function registerAdminRoute(adminHttp) {
1251
1405
  sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
1252
1406
  return;
1253
1407
  }
1254
- const result = await openFeedbackSession(parsed);
1408
+ // Service identity: only the in-process invoke() sets this symbol on the
1409
+ // request; an HTTP request cannot, and the body is never consulted.
1410
+ const trusted = req[TRUSTED_SERVICE];
1411
+ const trustedServiceId = trusted && typeof trusted.serviceId === 'string' ? trusted.serviceId : null;
1412
+ const lookup = getServiceStore || (() => require('../../webRemote.cjs').getServiceStore());
1413
+ const result = await openFeedbackSession(
1414
+ parsed,
1415
+ trustedServiceId
1416
+ ? { trustedServiceId, findService: (id) => lookup().list().find((x) => x.serviceId === id) || null }
1417
+ : {},
1418
+ );
1255
1419
  if (!result.ok) {
1256
1420
  sendJson(res, result.status ?? 400, { ok: false, error: result.error });
1257
1421
  return;
@@ -1265,7 +1429,10 @@ function registerAdminRoute(adminHttp) {
1265
1429
  // where a feedback session may be written (that stays governed by
1266
1430
  // openFeedbackSession's own validatePath + ops-root checks).
1267
1431
  const projectsDir = query?.get('projectsDir') || undefined;
1268
- const result = await listFeedbackTargets({ projectsDir });
1432
+ const cwd = query?.get('cwd') ?? undefined;
1433
+ const limit = query?.get('limit') ?? undefined;
1434
+ const offset = query?.get('offset') ?? undefined;
1435
+ const result = await listFeedbackTargets({ projectsDir, cwd, limit, offset });
1269
1436
  sendJson(res, 200, { ok: true, ...result });
1270
1437
  });
1271
1438
  }
@@ -1279,6 +1446,8 @@ module.exports = {
1279
1446
  MAX_REFERENCES,
1280
1447
  MAX_MACRO_AUTO_STARTS,
1281
1448
  verifyMacroAutoStart,
1449
+ verifyServiceAutoStart,
1450
+ TRUSTED_SERVICE,
1282
1451
  quoteNamesTarget,
1283
1452
  PROJECTS_DIR,
1284
1453
  resolveProjectsDir,
@@ -1295,5 +1464,7 @@ module.exports = {
1295
1464
  findOpenReplyFallback,
1296
1465
  openReplyFallbackSession,
1297
1466
  listFeedbackTargets,
1467
+ lookupFeedbackTarget,
1468
+ __resetFeedbackTargetMemoForTests,
1298
1469
  registerAdminRoute,
1299
1470
  };
@@ -239,7 +239,7 @@ function createAdminHttp() {
239
239
  * serialized and streamed to the handler like an HTTP request body.
240
240
  * Resolves { status, json } (json null when the handler wrote non-JSON).
241
241
  */
242
- async function invoke(method, routePath, { body, query } = {}) {
242
+ async function invoke(method, routePath, { body, query, trustedService } = {}) {
243
243
  const urlObj = new URL(routePath, 'http://127.0.0.1');
244
244
  if (query) {
245
245
  const params = query instanceof URLSearchParams ? query : new URLSearchParams(
@@ -249,6 +249,10 @@ function createAdminHttp() {
249
249
  }
250
250
  const payload = body === undefined ? '' : JSON.stringify(body);
251
251
  const req = createInMemoryRequest(String(method).toUpperCase(), `${urlObj.pathname}${urlObj.search}`, payload);
252
+ // Trusted-channel service identity: a Symbol key no HTTP request can carry.
253
+ if (trustedService && typeof trustedService.serviceId === 'string') {
254
+ req[Symbol.for('sm.trustedService')] = { serviceId: trustedService.serviceId };
255
+ }
252
256
  const res = createResponseShim();
253
257
  try {
254
258
  await dispatch(req, res);
@@ -90,8 +90,10 @@ function isOk(answer) {
90
90
  return answer.status >= 200 && answer.status < 300 && answer.json?.ok === true;
91
91
  }
92
92
 
93
- async function callInvoke(invoke, req) {
94
- const answer = await invoke(req.method, req.path, { body: req.body, query: req.query });
93
+ async function callInvoke(invoke, req, trustedService) {
94
+ const opts = { body: req.body, query: req.query };
95
+ if (trustedService) opts.trustedService = trustedService;
96
+ const answer = await invoke(req.method, req.path, opts);
95
97
  return { status: Number(answer?.status) || 500, json: answer?.json ?? null };
96
98
  }
97
99
 
@@ -132,7 +134,8 @@ async function runTool(tool, args, { service, invoke, store }) {
132
134
  };
133
135
  }
134
136
  if (pinned.replyMode === undefined || pinned.replyMode === null) pinned.replyMode = 'event';
135
- const answer = await callInvoke(invoke, tool.toRequest(pinned));
137
+ // The service id rides the invoke option (in-process only), never the body.
138
+ const answer = await callInvoke(invoke, tool.toRequest(pinned), { serviceId: service.serviceId });
136
139
  const ledgerError = await recordEpic(store, service, answer, pinned.toCwd, pinned.externalRef);
137
140
  return { answer, result: isOk(answer) ? 'ok' : `error:${answer.status}`, ledgerError };
138
141
  }