claude-code-session-manager 0.129.0 → 0.130.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/assets/AgentLibrary-ctvNes4y.js +2 -0
  3. package/dist/assets/AppSettings-C03qTDSi.js +2 -0
  4. package/dist/assets/Button-fOCJry21.js +1 -0
  5. package/dist/assets/Extensions-BWiDwigT.js +13 -0
  6. package/dist/assets/{History-B2x-LMlT.js → History-BIQFPXM8.js} +2 -2
  7. package/dist/assets/Library-BGmD-xZN.js +32 -0
  8. package/dist/assets/ListDetail-BeO3lY8t.js +1 -0
  9. package/dist/assets/{Memory-CnalwnFf.js → Memory-BeXuYIcE.js} +8 -8
  10. package/dist/assets/{Panel-BzIklgKf.js → Panel-OUbLHNsS.js} +1 -1
  11. package/dist/assets/ProvenanceBadge-kr7arZqu.js +1 -0
  12. package/dist/assets/Scheduler-DycegnjH.js +16 -0
  13. package/dist/assets/Settings-BSq6VASG.js +2 -0
  14. package/dist/assets/{SkillReferenceGraph-DOhiCxuL.js → SkillReferenceGraph-CvPdxg56.js} +1 -1
  15. package/dist/assets/SourceChip-C2YMnlV8.js +1 -0
  16. package/dist/assets/SystemPrompt-fpXEK_Rm.js +1 -0
  17. package/dist/assets/{TiptapBody-Du6jRBoW.js → TiptapBody-DusJg0je.js} +1 -1
  18. package/dist/assets/{Toggle-Qdi2Z7VD.js → Toggle-BnJF4V6k.js} +1 -1
  19. package/dist/assets/ViewTabs-BYrRSHb6.js +1 -0
  20. package/dist/assets/VoiceButton-Bk66E-fP.js +1 -0
  21. package/dist/assets/{historyTotals-8ecP_6wF.js → historyTotals-DnuVADtI.js} +1 -1
  22. package/dist/assets/{index-DtdWBGrI.css → index-Bp8XE9A6.css} +1 -1
  23. package/dist/assets/index-DfWJO7nP.js +3086 -0
  24. package/dist/index.html +2 -2
  25. package/dist-web/app.css +1 -1
  26. package/dist-web/app.js +390 -406
  27. package/package.json +1 -1
  28. package/plugins/CLAUDE.md +2 -2
  29. package/plugins/session-manager-dev/.claude-plugin/plugin.json +2 -2
  30. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +2 -2
  31. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -3
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +62 -0
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +169 -0
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +183 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +39 -0
  36. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +79 -0
  37. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +400 -0
  38. package/scripts/scheduler-mcp-server.cjs +25 -6
  39. package/src/main/agentLibrary.cjs +36 -10
  40. package/src/main/build-info.json +4 -4
  41. package/src/main/config.cjs +15 -0
  42. package/src/main/health.cjs +49 -22
  43. package/src/main/index.cjs +19 -3
  44. package/src/main/ipcSchemas.cjs +36 -3
  45. package/src/main/lib/claude/modelCatalog.cjs +15 -31
  46. package/src/main/lib/claudeConfig.cjs +156 -0
  47. package/src/main/lib/effectiveSettings.cjs +120 -0
  48. package/src/main/lib/epic/delegationReadiness.cjs +3 -3
  49. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +84 -11
  50. package/src/main/lib/git/gitWorktree.cjs +400 -9
  51. package/src/main/lib/git/runtimeStateUntrack.cjs +124 -0
  52. package/src/main/lib/mcpToolCatalog.cjs +8 -2
  53. package/src/main/lib/memoryDirResolve.cjs +2 -8
  54. package/src/main/lib/opsOwnership.cjs +63 -2
  55. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -0
  56. package/src/main/lib/persona-macro/macroLibrary.cjs +34 -6
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +22 -0
  58. package/src/main/lib/updateCheck.cjs +6 -1
  59. package/src/main/pluginInstall.cjs +100 -1
  60. package/src/main/scheduler.cjs +12 -2
  61. package/src/main/seedDevPlugin.cjs +2 -1
  62. package/src/main/templates/PRD_AUTHORING.md +3 -3
  63. package/src/main/updaterIpc.cjs +5 -1
  64. package/src/main/usage.cjs +5 -20
  65. package/src/main/voiceHotkey.cjs +16 -0
  66. package/src/main/voiceSettings.cjs +24 -0
  67. package/src/main/voiceWizard.cjs +27 -36
  68. package/src/preload/api.d.ts +53 -2
  69. package/src/preload/apiSurface.json +63 -7
  70. package/src/preload/index.cjs +12 -1
  71. package/src/seed/agents/demo-video-builder.md +2 -2
  72. package/src/seed/agents/validator.md +2 -2
  73. package/dist/assets/AgentLibrary-Cp250YHF.js +0 -2
  74. package/dist/assets/Button-DU5UF-6L.js +0 -1
  75. package/dist/assets/DataModel-CPf6f17e.js +0 -1
  76. package/dist/assets/Hooks-BWr33C4Q.js +0 -3
  77. package/dist/assets/Library-DBNLTAa8.js +0 -46
  78. package/dist/assets/ListDetail-BGBw6egp.js +0 -1
  79. package/dist/assets/McpServers-DywZ50Ec.js +0 -2
  80. package/dist/assets/Permissions-mgRifwQc.js +0 -3
  81. package/dist/assets/Plugins-CV42zfid.js +0 -2
  82. package/dist/assets/ProvenanceBadge-DYmX4xgB.js +0 -1
  83. package/dist/assets/SaveBar-DxrAfnlC.js +0 -1
  84. package/dist/assets/Scheduler-iyUl1NDl.js +0 -16
  85. package/dist/assets/ScopeSwitcher-CC8BDPgf.js +0 -1
  86. package/dist/assets/Settings-CWBnQghD.js +0 -4
  87. package/dist/assets/Skills-3Er-9YA9.js +0 -2
  88. package/dist/assets/SystemPrompt-BLxdvZ9K.js +0 -1
  89. package/dist/assets/TagLibrary-BZ6QHYMQ.js +0 -1
  90. package/dist/assets/ViewTabs-BKfFsziD.js +0 -1
  91. package/dist/assets/index-GI6F_j41.js +0 -3083
  92. package/dist/assets/listSkills-C1aWKf0T.js +0 -1
  93. package/dist/assets/settingsSchema-lHTHAabD.js +0 -1
  94. package/dist/assets/skillFrontmatter-8X1Uc282.js +0 -10
  95. package/dist/assets/useAgentsDirWatch-CcsoD1bp.js +0 -1
@@ -25,8 +25,9 @@ const { REVERIFY_INTERVAL_MS } = require('./scheduler/reviewLadder.cjs');
25
25
  const { findStarvedProjects, findUnresolvableDepRoots, DEFAULT_PROJECT_CWD, DEP_HISTORY_FAIL_OPEN } = require('./lib/scheduler/schedulerBatch.cjs');
26
26
  const { auditLogPath, readTail } = require('./lib/telemetry/auditLog.cjs');
27
27
  const { checkMainDependencyHealth } = require('./lib/git/depHealth.cjs');
28
+ const { findTrackedRuntimeState } = require('./lib/git/runtimeStateUntrack.cjs');
28
29
  const { resolveBuildIdentity } = require('./lib/buildIdentity.cjs');
29
- const { computeReport, isRetentionEnabled, liveKeysFromJobs } = require('./lib/scheduler/runLogRetention.cjs');
30
+ const { computeReport, isRetentionEnabled, liveKeysFromJobs, resolveRetentionConfig } = require('./lib/scheduler/runLogRetention.cjs');
30
31
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
31
32
  const { scanEpicTranscripts } = require('./lib/epic/epicTranscriptDiagnostic.cjs');
32
33
 
@@ -1271,27 +1272,7 @@ async function check(opts = {}) {
1271
1272
  // model. schedulerRunLogRetention lives in scheduler-machine.json's
1272
1273
  // `config`, same home as every other scheduler machine setting.
1273
1274
  try {
1274
- const retentionCfg = queueState?.config?.schedulerRunLogRetention;
1275
- const runsDir = schedulerPaths.runsDir();
1276
- const liveKeys = liveKeysFromJobs(queueState?.jobs || [], { runsDir });
1277
- const report = computeReport(
1278
- runsDir,
1279
- retentionCfg?.policy || {},
1280
- { liveKeys }
1281
- );
1282
- status.components.run_log_retention = {
1283
- ok: true,
1284
- path: runsDir,
1285
- totalBytes: report.usage.totalBytes,
1286
- dirCount: report.usage.dirCount,
1287
- runCount: report.usage.runCount,
1288
- oldestRunAt: report.usage.oldestRunAt,
1289
- policyConfigured: !!retentionCfg?.policy,
1290
- retentionEnabled: isRetentionEnabled(queueState?.config || {}),
1291
- wouldRemoveCount: report.eligibleSummary.count,
1292
- wouldRemoveBytes: report.eligibleSummary.bytes,
1293
- wouldRemoveDirs: report.removableDirs.length,
1294
- };
1275
+ status.components.run_log_retention = evaluateRunLogRetention(queueState);
1295
1276
  } catch (e) {
1296
1277
  status.components.run_log_retention = { ok: true, error: e.message };
1297
1278
  }
@@ -1384,6 +1365,26 @@ async function check(opts = {}) {
1384
1365
  }
1385
1366
  }
1386
1367
 
1368
+ // 6.76. Tracked runtime state: projects that committed Session Manager
1369
+ // runtime namespaces. Warning only (never flips ok) — untrack via
1370
+ // runtimeStateUntrack.untrackRuntimeState from the project's main checkout.
1371
+ try {
1372
+ const roots = [...new Set(allProjectCwds())].slice(0, 100).filter((cwd) => fs.existsSync(cwd));
1373
+ const hits = [];
1374
+ for (const cwd of roots) {
1375
+ const n = (await findTrackedRuntimeState(cwd)).length;
1376
+ if (n > 0) hits.push({ cwd, count: n });
1377
+ }
1378
+ status.components.tracked_runtime_state = hits.length === 0
1379
+ ? { ok: true }
1380
+ : { ok: true, warn: true, projects: hits };
1381
+ for (const h of hits) {
1382
+ status.issues.push(`warn: ${h.cwd} tracks ${h.count} Session Manager runtime-state file(s) in git — untrack from its main checkout`);
1383
+ }
1384
+ } catch (e) {
1385
+ status.components.tracked_runtime_state = { ok: true, error: e.message };
1386
+ }
1387
+
1387
1388
  // 6.8. Credential health (informational-but-loud): is the Claude OAuth token
1388
1389
  // usable? An expired/absent token silently voids every headless `claude -p`
1389
1390
  // job — the queue "runs" but nothing authenticates. refreshIfNeeded() reads
@@ -1420,8 +1421,34 @@ if (require.main === module) {
1420
1421
  })();
1421
1422
  }
1422
1423
 
1424
+ /**
1425
+ * Run-log retention component. Resolves the policy through runLogRetention.cjs's
1426
+ * resolveRetentionConfig (ops-retention.json first, as the runtime does).
1427
+ */
1428
+ function evaluateRunLogRetention(queueState) {
1429
+ const retentionCfg = resolveRetentionConfig(queueState?.config || {});
1430
+ const runsDir = schedulerPaths.runsDir();
1431
+ const liveKeys = liveKeysFromJobs(queueState?.jobs || [], { runsDir });
1432
+ const report = computeReport(runsDir, retentionCfg?.policy || {}, { liveKeys });
1433
+ return {
1434
+ ok: true,
1435
+ path: runsDir,
1436
+ totalBytes: report.usage.totalBytes,
1437
+ dirCount: report.usage.dirCount,
1438
+ runCount: report.usage.runCount,
1439
+ oldestRunAt: report.usage.oldestRunAt,
1440
+ policyConfigured: !!retentionCfg?.policy,
1441
+ retentionEnabled: isRetentionEnabled(queueState?.config || {}),
1442
+ policy: retentionCfg?.policy || null,
1443
+ wouldRemoveCount: report.eligibleSummary.count,
1444
+ wouldRemoveBytes: report.eligibleSummary.bytes,
1445
+ wouldRemoveDirs: report.removableDirs.length,
1446
+ };
1447
+ }
1448
+
1423
1449
  module.exports = {
1424
1450
  check,
1451
+ evaluateRunLogRetention,
1425
1452
  evaluateTickLiveness,
1426
1453
  readFreshHeartbeat,
1427
1454
  lastTickFromHeartbeat,
@@ -59,7 +59,6 @@ try {
59
59
  }
60
60
  crashDiagnostics.startCrashReporter();
61
61
  const voiceHotkey = require('./voiceHotkey.cjs');
62
- const voiceWizard = require('./voiceWizard.cjs');
63
62
  const scheduler = require('./scheduler.cjs');
64
63
  const { createAdminHttp } = require('./lib/feedback-remote/localAdminHttp.cjs');
65
64
  const prdCreate = require('./lib/prd/prdCreate.cjs');
@@ -571,7 +570,6 @@ function createWindow() {
571
570
 
572
571
  ipcMain.handle('app:version', () => app.getVersion());
573
572
 
574
- ipcMain.handle('app:update-status', () => require('./lib/updateCheck.cjs').getUpdateStatus());
575
573
 
576
574
  ipcMain.handle('app:home-dir', () => os.homedir());
577
575
 
@@ -617,6 +615,20 @@ require('./lib/persona-macro/macroJobIpc.cjs').registerMacroJobIpc(ipcMain, {
617
615
  loadJobs: async () => (await require('./lib/scheduler/queueStore.cjs').readMerged()).jobs || [],
618
616
  archivePrd: (slug, cwd) => queueOps.archiveMany([slug], cwd),
619
617
  });
618
+ // claudeConfig (lib/claudeConfig.cjs): key-scoped read/patch of Claude's JSON config files.
619
+ // A successful patch broadcasts `config:changed` so renderer state refreshes.
620
+ ipcMain.handle('claudeConfig:read', validated(schemas.claudeConfigRead, async (p) => {
621
+ if (p.cwd) configMgr.validatePath(p.cwd);
622
+ return require('./lib/claudeConfig.cjs').read(p);
623
+ }));
624
+ ipcMain.handle('claudeConfig:patch', validated(schemas.claudeConfigPatch, async (p) => {
625
+ if (p.cwd) configMgr.validatePath(p.cwd);
626
+ const result = await require('./lib/claudeConfig.cjs').patch(p);
627
+ let mtimeMs = 0;
628
+ try { mtimeMs = (await require('node:fs/promises').stat(result.path)).mtimeMs; } catch { /* ignore */ }
629
+ sendIfAlive(mainWindow, 'config:changed', { path: result.path, mtimeMs, kind: 'change' });
630
+ return result;
631
+ }));
620
632
  ipcMain.handle('macros:save', validated(schemas.macrosSave, async (payload) => {
621
633
  const macro = await macroLibrary.saveMacro(payload);
622
634
  broadcastMacrosChanged();
@@ -627,6 +639,11 @@ ipcMain.handle('macros:delete', validated(schemas.macrosDelete, async (payload)
627
639
  broadcastMacrosChanged();
628
640
  return result;
629
641
  }));
642
+ ipcMain.handle('macros:remove-from-project', validated(schemas.macrosRemoveFromProject, async (payload) => {
643
+ const result = await macroLibrary.removeMacroFromProject(payload);
644
+ if (result.ok) broadcastMacrosChanged();
645
+ return result;
646
+ }));
630
647
  ipcMain.handle('macros:set-project', validated(schemas.macrosSetProject, async (payload) => {
631
648
  const result = await macroLibrary.setMacroProject(payload);
632
649
  if (result.ok) broadcastMacrosChanged();
@@ -1043,7 +1060,6 @@ layoutStore.registerLayoutHandlers();
1043
1060
  billing.registerBillingHandlers();
1044
1061
  logs.registerLogHandlers();
1045
1062
  voiceHotkey.registerHotkeyHandlers();
1046
- voiceWizard.registerWizardHandlers();
1047
1063
  scheduler.registerScheduleHandlers();
1048
1064
  watchers.registerWatcherHandlers();
1049
1065
  queueOps.registerQueueOpsHandlers({ retireCompletedSlugs: scheduler.retireCompletedSlugs });
@@ -13,7 +13,8 @@ const { PromptSessionSchema, EpicTagSchema, EpicSourceSchema, EpicIntakeSectionS
13
13
  const { PrdWorkTypeSchema } = require('./lib/prd/workTypeLibrary.cjs');
14
14
  const { PERSONA_NAME_RE } = require('./agentLibrary.cjs');
15
15
  const { AgentPersonaSaveSchema } = require('./lib/persona-macro/agentPersonaSchema.cjs');
16
- const { MacroSaveSchema, MacroDeleteSchema, MacroSetProjectSchema, MacroInputSchema } = require('./lib/persona-macro/macroLibrary.cjs');
16
+ const { MacroSaveSchema, MacroDeleteSchema, MacroSetProjectSchema, MacroRemoveFromProjectSchema, MacroInputSchema } = require('./lib/persona-macro/macroLibrary.cjs');
17
+ const { MAX_SLOTS } = require('./lib/scheduler/sessionSlots.cjs');
17
18
 
18
19
  // ──────────────────────────────────────────── PTY
19
20
  const ptySpawn = z.object({
@@ -649,10 +650,10 @@ const setConfigSchema = z.object({
649
650
 
650
651
  // Machine-wide claude -p slot pool cap (sessionSlots.cjs) — deliberately its own
651
652
  // schema/channel rather than folded into setConfigSchema: it governs the shared
652
- // process pool, not any one project's scheduler config, and its range (0-10, 0
653
+ // process pool, not any one project's scheduler config, and its range (0-MAX_SLOTS, 0
653
654
  // pauses new launches) is the single concurrency control.
654
655
  const setSessionSlotsSchema = z.object({
655
- cap: z.number().int().min(0).max(10),
656
+ cap: z.number().int().min(0).max(MAX_SLOTS),
656
657
  }).strict();
657
658
 
658
659
  // ──────────────────────────────────────────── Agent Library
@@ -662,9 +663,25 @@ const setSessionSlotsSchema = z.object({
662
663
  // Full field-level rules live in lib/persona-macro/agentPersonaSchema.cjs, mirroring
663
664
  // AgentPersonaSaveInput (src/preload/api.d.ts) field-for-field.
664
665
  const agentsSavePersona = AgentPersonaSaveSchema;
666
+ // claudeConfig:read / claudeConfig:patch — mirrors ClaudeConfigReadInput /
667
+ // ClaudeConfigPatchInput (src/preload/api.d.ts). fileId comes from the registry in
668
+ // lib/claudeConfig.cjs; `value` absent => delete the key.
669
+ const CLAUDE_CONFIG_FILE_IDS = /** @type {[string, ...string[]]} */ (Object.keys(require('./lib/claudeConfig.cjs').REGISTRY));
670
+ const claudeConfigBase = {
671
+ fileId: z.enum(CLAUDE_CONFIG_FILE_IDS),
672
+ scope: z.enum(['user', 'project', 'local']),
673
+ cwd: z.string().min(1).max(4096).nullish(),
674
+ };
675
+ const claudeConfigRead = z.object(claudeConfigBase).strict();
676
+ const claudeConfigPatch = z.object({
677
+ ...claudeConfigBase,
678
+ keyPath: z.array(z.string().min(1).max(256)).min(1).max(8),
679
+ value: z.unknown().optional(),
680
+ }).strict();
665
681
  const macrosSave = MacroSaveSchema;
666
682
  const macrosDelete = MacroDeleteSchema;
667
683
  const macrosSetProject = MacroSetProjectSchema;
684
+ const macrosRemoveFromProject = MacroRemoveFromProjectSchema;
668
685
  // Background macro job (macroJobIpc.cjs): press a built-in macro as a scheduler PRD inside an existing Epic.
669
686
  const macrosDispatchJob = z.object({
670
687
  cwd: z.string().min(1).max(4096),
@@ -984,6 +1001,7 @@ const AUDIT_LOG_KIND = z.enum([
984
1001
  'epic_delete',
985
1002
  'epic_resume',
986
1003
  'epic_duplicate',
1004
+ 'epic_draft_update',
987
1005
  ]);
988
1006
  const auditLogAppend = z.object({
989
1007
  kind: AUDIT_LOG_KIND,
@@ -1256,6 +1274,15 @@ const pluginsInstall = z.object({
1256
1274
  const pluginsAbort = z.object({
1257
1275
  slug: z.string().regex(PLUGIN_SLUG_RE).min(1).max(128),
1258
1276
  }).passthrough();
1277
+ const pluginsList = z.object({}).strict();
1278
+ const pluginsSetEnabled = z.object({
1279
+ key: z.string().regex(/^[a-z0-9][a-z0-9._\-]*@[a-z0-9][a-z0-9._\-]*$/i).max(256),
1280
+ enabled: z.boolean(),
1281
+ }).strict();
1282
+ const pluginsUninstall = z.object({
1283
+ slug: z.string().regex(PLUGIN_SLUG_RE).min(1).max(128),
1284
+ marketplaceName: z.string().regex(PLUGIN_SLUG_RE).min(1).max(128),
1285
+ }).strict();
1259
1286
 
1260
1287
  // ──────────────────────────────────────────── Product telemetry (bilko.run)
1261
1288
  // Mirrors telemetrySettings.cjs's own isValid() shape — the renderer always
@@ -1434,6 +1461,9 @@ module.exports = {
1434
1461
  repoAnalyze,
1435
1462
  pluginsInstall,
1436
1463
  pluginsAbort,
1464
+ pluginsList,
1465
+ pluginsSetEnabled,
1466
+ pluginsUninstall,
1437
1467
  memoryList,
1438
1468
  memoryRead,
1439
1469
  memoryWrite,
@@ -1494,9 +1524,12 @@ module.exports = {
1494
1524
  remoteSessionPrds,
1495
1525
  exchangesList,
1496
1526
  agentsSavePersona,
1527
+ claudeConfigRead,
1528
+ claudeConfigPatch,
1497
1529
  macrosSave,
1498
1530
  macrosDelete,
1499
1531
  macrosSetProject,
1532
+ macrosRemoveFromProject,
1500
1533
  macrosDispatchJob,
1501
1534
  macrosJobStatus,
1502
1535
  agentsGetPersonaBody,
@@ -19,6 +19,7 @@
19
19
  const fs = require('node:fs');
20
20
  const os = require('node:os');
21
21
  const path = require('node:path');
22
+ const { effectiveSettings, pickByPrecedence } = require('../effectiveSettings.cjs');
22
23
 
23
24
  const CACHE_FILE = 'model-catalog.json';
24
25
  const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
@@ -114,47 +115,30 @@ function readSettingsEffortLevels(fsImpl) {
114
115
  } catch { return null; }
115
116
  }
116
117
 
118
+ function resolveRoot(cwd, d) {
119
+ if (!cwd) return null;
120
+ try { return (d.projectRootOf || require('../activeSessions.cjs').projectRootOf)(path.resolve(cwd)); } catch { return path.resolve(cwd); }
121
+ }
122
+
117
123
  function readAvailableModels(cwd, d, fsImpl) {
118
124
  const home = d.homeDir ? d.homeDir() : os.homedir();
119
- let root = null;
120
- if (cwd) {
121
- try { root = (d.projectRootOf || require('../activeSessions.cjs').projectRootOf)(path.resolve(cwd)); } catch { root = path.resolve(cwd); }
122
- }
123
- const files = [path.join(home, '.claude', 'settings.json')];
124
- if (root) files.push(path.join(root, '.claude', 'settings.json'), path.join(root, '.claude', 'settings.local.json'));
125
- let merged = null;
126
- for (const f of files) {
127
- try {
128
- const a = JSON.parse(fsImpl.readFileSync(f, 'utf8')).availableModels;
129
- if (Array.isArray(a)) merged = [...(merged || []), ...a.filter((x) => typeof x === 'string')];
130
- } catch { /* missing/unreadable scope */ }
131
- }
132
- return merged ? [...new Set(merged)] : null;
125
+ const { merged } = effectiveSettings({ home, cwd: resolveRoot(cwd, d), fs: fsImpl });
126
+ const a = merged.availableModels;
127
+ if (!Array.isArray(a)) return null;
128
+ return [...new Set(a.filter((x) => typeof x === 'string'))];
133
129
  }
134
130
 
135
131
  /**
136
- * The `model` key of the user's Claude settings: first non-empty string from
137
- * <projectRoot>/.claude/settings.local.json, <projectRoot>/.claude/settings.json,
138
- * then ~/.claude/settings.json (local over project over user). Never throws; null when none.
132
+ * The `model` key of the effective Claude settings (managed > local > project > user):
133
+ * first non-empty string. Never throws; null when none.
139
134
  */
140
135
  function readSettingsModel(cwd, deps = {}) {
141
136
  try {
142
137
  const d = deps || {};
143
- const fsImpl = d.fs || fs;
144
138
  const home = d.homeDir ? d.homeDir() : os.homedir();
145
- const files = [];
146
- if (cwd) {
147
- let root;
148
- try { root = (d.projectRootOf || require('../activeSessions.cjs').projectRootOf)(path.resolve(cwd)); } catch { root = path.resolve(cwd); }
149
- if (root) files.push(path.join(root, '.claude', 'settings.local.json'), path.join(root, '.claude', 'settings.json'));
150
- }
151
- files.push(path.join(home, '.claude', 'settings.json'));
152
- for (const f of files) {
153
- try {
154
- const m = JSON.parse(fsImpl.readFileSync(f, 'utf8')).model;
155
- if (typeof m === 'string' && m.trim()) return m.trim();
156
- } catch { /* missing/unreadable scope */ }
157
- }
139
+ const layers = effectiveSettings({ home, cwd: resolveRoot(cwd, d), fs: d.fs || fs }).layers;
140
+ const m = pickByPrecedence(layers, 'model', (v) => typeof v === 'string' && v.trim() !== '');
141
+ if (typeof m === 'string') return m.trim();
158
142
  } catch { /* never throws */ }
159
143
  return null;
160
144
  }
@@ -0,0 +1,156 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * claudeConfig.cjs — registry of Claude Code's JSON config files plus a
6
+ * key-scoped patch(). patch() re-reads the file fresh under a per-file lock,
7
+ * sets (or deletes) ONE key path and writes atomically, so a stale renderer
8
+ * draft can never clobber keys the CLI (or another writer) changed meanwhile.
9
+ * Writes go through config.cjs writeJson => validatePath + validateWrite +
10
+ * lib/util/atomicFs.cjs. No IPC here.
11
+ */
12
+
13
+ const os = require('node:os');
14
+ const path = require('node:path');
15
+ const fsp = require('node:fs/promises');
16
+ const config = require('../config.cjs');
17
+
18
+ /** @typedef {'user'|'project'|'local'} Scope */
19
+ /** @typedef {{ scopes: Scope[], resolve: (scope: string, home: string, cwd?: string|null) => string|null }} FileSpec */
20
+
21
+ /** @type {Record<string, FileSpec>} */
22
+ const REGISTRY = {
23
+ settings: {
24
+ scopes: ['user', 'project', 'local'],
25
+ resolve: (scope, home, cwd) => {
26
+ if (scope === 'user') return path.join(home, '.claude', 'settings.json');
27
+ if (!cwd) return null;
28
+ if (scope === 'project') return path.join(cwd, '.claude', 'settings.json');
29
+ if (scope === 'local') return path.join(cwd, '.claude', 'settings.local.json');
30
+ return null;
31
+ },
32
+ },
33
+ claudeJson: {
34
+ scopes: ['user'],
35
+ resolve: (scope, home) => (scope === 'user' ? path.join(home, '.claude.json') : null),
36
+ },
37
+ mcpJson: {
38
+ scopes: ['project'],
39
+ resolve: (scope, _home, cwd) => (scope === 'project' && cwd ? path.join(cwd, '.mcp.json') : null),
40
+ },
41
+ };
42
+
43
+ /**
44
+ * @param {{ fileId: string, scope: string, cwd?: string|null, home?: string }} p
45
+ * @returns {string}
46
+ */
47
+ function resolvePath({ fileId, scope, cwd, home }) {
48
+ if (!Object.prototype.hasOwnProperty.call(REGISTRY, fileId)) {
49
+ throw new Error(`claudeConfig: unknown fileId "${fileId}"`);
50
+ }
51
+ const spec = REGISTRY[fileId];
52
+ if (!/** @type {string[]} */ (spec.scopes).includes(scope)) {
53
+ throw new Error(`claudeConfig: file "${fileId}" does not support scope "${scope}"`);
54
+ }
55
+ const abs = spec.resolve(scope, home || os.homedir(), cwd);
56
+ if (!abs) throw new Error(`claudeConfig: cannot resolve "${fileId}" at scope "${scope}" without a cwd`);
57
+ return abs;
58
+ }
59
+
60
+ /**
61
+ * Read + parse. Missing file => {}. Invalid JSON / non-object => throws naming the path.
62
+ * @param {string} abs
63
+ * @returns {Promise<Record<string, any>>}
64
+ */
65
+ async function readParsed(abs) {
66
+ let text;
67
+ try {
68
+ text = await fsp.readFile(abs, 'utf8');
69
+ } catch (e) {
70
+ if (/** @type {any} */ (e)?.code === 'ENOENT') return {};
71
+ throw e;
72
+ }
73
+ if (text.trim() === '') return {};
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(text);
77
+ } catch (e) {
78
+ throw new Error(`claudeConfig: ${abs} is not valid JSON (${/** @type {Error} */ (e).message})`);
79
+ }
80
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
81
+ throw new Error(`claudeConfig: ${abs} does not contain a JSON object`);
82
+ }
83
+ return parsed;
84
+ }
85
+
86
+ /**
87
+ * @param {{ fileId: string, scope: string, cwd?: string|null, home?: string }} p
88
+ * @returns {Promise<{ path: string, data: Record<string, any> }>}
89
+ */
90
+ async function read(p) {
91
+ const abs = resolvePath(p);
92
+ return { path: abs, data: await readParsed(abs) };
93
+ }
94
+
95
+ /** @type {Map<string, Promise<unknown>>} */
96
+ const locks = new Map();
97
+
98
+ /**
99
+ * @template T
100
+ * @param {string} key
101
+ * @param {() => Promise<T>} fn
102
+ * @returns {Promise<T>}
103
+ */
104
+ function withLock(key, fn) {
105
+ const prev = locks.get(key) || Promise.resolve();
106
+ const run = prev.then(fn, fn);
107
+ const tail = run.catch(() => {});
108
+ locks.set(key, tail);
109
+ tail.then(() => { if (locks.get(key) === tail) locks.delete(key); });
110
+ return run;
111
+ }
112
+
113
+ /** @param {string|string[]} keyPath */
114
+ function toSegments(keyPath) {
115
+ const segs = Array.isArray(keyPath) ? keyPath : String(keyPath).split('.');
116
+ if (!segs.length || segs.some((s) => typeof s !== 'string' || s === '')) {
117
+ throw new Error('claudeConfig: keyPath must be non-empty');
118
+ }
119
+ if (segs.some((s) => s === '__proto__' || s === 'constructor' || s === 'prototype')) {
120
+ throw new Error('claudeConfig: forbidden keyPath segment');
121
+ }
122
+ return segs;
123
+ }
124
+
125
+ /**
126
+ * Set one key path (value === undefined deletes it) under the per-file lock.
127
+ * @param {{ fileId: string, scope: string, cwd?: string|null, keyPath: string|string[], value: any, home?: string }} p
128
+ * @returns {Promise<{ ok: true, path: string, data: Record<string, any> }>}
129
+ */
130
+ async function patch(p) {
131
+ const abs = resolvePath(p);
132
+ const segs = toSegments(p.keyPath);
133
+ return withLock(abs, async () => {
134
+ const data = await readParsed(abs);
135
+ let node = data;
136
+ if (p.value === undefined) {
137
+ for (let i = 0; i < segs.length - 1; i++) {
138
+ const next = node[segs[i]];
139
+ if (!next || typeof next !== 'object') { node = /** @type {any} */ (null); break; }
140
+ node = next;
141
+ }
142
+ if (node) delete node[segs[segs.length - 1]];
143
+ } else {
144
+ for (let i = 0; i < segs.length - 1; i++) {
145
+ const next = node[segs[i]];
146
+ if (!next || typeof next !== 'object' || Array.isArray(next)) node[segs[i]] = {};
147
+ node = node[segs[i]];
148
+ }
149
+ node[segs[segs.length - 1]] = p.value;
150
+ }
151
+ await config.writeJson(abs, data);
152
+ return { ok: /** @type {const} */ (true), path: abs, data };
153
+ });
154
+ }
155
+
156
+ module.exports = { REGISTRY, read, patch };
@@ -0,0 +1,120 @@
1
+ // @ts-check
2
+ /**
3
+ * effectiveSettings.cjs — the ONE main-process resolver for Claude Code settings.
4
+ *
5
+ * Precedence (high → low): managed > local > project > user. Merge rules mirror
6
+ * src/renderer/lib/mergeScopes.ts: objects deep-merge, arrays accumulate across scopes
7
+ * (low → high order, so callers can dedupe keeping first sight), scalars/mixed → highest wins.
8
+ * Missing or invalid files are skipped and reported in `errors` (never thrown).
9
+ */
10
+ 'use strict';
11
+
12
+ const fs = require('node:fs');
13
+ const os = require('node:os');
14
+ const path = require('node:path');
15
+
16
+ /** @typedef {'managed'|'user'|'project'|'local'} SettingsScope */
17
+
18
+ /** Scopes low → high precedence. */
19
+ const SCOPE_ORDER = /** @type {SettingsScope[]} */ (['user', 'project', 'local', 'managed']);
20
+
21
+ /** @param {string} [platform] */
22
+ function managedSettingsPath(platform = process.platform) {
23
+ return platform === 'darwin'
24
+ ? '/Library/Application Support/ClaudeCode/managed-settings.json'
25
+ : '/etc/claude-code/managed-settings.json';
26
+ }
27
+
28
+ /** @param {unknown} v @returns {'array'|'object'|'scalar'} */
29
+ function kindOf(v) {
30
+ if (Array.isArray(v)) return 'array';
31
+ if (v !== null && typeof v === 'object') return 'object';
32
+ return 'scalar';
33
+ }
34
+
35
+ /**
36
+ * Merge entries (LOW → HIGH precedence) into one value + per-leaf winner map.
37
+ * @param {{scope: SettingsScope, data: any}[]} entries
38
+ * @returns {{ merged: Record<string, any>, winnerByKey: Record<string, SettingsScope> }}
39
+ */
40
+ function mergeLayers(entries) {
41
+ /** @type {Record<string, SettingsScope>} */
42
+ const winnerByKey = {};
43
+ /** @param {{scope: SettingsScope, data: any}[]} scoped @param {string[]} p @returns {any} */
44
+ const walk = (scoped, p) => {
45
+ if (scoped.every((s) => kindOf(s.data) === 'object')) {
46
+ /** @type {Record<string, any>} */
47
+ const out = {};
48
+ const keys = new Set(scoped.flatMap((s) => Object.keys(s.data)));
49
+ for (const k of keys) {
50
+ out[k] = walk(
51
+ scoped.filter((s) => Object.prototype.hasOwnProperty.call(s.data, k)).map((s) => ({ scope: s.scope, data: s.data[k] })),
52
+ [...p, k],
53
+ );
54
+ }
55
+ return out;
56
+ }
57
+ const top = scoped[scoped.length - 1];
58
+ winnerByKey[p.join('.')] = top.scope;
59
+ if (scoped.every((s) => kindOf(s.data) === 'array')) return scoped.flatMap((s) => s.data);
60
+ return top.data;
61
+ };
62
+ const live = entries.filter((e) => kindOf(e.data) === 'object');
63
+ return { merged: live.length ? walk(live, []) : {}, winnerByKey };
64
+ }
65
+
66
+ /**
67
+ * Highest-precedence value of `key` among layered settings ({user,project,local,managed}) that
68
+ * passes `pred`; an invalid value in a higher layer falls through to the next one.
69
+ * @param {Record<string, any> | null | undefined} layers
70
+ * @param {string} key
71
+ * @param {(v: any) => boolean} pred
72
+ */
73
+ function pickByPrecedence(layers, key, pred) {
74
+ for (const scope of [...SCOPE_ORDER].reverse()) {
75
+ const s = layers && layers[scope];
76
+ if (s && typeof s === 'object' && pred(s[key])) return s[key];
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ /**
82
+ * @param {{ home?: string, cwd?: string|null, fs?: any, platform?: string, managedPath?: string }} [opts]
83
+ * `cwd` is the project root (whose `.claude/` holds project + local settings); omit for user/managed only.
84
+ * @returns {{ merged: Record<string, any>, winnerByKey: Record<string, SettingsScope>,
85
+ * layers: Partial<Record<SettingsScope, any>>, errors: { file: string, scope: SettingsScope, error: string }[] }}
86
+ */
87
+ function effectiveSettings(opts = {}) {
88
+ const fsImpl = opts.fs || fs;
89
+ const home = opts.home || os.homedir();
90
+ const cwd = opts.cwd ? path.resolve(opts.cwd) : null;
91
+ /** @type {{scope: SettingsScope, file: string}[]} */
92
+ const files = [{ scope: 'user', file: path.join(home, '.claude', 'settings.json') }];
93
+ if (cwd) files.push({ scope: 'project', file: path.join(cwd, '.claude', 'settings.json') });
94
+ files.push({ scope: 'local', file: path.join(home, '.claude', 'settings.local.json') });
95
+ if (cwd) files.push({ scope: 'local', file: path.join(cwd, '.claude', 'settings.local.json') });
96
+ files.push({ scope: 'managed', file: opts.managedPath || managedSettingsPath(opts.platform) });
97
+
98
+ /** @type {{ file: string, scope: SettingsScope, error: string }[]} */
99
+ const errors = [];
100
+ /** @type {Partial<Record<SettingsScope, any>>} */
101
+ const layers = {};
102
+ /** @type {{scope: SettingsScope, data: any}[]} */
103
+ const entries = [];
104
+ for (const { scope, file } of files) {
105
+ try {
106
+ const data = JSON.parse(fsImpl.readFileSync(file, 'utf8'));
107
+ if (kindOf(data) !== 'object') throw new Error('not a JSON object');
108
+ entries.push({ scope, data });
109
+ layers[scope] = layers[scope] ? mergeLayers([{ scope, data: layers[scope] }, { scope, data }]).merged : data;
110
+ } catch (e) {
111
+ errors.push({ file, scope, error: e instanceof Error ? e.message : String(e) });
112
+ }
113
+ }
114
+ // Stable sort by scope rank (same-scope files keep file order: home-local below project-local).
115
+ entries.sort((a, b) => SCOPE_ORDER.indexOf(a.scope) - SCOPE_ORDER.indexOf(b.scope));
116
+ const { merged, winnerByKey } = mergeLayers(entries);
117
+ return { merged, winnerByKey, layers, errors };
118
+ }
119
+
120
+ module.exports = { effectiveSettings, mergeLayers, pickByPrecedence, managedSettingsPath, SCOPE_ORDER };
@@ -335,7 +335,7 @@ function checkDevPlugin({ homeDir }) {
335
335
  ...base,
336
336
  ok: false,
337
337
  detail: `${DEV_PLUGIN_ENABLED_KEY} missing from ~/.claude/settings.json enabledPlugins`,
338
- fix: 'Enable in Plugins tab: session-manager-dev (Session Manager)',
338
+ fix: 'Turn on the switch for session-manager-dev in Extensions › Plugins (writes ~/.claude/settings.json enabledPlugins)',
339
339
  };
340
340
  }
341
341
 
@@ -410,7 +410,7 @@ function checkAgentPersonas({ cwd, homeDir }) {
410
410
  detail: ok
411
411
  ? `${count} persona(s) across ~/.claude/agents/ and ${cwd}/.claude/agents/`
412
412
  : `no .md personas in ~/.claude/agents/ or ${cwd}/.claude/agents/`,
413
- fix: ok ? null : 'Create a persona in the Agent Library tab',
413
+ fix: ok ? null : 'Create a persona on the Agents page',
414
414
  };
415
415
  }
416
416
 
@@ -542,7 +542,7 @@ function checkGuard(def, { cwd, homeDir = os.homedir() }) {
542
542
  detail,
543
543
  fix: ok
544
544
  ? null
545
- : `Add a PreToolUse hook to ${cwd}/.claude/settings.json matching ${def.matcher} that runs ${nodeShellCommand(guardShimPath(def.scriptBasename, homeDir))}${def.nudge ? ' (a nudge, not a hard gate)' : ''}`,
545
+ : `Add a PreToolUse hook (Settings › Hooks) to ${cwd}/.claude/settings.json matching ${def.matcher} that runs ${nodeShellCommand(guardShimPath(def.scriptBasename, homeDir))}${def.nudge ? ' (a nudge, not a hard gate)' : ''}`,
546
546
  fixAction: ok ? null : def.fixActionId,
547
547
  };
548
548
  }