claude-code-session-manager 0.143.0 → 0.144.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 (119) hide show
  1. package/README.md +3 -1
  2. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  3. package/dist/assets/{History-DTttbvPb.js → History-C3E6y_7t.js} +2 -2
  4. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  5. package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CnfWs46Z.js} +1 -1
  6. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  7. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  9. package/dist/assets/{Skills-cfV7sgk6.js → Skills-Bg5O2Hyn.js} +23 -23
  10. package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-BdzoBmqu.js} +27 -27
  11. package/dist/assets/{Toggle-CYajnSdx.js → Toggle-Dt5K1OXt.js} +1 -1
  12. package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-CTLyRgdF.js} +1 -1
  13. package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B2_KWBga.js} +1 -1
  14. package/dist/assets/{index-CdTppjKR.js → index-446b69rr.js} +698 -697
  15. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +439 -436
  19. package/package.json +4 -2
  20. package/plugins/session-manager-dev/skills/develop/SKILL.md +14 -13
  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 +87 -0
  23. package/scripts/README.md +1 -1
  24. package/scripts/scheduler-mcp-server.cjs +77 -0
  25. package/src/main/adminRouteRegistry.cjs +6 -0
  26. package/src/main/agentLibrary.cjs +60 -11
  27. package/src/main/agentsIpc.cjs +19 -0
  28. package/src/main/build-info.json +4 -4
  29. package/src/main/chatRunner.cjs +109 -0
  30. package/src/main/health.cjs +59 -17
  31. package/src/main/index.cjs +4 -0
  32. package/src/main/ipcSchemas.cjs +50 -1
  33. package/src/main/lib/claude/agentArmory.cjs +128 -0
  34. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  35. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  36. package/src/main/lib/claude/builtinTools.cjs +110 -0
  37. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  38. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  39. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  40. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  41. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  42. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  43. package/src/main/lib/epic/epicSettle.cjs +48 -4
  44. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  45. package/src/main/lib/epic/epicValidationHook.cjs +9 -1
  46. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  48. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  49. package/src/main/lib/externalContract.cjs +12 -0
  50. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  51. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  52. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
  53. package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
  54. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  55. package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
  56. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  57. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  58. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  59. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  60. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  61. package/src/main/lib/git/gitWorktree.cjs +1 -1
  62. package/src/main/lib/git/worktreeDeps.cjs +9 -3
  63. package/src/main/lib/mcpToolCatalog.cjs +43 -5
  64. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  65. package/src/main/lib/packs/packCatalog.cjs +98 -5
  66. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  67. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  68. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  69. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  70. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  71. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  72. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  73. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
  74. package/src/main/lib/prd/prdCreate.cjs +48 -5
  75. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  76. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  77. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  78. package/src/main/lib/process/peerChatSession.cjs +165 -0
  79. package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
  80. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
  81. package/src/main/lib/promptSessionSchema.cjs +2 -0
  82. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  83. package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
  84. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  85. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  86. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  87. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  88. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  89. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  90. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  91. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
  92. package/src/main/lib/tasks/memoryConsolidation.cjs +109 -37
  93. package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
  94. package/src/main/lib/tasks/taskRun.cjs +3 -1
  95. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  96. package/src/main/projectPages.cjs +22 -14
  97. package/src/main/pty.cjs +3 -0
  98. package/src/main/runVerify.cjs +3 -2
  99. package/src/main/scheduler/planReviewHold.cjs +140 -0
  100. package/src/main/scheduler/prdParser.cjs +1 -0
  101. package/src/main/scheduler/reviewLadder.cjs +2 -0
  102. package/src/main/scheduler/utilizationHold.cjs +7 -2
  103. package/src/main/scheduler.cjs +532 -78
  104. package/src/main/seedAgentPersonas.cjs +11 -6
  105. package/src/main/seedStatus.cjs +1 -1
  106. package/src/main/templates/PRD_AUTHORING.md +16 -1
  107. package/src/main/webRemote.cjs +47 -7
  108. package/src/preload/api.d.ts +71 -1
  109. package/src/preload/apiSurface.json +28 -0
  110. package/src/preload/index.cjs +9 -0
  111. package/src/seed/agents/architect.md +28 -43
  112. package/src/seed/agents/dev-lead.md +3 -1
  113. package/src/seed/agents/md-network-curator.md +27 -0
  114. package/src/seed/agents/plan-reviewer.md +47 -0
  115. package/src/seed/agents/validator.md +2 -1
  116. package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
  117. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
  118. package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
  119. package/dist/assets/Scheduler-CNLjn90m.js +0 -16
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * scriptStartedBy.cjs — how a script-started Epic records who started it.
5
+ * EpicSource.startedBy = { kind: 'script', route, caller?, fromCwd?, fromEpicId? };
6
+ * absent for every human press. 'new-epic-ui' stays the mint authority
7
+ * (epicMint.cjs); startedBy sits next to it. The stored shape is lenient
8
+ * (promptSessionSchema.cjs); this is the strict entry-point validator.
9
+ */
10
+
11
+ const { z } = require('zod');
12
+
13
+ const CallerSchema = z.object({
14
+ pipeline: z.string().max(200).optional(),
15
+ runId: z.string().max(200).optional(),
16
+ step: z.string().max(200).optional(),
17
+ attempt: z.number().int().min(0).optional(),
18
+ }).strict();
19
+
20
+ const StartedBySchema = z.object({
21
+ kind: z.literal('script'),
22
+ route: z.string().min(1).max(200),
23
+ caller: CallerSchema.optional(),
24
+ fromCwd: z.string().max(4096).optional(),
25
+ fromEpicId: z.string().max(200).optional(),
26
+ }).strict();
27
+
28
+ /**
29
+ * Build a StartedBySchema-valid object, omitting absent/empty keys.
30
+ * @param {{ route: string, caller?: object, fromCwd?: string, fromEpicId?: string }} args
31
+ */
32
+ function buildStartedBy({ route, caller, fromCwd, fromEpicId } = {}) {
33
+ const out = { kind: 'script', route };
34
+ if (caller && typeof caller === 'object') {
35
+ const c = {};
36
+ for (const [k, v] of Object.entries(caller)) {
37
+ if (v !== undefined && v !== null && v !== '') c[k] = v;
38
+ }
39
+ if (Object.keys(c).length) out.caller = c;
40
+ }
41
+ if (typeof fromCwd === 'string' && fromCwd) out.fromCwd = fromCwd;
42
+ if (typeof fromEpicId === 'string' && fromEpicId) out.fromEpicId = fromEpicId;
43
+ return StartedBySchema.parse(out);
44
+ }
45
+
46
+ /**
47
+ * startedBy for a request: validated body caller + the chat that made the
48
+ * loopback call (resolved from the socket), mapped to its Epic when found.
49
+ * @param {{ route: string, caller?: object, socket?: object }} args
50
+ * @param {{ resolvePeerChatSession?: Function, findEpicByClaudeSessionId?: Function }} [deps]
51
+ */
52
+ async function startedByFromRequest({ route, caller, socket } = {}, deps = {}) {
53
+ let fromCwd;
54
+ let fromEpicId;
55
+ try {
56
+ const resolve = deps.resolvePeerChatSession || require('../process/peerChatSession.cjs').resolvePeerChatSession;
57
+ const peer = await resolve(socket);
58
+ if (peer && peer.chatSessionId && peer.projectRoot) {
59
+ const find = deps.findEpicByClaudeSessionId || require('../claude/agentModelResolve.cjs').findEpicByClaudeSessionId;
60
+ const epic = find(peer.projectRoot, peer.chatSessionId);
61
+ if (epic) {
62
+ fromCwd = peer.projectRoot;
63
+ fromEpicId = epic.id || epic.epicId || undefined;
64
+ if (!fromEpicId) fromCwd = undefined;
65
+ }
66
+ }
67
+ } catch { /* resolution is best-effort */ }
68
+ return buildStartedBy({ route, caller, fromCwd, fromEpicId });
69
+ }
70
+
71
+ module.exports = { CallerSchema, StartedBySchema, buildStartedBy, startedByFromRequest };
@@ -60,6 +60,9 @@ const CONTRACT = deepFreeze({
60
60
  { method: 'GET', path: '/__admin/health' },
61
61
  { method: 'POST', path: '/admin/feedback/open-session' },
62
62
  { method: 'POST', path: '/admin/macros/run' },
63
+ { method: 'POST', path: '/admin/projects/create' },
64
+ { method: 'POST', path: '/admin/services/pair-local' },
65
+ { method: 'POST', path: '/admin/services/pair-local/confirm' },
63
66
  { method: 'GET', path: '/admin/epics' },
64
67
  { method: 'GET', path: '/admin/epic' },
65
68
  // GET /admin/events: no epicId → audit-log rows { events, next, more, gap } (eventKinds below);
@@ -91,6 +94,7 @@ const CONTRACT = deepFreeze({
91
94
  epicRecordFields: [
92
95
  'epicId', 'cwd', 'title', 'goal', 'tag', 'agentType', 'status', 'state', 'phase', 'blocked', 'prds',
93
96
  'verified', 'refuted', 'unvalidated', 'externalRef', 'source', 'createdAt', 'completedAt', 'verdicts',
97
+ 'planReviews', 'planReviewStats',
94
98
  ],
95
99
  receiptFields: ['jobs', 'chat'],
96
100
  epicStateChangedFields: ['at', 'kind', 'cwd', 'epicId', 'from', 'to', 'blockedKind', 'externalRef'],
@@ -165,6 +169,10 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
165
169
  // back to the v1 shape 0.141.0 served; 0.142.0 served lifecycle words only, after C6 909f6e47 narrowed it).
166
170
  // then GET /admin/usage-hold (scheduler/usageHoldRoute.cjs): the 'pause above' hold POST /admin/tasks refuses on.
167
171
  // then usage_hold_get: the MCP tool over GET /admin/usage-hold (scheduler-mcp-server.cjs).
172
+ // then POST /admin/projects/create (feedback-remote/projectCreate.cjs); no tool entry, mirroring macro_run.
173
+ // then POST /admin/services/pair-local + /confirm (feedback-remote/servicePairLocalRoutes.cjs).
174
+ // then 'planReviews' on epicRecordFields (stored plan-review records + release from plan-records/*.plan-review.json).
175
+ // then 'planReviewStats' on epicRecordFields (planReviewStats.cjs: reviewed vs unreviewed plan comparison).
168
176
  1: Object.freeze([
169
177
  '5a56abbb70184ff4a34346a5c6da4c5e6edbd756b54573c199b812d3f5a04101',
170
178
  '7383ff32c80561b1b2c505a78a1e8313ae2851bdc6e8fce6c6a88e1ab119bf5a',
@@ -175,6 +183,10 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
175
183
  '4f4ee647977bb670c71db57c6fdfa8dc5db89ce789a1f05dbf23f9468dcff30b',
176
184
  '2c87717d95b8b7dceb8a2138affcd3fc990f762072691de7a433b2874fe89d4d',
177
185
  '9490d3b89b9468f20666553747b3d4be3558e78ffcb5b79d63397cfa4ddd5235',
186
+ '799f062f9dd858b81afa20cf2153357e8fc7a3be2c748573d0f4c12b430d6683',
187
+ 'feaad10fabd300203314318c5484a8aed9b1cef496d2fbfb48464b06ff64628a',
188
+ 'e0ee3a1a0970e44c52b336d935ac59d05c4bfba3b4f3c602222292fbb5c77174',
189
+ '6fa520f745b48c393733123633029537aa54109040081bed320fa976888f1e77',
178
190
  ]),
179
191
  });
180
192
 
@@ -0,0 +1,291 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * createdProjects.cjs — store of every project folder the project_create tool
6
+ * created. Pure Node — no Electron — importable in unit tests.
7
+ *
8
+ * File (default ~/.claude/session-manager/created-projects.json, mode 0600,
9
+ * override SM_CREATED_PROJECTS_FILE):
10
+ * { version: 1, projects: [{ cwd, fromCwd, externalRef, repo, createdAt }] }
11
+ *
12
+ * - A repeat project_create with the same (fromCwd, externalRef) answers with
13
+ * the same folder via findByRef.
14
+ * - The project list can include a folder before it has any Claude transcript
15
+ * via list().
16
+ *
17
+ * Mirrors servicePairings.cjs: state is read once from disk (missing/corrupt =
18
+ * empty) and kept in memory; every mutation is written atomically, serialized
19
+ * through one queue. Reads are synchronous over the in-memory copy. This store
20
+ * is the only writer of that file (it lives under ~/.claude, not an ops root).
21
+ */
22
+
23
+ const path = require('node:path');
24
+ const { writeTextAtomic, readJsonOrSync } = require('../util/atomicFs.cjs');
25
+
26
+ const STORE_VERSION = 1;
27
+ const MAX_PROJECTS = 1000;
28
+ const MAX_EXTERNAL_REF_LEN = 200;
29
+ const MAX_REPO_LEN = 200;
30
+
31
+ /**
32
+ * @typedef {{ cwd: string, fromCwd: string, externalRef: string, repo: string | null, createdAt: number }} CreatedProject
33
+ * @typedef {{ version: number, projects: CreatedProject[] }} StoreState
34
+ * @typedef {{ cwd?: unknown, fromCwd?: unknown, externalRef?: unknown, repo?: unknown }} RecordInput
35
+ * @typedef {{
36
+ * findByRef: (fromCwd: unknown, externalRef: unknown) => CreatedProject | null,
37
+ * findByCwd: (cwd: unknown) => CreatedProject | null,
38
+ * record: (input: RecordInput) => Promise<CreatedProject>,
39
+ * setRepo: (cwd: unknown, repo: unknown) => Promise<CreatedProject | null>,
40
+ * list: () => CreatedProject[],
41
+ * }} CreatedProjectsStore
42
+ */
43
+
44
+ /** @returns {string} */
45
+ function defaultFilePath() {
46
+ const override = process.env.SM_CREATED_PROJECTS_FILE;
47
+ if (typeof override === 'string' && override.length > 0) return override;
48
+ const { claudeHome } = require('../scheduler/schedulerPaths.cjs');
49
+ return path.join(claudeHome(), 'session-manager', 'created-projects.json');
50
+ }
51
+
52
+ /**
53
+ * @param {unknown} p
54
+ * @returns {p is string}
55
+ */
56
+ function isAbsPath(p) {
57
+ return typeof p === 'string' && p.length > 0 && path.isAbsolute(p) && !p.includes('\0');
58
+ }
59
+
60
+ /**
61
+ * @param {unknown} p
62
+ * @param {string} label
63
+ * @returns {string}
64
+ */
65
+ function validateAbs(p, label) {
66
+ if (!isAbsPath(p)) throw new Error(`${label} must be an absolute path`);
67
+ return path.resolve(p);
68
+ }
69
+
70
+ /**
71
+ * @param {unknown} ref
72
+ * @returns {string}
73
+ */
74
+ function validateExternalRef(ref) {
75
+ if (typeof ref !== 'string' || ref.length === 0 || ref.length > MAX_EXTERNAL_REF_LEN) {
76
+ throw new Error(`externalRef must be a string of 1 to ${MAX_EXTERNAL_REF_LEN} chars`);
77
+ }
78
+ return ref;
79
+ }
80
+
81
+ /**
82
+ * @param {unknown} repo
83
+ * @param {boolean} allowNull
84
+ * @returns {string | null}
85
+ */
86
+ function validateRepo(repo, allowNull) {
87
+ if (allowNull && (repo === undefined || repo === null)) return null;
88
+ if (typeof repo !== 'string' || repo.length === 0 || repo.length > MAX_REPO_LEN || /[\r\n\0]/.test(repo)) {
89
+ throw new Error(`repo must be a one-line string of 1 to ${MAX_REPO_LEN} chars`);
90
+ }
91
+ return repo;
92
+ }
93
+
94
+ /**
95
+ * @param {CreatedProject} e
96
+ * @returns {CreatedProject}
97
+ */
98
+ function copy(e) {
99
+ return { cwd: e.cwd, fromCwd: e.fromCwd, externalRef: e.externalRef, repo: e.repo, createdAt: e.createdAt };
100
+ }
101
+
102
+ /**
103
+ * @param {unknown} e
104
+ * @returns {e is CreatedProject}
105
+ */
106
+ function isEntry(e) {
107
+ if (!e || typeof e !== 'object') return false;
108
+ const r = /** @type {Record<string, unknown>} */ (e);
109
+ return isAbsPath(r.cwd) && isAbsPath(r.fromCwd)
110
+ && typeof r.externalRef === 'string' && r.externalRef.length > 0
111
+ && typeof r.createdAt === 'number';
112
+ }
113
+
114
+ /**
115
+ * A repo read from disk: kept only when it passes validateRepo, else null.
116
+ * @param {unknown} repo
117
+ * @returns {string | null}
118
+ */
119
+ function loadedRepo(repo) {
120
+ if (typeof repo !== 'string') return null;
121
+ try {
122
+ return validateRepo(repo, false);
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * @param {unknown} raw
130
+ * @returns {StoreState}
131
+ */
132
+ function normalizeLoaded(raw) {
133
+ /** @type {StoreState} */
134
+ const empty = { version: STORE_VERSION, projects: [] };
135
+ if (!raw || typeof raw !== 'object') return empty;
136
+ const list = /** @type {{ projects?: unknown }} */ (raw).projects;
137
+ if (!Array.isArray(list)) return empty;
138
+ const projects = list.filter(isEntry).map((e) => ({
139
+ cwd: path.resolve(e.cwd),
140
+ fromCwd: path.resolve(e.fromCwd),
141
+ externalRef: e.externalRef,
142
+ repo: loadedRepo(e.repo),
143
+ createdAt: e.createdAt,
144
+ }));
145
+ return { version: STORE_VERSION, projects: projects.slice(-MAX_PROJECTS) };
146
+ }
147
+
148
+ /**
149
+ * @param {{ filePath?: string, now?: () => number }} [opts]
150
+ * @returns {CreatedProjectsStore}
151
+ */
152
+ function createCreatedProjects({ filePath, now } = {}) {
153
+ const file = filePath || defaultFilePath();
154
+ const clock = typeof now === 'function' ? now : () => Date.now();
155
+ /** @type {StoreState | null} */
156
+ let state = null;
157
+ /** @type {Promise<unknown>} */
158
+ let queue = Promise.resolve();
159
+
160
+ /** @returns {StoreState} */
161
+ function load() {
162
+ if (!state) state = normalizeLoaded(readJsonOrSync(file, null));
163
+ return state;
164
+ }
165
+
166
+ /**
167
+ * Run a mutation then persist; serialized so writes never interleave.
168
+ * @template T
169
+ * @param {(s: StoreState) => T} fn
170
+ * @returns {Promise<T>}
171
+ */
172
+ function mutate(fn) {
173
+ const run = queue.then(async () => {
174
+ /** @type {StoreState} */
175
+ const next = JSON.parse(JSON.stringify(load()));
176
+ const result = fn(next);
177
+ await writeTextAtomic(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
178
+ state = next;
179
+ return result;
180
+ });
181
+ queue = run.catch(() => {});
182
+ return run;
183
+ }
184
+
185
+ /**
186
+ * @param {StoreState} s
187
+ * @param {string} cwd
188
+ */
189
+ function entryByCwd(s, cwd) {
190
+ return s.projects.find((e) => e.cwd === cwd) || null;
191
+ }
192
+
193
+ /**
194
+ * @param {StoreState} s
195
+ * @param {string} fromCwd
196
+ * @param {string} externalRef
197
+ */
198
+ function entryByRef(s, fromCwd, externalRef) {
199
+ return s.projects.find((e) => e.fromCwd === fromCwd && e.externalRef === externalRef) || null;
200
+ }
201
+
202
+ return {
203
+ findByRef(fromCwd, externalRef) {
204
+ if (!isAbsPath(fromCwd) || typeof externalRef !== 'string' || externalRef.length === 0) return null;
205
+ const e = entryByRef(load(), path.resolve(fromCwd), externalRef);
206
+ return e ? copy(e) : null;
207
+ },
208
+
209
+ findByCwd(cwd) {
210
+ if (!isAbsPath(cwd)) return null;
211
+ const e = entryByCwd(load(), path.resolve(cwd));
212
+ return e ? copy(e) : null;
213
+ },
214
+
215
+ record(input) {
216
+ /** @type {string} */ let cwd;
217
+ /** @type {string} */ let fromCwd;
218
+ /** @type {string} */ let externalRef;
219
+ /** @type {string | null} */ let repo;
220
+ try {
221
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
222
+ throw new Error('record expects { cwd, fromCwd, externalRef, repo? }');
223
+ }
224
+ cwd = validateAbs(input.cwd, 'cwd');
225
+ fromCwd = validateAbs(input.fromCwd, 'fromCwd');
226
+ externalRef = validateExternalRef(input.externalRef);
227
+ repo = validateRepo(input.repo, true);
228
+ } catch (e) {
229
+ return Promise.reject(e);
230
+ }
231
+ return mutate((s) => {
232
+ const byCwd = entryByCwd(s, cwd);
233
+ if (byCwd) {
234
+ if (byCwd.fromCwd === fromCwd && byCwd.externalRef === externalRef) return copy(byCwd);
235
+ throw new Error(`cwd is already recorded under another externalRef: ${cwd}`);
236
+ }
237
+ const byRef = entryByRef(s, fromCwd, externalRef);
238
+ if (byRef) throw new Error(`externalRef already names a different cwd: ${byRef.cwd}`);
239
+ /** @type {CreatedProject} */
240
+ const entry = { cwd, fromCwd, externalRef, repo, createdAt: clock() };
241
+ s.projects.push(entry);
242
+ if (s.projects.length > MAX_PROJECTS) s.projects = s.projects.slice(-MAX_PROJECTS);
243
+ return copy(entry);
244
+ });
245
+ },
246
+
247
+ setRepo(cwd, repo) {
248
+ /** @type {string} */ let want;
249
+ /** @type {string} */ let value;
250
+ try {
251
+ want = validateAbs(cwd, 'cwd');
252
+ value = /** @type {string} */ (validateRepo(repo, false));
253
+ } catch (e) {
254
+ return Promise.reject(e);
255
+ }
256
+ return mutate((s) => {
257
+ const e = entryByCwd(s, want);
258
+ if (!e) return null;
259
+ e.repo = value;
260
+ return copy(e);
261
+ });
262
+ },
263
+
264
+ list() {
265
+ const items = load().projects.map((e, i) => ({ e, i }));
266
+ items.sort((a, b) => (b.e.createdAt - a.e.createdAt) || (b.i - a.i));
267
+ return items.map(({ e }) => copy(e));
268
+ },
269
+ };
270
+ }
271
+
272
+ /** @type {CreatedProjectsStore | null} */
273
+ let singleton = null;
274
+
275
+ /** @returns {CreatedProjectsStore} */
276
+ function getCreatedProjects() {
277
+ if (!singleton) singleton = createCreatedProjects();
278
+ return singleton;
279
+ }
280
+
281
+ function __resetCreatedProjectsForTests() {
282
+ singleton = null;
283
+ }
284
+
285
+ module.exports = {
286
+ createCreatedProjects,
287
+ getCreatedProjects,
288
+ __resetCreatedProjectsForTests,
289
+ MAX_PROJECTS,
290
+ MAX_EXTERNAL_REF_LEN,
291
+ };
@@ -1126,17 +1126,26 @@ async function openReplyFallbackSession(input = {}, deps = {}) {
1126
1126
  * requires everywhere else: a PROJECT IS A CWD, resolved from transcript
1127
1127
  * CONTENT, never by naively decoding a `~/.claude/projects/` folder name back
1128
1128
  * into a path. A folder whose cwd cannot be resolved is DROPPED, not guessed.
1129
+ *
1130
+ * Two sources:
1131
+ * 1. transcript folders under `~/.claude/projects/` (above);
1132
+ * 2. the created-projects ledger (`createdProjects.cjs`, injectable as
1133
+ * `createdProjects`, default `getCreatedProjects()`), so a folder made by
1134
+ * project_create is a target before anyone has worked in it. Ledger cwds
1135
+ * are recorded main checkouts, so they skip resolveProjectContext; their
1136
+ * lastActivity is the later of transcript activity and createdAt, and a
1137
+ * cwd in both sources is listed once.
1129
1138
  * Results are then filtered to directories that still exist AND already carry
1130
1139
  * an operations root — exactly `openFeedbackSession`'s own precondition, so
1131
1140
  * this list can't offer a target that would then be refused.
1132
1141
  */
1133
- async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir } = {}) {
1142
+ async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir, createdProjects } = {}) {
1134
1143
  const root = resolveProjectsDir(projectsDir);
1135
1144
  let entries;
1136
1145
  try {
1137
1146
  entries = await fsp.readdir(root, { withFileTypes: true });
1138
1147
  } catch {
1139
- return { projects: [], scanned: 0, truncated: 0 };
1148
+ entries = [];
1140
1149
  }
1141
1150
  const dirs = entries.filter((e) => e.isDirectory());
1142
1151
 
@@ -1166,6 +1175,19 @@ async function listFeedbackTargets({ limit = TARGET_SCAN_LIMIT, projectsDir } =
1166
1175
  if (!prior || prior.lastActivity < mtimeMs) byCwd.set(cwd, { cwd, lastActivity: mtimeMs });
1167
1176
  }
1168
1177
 
1178
+ // Second source: the created-projects ledger. A broken ledger never hides
1179
+ // the transcript-derived list.
1180
+ let ledgerEntries = [];
1181
+ try {
1182
+ const store = createdProjects || require('./createdProjects.cjs').getCreatedProjects();
1183
+ ledgerEntries = store.list();
1184
+ } catch { ledgerEntries = []; }
1185
+ for (const e of ledgerEntries) {
1186
+ if (!e || typeof e.cwd !== 'string' || typeof e.createdAt !== 'number') continue;
1187
+ const prior = byCwd.get(e.cwd);
1188
+ if (!prior || prior.lastActivity < e.createdAt) byCwd.set(e.cwd, { cwd: e.cwd, lastActivity: e.createdAt });
1189
+ }
1190
+
1169
1191
  const projects = [...byCwd.values()]
1170
1192
  .filter((p) => isDirectory(p.cwd) && isSessionManagerProject(p.cwd))
1171
1193
  .sort((a, b) => b.lastActivity - a.lastActivity)
@@ -44,7 +44,7 @@
44
44
  * `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
45
45
  * matching the IPC handlers in index.cjs.
46
46
  *
47
- * POST /admin/macros/run {cwd, id, inputs?, effort?, externalRef?}
47
+ * POST /admin/macros/run {cwd, id, inputs?, effort?, externalRef?, caller?}
48
48
  * -> { ok, epicId, alreadyRunning, externalRef? }
49
49
  * Starts a saved macro from a script (e.g. a systemd timer) through the
50
50
  * renderer's press path (deps.startExternalNewSession: same persona, tag, AIM
@@ -58,6 +58,10 @@
58
58
  * macro at most once per ref: it rides in the payload, is recorded in
59
59
  * externalRefIndex and audited; a repeat with the same cwd + ref answers
60
60
  * { existing: true } with that Epic (409 if another producer/macro owns the ref).
61
+ * caller ({pipeline?, runId?, step?, attempt?}, CallerSchema in
62
+ * epic/scriptStartedBy.cjs; invalid = 400, no launch) rides in the audit event as scriptCaller (the audit log stamps its own `caller`);
63
+ * every launch payload carries startedBy (deps.startedByFromRequest) so the Epic
64
+ * records it was script-started. The mint producer stays 'new-epic-ui'.
61
65
  * curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/macros/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","id":"<macro-id>"}'
62
66
  */
63
67
  'use strict';
@@ -70,6 +74,7 @@ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
70
74
  const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
71
75
  const { readActiveIndex } = require('../epic/epicMint.cjs');
72
76
  const { PRD_EFFORT_LEVELS } = require('../prd/prdFrontmatter.cjs');
77
+ const { CallerSchema, startedByFromRequest: defaultStartedByFromRequest } = require('../epic/scriptStartedBy.cjs');
73
78
  const { normalizeExternalRef } = require('../epic/externalRef.cjs');
74
79
  const { findEpicByExternalRef, recordExternalRef, withExternalRefLock } = require('../epic/externalRefIndex.cjs');
75
80
 
@@ -379,6 +384,14 @@ function runHandler(deps, libOpts) {
379
384
  if (effort !== undefined && !PRD_EFFORT_LEVELS.includes(effort)) {
380
385
  return bad(`effort must be one of: ${PRD_EFFORT_LEVELS.join(', ')}`);
381
386
  }
387
+ let caller;
388
+ if (body.caller !== undefined) {
389
+ const parsedCaller = CallerSchema.safeParse(body.caller);
390
+ if (!parsedCaller.success) {
391
+ return bad(`caller: ${parsedCaller.error.issues?.[0]?.message ?? 'invalid'}`);
392
+ }
393
+ caller = parsedCaller.data;
394
+ }
382
395
  const ref = normalizeExternalRef(body.externalRef);
383
396
  if (!ref.ok) return bad(ref.error);
384
397
  const rendered = macroLibrary.renderMacroPrompt(macro.prompt, macro.inputs, {
@@ -388,7 +401,7 @@ function runHandler(deps, libOpts) {
388
401
  if (!rendered.ok) return bad(rendered.error);
389
402
 
390
403
  if (ref.value !== undefined) {
391
- await runWithExternalRef({ deps, res, cwd, macro, prompt: rendered.prompt, effort, externalRef: ref.value });
404
+ await runWithExternalRef({ deps, req, res, caller, cwd, macro, prompt: rendered.prompt, effort, externalRef: ref.value });
392
405
  return;
393
406
  }
394
407
 
@@ -411,6 +424,8 @@ function runHandler(deps, libOpts) {
411
424
 
412
425
  if (refusedByUsageHold(deps, res)) return;
413
426
 
427
+ const startedBy = await (deps.startedByFromRequest || defaultStartedByFromRequest)(
428
+ { route: '/admin/macros/run', caller, socket: req.socket }, deps);
414
429
  const payload = {
415
430
  cwd,
416
431
  agentName: macro.agentName,
@@ -419,6 +434,7 @@ function runHandler(deps, libOpts) {
419
434
  prompt: rendered.prompt,
420
435
  macroId: macro.id,
421
436
  via: 'script',
437
+ startedBy,
422
438
  ...(effort !== undefined ? { effort } : {}),
423
439
  };
424
440
  const launch = (async () => {
@@ -449,6 +465,7 @@ function runHandler(deps, libOpts) {
449
465
  macroId: macro.id,
450
466
  epicId: result.epicId,
451
467
  alreadyRunning: false,
468
+ ...(caller ? { scriptCaller: caller } : {}),
452
469
  });
453
470
  sendJson(res, 200, { ok: true, epicId: result.epicId, alreadyRunning: false });
454
471
  };
@@ -491,7 +508,7 @@ function launchFailureError(result) {
491
508
  * (cwd, externalRef) share one launch. The macro-wide findRunningEpic shortcut
492
509
  * is skipped: a new ref is a new run even while another run is busy.
493
510
  */
494
- async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, externalRef }) {
511
+ async function runWithExternalRef({ deps, req, res, caller, cwd, macro, prompt, effort, externalRef }) {
495
512
  const isTabBusy = deps.isTabBusy || (() => false);
496
513
  const existingAnswer = (epicId) => sendJson(res, 200, {
497
514
  ok: true, epicId, existing: true, alreadyRunning: !!isTabBusy(epicId), externalRef,
@@ -529,6 +546,8 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
529
546
 
530
547
  if (refusedByUsageHold(deps, res)) return;
531
548
 
549
+ const startedBy = await (deps.startedByFromRequest || defaultStartedByFromRequest)(
550
+ { route: '/admin/macros/run', caller, socket: req.socket }, deps);
532
551
  const payload = {
533
552
  cwd,
534
553
  agentName: macro.agentName,
@@ -537,6 +556,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
537
556
  prompt,
538
557
  macroId: macro.id,
539
558
  via: 'script',
559
+ startedBy,
540
560
  externalRef,
541
561
  ...(effort !== undefined ? { effort } : {}),
542
562
  };
@@ -577,6 +597,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
577
597
  epicId: result.epicId,
578
598
  alreadyRunning: false,
579
599
  externalRef,
600
+ ...(caller ? { scriptCaller: caller } : {}),
580
601
  });
581
602
  sendJson(res, 200, {
582
603
  ok: true, epicId: result.epicId, alreadyRunning: false, externalRef,
@@ -24,11 +24,11 @@ const crypto = require('node:crypto');
24
24
  const path = require('node:path');
25
25
  const { writeJsonAtomicSync, readJsonOrSync } = require('../util/atomicFs.cjs');
26
26
  const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
27
+ const { isCommitHash, MAX_COMMITS } = require('./replyClaims.cjs');
27
28
 
28
29
  const STORE_VERSION = 1;
29
30
  const FILE_NAME = 'pending-replies.json';
30
31
  const SEMVER_RE = /^\d+\.\d+\.\d+$/;
31
- const COMMIT_RE = /^[0-9a-f]{7,40}$/;
32
32
  /** Failed delivery attempts (one per hourly pass) before an entry gives up for good. */
33
33
  const MAX_DELIVERY_ATTEMPTS = 24;
34
34
 
@@ -82,14 +82,18 @@ function normalizeYSource(v) {
82
82
  try { return JSON.parse(JSON.stringify(v)); } catch { return null; }
83
83
  }
84
84
 
85
- /** Lowercased, de-duplicated commit hashes (7-40 hex); [] when none are valid. */
85
+ /**
86
+ * Lowercased, de-duplicated commit hashes (replyClaims.isCommitHash), at most
87
+ * MAX_COMMITS; invalid entries are dropped (the route already validated). [] when none.
88
+ */
86
89
  function normalizeCommits(v) {
87
90
  if (!Array.isArray(v)) return [];
88
91
  const out = [];
89
92
  for (const c of v) {
90
- if (typeof c !== 'string') continue;
93
+ if (out.length === MAX_COMMITS) break;
94
+ if (!isCommitHash(c)) continue;
91
95
  const lc = c.toLowerCase();
92
- if (COMMIT_RE.test(lc) && !out.includes(lc)) out.push(lc);
96
+ if (!out.includes(lc)) out.push(lc);
93
97
  }
94
98
  return out;
95
99
  }