claude-code-session-manager 0.143.0 → 0.145.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 (128) hide show
  1. package/README.md +3 -1
  2. package/dist/assets/AppSettings-BR5b6oof.js +2 -0
  3. package/dist/assets/{History-DTttbvPb.js → History-B4U0mCdK.js} +2 -2
  4. package/dist/assets/HomeClaudeConfig-DQqG7lFE.js +5 -0
  5. package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CwsOJ0nI.js} +1 -1
  6. package/dist/assets/ProjectClaudeConfig-BzRowu8x.js +26 -0
  7. package/dist/assets/Scheduler-dr7CNOcL.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-CroBPY4C.js} +1 -1
  9. package/dist/assets/{Skills-cfV7sgk6.js → Skills-BiW2lCnD.js} +23 -23
  10. package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-CYTkQiva.js} +27 -27
  11. package/dist/assets/{Toggle-CYajnSdx.js → Toggle-WFBYo8JI.js} +1 -1
  12. package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-DZu8dTpO.js} +1 -1
  13. package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B7KeXLSE.js} +1 -1
  14. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  15. package/dist/assets/{index-CdTppjKR.js → index-hXRNm0UJ.js} +698 -697
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +442 -439
  19. package/package.json +4 -2
  20. package/plugins/session-manager-dev/skills/develop/SKILL.md +25 -19
  21. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  22. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +91 -0
  23. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +9 -6
  24. package/scripts/README.md +1 -1
  25. package/scripts/scheduler-mcp-server.cjs +77 -0
  26. package/src/main/adminRouteRegistry.cjs +6 -0
  27. package/src/main/agentLibrary.cjs +60 -11
  28. package/src/main/agentsIpc.cjs +19 -0
  29. package/src/main/build-info.json +4 -4
  30. package/src/main/chatRunner.cjs +139 -0
  31. package/src/main/config.cjs +12 -0
  32. package/src/main/health.cjs +59 -17
  33. package/src/main/index.cjs +6 -2
  34. package/src/main/ipcSchemas.cjs +55 -1
  35. package/src/main/lib/claude/agentArmory.cjs +128 -0
  36. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  37. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  38. package/src/main/lib/claude/builtinTools.cjs +110 -0
  39. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  40. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  41. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  42. package/src/main/lib/claude/personaToolScope.cjs +100 -14
  43. package/src/main/lib/demo-video-kit/resumableRun.cjs +21 -14
  44. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  45. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  46. package/src/main/lib/epic/epicOutsideRead.cjs +74 -2
  47. package/src/main/lib/epic/epicSettle.cjs +48 -4
  48. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  49. package/src/main/lib/epic/epicValidationHook.cjs +9 -1
  50. package/src/main/lib/epic/planReviewInput.cjs +125 -0
  51. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  52. package/src/main/lib/epic/scriptStartedBy.cjs +86 -0
  53. package/src/main/lib/externalContract.cjs +12 -0
  54. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  55. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +108 -14
  56. package/src/main/lib/feedback-remote/localAdminHttp.cjs +5 -1
  57. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
  58. package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
  59. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  60. package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
  61. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +35 -4
  62. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  63. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  64. package/src/main/lib/feedback-remote/servicePairings.cjs +95 -7
  65. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +104 -1
  66. package/src/main/lib/git/gitWorktree.cjs +1 -1
  67. package/src/main/lib/git/worktreeDeps.cjs +9 -3
  68. package/src/main/lib/mcpToolCatalog.cjs +47 -7
  69. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  70. package/src/main/lib/opsOwnership.cjs +2 -0
  71. package/src/main/lib/packs/packCatalog.cjs +98 -5
  72. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  73. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  74. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  75. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  76. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  77. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  78. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  79. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
  80. package/src/main/lib/prd/prdCreate.cjs +49 -5
  81. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  82. package/src/main/lib/prd/prdMcpReachWarnings.cjs +46 -0
  83. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  84. package/src/main/lib/process/peerChatSession.cjs +165 -0
  85. package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
  86. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
  87. package/src/main/lib/promptSessionSchema.cjs +2 -0
  88. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  89. package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
  90. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  91. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  92. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  93. package/src/main/lib/scheduler/planReviewStore.cjs +150 -0
  94. package/src/main/lib/scheduler/reviewNotice.cjs +3 -1
  95. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  96. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  97. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  98. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
  99. package/src/main/lib/tasks/memoryConsolidation.cjs +118 -37
  100. package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
  101. package/src/main/lib/tasks/taskRun.cjs +3 -1
  102. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +298 -0
  103. package/src/main/projectPages.cjs +22 -14
  104. package/src/main/pty.cjs +3 -0
  105. package/src/main/runVerify.cjs +80 -5
  106. package/src/main/scheduler/gitTreeGuard.cjs +6 -0
  107. package/src/main/scheduler/planReviewHold.cjs +146 -0
  108. package/src/main/scheduler/prdParser.cjs +1 -0
  109. package/src/main/scheduler/prdPaths.cjs +10 -1
  110. package/src/main/scheduler/reviewLadder.cjs +2 -0
  111. package/src/main/scheduler/utilizationHold.cjs +7 -2
  112. package/src/main/scheduler.cjs +692 -86
  113. package/src/main/seedAgentPersonas.cjs +11 -6
  114. package/src/main/seedStatus.cjs +1 -1
  115. package/src/main/templates/PRD_AUTHORING.md +17 -2
  116. package/src/main/webRemote.cjs +69 -7
  117. package/src/preload/api.d.ts +79 -1
  118. package/src/preload/apiSurface.json +39 -0
  119. package/src/preload/index.cjs +11 -0
  120. package/src/seed/agents/architect.md +28 -43
  121. package/src/seed/agents/dev-lead.md +3 -1
  122. package/src/seed/agents/md-network-curator.md +27 -0
  123. package/src/seed/agents/plan-reviewer.md +47 -0
  124. package/src/seed/agents/validator.md +2 -1
  125. package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
  126. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
  127. package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
  128. package/dist/assets/Scheduler-CNLjn90m.js +0 -16
@@ -0,0 +1,91 @@
1
+ // @ts-check
2
+ /**
3
+ * servicePairLocalRoutes.cjs — POST /admin/services/pair-local (start) and
4
+ * POST /admin/services/pair-local/confirm on the token-guarded loopback admin
5
+ * transport, so a same-machine agent can pair a service with no window step.
6
+ * Auth is the transport's job (401 before the handler runs).
7
+ */
8
+ 'use strict';
9
+
10
+ const { z } = require('zod');
11
+
12
+ /** @param {string} error */
13
+ function statusOf(error) {
14
+ if (error === 'web_remote_off' || error === 'no_paired_device') return 409;
15
+ if (error === 'not_local_pairing' || error === 'no_pending_service') return 404;
16
+ if (error === 'sas_mismatch') return 403;
17
+ return 400;
18
+ }
19
+
20
+ /**
21
+ * @param {{ registerRoute: (method: string, path: string, handler: (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>) => void }} adminHttp
22
+ * @param {{ webRemote?: any }} [opts]
23
+ */
24
+ function registerAdminRoute(adminHttp, { webRemote } = {}) {
25
+ const { readBody, sendJson } = require('./localAdminHttp.cjs');
26
+ const { SERVICE_TOOL_NAMES } = require('./servicePairings.cjs');
27
+ const wr = () => webRemote || require('../../webRemote.cjs');
28
+ const path = require('node:path');
29
+
30
+ const startSchema = z.object({
31
+ name: z.string().min(1).max(80),
32
+ homeCwd: z.string().min(1).refine((p) => path.isAbsolute(p), 'homeCwd must be an absolute path'),
33
+ tools: z.array(z.enum(/** @type {[string, ...string[]]} */ (SERVICE_TOOL_NAMES))).min(1),
34
+ projectRoot: z.string().min(1).optional(),
35
+ }).strict();
36
+ const confirmSchema = z.object({
37
+ pairingId: z.string().min(1),
38
+ sas: z.string().regex(/^\d{6}$/),
39
+ }).strict();
40
+
41
+ /**
42
+ * @template {z.ZodTypeAny} S
43
+ * @param {import('node:http').IncomingMessage} req @param {import('node:http').ServerResponse} res @param {S} schema
44
+ * @returns {Promise<z.infer<S> | null>}
45
+ */
46
+ async function parse(req, res, schema) {
47
+ const raw = await readBody(req);
48
+ let json;
49
+ try {
50
+ json = raw ? JSON.parse(raw) : {};
51
+ } catch {
52
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
53
+ return null;
54
+ }
55
+ const r = schema.safeParse(json);
56
+ if (!r.success) {
57
+ const i = r.error.issues[0];
58
+ sendJson(res, 400, { ok: false, error: `${(i.path || []).join('.') || 'body'}: ${i.message}` });
59
+ return null;
60
+ }
61
+ return r.data;
62
+ }
63
+
64
+ adminHttp.registerRoute('POST', '/admin/services/pair-local', async (req, res) => {
65
+ const b = await parse(req, res, startSchema);
66
+ if (!b) return;
67
+ const r = await wr().servicePairStartLocal({ name: b.name, homeCwd: b.homeCwd, scope: b.tools, projectRoot: b.projectRoot });
68
+ if (!r || !r.ok) {
69
+ const error = (r && r.error) || 'pairing failed';
70
+ sendJson(res, statusOf(error), { ok: false, error });
71
+ return;
72
+ }
73
+ const { code, pairingId, codeExpiresAt, deviceId } = r;
74
+ sendJson(res, 200, { ok: true, code, pairingId, codeExpiresAt, deviceId });
75
+ });
76
+
77
+ adminHttp.registerRoute('POST', '/admin/services/pair-local/confirm', async (req, res) => {
78
+ const b = await parse(req, res, confirmSchema);
79
+ if (!b) return;
80
+ const r = await wr().confirmServiceSasLocal(b.pairingId, b.sas);
81
+ if (!r || !r.ok) {
82
+ const error = (r && r.error) || 'confirm failed';
83
+ sendJson(res, statusOf(error), { ok: false, error });
84
+ return;
85
+ }
86
+ const { pubKey: _omit, ...service } = r.service || {};
87
+ sendJson(res, 200, { ok: true, service });
88
+ });
89
+ }
90
+
91
+ module.exports = { registerAdminRoute };
@@ -7,13 +7,16 @@
7
7
  * File (default ~/.claude/session-manager/remote-services.json, mode 0600):
8
8
  * { version: 1, pending: [...], services: [...] }
9
9
  *
10
- * - pending: { pairingId, name, homeCwd, scope, createdAt, expiresAt } — a
10
+ * - pending: { pairingId, name, homeCwd, scope, projectRoot, createdAt, expiresAt } — a
11
11
  * pairing the owner started; lives 10 minutes (the relay code itself lasts 5).
12
- * - services: { serviceId, name, homeCwd, scope, pubKey, relayClientId,
12
+ * - services: { serviceId, name, homeCwd, scope, projectRoot, pubKey, relayClientId,
13
13
  * pairedAt, lastSeenAt, opened: [{ cwd, epicId, externalRef?, at }] } — a
14
14
  * confirmed service with its pinned P-256 public key and the ledger of Epics
15
15
  * it opened (newest 1000), each keyed by project + id: an Epic id matches
16
16
  * only in the project the service opened it in.
17
+ * - projectRoot: the owner-approved projects folder project_create creates
18
+ * into — required when scope grants project_create, null otherwise (and for
19
+ * a record saved before the field existed).
17
20
  *
18
21
  * State is read once from disk (missing/corrupt = empty) and kept in memory;
19
22
  * every mutation is written atomically, serialized through one queue. Reads
@@ -40,6 +43,7 @@ const SERVICE_TOOL_NAMES = Object.freeze([
40
43
  'macro_run',
41
44
  'epic_get',
42
45
  'events_read',
46
+ 'project_create',
43
47
  ]);
44
48
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
49
 
@@ -62,6 +66,15 @@ function validateHomeCwd(homeCwd) {
62
66
  return homeCwd;
63
67
  }
64
68
 
69
+ /** Required (absolute, no NUL, resolved) when the scope grants project_create; null otherwise. */
70
+ function validateProjectRoot(projectRoot, scope) {
71
+ if (!scope.includes('project_create')) return null;
72
+ if (typeof projectRoot !== 'string' || projectRoot.length === 0 || !path.isAbsolute(projectRoot) || projectRoot.includes('\0')) {
73
+ throw new Error('projectRoot must be an absolute path when scope includes project_create');
74
+ }
75
+ return path.resolve(projectRoot);
76
+ }
77
+
65
78
  function validateScope(scope) {
66
79
  if (!Array.isArray(scope) || scope.length === 0) throw new Error('scope must be a non-empty list of tool names');
67
80
  for (const t of scope) {
@@ -107,35 +120,91 @@ function validateExternalRef(externalRef) {
107
120
  return externalRef;
108
121
  }
109
122
 
123
+ const PAIRED_VIA = ['window', 'local'];
124
+ const START_WORK_ALL = '*';
125
+ const MAX_START_WORK_TARGETS = 200;
126
+
127
+ /** Owner grant targets: absolute cwds (resolved) or '*'. Throws on anything else. */
128
+ function validateStartWorkTargets(targets) {
129
+ if (!Array.isArray(targets) || targets.length > MAX_START_WORK_TARGETS) {
130
+ throw new Error(`targets must be a list of at most ${MAX_START_WORK_TARGETS} project paths or '*'`);
131
+ }
132
+ const out = [];
133
+ for (const t of targets) {
134
+ let n;
135
+ if (t === START_WORK_ALL) n = START_WORK_ALL;
136
+ else if (typeof t === 'string' && t.length > 0 && path.isAbsolute(t) && !t.includes('\0')) n = path.resolve(t);
137
+ else throw new Error(`target must be an absolute project path or '*': ${String(t)}`);
138
+ if (!out.includes(n)) out.push(n);
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /** The stored startWork { targets } read back leniently: absent/invalid = off (null). */
144
+ function startWorkOf(raw) {
145
+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.targets)) return null;
146
+ try {
147
+ const targets = validateStartWorkTargets(raw.targets);
148
+ return targets.length ? { targets } : null;
149
+ } catch { return null; }
150
+ }
151
+
110
152
  function publicService(s) {
111
153
  return {
112
154
  serviceId: s.serviceId,
113
155
  name: s.name,
114
156
  homeCwd: s.homeCwd,
115
157
  scope: [...s.scope],
158
+ projectRoot: typeof s.projectRoot === 'string' ? s.projectRoot : null,
116
159
  pubKey: s.pubKey,
117
160
  relayClientId: s.relayClientId,
118
161
  pairedAt: s.pairedAt,
119
162
  lastSeenAt: s.lastSeenAt,
163
+ pairedVia: s.pairedVia === 'local' ? 'local' : 'window',
164
+ startWork: startWorkOf(s.startWork),
120
165
  };
121
166
  }
122
167
 
123
168
  function publicPending(p) {
124
- return { pairingId: p.pairingId, name: p.name, homeCwd: p.homeCwd, scope: [...p.scope], createdAt: p.createdAt, expiresAt: p.expiresAt };
169
+ return {
170
+ pairingId: p.pairingId,
171
+ name: p.name,
172
+ homeCwd: p.homeCwd,
173
+ scope: [...p.scope],
174
+ projectRoot: typeof p.projectRoot === 'string' ? p.projectRoot : null,
175
+ createdAt: p.createdAt,
176
+ expiresAt: p.expiresAt,
177
+ pairedVia: p.pairedVia === 'local' ? 'local' : 'window',
178
+ };
125
179
  }
126
180
 
127
181
  function normalizeLoaded(raw) {
128
182
  const empty = { version: STORE_VERSION, pending: [], services: [] };
129
183
  if (!raw || typeof raw !== 'object') return empty;
130
- const pending = Array.isArray(raw.pending) ? raw.pending.filter((p) => p && typeof p.pairingId === 'string') : [];
184
+ const rootOf = (x) => (typeof x.projectRoot === 'string' && x.projectRoot !== '' ? x.projectRoot : null);
185
+ const pending = Array.isArray(raw.pending)
186
+ ? raw.pending.filter((p) => p && typeof p.pairingId === 'string').map((p) => ({ ...p, projectRoot: rootOf(p) }))
187
+ : [];
131
188
  const services = Array.isArray(raw.services)
132
189
  ? raw.services
133
190
  .filter((s) => s && typeof s.serviceId === 'string' && typeof s.pubKey === 'string')
134
- .map((s) => ({ ...s, scope: Array.isArray(s.scope) ? s.scope : [], opened: Array.isArray(s.opened) ? s.opened : [] }))
191
+ .map((s) => ({
192
+ ...s,
193
+ scope: Array.isArray(s.scope) ? s.scope : [],
194
+ projectRoot: rootOf(s),
195
+ opened: Array.isArray(s.opened) ? s.opened : [],
196
+ }))
135
197
  : [];
136
198
  return { version: STORE_VERSION, pending, services };
137
199
  }
138
200
 
201
+ /** True iff the service's startWork grant covers `toCwd` ('*' or its resolved cwd). */
202
+ function startWorkAllows(service, toCwd) {
203
+ const grant = startWorkOf(service && service.startWork);
204
+ if (!grant || typeof toCwd !== 'string' || !path.isAbsolute(toCwd)) return false;
205
+ return grant.targets.includes(START_WORK_ALL) || grant.targets.includes(path.resolve(toCwd));
206
+ }
207
+
139
208
  /**
140
209
  * @param {{ filePath?: string, now?: () => number }} [opts]
141
210
  */
@@ -173,15 +242,19 @@ function createServicePairings({ filePath, now } = {}) {
173
242
  }
174
243
 
175
244
  return {
176
- createPending({ name, homeCwd, scope } = /** @type {any} */ ({})) {
245
+ createPending({ name, homeCwd, scope, projectRoot, pairedVia = 'window' } = /** @type {any} */ ({})) {
177
246
  let entry;
178
247
  try {
179
248
  const t = clock();
249
+ if (!PAIRED_VIA.includes(pairedVia)) throw new Error(`pairedVia must be one of: ${PAIRED_VIA.join(', ')}`);
250
+ const grants = validateScope(scope);
180
251
  entry = {
181
252
  pairingId: crypto.randomUUID(),
182
253
  name: validateName(name),
183
254
  homeCwd: validateHomeCwd(homeCwd),
184
- scope: validateScope(scope),
255
+ scope: grants,
256
+ projectRoot: validateProjectRoot(projectRoot, grants),
257
+ pairedVia,
185
258
  createdAt: t,
186
259
  expiresAt: t + PENDING_TTL_MS,
187
260
  };
@@ -226,10 +299,12 @@ function createServicePairings({ filePath, now } = {}) {
226
299
  name: p.name,
227
300
  homeCwd: p.homeCwd,
228
301
  scope: [...p.scope],
302
+ projectRoot: typeof p.projectRoot === 'string' ? p.projectRoot : null,
229
303
  pubKey: key,
230
304
  relayClientId: relayId,
231
305
  pairedAt: t,
232
306
  lastSeenAt: t,
307
+ pairedVia: p.pairedVia === 'local' ? 'local' : 'window',
233
308
  opened: [],
234
309
  };
235
310
  s.services.push(svc);
@@ -294,6 +369,18 @@ function createServicePairings({ filePath, now } = {}) {
294
369
  return !!svc && svc.opened.some((o) => o && o.epicId === epicId && o.cwd === want);
295
370
  },
296
371
 
372
+ /** Owner grant: auto-start work this service opens in `targets` (cwds or '*'). [] removes it. */
373
+ setStartWork(serviceId, targets) {
374
+ let list;
375
+ try { list = validateStartWorkTargets(targets); } catch (e) { return Promise.reject(e); }
376
+ return mutate((s) => {
377
+ const svc = s.services.find((x) => x.serviceId === serviceId);
378
+ if (!svc) throw new Error('no paired service with that id');
379
+ if (list.length === 0) delete svc.startWork; else svc.startWork = { targets: list };
380
+ return publicService(svc);
381
+ });
382
+ },
383
+
297
384
  touchLastSeen(serviceId) {
298
385
  return mutate((s) => {
299
386
  const svc = s.services.find((x) => x.serviceId === serviceId);
@@ -307,6 +394,7 @@ function createServicePairings({ filePath, now } = {}) {
307
394
 
308
395
  module.exports = {
309
396
  createServicePairings,
397
+ startWorkAllows,
310
398
  SERVICE_TOOL_NAMES,
311
399
  PENDING_TTL_MS,
312
400
  MAX_OPENED,
@@ -41,6 +41,7 @@ const USAGE = [
41
41
  'usage:',
42
42
  ' claude-code-session-manager service pair --code <code> --name <name> --state-dir <dir> [--device <prefix>] [--timeout <seconds>]',
43
43
  ' claude-code-session-manager service mcp --state-dir <dir>',
44
+ ' claude-code-session-manager service pair-local --state-dir <dir> --name <name> --home <cwd> --tools a,b,c [--project-root <dir>] [--device <prefix>] [--timeout <seconds>]',
44
45
  ].join('\n');
45
46
 
46
47
  /** Parses `--key value` / `--key=value` pairs. Returns { flags } or { error }. */
@@ -132,6 +133,105 @@ async function runPair(args, { stdout, stderr, clientFactory }) {
132
133
  }
133
134
  }
134
135
 
136
+ const NOT_RUNNING_MSG = 'session manager is not running (no admin-api.json)';
137
+
138
+ function errText(err) { return err && err.message ? err.message : String(err); }
139
+
140
+ /**
141
+ * Pairs a same-machine service through the loopback admin API, no window step.
142
+ * The redeem targets the start route's `deviceId` (this desktop), or `device` (a prefix) when the
143
+ * caller overrides it; without either, 2+ paired desktops fail with "choose a device".
144
+ * @param {{ stateDir: string, name: string, homeCwd: string, tools: string[], projectRoot?: string, device?: string, timeoutS?: number, fetchImpl?: Function, clientFactory?: Function, adminApiPath?: string }} opts
145
+ * @returns {Promise<{ ok: true, service: any } | { ok: false, error: string }>}
146
+ */
147
+ async function pairLocal(opts) {
148
+ const { stateDir, name, homeCwd, tools, projectRoot, device, timeoutS = DEFAULT_PAIR_TIMEOUT_S } = opts || {};
149
+ const fetchImpl = (opts && opts.fetchImpl) || globalThis.fetch;
150
+ const clientFactory = (opts && opts.clientFactory) || defaultClientFactory;
151
+ let admin;
152
+ try {
153
+ const adminApiPath = (opts && opts.adminApiPath) || require('../scheduler/schedulerPaths.cjs').adminTokenPath();
154
+ admin = require('../util/atomicFs.cjs').readJsonOrSync(adminApiPath, null);
155
+ } catch { return { ok: false, error: NOT_RUNNING_MSG }; }
156
+ if (!admin || !admin.port || !admin.token) return { ok: false, error: NOT_RUNNING_MSG };
157
+ const base = `http://127.0.0.1:${admin.port}/admin/services/pair-local`;
158
+
159
+ const post = async (url, body) => {
160
+ let res;
161
+ try {
162
+ res = await fetchImpl(url, {
163
+ method: 'POST',
164
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${admin.token}` },
165
+ body: JSON.stringify(body),
166
+ });
167
+ } catch (err) { return { ok: false, error: `admin api unreachable: ${errText(err)}` }; }
168
+ let json = null;
169
+ try { json = await res.json(); } catch { /* non-JSON */ }
170
+ if (!res.ok || !json || json.ok === false) return { ok: false, error: (json && json.error) || `admin api HTTP ${res.status}` };
171
+ return json;
172
+ };
173
+
174
+ let client;
175
+ let timer = null;
176
+ try {
177
+ const startBody = { name, homeCwd, tools };
178
+ if (projectRoot) startBody.projectRoot = projectRoot;
179
+ const started = await post(base, startBody);
180
+ if (!started.ok) return { ok: false, error: started.error };
181
+
182
+ let rejectConfirm;
183
+ const confirmFailed = new Promise((_, rej) => { rejectConfirm = rej; });
184
+ confirmFailed.catch(() => {});
185
+ let confirmP = null;
186
+ const onSas = (sas) => {
187
+ if (confirmP || !sas) return;
188
+ confirmP = post(`${base}/confirm`, { pairingId: started.pairingId, sas: String(sas).replace(/\D/g, '') });
189
+ confirmP.then((r) => { if (!r.ok) rejectConfirm(new Error(r.error)); });
190
+ };
191
+ client = clientFactory({ stateDir, onSas });
192
+ const pairArgs = { code: started.code, name };
193
+ const target = device || started.deviceId;
194
+ if (target) pairArgs.device = String(target);
195
+ await client.pair(pairArgs);
196
+ const timeout = new Promise((_, reject) => {
197
+ timer = setTimeout(() => reject(new Error(`timed out after ${timeoutS} s waiting for pairing to confirm`)), timeoutS * 1000);
198
+ });
199
+ const res = await Promise.race([client.connect(), confirmFailed, timeout]);
200
+ if (res && res.sas) onSas(res.sas);
201
+ const confirmed = confirmP ? await confirmP : { ok: false, error: 'no SAS was derived' };
202
+ if (!confirmed.ok) return { ok: false, error: confirmed.error };
203
+ return { ok: true, service: confirmed.service };
204
+ } catch (err) {
205
+ return { ok: false, error: errText(err) };
206
+ } finally {
207
+ clearTimeout(timer);
208
+ try { if (client) client.close(); } catch { /* best-effort */ }
209
+ }
210
+ }
211
+
212
+ async function runPairLocal(args, { stdout, stderr, clientFactory, fetchImpl, adminApiPath }) {
213
+ const parsed = parseFlags(args, ['state-dir', 'name', 'home', 'tools', 'project-root', 'device', 'timeout']);
214
+ if (parsed.error) { line(stderr, `${parsed.error}\n${USAGE}`); return EXIT_USAGE; }
215
+ const { flags } = parsed;
216
+ for (const k of ['state-dir', 'name', 'home', 'tools']) {
217
+ if (!flags[k]) { line(stderr, `missing --${k}\n${USAGE}`); return EXIT_USAGE; }
218
+ }
219
+ const tools = flags.tools.split(',').map((t) => t.trim()).filter(Boolean);
220
+ if (!tools.length) { line(stderr, `missing --tools\n${USAGE}`); return EXIT_USAGE; }
221
+ let timeoutS = DEFAULT_PAIR_TIMEOUT_S;
222
+ if (flags.timeout !== undefined) {
223
+ timeoutS = Number(flags.timeout);
224
+ if (!Number.isFinite(timeoutS) || timeoutS <= 0) { line(stderr, `--timeout must be a positive number of seconds\n${USAGE}`); return EXIT_USAGE; }
225
+ }
226
+ const r = await pairLocal({
227
+ stateDir: flags['state-dir'], name: flags.name, homeCwd: flags.home, tools,
228
+ projectRoot: flags['project-root'], device: flags.device, timeoutS, clientFactory, fetchImpl, adminApiPath,
229
+ });
230
+ if (!r.ok) { line(stderr, `service pair-local: ${r.error}`); return EXIT_FAIL; }
231
+ line(stdout, `Paired locally: ${flags.name}`);
232
+ return EXIT_OK;
233
+ }
234
+
135
235
  function runMcp(args, { stdin, stdout, stderr, clientFactory }) {
136
236
  const parsed = parseFlags(args, ['state-dir']);
137
237
  if (parsed.error) { line(stderr, `${parsed.error}\n${USAGE}`); return Promise.resolve(EXIT_USAGE); }
@@ -279,12 +379,15 @@ async function runServiceCli(argv, io = {}) {
279
379
  stdout: io.stdout || process.stdout,
280
380
  stderr: io.stderr || process.stderr,
281
381
  clientFactory: io.clientFactory || defaultClientFactory,
382
+ fetchImpl: io.fetchImpl,
383
+ adminApiPath: io.adminApiPath,
282
384
  };
283
385
  const [sub, ...rest] = Array.isArray(argv) ? argv : [];
284
386
  if (sub === 'pair') return runPair(rest, deps);
387
+ if (sub === 'pair-local') return runPairLocal(rest, deps);
285
388
  if (sub === 'mcp') return runMcp(rest, deps);
286
389
  line(deps.stderr, sub ? `unknown service subcommand: ${sub}\n${USAGE}` : USAGE);
287
390
  return EXIT_USAGE;
288
391
  }
289
392
 
290
- module.exports = { runServiceCli, USAGE, CONFIRM_HINT, REVOKED_MSG, EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_REVOKED };
393
+ module.exports = { runServiceCli, pairLocal, USAGE, CONFIRM_HINT, REVOKED_MSG, EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_REVOKED };
@@ -984,7 +984,7 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
984
984
  // since (and drop links main lost). Best-effort — never fails the reuse.
985
985
  try {
986
986
  const sync = await require('./worktreeDeps.cjs').syncNodeModulesLinks({ mainCwd: cwd, worktreeCwd: epicDir });
987
- if (sync && (sync.added || sync.removed)) console.log(`[gitWorktree] synced dep links: +${sync.added} -${sync.removed} -> ${epicDir}`);
987
+ if (sync && (sync.added || sync.removed || sync.kept)) console.log(`[gitWorktree] synced dep links: +${sync.added} -${sync.removed} kept=${sync.kept} -> ${epicDir}`);
988
988
  } catch (err) {
989
989
  console.warn(`[gitWorktree] dep link sync failed for ${epicDir}: ${(err && err.message) || err}`);
990
990
  }
@@ -374,7 +374,8 @@ async function linkDependencyDirs({ mainCwd, worktreeCwd, names = DEFAULT_DEP_DI
374
374
 
375
375
  /**
376
376
  * Refresh one worktree node_modules (`rel`) against the main checkout's: link entries main
377
- * gained since the snapshot, unlink worktree links whose target is gone. Skips unless the
377
+ * gained since the snapshot, unlink dangling worktree links whose target lay inside main's
378
+ * `rel` (others are kept, counted in `counts.kept`). Skips unless the
378
379
  * worktree folder is a real directory (a whole-folder symlink is left alone). Reads main
379
380
  * only. Never throws.
380
381
  */
@@ -385,10 +386,13 @@ function syncModulesDir(mainCwd, worktreeCwd, rel, counts) {
385
386
  if (st.isSymbolicLink() || !st.isDirectory()) return;
386
387
  const src = path.join(mainCwd, rel);
387
388
  if (isDir(src)) counts.added += linkMissingModulesEntries(src, dest, false);
389
+ const ownPrefix = path.resolve(src) + path.sep; // trailing sep: main/node_modules-x is not inside
388
390
  for (const name of fs.readdirSync(dest)) {
389
391
  const link = path.join(dest, name);
390
392
  try {
391
393
  if (!fs.lstatSync(link).isSymbolicLink() || fs.existsSync(link)) continue;
394
+ const target = path.resolve(dest, fs.readlinkSync(link));
395
+ if (!target.startsWith(ownPrefix)) { counts.kept++; continue; } // not linker-made: leave it
392
396
  fs.unlinkSync(link); // removes the dangling link itself, never a target
393
397
  counts.removed++;
394
398
  } catch { /* best-effort per entry */ }
@@ -402,10 +406,12 @@ function syncModulesDir(mainCwd, worktreeCwd, rel, counts) {
402
406
  * considers). pnpm projects are skipped (their worktree node_modules is a real install).
403
407
  * No-op under SM_WORKTREE_DEP_LINK_DISABLE=1. Never throws.
404
408
  * @param {{ mainCwd: string, worktreeCwd: string }} opts
405
- * @returns {Promise<{ added: number, removed: number }>}
409
+ * Only dangling links into the main checkout's matching node_modules (the linker's own) are
410
+ * removed; any other dangling link (e.g. a workspace package mid-build) is kept and counted.
411
+ * @returns {Promise<{ added: number, removed: number, kept: number }>}
406
412
  */
407
413
  async function syncNodeModulesLinks({ mainCwd, worktreeCwd }) {
408
- const counts = { added: 0, removed: 0 };
414
+ const counts = { added: 0, removed: 0, kept: 0 };
409
415
  try {
410
416
  if (process.env.SM_WORKTREE_DEP_LINK_DISABLE === '1') return counts;
411
417
  if (!mainCwd || !worktreeCwd || isPnpmProject(mainCwd)) return counts;
@@ -190,6 +190,24 @@ const MCP_TOOL_CATALOG = [
190
190
  },
191
191
  notes: 'See /develop.',
192
192
  },
193
+ {
194
+ name: 'scheduler_release_plan',
195
+ group: 'scheduler',
196
+ purpose: 'Release a plan held for independent review via the session-manager app admin API (POST /admin/scheduler/release-plan). '
197
+ + 'Records the accepted finding count and one non-empty reason per rejected finding, then lets the plan\'s PRDs dispatch. '
198
+ + 'A second call returns alreadyReleased. With rereview: true it instead asks for ONE more review after a block '
199
+ + '(allowed only when the latest review has a block decision and the plan is at round 1; at most once per plan).',
200
+ summary: 'Release a reviewed plan, or request its single re-review.',
201
+ whenToUse: 'Use after reading the plan review: call once with accepted (count) and rejected [{ finding, reason }], or with rereview: true after a block.',
202
+ whenNotToUse: 'Not callable from inside a headless scheduled job (same refusal as scheduler_create_prds). Do not use to edit PRDs or to request a second re-review.',
203
+ exampleArgs: {
204
+ epicId: 'abc123',
205
+ validateSlug: 'validate-my-plan',
206
+ accepted: 2,
207
+ rejected: [{ finding: 'prd-3: add a failure-path test', reason: 'covered by the gate in prd-2' }],
208
+ },
209
+ notes: null,
210
+ },
193
211
  {
194
212
  name: 'scheduler_list_prds',
195
213
  group: 'scheduler',
@@ -330,14 +348,16 @@ const MCP_TOOL_CATALOG = [
330
348
  + '`acceptanceCriteria`; put evidence, symptom and references in `body`. Name the file in THEIR repo '
331
349
  + 'that looks responsible if you know it. When one request is split into several proposals, send '
332
350
  + 'them ALL with one shared `series` {key, title, total} (plus each one\'s `index`) and summarise '
333
- + 'the overall plan in each motivation. THREE MODES: (1) agent-initiated (your own idea) = PROPOSED, a '
351
+ + 'the overall plan in each motivation. FOUR MODES: (1) agent-initiated (your own idea) = PROPOSED, a '
334
352
  + 'human in the receiving project must approve it; pass neither autoStart nor humanRequestQuote. '
335
353
  + '(2) human-requested = the human in THIS conversation explicitly asked for the work in that other '
336
354
  + 'project: pass `autoStart: true` plus `humanRequestQuote`, copied VERBATIM from their own message, '
337
355
  + 'whose quoted words themselves must name the target project. An unverified request silently falls back to PROPOSED. '
338
356
  + '(3) macro auto-start = a session launched from a macro with "Can start work in other projects" on '
339
357
  + 'auto-starts sends tagged `bug` or `feature` to allowed projects with no flag and no quote; otherwise it stays '
340
- + 'a proposal. Pass tag `bug` or `feature` for work you want started.',
358
+ + 'a proposal. (4) paired-service grant = a paired service whose owner ticked "May start work it opens" '
359
+ + 'for the target project auto-starts `autoStart: true` sends tagged `bug` or `feature`; without the grant it '
360
+ + 'stays proposed. Pass tag `bug` or `feature` for work you want started.',
341
361
  whenNotToUse: 'WHEN NOT TO USE IT: for work in the project you are ALREADY in, run /develop inside the Epic you '
342
362
  + 'are already in — this tool refuses toCwd === fromCwd outright.',
343
363
  exampleArgs: {
@@ -401,6 +421,25 @@ const MCP_TOOL_CATALOG = [
401
421
  + 'or release. A done reply that names a Session Manager version must carry release.commits (or it is '
402
422
  + 'refused): write `{version}`, never hand-type a version.',
403
423
  },
424
+ {
425
+ name: 'service_pair_local',
426
+ group: 'feedback',
427
+ purpose: 'Pair a service that runs on THIS machine with Session Manager in one call, with no window step: '
428
+ + 'the same pairing as `service pair-local`, through the loopback admin API. Returns the paired service (never its key).',
429
+ summary: 'Pair a same-machine service with Session Manager, no window step.',
430
+ whenToUse: 'Use when the human asked you to pair a service running on this same machine (for example Kiln). '
431
+ + 'Give the absolute stateDir the service keeps its pairing in, a name, its homeCwd, and the tools it may call.',
432
+ whenNotToUse: 'Do not use for a service on another machine (that needs the window pairing). Web remote must be on or the '
433
+ + 'call is refused. Refused inside a scheduled job and outside a Session Manager chat or terminal session. '
434
+ + 'The pairing can be revoked in App Settings → Web remote.',
435
+ exampleArgs: {
436
+ stateDir: '/home/bilko/.local/state/kiln',
437
+ name: 'Kiln',
438
+ homeCwd: '/home/bilko/Projects/kiln',
439
+ tools: ['feedback_list_projects', 'feedback_open_session'],
440
+ },
441
+ notes: 'Result: { ok: true, service } or an error with the route\'s refusal text. Report only what was paired; the human revokes it in App Settings → Web remote.',
442
+ },
404
443
  {
405
444
  name: 'project_home_write',
406
445
  group: 'project-home',
@@ -899,12 +938,12 @@ const MCP_TOOL_CATALOG = [
899
938
  purpose: "Read-only list of one project's open Epics (sessions) via the session-manager app's admin API "
900
939
  + '(GET /admin/epics) — the same outside-facing records a script gets: each Epic\'s epicId, title, '
901
940
  + 'outside-facing state and PRD progress. Optionally filter by `state`. Results are paginated (default limit 50, '
902
- + 'max 200) — check `hasMore`/`total` before assuming you received every Epic; page further with `offset`.',
941
+ + 'max 200) — check `hasMore`/`total` before assuming you received every Epic; page further with `offset`. '
942
+ + 'Each record\'s source.startedBy is absent/null when a person pressed New Epic; otherwise a script started it, with its caller and fromEpicId.',
903
943
  summary: 'List the open sessions of one project and what state each is in.',
904
944
  whenToUse: 'Use to survey which Epics a project has open and which need input, review or approval, before '
905
945
  + 'reading one in full with epic_get.',
906
- whenNotToUse: 'Do not use this to create, approve or change an Epic — it is read-only, and an Epic is only '
907
- + 'ever created by a human pressing New Epic. Do not use it for PRD status; use scheduler_list_prds.',
946
+ whenNotToUse: 'Do not use this to create, approve or change an Epic — it is read-only. Do not use it for PRD status; use scheduler_list_prds.',
908
947
  exampleArgs: { cwd: '/home/bilko/Projects/session-manager', state: 'needs_input' },
909
948
  notes: 'A partial page carries a `note` naming how many Epics were returned out of `total`.',
910
949
  },
@@ -913,7 +952,8 @@ const MCP_TOOL_CATALOG = [
913
952
  group: 'epics',
914
953
  purpose: "Read-only fetch of one Epic's outside-facing record via the session-manager app's admin API "
915
954
  + '(GET /admin/epic), looked up in project `cwd` by exactly one of `id` (the Epic id) or `externalRef` '
916
- + '(the reference it was opened with). Returns `{ ok: true, epic }`, or `{ ok: false, error: "not found" }`.',
955
+ + '(the reference it was opened with). Returns `{ ok: true, epic }`, or `{ ok: false, error: "not found" }`. '
956
+ + 'epic.source.startedBy is absent/null when a person pressed New Epic; otherwise a script started it, with its caller and fromEpicId.',
917
957
  summary: 'Read one session by its id or by the outside reference it was opened with.',
918
958
  whenToUse: 'Use after epic_list, or when you already hold an Epic id or external reference, to read that '
919
959
  + "one Epic's state and progress.",
@@ -1189,7 +1229,7 @@ const MCP_RECIPES = [
1189
1229
  + 'curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/project-home/videos/run" '
1190
1230
  + '-H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H \'Content-Type: application/json\' '
1191
1231
  + '-d \'{"cwd":"/abs/project","kind":"Blog post","target":"https://example.com/blog/hello","externalRef":"hello"}\'. '
1192
- + 'Optional keys: length, style, character, voiceId, focus, reviewFirst. Success is { ok, entryId, epicId, slug, stage }; the same externalRef again answers { ok, existing: true, entryId, epicId } instead of a second run.',
1232
+ + 'Optional keys: length, style, character, voiceId, focus, reviewFirst, and caller { pipeline, runId, step, attempt } (recorded on the Epic as source.startedBy.caller), e.g. "caller":{"pipeline":"blog-videos","runId":"run-42","step":"render","attempt":1}; a press from an SM chat records that chat\'s Epic automatically (fromEpicId). Success is { ok, entryId, epicId, slug, stage }; the same externalRef again answers { ok, existing: true, entryId, epicId } instead of a second run.',
1193
1233
  'Read the outcome with GET /admin/project-home/videos/status?cwd=<encoded>&id=<entryId> (same bearer token): state is queued, running, awaiting_review, saved (files.index/meta/mp4/poster, absolute paths), season-complete or failed (reason).',
1194
1234
  '409 already_building means a Demo Video job for this project is already pending or running — retry later; never loop tightly.',
1195
1235
  'With Review first (reviewFirst: true) the run stops at awaiting_review: only the human approves or asks for changes in Project Home > Video, then the final video builds. A script just keeps reading the status.',
@@ -825,7 +825,24 @@ async function checkConfiguredMcpServer(request, options) {
825
825
  const { home, check = checkMcpServer, timeoutMs, clientVersion } = options || {};
826
826
  const target = await resolveMcpServerConfig(request, { home });
827
827
  if (!target) return { ok: false, status: 'failed', error: 'server not found', checkedAt: Date.now() };
828
- return check(target.server, { timeoutMs, clientVersion, cwd: target.cwd });
828
+ const result = await check(target.server, { timeoutMs, clientVersion, cwd: target.cwd });
829
+ const { source, name } = request;
830
+ if (typeof name === 'string' && typeof source === 'string') lastProbes.set(`${source}\u0000${name}`, { scope: source, name, result });
831
+ return result;
829
832
  }
830
833
 
831
- module.exports = { checkMcpServer, resolveMcpServerConfig, checkConfiguredMcpServer };
834
+ /** Last checkConfiguredMcpServer result per (scope, name), this process only. */
835
+ const lastProbes = new Map();
836
+
837
+ /** @returns {object | null} the last result for the server, or null if never checked. */
838
+ function lastProbe(scope, name) {
839
+ const hit = lastProbes.get(`${scope}\u0000${name}`);
840
+ return hit ? hit.result : null;
841
+ }
842
+
843
+ /** @param {string} scope @returns {{ name: string, scope: string }[]} servers with a stored result in the scope. */
844
+ function probedServers(scope) {
845
+ return [...lastProbes.values()].filter((e) => e.scope === scope).map((e) => ({ name: e.name, scope: e.scope }));
846
+ }
847
+
848
+ module.exports = { checkMcpServer, resolveMcpServerConfig, checkConfiguredMcpServer, lastProbe, probedServers };
@@ -144,6 +144,8 @@ const GIT_CLASS = Object.freeze({
144
144
  HUMAN_LEARN: 'tracked',
145
145
  manual: 'tracked',
146
146
  reviews: 'tracked',
147
+ // Human-written steering for the weekly MD consolidation; code only reads it.
148
+ 'md-network': 'tracked',
147
149
  });
148
150
 
149
151
  /**