claude-code-session-manager 0.142.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -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,17 +58,23 @@
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';
64
68
 
65
69
  const { readBody, sendJson } = require('./localAdminHttp.cjs');
70
+ const { usageHeldBody } = require('../scheduler/usageHoldRoute.cjs');
66
71
  const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
67
72
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
68
73
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
69
74
  const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
70
75
  const { readActiveIndex } = require('../epic/epicMint.cjs');
71
76
  const { PRD_EFFORT_LEVELS } = require('../prd/prdFrontmatter.cjs');
77
+ const { CallerSchema, startedByFromRequest: defaultStartedByFromRequest } = require('../epic/scriptStartedBy.cjs');
72
78
  const { normalizeExternalRef } = require('../epic/externalRef.cjs');
73
79
  const { findEpicByExternalRef, recordExternalRef, withExternalRefLock } = require('../epic/externalRefIndex.cjs');
74
80
 
@@ -378,6 +384,14 @@ function runHandler(deps, libOpts) {
378
384
  if (effort !== undefined && !PRD_EFFORT_LEVELS.includes(effort)) {
379
385
  return bad(`effort must be one of: ${PRD_EFFORT_LEVELS.join(', ')}`);
380
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
+ }
381
395
  const ref = normalizeExternalRef(body.externalRef);
382
396
  if (!ref.ok) return bad(ref.error);
383
397
  const rendered = macroLibrary.renderMacroPrompt(macro.prompt, macro.inputs, {
@@ -387,7 +401,7 @@ function runHandler(deps, libOpts) {
387
401
  if (!rendered.ok) return bad(rendered.error);
388
402
 
389
403
  if (ref.value !== undefined) {
390
- 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 });
391
405
  return;
392
406
  }
393
407
 
@@ -408,6 +422,10 @@ function runHandler(deps, libOpts) {
408
422
  return;
409
423
  }
410
424
 
425
+ if (refusedByUsageHold(deps, res)) return;
426
+
427
+ const startedBy = await (deps.startedByFromRequest || defaultStartedByFromRequest)(
428
+ { route: '/admin/macros/run', caller, socket: req.socket }, deps);
411
429
  const payload = {
412
430
  cwd,
413
431
  agentName: macro.agentName,
@@ -416,6 +434,7 @@ function runHandler(deps, libOpts) {
416
434
  prompt: rendered.prompt,
417
435
  macroId: macro.id,
418
436
  via: 'script',
437
+ startedBy,
419
438
  ...(effort !== undefined ? { effort } : {}),
420
439
  };
421
440
  const launch = (async () => {
@@ -446,11 +465,36 @@ function runHandler(deps, libOpts) {
446
465
  macroId: macro.id,
447
466
  epicId: result.epicId,
448
467
  alreadyRunning: false,
468
+ ...(caller ? { scriptCaller: caller } : {}),
449
469
  });
450
470
  sendJson(res, 200, { ok: true, epicId: result.epicId, alreadyRunning: false });
451
471
  };
452
472
  }
453
473
 
474
+ const USAGE_HOLD_HINT =
475
+ "Usage is above 'pause above': script presses wait until the window resets or usage drops below it. "
476
+ + 'Retry after hold.resetsAt. GET /admin/usage-hold reads the hold.';
477
+
478
+ /**
479
+ * The usage hold ('pause above') gate in front of every script-press
480
+ * startExternalNewSession call. Replies 429 usage_held / 503 usage_hold_error
481
+ * and returns true when the press must not start; false when it may.
482
+ * Read lazily so scheduler.cjs never loads at module load.
483
+ */
484
+ function refusedByUsageHold(deps, res) {
485
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
486
+ let hold;
487
+ try {
488
+ hold = usageHold();
489
+ } catch (e) {
490
+ sendJson(res, 503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
491
+ return true;
492
+ }
493
+ if (!hold) return false;
494
+ sendJson(res, 429, usageHeldBody(hold, USAGE_HOLD_HINT));
495
+ return true;
496
+ }
497
+
454
498
  /** 503 error text for a failed startExternalNewSession result. */
455
499
  function launchFailureError(result) {
456
500
  return result?.reason === 'timeout'
@@ -464,7 +508,7 @@ function launchFailureError(result) {
464
508
  * (cwd, externalRef) share one launch. The macro-wide findRunningEpic shortcut
465
509
  * is skipped: a new ref is a new run even while another run is busy.
466
510
  */
467
- async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, externalRef }) {
511
+ async function runWithExternalRef({ deps, req, res, caller, cwd, macro, prompt, effort, externalRef }) {
468
512
  const isTabBusy = deps.isTabBusy || (() => false);
469
513
  const existingAnswer = (epicId) => sendJson(res, 200, {
470
514
  ok: true, epicId, existing: true, alreadyRunning: !!isTabBusy(epicId), externalRef,
@@ -500,6 +544,10 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
500
544
  recentRuns.delete(key);
501
545
  }
502
546
 
547
+ if (refusedByUsageHold(deps, res)) return;
548
+
549
+ const startedBy = await (deps.startedByFromRequest || defaultStartedByFromRequest)(
550
+ { route: '/admin/macros/run', caller, socket: req.socket }, deps);
503
551
  const payload = {
504
552
  cwd,
505
553
  agentName: macro.agentName,
@@ -508,6 +556,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
508
556
  prompt,
509
557
  macroId: macro.id,
510
558
  via: 'script',
559
+ startedBy,
511
560
  externalRef,
512
561
  ...(effort !== undefined ? { effort } : {}),
513
562
  };
@@ -548,6 +597,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
548
597
  epicId: result.epicId,
549
598
  alreadyRunning: false,
550
599
  externalRef,
600
+ ...(caller ? { scriptCaller: caller } : {}),
551
601
  });
552
602
  sendJson(res, 200, {
553
603
  ok: true, epicId: result.epicId, alreadyRunning: false, externalRef,
@@ -559,6 +609,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
559
609
  /**
560
610
  * @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
561
611
  * isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>>,
612
+ * usageHold?: () => any,
562
613
  * checkProjectVideoToolRunnable?: (i: { cwd: string, agentName: string, job: object }) => Promise<{ ok: boolean, error?: string }> }} deps
563
614
  */
564
615
  function registerAdminRoute(adminHttp, deps = {}, opts = {}) {
@@ -11,6 +11,8 @@
11
11
  * admin-api.json; honors SM_SCHEDULER_HOME) = { version: 1, entries }.
12
12
  * An entry is due once appVersionAbove < running appVersion (strictly, via
13
13
  * seedDevPlugin.cjs compareSemver — an equal version is not due).
14
+ * An entry with `commits` (release.commits) is further gated by the
15
+ * deliverer on tag v<running version> containing every commit.
14
16
  * A missing or unreadable file reads as empty. Writes go through
15
17
  * util/atomicFs.cjs.
16
18
  *
@@ -22,6 +24,7 @@ const crypto = require('node:crypto');
22
24
  const path = require('node:path');
23
25
  const { writeJsonAtomicSync, readJsonOrSync } = require('../util/atomicFs.cjs');
24
26
  const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
27
+ const { isCommitHash, MAX_COMMITS } = require('./replyClaims.cjs');
25
28
 
26
29
  const STORE_VERSION = 1;
27
30
  const FILE_NAME = 'pending-replies.json';
@@ -79,12 +82,30 @@ function normalizeYSource(v) {
79
82
  try { return JSON.parse(JSON.stringify(v)); } catch { return null; }
80
83
  }
81
84
 
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
+ */
89
+ function normalizeCommits(v) {
90
+ if (!Array.isArray(v)) return [];
91
+ const out = [];
92
+ for (const c of v) {
93
+ if (out.length === MAX_COMMITS) break;
94
+ if (!isCommitHash(c)) continue;
95
+ const lc = c.toLowerCase();
96
+ if (!out.includes(lc)) out.push(lc);
97
+ }
98
+ return out;
99
+ }
100
+
82
101
  /** Pure: build a full ledger entry from caller input. Throws on a bad appVersionAbove. */
83
102
  function buildEntry(input, now = new Date()) {
84
103
  const e = input && typeof input === 'object' ? input : {};
85
104
  if (!isSemver(e.appVersionAbove)) {
86
105
  throw new Error(`pendingReplies: appVersionAbove must be x.y.z, got ${JSON.stringify(e.appVersionAbove)}`);
87
106
  }
107
+ // release.commits the reply claims: delivery waits until tag v<running> holds every one.
108
+ const commits = normalizeCommits(e.commits);
88
109
  return {
89
110
  id: crypto.randomUUID(),
90
111
  createdAt: now.toISOString(),
@@ -97,6 +118,7 @@ function buildEntry(input, now = new Date()) {
97
118
  message: str(e.message),
98
119
  referencePaths: Array.isArray(e.referencePaths) ? e.referencePaths.filter((p) => typeof p === 'string') : [],
99
120
  appVersionAbove: e.appVersionAbove,
121
+ ...(commits.length ? { commits } : {}),
100
122
  // What delivery needs once the scheduling Epic has closed: its source
101
123
  // (externalRef / proposal / replyTo) and the cap count this reply took.
102
124
  ySource: normalizeYSource(e.ySource),
@@ -0,0 +1,415 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * projectCreate.cjs — the logic behind the project_create tool: create a new
6
+ * local project folder for a paired service (and optionally a private GitHub
7
+ * repo for it), so the service can open a Build Epic in it.
8
+ *
9
+ * createServiceProject(input, deps):
10
+ * 1. validates everything before touching disk — any refusal creates nothing;
11
+ * 2. under one module-level queue: answers a repeat (same fromCwd +
12
+ * externalRef) with the recorded folder, else mkdirs <parentDir>/<name>
13
+ * (non-recursive, via createProjectFolder), runs `git init` on main with
14
+ * one empty commit (so Epic worktrees can fork), creates the bare
15
+ * operations root (so feedback_open_session accepts it as toCwd) and
16
+ * records it in the created-projects ledger;
17
+ * 3. optionally runs `gh repo create <login>/<name> --private` with the new
18
+ * folder as source and origin. A GitHub failure keeps the local project.
19
+ *
20
+ * Never throws; returns a result object. Never uses a shell.
21
+ */
22
+
23
+ const fs = require('node:fs');
24
+ const path = require('node:path');
25
+ const { execFile } = require('node:child_process');
26
+ const { createProjectFolder, validateProjectName } = require('../projectFolder.cjs');
27
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
28
+ const { OPS_ROOT_DIR } = require('../opsOwnership.cjs');
29
+
30
+ const SERVICE_PROJECT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
31
+ const GH_TIMEOUT_MS = 60_000;
32
+ const GITHUB_REMOTE_RE = /github\.com[:/]([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/;
33
+
34
+ /**
35
+ * @typedef {{ fullName: string, url: string, private: true }} RepoInfo
36
+ * @typedef {import('./createdProjects.cjs').CreatedProjectsStore} Ledger
37
+ * @typedef {(cwd: string, args: string[], opts?: { timeout?: number, env?: Record<string, string> }) => Promise<string>} ExecGit
38
+ * @typedef {(args: string[], opts?: { cwd?: string }) => Promise<{ stdout: string, stderr?: string }>} ExecGh
39
+ * @typedef {{
40
+ * ledger?: Ledger,
41
+ * execGit?: ExecGit,
42
+ * execGh?: ExecGh,
43
+ * validatePath?: (abs: string) => string,
44
+ * appendAudit?: (kind: string, fields: Record<string, unknown>) => void,
45
+ * }} Deps
46
+ * @typedef {{
47
+ * name?: unknown,
48
+ * parentDir?: unknown,
49
+ * fromCwd?: unknown,
50
+ * externalRef?: unknown,
51
+ * github?: unknown,
52
+ * }} Input
53
+ * @typedef {{ ok: false, status: number, code: string, error: string }} Refusal
54
+ * @typedef {{
55
+ * ok: true,
56
+ * status: 'created' | 'existing',
57
+ * existing?: true,
58
+ * cwd: string,
59
+ * name: string,
60
+ * externalRef: string,
61
+ * repo: RepoInfo | null,
62
+ * github?: { ok: false, error: string },
63
+ * }} Success
64
+ */
65
+
66
+ /** @type {ExecGh} */
67
+ function defaultExecGh(args, opts = {}) {
68
+ return new Promise((resolve, reject) => {
69
+ execFile('gh', args, {
70
+ cwd: opts.cwd,
71
+ timeout: GH_TIMEOUT_MS,
72
+ windowsHide: true,
73
+ encoding: 'utf8',
74
+ }, (err, stdout, stderr) => {
75
+ if (err) {
76
+ reject(Object.assign(err, { stderrText: stderr }));
77
+ return;
78
+ }
79
+ resolve({ stdout: stdout || '', stderr: stderr || '' });
80
+ });
81
+ });
82
+ }
83
+
84
+ /**
85
+ * @param {Deps} deps
86
+ * @returns {Required<Deps>}
87
+ */
88
+ function resolveDeps(deps) {
89
+ return {
90
+ ledger: deps.ledger || require('./createdProjects.cjs').getCreatedProjects(),
91
+ execGit: deps.execGit || require('../git/gitExec.cjs').execGit,
92
+ execGh: deps.execGh || defaultExecGh,
93
+ validatePath: deps.validatePath || ((abs) => require('../../config.cjs').validatePath(abs)),
94
+ appendAudit: deps.appendAudit || ((kind, fields) => {
95
+ require('../telemetry/auditLog.cjs').appendAuditEvent(kind, fields);
96
+ }),
97
+ };
98
+ }
99
+
100
+ /**
101
+ * @param {number} status
102
+ * @param {string} code
103
+ * @param {string} error
104
+ * @returns {Refusal}
105
+ */
106
+ function refuse(status, code, error) {
107
+ return { ok: false, status, code, error };
108
+ }
109
+
110
+ /**
111
+ * @param {unknown} err
112
+ * @returns {string}
113
+ */
114
+ function errText(err) {
115
+ const e = err && typeof err === 'object' ? /** @type {{ stderrText?: unknown, message?: unknown }} */ (err) : null;
116
+ const stderr = e && typeof e.stderrText === 'string' ? e.stderrText.trim() : '';
117
+ if (stderr) return stderr;
118
+ return (e && typeof e.message === 'string' && e.message) || String(err);
119
+ }
120
+
121
+ /**
122
+ * undefined/false = no repo; true = {}; an object may carry owner + private.
123
+ * @param {unknown} github
124
+ * @returns {{ ok: true, value: { owner?: string } | null } | { ok: false, error: string }}
125
+ */
126
+ function normalizeGithub(github) {
127
+ if (github === undefined || github === null || github === false) return { ok: true, value: null };
128
+ if (github === true) return { ok: true, value: {} };
129
+ if (typeof github !== 'object' || Array.isArray(github)) {
130
+ return { ok: false, error: 'github must be true, false or { owner?, private? }.' };
131
+ }
132
+ const g = /** @type {Record<string, unknown>} */ (github);
133
+ if (g.private === false) return { ok: false, error: 'Only private GitHub repositories can be created.' };
134
+ if (g.private !== undefined && g.private !== true) {
135
+ return { ok: false, error: 'github.private must be true when given.' };
136
+ }
137
+ if (g.owner !== undefined && (typeof g.owner !== 'string' || !g.owner.trim())) {
138
+ return { ok: false, error: 'github.owner must be a non-empty string when given.' };
139
+ }
140
+ return { ok: true, value: typeof g.owner === 'string' ? { owner: g.owner.trim() } : {} };
141
+ }
142
+
143
+ /**
144
+ * @param {string} url
145
+ * @returns {RepoInfo | null}
146
+ */
147
+ function parseGithubRemote(url) {
148
+ const m = GITHUB_REMOTE_RE.exec(String(url || '').trim());
149
+ if (!m) return null;
150
+ const fullName = `${m[1]}/${m[2]}`;
151
+ return { fullName, url: `https://github.com/${fullName}`, private: true };
152
+ }
153
+
154
+ /**
155
+ * @param {ExecGit} execGit
156
+ * @param {string} cwd
157
+ * @returns {Promise<string | null>}
158
+ */
159
+ async function readOrigin(execGit, cwd) {
160
+ try {
161
+ const out = (await execGit(cwd, ['remote', 'get-url', 'origin'])).trim();
162
+ return out || null;
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Create the private repo, wire it as origin, record it.
170
+ * @param {Required<Deps>} d
171
+ * @param {string} cwd
172
+ * @param {string} login
173
+ * @param {string} name
174
+ * @returns {Promise<{ ok: true, repo: RepoInfo } | { ok: false, error: string }>}
175
+ */
176
+ async function runGithubStep(d, cwd, login, name) {
177
+ try {
178
+ await d.execGh(
179
+ ['repo', 'create', `${login}/${name}`, '--private', `--source=${cwd}`, '--remote=origin', '--push'],
180
+ { cwd },
181
+ );
182
+ } catch (err) {
183
+ return { ok: false, error: `gh repo create failed: ${errText(err)}` };
184
+ }
185
+ const origin = await readOrigin(d.execGit, cwd);
186
+ const repo = origin ? parseGithubRemote(origin) : null;
187
+ if (!repo) return { ok: false, error: `origin is not a GitHub remote after gh repo create: ${origin || '(unset)'}` };
188
+ try {
189
+ await d.ledger.setRepo(cwd, repo.url);
190
+ } catch (err) {
191
+ return { ok: false, error: `could not record the repo: ${errText(err)}` };
192
+ }
193
+ return { ok: true, repo };
194
+ }
195
+
196
+ /** @param {unknown} err */
197
+ function isIdentityError(err) {
198
+ const t = errText(err);
199
+ return /tell me who you are|user\.email|user\.name|empty ident|unable to auto-detect email/i.test(t);
200
+ }
201
+
202
+ /** @type {Promise<unknown>} */
203
+ let queue = Promise.resolve();
204
+
205
+ /**
206
+ * @template T
207
+ * @param {() => Promise<T>} fn
208
+ * @returns {Promise<T>}
209
+ */
210
+ function serialize(fn) {
211
+ const run = queue.then(fn);
212
+ queue = run.catch(() => {});
213
+ return run;
214
+ }
215
+
216
+ /**
217
+ * @param {Input} input
218
+ * @param {Deps} [deps]
219
+ * @returns {Promise<Success | Refusal>}
220
+ */
221
+ async function createServiceProject(input, deps = {}) {
222
+ const d = resolveDeps(deps || {});
223
+ const { name, parentDir, fromCwd, externalRef, github } = input && typeof input === 'object' ? input : /** @type {Input} */ ({});
224
+
225
+ const ref = normalizeExternalRef(externalRef);
226
+ if (!ref.ok) return refuse(400, 'invalid-ref', ref.error);
227
+ if (!ref.value) return refuse(400, 'invalid-ref', 'externalRef is required.');
228
+ const refValue = ref.value;
229
+
230
+ if (typeof fromCwd !== 'string' || !path.isAbsolute(fromCwd) || fromCwd.includes('\0')) {
231
+ return refuse(400, 'invalid-ref', 'fromCwd must be an absolute path.');
232
+ }
233
+ const from = path.resolve(fromCwd);
234
+
235
+ if (typeof parentDir !== 'string' || !path.isAbsolute(parentDir) || parentDir.includes('\0')) {
236
+ return refuse(400, 'invalid-parent', 'parentDir must be an absolute path.');
237
+ }
238
+ try {
239
+ d.validatePath(parentDir);
240
+ } catch (err) {
241
+ return refuse(400, 'invalid-parent', errText(err));
242
+ }
243
+ try {
244
+ if (!fs.statSync(parentDir).isDirectory()) {
245
+ return refuse(400, 'invalid-parent', `${parentDir} is not a folder.`);
246
+ }
247
+ } catch {
248
+ return refuse(400, 'invalid-parent', `Parent folder ${parentDir} does not exist.`);
249
+ }
250
+ const parent = path.resolve(parentDir);
251
+
252
+ const v = validateProjectName(name);
253
+ if (!v.ok) return refuse(400, 'invalid-name', v.error);
254
+ if (v.name !== name || !SERVICE_PROJECT_NAME_RE.test(v.name)) {
255
+ return refuse(400, 'invalid-name', 'Project name must be 1 to 100 letters, digits or . _ - and start with a letter or digit.');
256
+ }
257
+ if (/\.git$/i.test(v.name)) return refuse(400, 'invalid-name', 'Project name cannot end in ".git".');
258
+ const projectName = v.name;
259
+
260
+ const g = normalizeGithub(github);
261
+ if (!g.ok) return refuse(400, 'invalid-github', g.error);
262
+ /** @type {string | null} */
263
+ let login = null;
264
+ if (g.value) {
265
+ try {
266
+ const { stdout } = await d.execGh(['api', 'user', '--jq', '.login']);
267
+ login = String(stdout || '').trim();
268
+ } catch (err) {
269
+ return refuse(400, 'gh-unavailable', `gh is not available or not signed in: ${errText(err)}`);
270
+ }
271
+ if (!login) return refuse(400, 'gh-unavailable', 'gh api user returned no login.');
272
+ if (g.value.owner && g.value.owner.toLowerCase() !== login.toLowerCase()) {
273
+ return refuse(403, 'gh-owner', `github.owner ${g.value.owner} is not the signed-in gh account.`);
274
+ }
275
+ }
276
+
277
+ return serialize(async () => {
278
+ const recorded = d.ledger.findByRef(from, refValue);
279
+ if (recorded) return answerExisting(d, recorded.cwd, refValue, login);
280
+
281
+ const made = await createProjectFolder({ parentDir: parent, name: projectName });
282
+ if (!made.ok) {
283
+ if (made.code === 'exists') return refuse(409, 'exists', made.error);
284
+ if (made.code === 'invalid-name') return refuse(400, 'invalid-name', made.error);
285
+ if (made.code === 'invalid-parent') return refuse(400, 'invalid-parent', made.error);
286
+ return refuse(500, 'io', made.error);
287
+ }
288
+ const cwd = made.path;
289
+
290
+ /** @param {string} msg */
291
+ const rollback = async (msg) => {
292
+ try { await fs.promises.rm(cwd, { recursive: true, force: true }); } catch { /* best effort */ }
293
+ return refuse(500, 'io', msg);
294
+ };
295
+
296
+ try {
297
+ await d.execGit(cwd, ['init', '--initial-branch=main']);
298
+ } catch (err) {
299
+ return rollback(`git init failed: ${errText(err)}`);
300
+ }
301
+ try {
302
+ await d.execGit(cwd, ['commit', '--allow-empty', '-m', 'Initial commit']);
303
+ } catch (err) {
304
+ const hint = isIdentityError(err)
305
+ ? ' Set git user.name and user.email (git config --global user.name / user.email) and retry.'
306
+ : '';
307
+ return rollback(`git commit failed: ${errText(err)}.${hint}`);
308
+ }
309
+ try {
310
+ await fs.promises.mkdir(path.join(cwd, OPS_ROOT_DIR));
311
+ } catch (err) {
312
+ return rollback(`could not create ${OPS_ROOT_DIR}/: ${errText(err)}`);
313
+ }
314
+ try {
315
+ await d.ledger.record({ cwd, fromCwd: from, externalRef: refValue, repo: null });
316
+ } catch (err) {
317
+ return rollback(`could not record the project: ${errText(err)}`);
318
+ }
319
+ try {
320
+ d.appendAudit('project_created', { cwd, fromCwd: from, externalRef: refValue, repo: null });
321
+ } catch { /* best effort */ }
322
+
323
+ /** @type {Success} */
324
+ const answer = { ok: true, status: 'created', cwd, name: projectName, externalRef: refValue, repo: null };
325
+ if (login) {
326
+ const gh = await runGithubStep(d, cwd, login, projectName);
327
+ if (gh.ok) answer.repo = gh.repo;
328
+ else answer.github = { ok: false, error: gh.error };
329
+ }
330
+ return answer;
331
+ });
332
+ }
333
+
334
+ /**
335
+ * @param {Required<Deps>} d
336
+ * @param {string} cwd
337
+ * @param {string} externalRef
338
+ * @param {string | null} login
339
+ * @returns {Promise<Success | Refusal>}
340
+ */
341
+ async function answerExisting(d, cwd, externalRef, login) {
342
+ let present = false;
343
+ try { present = fs.statSync(cwd).isDirectory(); } catch { present = false; }
344
+ if (!present) return refuse(409, 'gone', `The project created for ${externalRef} no longer exists at ${cwd}.`);
345
+ const name = path.basename(cwd);
346
+ const origin = await readOrigin(d.execGit, cwd);
347
+ /** @type {Success} */
348
+ const answer = {
349
+ ok: true,
350
+ status: 'existing',
351
+ existing: true,
352
+ cwd,
353
+ name,
354
+ externalRef,
355
+ repo: origin ? parseGithubRemote(origin) : null,
356
+ };
357
+ if (login && !origin) {
358
+ const gh = await runGithubStep(d, cwd, login, name);
359
+ if (gh.ok) answer.repo = gh.repo;
360
+ else answer.github = { ok: false, error: gh.error };
361
+ }
362
+ return answer;
363
+ }
364
+
365
+ /**
366
+ * Tell every renderer window a project was freshly created, so the app can
367
+ * open it as a dormant tab. Electron is required lazily so unit tests never
368
+ * need it. Never throws. Mirrors crossProjectFeedback.cjs defaultNotifyRenderer.
369
+ * @param {{ cwd: string }} payload
370
+ */
371
+ function defaultNotifyRenderer(payload) {
372
+ try {
373
+ const { BrowserWindow } = require('electron');
374
+ const { sendIfAlive } = require('../sendToRenderer.cjs');
375
+ for (const win of BrowserWindow.getAllWindows()) {
376
+ try {
377
+ sendIfAlive(win, 'projects:created', payload);
378
+ } catch { /* window going away */ }
379
+ }
380
+ } catch { /* not running under Electron */ }
381
+ }
382
+
383
+ /**
384
+ * @typedef {{
385
+ * registerRoute: (method: string, path: string, handler: (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>) => void,
386
+ * }} AdminHttp
387
+ */
388
+
389
+ /**
390
+ * Registers POST /admin/projects/create on the injected loopback admin
391
+ * transport (auth is the transport's job). Only a fresh create notifies.
392
+ * @param {AdminHttp} adminHttp
393
+ * @param {{ notify?: (payload: { cwd: string }) => void, deps?: Deps }} [opts]
394
+ */
395
+ function registerAdminRoute(adminHttp, { notify = defaultNotifyRenderer, deps } = {}) {
396
+ const { readBody, sendJson } = require('./localAdminHttp.cjs');
397
+ adminHttp.registerRoute('POST', '/admin/projects/create', async (req, res) => {
398
+ const raw = await readBody(req);
399
+ /** @type {Input} */
400
+ let parsed;
401
+ try {
402
+ parsed = raw ? JSON.parse(raw) : {};
403
+ } catch {
404
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
405
+ return;
406
+ }
407
+ const result = await createServiceProject(parsed, deps);
408
+ if (result.ok && result.status === 'created') {
409
+ try { notify({ cwd: result.cwd }); } catch { /* a notify failure never fails the create */ }
410
+ }
411
+ sendJson(res, result.ok ? 200 : result.status, result);
412
+ });
413
+ }
414
+
415
+ module.exports = { createServiceProject, SERVICE_PROJECT_NAME_RE, parseGithubRemote, registerAdminRoute, defaultNotifyRenderer };