claude-code-session-manager 0.130.2 → 0.130.3

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 (58) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-BmrXNwK8.js +2 -0
  4. package/dist/assets/{AppSettings-Bpwynea4.js → AppSettings-Cs4POznd.js} +1 -1
  5. package/dist/assets/{Button-DSoqrxCB.js → Button-UUr5giu8.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-C46Hj0lz.js +1 -0
  7. package/dist/assets/Extensions-B9QdiNOV.js +2 -0
  8. package/dist/assets/{History-DzMo9Otn.js → History-Bndupj87.js} +2 -2
  9. package/dist/assets/{Library-C5wKMTSn.js → Library-DFn0YPIW.js} +5 -5
  10. package/dist/assets/{ListDetail-DDQ1S0yu.js → ListDetail-DjMn8a_3.js} +1 -1
  11. package/dist/assets/{Panel-B-3NWUlv.js → Panel-CIvb-XXN.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BQQRtMdK.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-CUChwz4Z.js → ProvenanceBadge-ej8W2ZIK.js} +1 -1
  14. package/dist/assets/{Scheduler-CkGHMXvo.js → Scheduler-DSVBWqRK.js} +8 -8
  15. package/dist/assets/Settings-DqxUna06.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-C6JEdypC.js → SkillReferenceGraph-BEMTdxdD.js} +1 -1
  17. package/dist/assets/Skills-DTXehVS7.js +12 -0
  18. package/dist/assets/{SourceChip-DcBNYYhe.js → SourceChip-BrPci8FX.js} +1 -1
  19. package/dist/assets/SystemPrompt-B43hNP0X.js +1 -0
  20. package/dist/assets/{TiptapBody-DiVYC-_O.js → TiptapBody-B-R2Bpda.js} +1 -1
  21. package/dist/assets/{Toggle-Cs3k6I96.js → Toggle-DKb4x1BP.js} +1 -1
  22. package/dist/assets/ViewTabs-CcJdFZgv.js +1 -0
  23. package/dist/assets/{VoiceButton-C3NLotUZ.js → VoiceButton-BSH0UI3u.js} +1 -1
  24. package/dist/assets/{historyTotals-f-E0L9Xw.js → historyTotals-5oUEu_fe.js} +1 -1
  25. package/dist/assets/index-C9w-dVzo.js +3090 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-CMCcT2yg.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +420 -416
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/src/main/agentLibrary.cjs +81 -29
  35. package/src/main/agentsIpc.cjs +21 -16
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/ipcSchemas.cjs +7 -1
  38. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  39. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  40. package/src/main/lib/git/gitWorktree.cjs +216 -43
  41. package/src/main/lib/mdNetworkScan.cjs +555 -0
  42. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  43. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  44. package/src/main/lib/persona-macro/macroJobDispatch.cjs +9 -2
  45. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  46. package/src/main/projectPages.cjs +32 -7
  47. package/src/main/scheduler/gitTreeGuard.cjs +85 -12
  48. package/src/main/scheduler.cjs +16 -5
  49. package/src/preload/api.d.ts +91 -6
  50. package/src/preload/apiSurface.json +7 -0
  51. package/src/preload/index.cjs +1 -0
  52. package/dist/assets/AgentLibrary-Bfj862qf.js +0 -2
  53. package/dist/assets/Extensions-BziIutWV.js +0 -13
  54. package/dist/assets/Memory-Bq5T33d2.js +0 -25
  55. package/dist/assets/Settings-DGxvyajs.js +0 -2
  56. package/dist/assets/SystemPrompt-CfozyVQx.js +0 -1
  57. package/dist/assets/ViewTabs-DFXH03tb.js +0 -1
  58. package/dist/assets/index-CuAfFXNd.js +0 -3086
@@ -24,10 +24,17 @@ function buildGate(absPath, nowMs) {
24
24
  }
25
25
 
26
26
  const PAGE_IDS = { 'how it works': 'how-it-works', faq: 'faq', overview: 'overview' };
27
+ // Same rule as ENTRY_ID_RE in ipcSchemas.cjs. The id becomes a path segment in
28
+ // artifactPaths, so an id taken from free text must pass it first.
29
+ const ENTRY_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
27
30
 
28
- // Entry id: videos get a fresh one per press; knowledge pages are named by a
29
- // 'Page: <name>' line in the extra instructions (default 'overview').
31
+ // Entry id: a valid 'Replace entry: <id>' line in the extra instructions
32
+ // (Regenerate) rebuilds that entry in place, for either kind; an invalid one
33
+ // is ignored. Otherwise videos get a fresh id per press and knowledge pages
34
+ // are named by a 'Page: <name>' line (default 'overview').
30
35
  function entryIdFor(kind, extra, t) {
36
+ const replace = /^\s*Replace entry:\s*(\S+)\s*$/im.exec(extra || '');
37
+ if (replace && ENTRY_ID_RE.test(replace[1])) return replace[1];
31
38
  if (kind === 'video') return `vid-${t.toString(36)}${Math.random().toString(36).slice(2, 5).padEnd(3, '0')}`;
32
39
  const m = /^\s*Page:\s*(.+?)\s*$/im.exec(extra || '');
33
40
  if (!m) return 'overview';
@@ -28,6 +28,64 @@ const COMPLETED_EQUIVALENT_VERDICTS = new Set([
28
28
  // the full runs/ directory (which can hold thousands of entries).
29
29
  const MAX_DIRS_SCANNED = 5;
30
30
 
31
+ // runsDir -> { dirFiles: Map<dirName, Set<slug>> } — slugs whose
32
+ // <slug>.meta.json exists in that run dir. Dirs older than IMMUTABLE_AFTER_MS
33
+ // are listed once and cached for good; younger ones are re-listed each call.
34
+ const indexes = new Map();
35
+ const IMMUTABLE_AFTER_MS = 24 * 60 * 60 * 1000;
36
+ const META_SUFFIX = '.meta.json';
37
+
38
+ /** Run-dir name (ISO with ':'/'.' -> '-') to epoch ms, or NaN. */
39
+ function runDirTime(name) {
40
+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(name);
41
+ if (!m) return NaN;
42
+ return Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z`);
43
+ }
44
+
45
+ function isYoung(name, now) {
46
+ const t = runDirTime(name);
47
+ return Number.isNaN(t) || now - t < IMMUTABLE_AFTER_MS;
48
+ }
49
+
50
+ function refreshIndex(runsDir, fsImpl) {
51
+ const names = fsImpl.readdirSync(runsDir); // throws -> caller returns null
52
+ if (!Array.isArray(names)) return new Map();
53
+ let idx = indexes.get(runsDir);
54
+ if (!idx) {
55
+ idx = { dirFiles: new Map() };
56
+ indexes.set(runsDir, idx);
57
+ }
58
+ const present = new Set(names);
59
+ for (const cached of idx.dirFiles.keys()) {
60
+ if (!present.has(cached)) idx.dirFiles.delete(cached);
61
+ }
62
+ const now = Date.now();
63
+ for (const name of names) {
64
+ if (idx.dirFiles.has(name) && !isYoung(name, now)) continue;
65
+ const slugs = new Set();
66
+ try {
67
+ for (const f of fsImpl.readdirSync(path.join(runsDir, name))) {
68
+ if (typeof f === 'string' && f.endsWith(META_SUFFIX)) slugs.add(f.slice(0, -META_SUFFIX.length));
69
+ }
70
+ } catch {
71
+ // unlistable dir (e.g. a stray file) — treat as having no runs
72
+ }
73
+ idx.dirFiles.set(name, slugs);
74
+ }
75
+ return idx.dirFiles;
76
+ }
77
+
78
+ function matchingDirs(slug, runsDir, fsImpl) {
79
+ const dirFiles = refreshIndex(runsDir, fsImpl);
80
+ const out = [];
81
+ for (const [name, slugs] of dirFiles) if (slugs.has(slug)) out.push(name);
82
+ return out;
83
+ }
84
+
85
+ function __resetRunIndexForTests() {
86
+ indexes.clear();
87
+ }
88
+
31
89
  /**
32
90
  * Returns { status: 'completed'|'failed', runId, finishedAt } for the newest
33
91
  * run directory containing a `<slug>.meta.json`, or null if none is found or
@@ -36,24 +94,12 @@ const MAX_DIRS_SCANNED = 5;
36
94
  */
37
95
  function latestTerminalOutcomeForSlug(slug, { runsDir, fsImpl = fs } = {}) {
38
96
  if (!slug || !runsDir) return null;
39
- let dirs;
97
+ let matches;
40
98
  try {
41
- dirs = fsImpl.readdirSync(runsDir);
99
+ matches = matchingDirs(slug, runsDir, fsImpl);
42
100
  } catch {
43
101
  return null;
44
102
  }
45
- if (!Array.isArray(dirs) || dirs.length === 0) return null;
46
-
47
- // Filter (cheap existence check) to dirs that actually have a run for this
48
- // slug, mirroring resolveRunId's existing pattern in scheduler.cjs — this
49
- // is a stat, not a read+parse.
50
- const matches = dirs.filter((d) => {
51
- try {
52
- return fsImpl.existsSync(path.join(runsDir, d, `${slug}.meta.json`));
53
- } catch {
54
- return false;
55
- }
56
- });
57
103
  if (!matches.length) return null;
58
104
 
59
105
  // Dir names are ISO timestamps with `:`/`.` replaced by `-` — lexical
@@ -110,4 +156,4 @@ function latestTerminalOutcomeForSlug(slug, { runsDir, fsImpl = fs } = {}) {
110
156
  return null;
111
157
  }
112
158
 
113
- module.exports = { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS, MAX_DIRS_SCANNED };
159
+ module.exports = { latestTerminalOutcomeForSlug, __resetRunIndexForTests, COMPLETED_EQUIVALENT_VERDICTS, MAX_DIRS_SCANNED };
@@ -10,6 +10,8 @@
10
10
  * home.html's content plus the demo video's { path, mtimeMs }, and a
11
11
  * refcounted per-cwd watcher pushes `project-pages:changed` for either. It
12
12
  * never writes content (watch()'s mkdir creates an empty directory only).
13
+ * mdNetwork() maps the project's markdown link network on demand
14
+ * (lib/mdNetworkScan.cjs) for the Tools pane.
13
15
  */
14
16
 
15
17
  const { ipcMain } = require('electron');
@@ -17,9 +19,10 @@ const fs = require('node:fs');
17
19
  const path = require('node:path');
18
20
  const chokidar = require('chokidar');
19
21
  const config = require('./config.cjs');
20
- const { opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
22
+ const { opsPath, assertOpsWrite, resolveProjectRoot } = require('./lib/opsOwnership.cjs');
21
23
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
22
24
  const { listLibrary, migrateLegacy } = require('./lib/project-pages/pagesLibrary.cjs');
25
+ const { scanMdNetwork } = require('./lib/mdNetworkScan.cjs');
23
26
 
24
27
  let mainWindow = null;
25
28
  function attachWindow(window) {
@@ -35,19 +38,25 @@ function demoVideoPath(cwd) {
35
38
  }
36
39
 
37
40
  /**
38
- * Resolve `cwd`'s home.html path, treating the opsOwnership "ephemeral cwd"
39
- * throw (a tmpdir/linked-worktree project root) as "no path available"
41
+ * Resolve `realCwd`'s project root, treating the opsOwnership "ephemeral cwd"
42
+ * throw (a tmpdir/linked-worktree project root) as "no root available"
40
43
  * rather than letting it propagate.
41
44
  */
42
- function tryHomePath(realCwd) {
45
+ function tryProjectRoot(realCwd) {
43
46
  try {
44
- return { file: homePath(realCwd), ephemeral: false };
47
+ return { root: resolveProjectRoot(realCwd), ephemeral: false };
45
48
  } catch (e) {
46
- if (e.ephemeral) return { file: null, ephemeral: true };
49
+ if (e.ephemeral) return { root: null, ephemeral: true };
47
50
  throw e;
48
51
  }
49
52
  }
50
53
 
54
+ /** `realCwd`'s home.html path, or no path where tryProjectRoot finds no root. */
55
+ function tryHomePath(realCwd) {
56
+ const { root, ephemeral } = tryProjectRoot(realCwd);
57
+ return { file: ephemeral ? null : homePath(root), ephemeral };
58
+ }
59
+
51
60
  const EMPTY = () => ({ knowledge: [], videos: [], html: null, mtimeMs: null, demoVideo: null });
52
61
 
53
62
  /**
@@ -57,7 +66,7 @@ const EMPTY = () => ({ knowledge: [], videos: [], html: null, mtimeMs: null, dem
57
66
  */
58
67
  async function get({ cwd }) {
59
68
  const realCwd = config.validatePath(cwd);
60
- const { ephemeral } = tryHomePath(realCwd);
69
+ const { ephemeral } = tryProjectRoot(realCwd);
61
70
  if (ephemeral) return EMPTY();
62
71
  await migrateLegacy(realCwd);
63
72
  const { knowledge, videos } = await listLibrary(realCwd);
@@ -80,6 +89,20 @@ async function get({ cwd }) {
80
89
  };
81
90
  }
82
91
 
92
+ const MD_NETWORK_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project to scan';
93
+
94
+ /**
95
+ * -> MdNetworkResult: the project's markdown link network from its root
96
+ * CLAUDE.md, scanned once per call (no watcher, no cache). `cwd` is validated
97
+ * like get() (an invalid path rejects); a cwd get() answers with EMPTY() gets
98
+ * `{ ok: false, error }`.
99
+ */
100
+ async function mdNetwork({ cwd }) {
101
+ const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
102
+ if (ephemeral) return { ok: false, error: MD_NETWORK_EPHEMERAL };
103
+ return scanMdNetwork(root);
104
+ }
105
+
83
106
  /** True for paths whose change should refresh the library (relative to project-pages/). */
84
107
  function isLibraryPath(rel) {
85
108
  const parts = rel.split(path.sep);
@@ -251,6 +274,7 @@ async function deleteEntry(input) {
251
274
  function registerProjectPagesIpc() {
252
275
  const { schemas: s, validated: v } = require('./ipcSchemas.cjs');
253
276
  ipcMain.handle('project-pages:get', v(s.projectPagesCwd, get));
277
+ ipcMain.handle('project-pages:md-network', v(s.projectPagesCwd, mdNetwork));
254
278
  ipcMain.handle('project-pages:watch', v(s.projectPagesCwd, ({ cwd }) => watchOutput(cwd)));
255
279
  ipcMain.handle('project-pages:rename', v(s.projectPagesRename, renameEntry));
256
280
  ipcMain.handle('project-pages:delete', v(s.projectPagesDelete, deleteEntry));
@@ -264,6 +288,7 @@ module.exports = {
264
288
  attachWindow,
265
289
  registerProjectPagesIpc,
266
290
  get,
291
+ mdNetwork,
267
292
  renameEntry,
268
293
  deleteEntry,
269
294
  watchOutput,
@@ -513,11 +513,18 @@ function gitRangeCommits(cwd, before, after) {
513
513
  }
514
514
 
515
515
  /**
516
- * Read-only check: is a job's `sm-job/<slug>` worktree branch already fully
517
- * integrated into `cwd`'s current HEAD — i.e. every commit on the branch is
518
- * an ancestor of (or equal to) HEAD? Mirrors gitWorktree.cjs's own
519
- * integrateBranch() no-op detection (`mergeBase === branchHead`) exactly, but
520
- * deliberately never calls integrateBranch itself: this is used by
516
+ * Read-only check: is a job's `sm-job/<slug>` worktree branch already
517
+ * integrated into `cwd`'s current HEAD? Two proofs, cheapest first:
518
+ * 1. Ancestry: the branch tip is an ancestor of (or equal to) HEAD, the
519
+ * same `mergeBase === branchHead` test as integrateBranch()'s no-op
520
+ * detection.
521
+ * 2. Content: `gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch })`.
522
+ * Linear landing (PRDs 2743, 2825) replays the branch onto the base, so a
523
+ * landed branch's own commits never become ancestors of HEAD. Proof 1
524
+ * alone made the reaper park a landed job as "still holds unintegrated
525
+ * work — never merged" (validator finding I-2). The helper also accepts
526
+ * patch-equivalent commits on HEAD, or a merge that would change nothing.
527
+ * Deliberately never calls integrateBranch itself: this is used by
521
528
  * reapDeadRunningJobs to PROVE a dead job's work already landed, never to
522
529
  * perform the landing — attempting a real merge from an audit check is a
523
530
  * mutating action with its own conflict/timing risk, and "land the still-
@@ -527,13 +534,13 @@ function gitRangeCommits(cwd, before, after) {
527
534
  * conservative failure direction here is needs_review, never a silent merge.
528
535
  *
529
536
  * Returns:
530
- * - true — branch exists and is fully contained in HEAD (already
531
- * integrated by a prior pass, or a genuine no-op branch that never
532
- * diverged from its base — both cases legitimately "landed").
533
- * - false — branch exists and still holds commits not in HEAD (a real
534
- * stranded deliverable, e.g. the PRD 1118 shape).
537
+ * - true — branch exists and its content is already in HEAD (integrated by
538
+ * a prior pass, landed as a linear replay, or a genuine no-op branch that
539
+ * never diverged from its base — all legitimately "landed").
540
+ * - false — branch exists and still holds work HEAD lacks (a real stranded
541
+ * deliverable, e.g. the PRD 1118 shape), or neither proof could be read.
535
542
  * - null — branch does not exist at all (never a worktree run — an
536
- * in-place run, or SM_JOB_WORKTREE_DISABLE), or the git calls errored.
543
+ * in-place run, or SM_JOB_WORKTREE_DISABLE), or `rev-parse` errored.
537
544
  * Never throws.
538
545
  */
539
546
  function isBranchAlreadyIntegrated(cwd, branch) {
@@ -550,7 +557,9 @@ function isBranchAlreadyIntegrated(cwd, branch) {
550
557
  { timeout: 10_000, windowsHide: true },
551
558
  (mbErr, mbOut) => {
552
559
  const mergeBase = mbErr ? '' : String(mbOut || '').trim();
553
- resolve(mergeBase !== '' && mergeBase === branchHead);
560
+ if (mergeBase !== '' && mergeBase === branchHead) { resolve(true); return; }
561
+ gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch })
562
+ .then((landed) => resolve(landed === true), () => resolve(false));
554
563
  },
555
564
  );
556
565
  },
@@ -558,6 +567,69 @@ function isBranchAlreadyIntegrated(cwd, branch) {
558
567
  });
559
568
  }
560
569
 
570
+ // replayBranchOnto (gitWorktree.cjs) copies exactly these four fields onto
571
+ // each commit it replays. With `-z` every record ends in a NUL, and no field
572
+ // can hold one, so a record is always exactly four fields.
573
+ const COMMIT_IDENTITY_FORMAT = '%an%x00%ae%x00%aI%x00%B';
574
+ const REPLAY_MATCH_MAX_COMMITS = 200;
575
+ const REPLAY_MATCH_MAX_BUFFER = 16 * 1024 * 1024;
576
+
577
+ /** `git log -z --format=COMMIT_IDENTITY_FORMAT` output → one comparable key per commit. */
578
+ function parseCommitIdentityLog(out) {
579
+ const fields = String(out || '').split('\0');
580
+ const keys = [];
581
+ for (let i = 0; i + 3 < fields.length; i += 4) {
582
+ // The message loses its trailing newlines, as replayBranchOnto trims the one it copies.
583
+ keys.push(JSON.stringify([fields[i], fields[i + 1], fields[i + 2], fields[i + 3].replace(/\n+$/, '')]));
584
+ }
585
+ return keys;
586
+ }
587
+
588
+ /**
589
+ * The subset of `shas` that linear landing copied off `branch`.
590
+ * replayBranchOnto (gitWorktree.cjs) re-creates each commit it replays with
591
+ * `commit-tree`, keeping its author name, author email, author date and
592
+ * message (trailing newlines trimmed). The copy on the base is therefore never
593
+ * an ancestor of the branch. A sha counts when those four fields equal those
594
+ * of a commit in `git log <sha>..<branch>` (the branch commits the sha does
595
+ * not already contain), reading at most REPLAY_MATCH_MAX_COMMITS of them.
596
+ * The branch is resolved once. A sha that is not a hex object name, or a
597
+ * branch name starting with '-', never reaches git. Never throws: a missing
598
+ * branch, an unresolvable sha or any git failure means no match.
599
+ *
600
+ * @param {string} cwd
601
+ * @param {string[]} shas
602
+ * @param {string} branch
603
+ * @returns {Promise<Set<string>>}
604
+ */
605
+ async function commitsReplayedFromBranch(cwd, shas, branch) {
606
+ const replayed = new Set();
607
+ if (!cwd || typeof branch !== 'string' || !branch || branch.startsWith('-') || !Array.isArray(shas)) return replayed;
608
+ const candidates = shas.filter((sha) => typeof sha === 'string' && /^[0-9a-f]{4,64}$/i.test(sha));
609
+ if (!candidates.length) return replayed;
610
+ try {
611
+ await sharedGitExec.execGit(cwd, ['rev-parse', '--verify', '--quiet', `${branch}^{commit}`], { timeout: 10_000 });
612
+ } catch {
613
+ return replayed; // no such branch, so nothing on it was replayed
614
+ }
615
+ const opts = { timeout: 10_000, maxBuffer: REPLAY_MATCH_MAX_BUFFER };
616
+ for (const sha of candidates) {
617
+ try {
618
+ const branchKeys = new Set(parseCommitIdentityLog(await sharedGitExec.execGit(
619
+ cwd,
620
+ ['log', '-z', `--max-count=${REPLAY_MATCH_MAX_COMMITS}`, `--format=${COMMIT_IDENTITY_FORMAT}`, `${sha}..${branch}`, '--'],
621
+ opts,
622
+ )));
623
+ if (!branchKeys.size) continue;
624
+ const [own] = parseCommitIdentityLog(await sharedGitExec.execGit(
625
+ cwd, ['log', '-z', '-1', `--format=${COMMIT_IDENTITY_FORMAT}`, sha, '--'], opts,
626
+ ));
627
+ if (own !== undefined && branchKeys.has(own)) replayed.add(sha);
628
+ } catch { /* unresolvable sha, or git failed: no match */ }
629
+ }
630
+ return replayed;
631
+ }
632
+
561
633
  /**
562
634
  * Override for a SIGTERM'd (143) run when a commit landed in its window.
563
635
  * Exit 143 alone doesn't prove the deliverable is missing — the 776/779
@@ -713,6 +785,7 @@ module.exports = {
713
785
  strandedCommitVerdict,
714
786
  gitRangeCommits,
715
787
  isBranchAlreadyIntegrated,
788
+ commitsReplayedFromBranch,
716
789
  classifySigtermWithCommit,
717
790
  evaluateFinalizeDrop,
718
791
  evaluateDispatchSidecarReconcile,
@@ -9409,9 +9409,14 @@ function applyRcaClassification(job, report) {
9409
9409
  * independent of whether it appears in `pathCommits` — it is definitionally
9410
9410
  * this job's own work, not something discovered by scanning history.
9411
9411
  * 2. 'job branch' — a path-overlapping commit reachable from (an ancestor of
9412
- * or equal to) this job's own `sm-job/<slug>` branch tip. Still
9413
- * job-specific even though it IS a `git log` scan: a sibling's commit can
9414
- * never be an ancestor of THIS job's own branch ref. In practice this
9412
+ * or equal to) this job's own `sm-job/<slug>` branch tip, or a copy of
9413
+ * one of that branch's commits that linear landing replayed onto the
9414
+ * base: same author name, author email, author date and message as a
9415
+ * commit in `git log <sha>..sm-job/<slug>`, at most 200 of them read
9416
+ * (gitTreeGuard.commitsReplayedFromBranch). Still job-specific even
9417
+ * though it IS a `git log` scan: a sibling's commit can never be an
9418
+ * ancestor of THIS job's own branch ref, nor share all four of those
9419
+ * fields with one of its commits. In practice this
9415
9420
  * branch is deleted on successful integration (gitWorktree.cjs's
9416
9421
  * `cleanupWorktree`), so this mainly fires when integration failed and
9417
9422
  * the branch was deliberately kept for recovery, or reverify runs before
@@ -9437,13 +9442,19 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
9437
9442
  }
9438
9443
 
9439
9444
  const branch = `sm-job/${job?.slug}`;
9440
- const branchCommits = [];
9445
+ const ancestors = new Set();
9441
9446
  for (const sha of pathCommits) {
9442
9447
  try {
9443
9448
  await execGitAt(cwd, ['merge-base', '--is-ancestor', sha, branch], { timeout: 10_000 });
9444
- branchCommits.push(sha);
9449
+ ancestors.add(sha);
9445
9450
  } catch { /* not an ancestor of this job's own branch, or branch doesn't exist */ }
9446
9451
  }
9452
+ // Linear landing put this job's own commits on the base as replayed copies,
9453
+ // which are never ancestors of the branch.
9454
+ const replayed = await gitTreeGuard.commitsReplayedFromBranch(
9455
+ cwd, pathCommits.filter((sha) => !ancestors.has(sha)), branch,
9456
+ );
9457
+ const branchCommits = pathCommits.filter((sha) => ancestors.has(sha) || replayed.has(sha));
9447
9458
  if (branchCommits.length) return { commits: branchCommits, rule: 'job branch' };
9448
9459
 
9449
9460
  if (job?.slug) {
@@ -404,10 +404,13 @@ export interface AgentPersona {
404
404
  executorOnly?: boolean;
405
405
  path: string;
406
406
  body: string;
407
- /** Project names (basename of cwd) whose currently-open tab overlays this agent. */
407
+ /** Project names (basename of cwd) whose currently-open tab overlays this agent. Display-only and never a key —
408
+ * two open projects can share a folder name; key on `overrideDetails[].cwd`. */
408
409
  overridingProjects: string[];
409
- /** Per open project with an overlay: which frontmatter keys / body the overlay overrides (merged view provenance). */
410
- overrideDetails?: { project: string; fields: string[]; values?: Record<string, string>; bodyOverridden: boolean; issue: string | null }[];
410
+ /** Per open project with an overlay: which frontmatter keys / body the overlay overrides (merged view provenance).
411
+ * `cwd` is the open project's normalized absolute cwd — the key for `savePersona`'s `projectCwd` and
412
+ * `removeOverride`; `project` is its folder name, a display label only. */
413
+ overrideDetails?: { project: string; cwd: string; fields: string[]; values?: Record<string, string>; bodyOverridden: boolean; issue: string | null }[];
411
414
  }
412
415
 
413
416
  /** Payload for `agents.savePersona` — creates or overwrites a global persona file. */
@@ -430,8 +433,9 @@ export interface AgentPersonaSaveInput {
430
433
  actionLabel?: string;
431
434
  /** Omit to keep the existing file's value. */
432
435
  title?: string;
433
- /** Open project name: write that project's frontmatter-only override (only `model`/`effort` are used) instead of the global file. */
434
- projectName?: string;
436
+ /** An OPEN project's absolute cwd: write that project's frontmatter-only override (only `model`/`effort` are used)
437
+ * instead of the global file. A cwd that is not open is rejected — never a global write. */
438
+ projectCwd?: string;
435
439
  /** Bundled-persona version stamp (seedAgentPersonas.cjs). Omit to carry over the existing file's stamp unchanged. */
436
440
  seedVersion?: number;
437
441
  /** Omit to keep the existing file's value. */
@@ -1597,6 +1601,84 @@ export interface ProjectPagesGetResult {
1597
1601
  demoVideo: { path: string; mtimeMs: number } | null;
1598
1602
  }
1599
1603
 
1604
+ // ────────────────────────────────────────────── Project Pages: markdown link network
1605
+ // Mirrors the JSDoc typedefs of the same names in src/main/lib/mdNetworkScan.cjs.
1606
+ // Every path is repo-relative POSIX.
1607
+
1608
+ /** 'hub' = the root CLAUDE.md; 'owner' = a CLAUDE.md / README.md / AGENTS.md one link from it; 'doc' = any other doc. */
1609
+ export type MdNetworkNodeType = 'hub' | 'owner' | 'doc';
1610
+
1611
+ /** One doc reachable by links from the root CLAUDE.md. */
1612
+ export interface MdNetworkNode {
1613
+ /** Same as `path`. */
1614
+ id: string;
1615
+ path: string;
1616
+ /** Links from the root along the shortest path (0 = the root). */
1617
+ depth: number;
1618
+ type: MdNetworkNodeType;
1619
+ /** Edges out of this doc, broken ones included. */
1620
+ linksOut: number;
1621
+ /** Edges into this doc. */
1622
+ linkedFrom: number;
1623
+ }
1624
+
1625
+ /** One per distinct (from, to) pair; a self link, or a link to a present non-doc target (code file, folder), makes no edge. */
1626
+ export interface MdNetworkEdge {
1627
+ from: string;
1628
+ /** For a broken edge, the missing (or outside-the-project) resolved target — not a node. */
1629
+ to: string;
1630
+ broken?: boolean;
1631
+ }
1632
+
1633
+ /** A link whose target does not exist or is outside the project. */
1634
+ export interface MdNetworkBrokenLink {
1635
+ type: 'broken-link';
1636
+ /** The linking doc. */
1637
+ file: string;
1638
+ /** 1-based line of the link in `file`. */
1639
+ line: number;
1640
+ /** The target as written, `#fragment` / `?query` stripped. */
1641
+ target: string;
1642
+ /** `target` resolved against `file`'s folder. */
1643
+ to: string;
1644
+ /** `${file}:${line} → ${target}` */
1645
+ where: string;
1646
+ detail: string;
1647
+ }
1648
+
1649
+ /** Docs that no link path from the root reaches, grouped by top-level folder. */
1650
+ export interface MdNetworkOrphan {
1651
+ type: 'orphan';
1652
+ /** The top-level folder with a trailing slash (`./` for root-level docs). */
1653
+ where: string;
1654
+ count: number;
1655
+ paths: string[];
1656
+ detail: string;
1657
+ }
1658
+
1659
+ /** Broken links come first (in walk order), then orphan groups (by folder). */
1660
+ export type MdNetworkFinding = MdNetworkBrokenLink | MdNetworkOrphan;
1661
+
1662
+ /** A project's markdown link network, mapped from its root CLAUDE.md. */
1663
+ export interface MdNetwork {
1664
+ ok: true;
1665
+ /** The root doc, 'CLAUDE.md'. */
1666
+ root: string;
1667
+ /** Breadth-first from the root. */
1668
+ nodes: MdNetworkNode[];
1669
+ edges: MdNetworkEdge[];
1670
+ findings: MdNetworkFinding[];
1671
+ /** Docs read — at most 2000; past that cap, docs no link reaches are dropped first. */
1672
+ docs: number;
1673
+ /** `edges.length`. */
1674
+ links: number;
1675
+ /** Top-level folders holding reachable docs, each with a trailing slash, sorted. */
1676
+ scopes: string[];
1677
+ }
1678
+
1679
+ /** `{ ok: false, error }` when there is nothing to map or the scan failed (not a git repo, no root CLAUDE.md, an ephemeral cwd). */
1680
+ export type MdNetworkResult = MdNetwork | { ok: false; error: string };
1681
+
1600
1682
  // ────────────────────────────────────────────── Git status (richer than app:git-branch)
1601
1683
 
1602
1684
  /** Mirrors the status returned by src/main/git.cjs mapStatus(). */
@@ -1941,7 +2023,8 @@ export interface SessionManagerAPI {
1941
2023
  listPersonas: () => Promise<AgentPersona[]>;
1942
2024
  savePersona: (payload: AgentPersonaSaveInput) => Promise<{ ok: boolean; path: string }>;
1943
2025
  deletePersona: (payload: { name: string }) => Promise<{ ok: boolean }>;
1944
- removeOverride: (payload: { name: string; projectName: string }) => Promise<{ ok: boolean }>;
2026
+ /** Drops the overlay of the OPEN project at `projectCwd` (an `overrideDetails[].cwd`). */
2027
+ removeOverride: (payload: { name: string; projectCwd: string }) => Promise<{ ok: boolean }>;
1945
2028
  /** Raw persona `.md` text for the New Epic AIM composer (epicIntake.ts's `agentBody`),
1946
2029
  * resolved with project-overlay-then-global precedence for `cwd` — unlike
1947
2030
  * `listPersonas` above, which only reads the global directory. Null when neither
@@ -2316,6 +2399,8 @@ export interface SessionManagerAPI {
2316
2399
  projectPages: {
2317
2400
  /** Read the project-pages library (knowledge/<id>/ pages and videos/<id>/ videos, each with its meta) as a `ProjectPagesGetResult`; empty lists if nothing exists yet. Never fires an LLM call. */
2318
2401
  get: (cwd: string) => Promise<ProjectPagesGetResult>;
2402
+ /** Map the project's markdown link network from its root CLAUDE.md (read-only, bounded, no LLM) for the Tools pane. Scans on every call — no watcher, no cache. `ok:false` (with `error`) for a cwd `get` answers with empty lists (tmpdir / linked worktree), a folder that is not a git repo, or no root CLAUDE.md; rejects on an invalid cwd, like `get`. */
2403
+ mdNetwork: (payload: { cwd: string }) => Promise<MdNetworkResult>;
2319
2404
  /** Start pushing `onChanged` events for this cwd's output dir. Refcounted per cwd; `ok:false` (reason 'ephemeral'|'invalid-cwd') means no live updates are possible, not an error. */
2320
2405
  watch: (cwd: string) => Promise<{ ok: boolean; reason?: 'ephemeral' | 'invalid-cwd' }>;
2321
2406
  /** Stop pushing `onChanged` events for this cwd — must be paired 1:1 with a prior `watch` call. */
@@ -1371,6 +1371,13 @@
1371
1371
  "kind": "invoke",
1372
1372
  "remote": "read"
1373
1373
  },
1374
+ {
1375
+ "ns": "projectPages",
1376
+ "method": "mdNetwork",
1377
+ "channel": "project-pages:md-network",
1378
+ "kind": "invoke",
1379
+ "remote": "read"
1380
+ },
1374
1381
  {
1375
1382
  "ns": "projectPages",
1376
1383
  "method": "watch",
@@ -396,6 +396,7 @@ contextBridge.exposeInMainWorld('api', {
396
396
  },
397
397
  projectPages: {
398
398
  get: (cwd) => ipcRenderer.invoke('project-pages:get', { cwd }),
399
+ mdNetwork: (payload) => ipcRenderer.invoke('project-pages:md-network', payload),
399
400
  watch: (cwd) => ipcRenderer.invoke('project-pages:watch', { cwd }),
400
401
  unwatch: (cwd) => ipcRenderer.invoke('project-pages:unwatch', { cwd }),
401
402
  rename: (cwd, kind, id, title) => ipcRenderer.invoke('project-pages:rename', { cwd, kind, id, title }),
@@ -1,2 +0,0 @@
1
- import{b9 as X,b4 as ve,aJ as y,Y as P,b1 as Z,a$ as N,at as e,l as K,a_ as z,a6 as je,ay as A,bk as we,b as V,aY as Ne,bc as ee,M as ye,d as Y,E as $e}from"./index-CuAfFXNd.js";import{P as te}from"./Panel-B-3NWUlv.js";import{L as ne}from"./ListDetail-DDQ1S0yu.js";import{V as Ce}from"./ViewTabs-DFXH03tb.js";import{S as se}from"./SourceChip-DcBNYYhe.js";import{B as R}from"./Button-DSoqrxCB.js";import{r as ke}from"./claude-settings-schema-COigsajx.js";import"./monaco-editor-BsIlgG7c.js";function ae(t,s){const a=X();ve([a?`${a}/.claude/agents`:null,t?`${t}/.claude/agents`:null],s)}function Se({onOpenPersona:t}){const[s,a]=y.useState(P[0].tag),{personas:d,refresh:l}=Z(o=>N.error(o.message||"failed to load agent personas"));ae(null,()=>{l()});const r=P.find(o=>o.tag===s)??null;return e.jsx(te,{toolbar:e.jsxs("span",{className:"text-fg-faint",children:[P.length," tag",P.length===1?"":"s"]}),children:e.jsx(ne,{sidebar:e.jsx("div",{className:"py-1",children:P.map(o=>{const p=z(o.tag),b=s===o.tag,c=(d==null?void 0:d.filter(v=>v.tags.includes(o.tag)).length)??0;return e.jsxs("button",{onClick:()=>{a(o.tag)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 ${b?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-semibold ${p.bg} ${p.text} ${p.border?"border border-current/30":""}`,children:["#",o.tag]}),e.jsx("span",{className:"truncate",children:o.label}),c>0&&e.jsx("span",{className:"ml-auto text-[10.5px] text-fg-faint font-mono shrink-0",children:c})]},o.tag)})}),detail:r?e.jsx(Ee,{entry:r,personas:d,onOpenPersona:t}):e.jsx(K,{title:"select a tag"})})})}const Le=y.memo(Se);function Ee({entry:t,personas:s,onOpenPersona:a}){const d=z(t.tag),l=je(t.tag),r=(s==null?void 0:s.filter(o=>o.tags.includes(t.tag)))??[];return e.jsxs("div",{className:"p-4 space-y-4 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-mono font-semibold ${d.bg} ${d.text} ${d.border?"border border-current/30":""}`,children:["#",t.tag]}),e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:t.description}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"/develop eagerness"}),e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:t.developEagerness})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"develops via"}),e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:t.developsVia})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"agents carrying this tag"}),s===null?e.jsx("div",{className:"text-xs text-fg-faint italic",children:"loading…"}):e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.map(o=>e.jsx("button",{onClick:()=>a==null?void 0:a(o.name),title:`Open ${o.name} in Personas`,className:"inline-flex items-center bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim hover:text-fg hover:bg-bg-hi",children:o.name},o.name)),r.length===0&&e.jsx("span",{className:"text-xs text-fg-faint italic mr-1",children:"no agent carries this tag yet."})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"opening framing — sent before the human's goal"}),e.jsx("pre",{className:"text-xs text-fg-dim whitespace-pre-wrap bg-bg-elev border border-line rounded p-3 leading-relaxed font-sans",children:l.initialPromptTemplate})]})]})}const De=new Set(P.map(t=>t.tag));function oe(t){return t.filter(s=>De.has(s))}function Te(t,s={}){return{name:t.name,originalName:t.name,description:t.description??"",tools:t.tools,model:t.model??"inherit",effort:t.effort??void 0,color:t.color??"",tags:oe(t.tags),projects:t.projects,action:t.action??void 0,actionLabel:t.actionLabel??void 0,title:t.title??void 0,body:t.body,...s}}const Oe=t=>{const[s,a]=t.split(".");return Number(s)+(a?Number(a)/100:0)};function Re(t){const s=/Effort is supported on ([^.]*?)(?:, with|\.|$)/.exec(t);if(!s)return[];const a=[];for(const d of s[1].split(/,\s*|\s+and\s+/)){const l=/^(\w+)\s+(\d+(?:\.\d+)?)$/.exec(d.trim());l&&a.push({family:l[1].toLowerCase(),version:Oe(l[2])})}return a}var q,Q;const Pe=Re(String(((Q=(q=ke.properties)==null?void 0:q.effortLevel)==null?void 0:Q.description)??""));function Ae(t,s){const a=new RegExp(`${s}-(\\d+)(?:-(\\d{1,2})(?!\\d))?`,"i").exec(t);if(a)return Number(a[1])+(a[2]?Number(a[2])/100:0);const d=new RegExp(`claude-(\\d+)(?:-(\\d{1,2}))?-${s}`,"i").exec(t);return d?Number(d[1])+(d[2]?Number(d[2])/100:0):null}function Fe(t,s=Pe){if(!t||t==="inherit"||s.length===0)return null;const a=A(t);if(!a)return null;const d=s.filter(r=>r.family===a);if(d.length===0)return!1;const l=Ae(t,a);return l===null?null:l>=Math.min(...d.map(r=>r.version))}const H=["Read","Grep","Glob","Bash","Write","Edit","WebFetch","WebSearch","Task"],Be=["","red","orange","yellow","green","cyan","blue","purple","pink"],re={red:"#c0392b",orange:"#b85c34",yellow:"#c9a227",green:"#6f7d52",cyan:"#3f8f8a",blue:"#4a6fa5",purple:"#7a6a8a",pink:"#b45a80"};function _(t){return{name:t.name,description:t.description??"",tools:t.tools,model:t.model??"inherit",effort:t.effort??"inherit",color:t.color??"",tags:t.tags,body:t.body}}const J={name:"new-agent",description:"",tools:["Read","Grep"],model:"inherit",effort:"inherit",color:"",tags:[],body:""};function Me(t){return t.overridingProjects.map(s=>{var l;const a=(l=t.overrideDetails)==null?void 0:l.find(r=>r.project===s);if(!a)return s;const d=[...a.fields.filter(r=>r!=="name"),...a.bodyOverridden?["full body"]:[]];return`${s}: ${d.join(", ")||"overlay"}`}).join(`
2
- `)}function Ve(){const[t,s]=y.useState("personas"),{personas:a,refresh:d}=Z(n=>N.error(n.message||"failed to load agent personas")),[l,r]=y.useState(null),[o,p]=y.useState(""),[b,c]=y.useState(null),[v,h]=y.useState(!1),[$,S]=y.useState(!1),[g,C]=y.useState(null),[L,k]=y.useState(!1),E=y.useRef(!0);y.useEffect(()=>()=>{E.current=!1},[]);const i=we(n=>{var u;return((u=n.tabs.find(T=>T.id===n.activeTabId))==null?void 0:u.cwd)??null}),w=i?i.replace(/\/+$/,"").split("/").pop()||i:null,j=async n=>{await d()&&n&&r(n)};ae(i,()=>j()),y.useEffect(()=>{const n=Ne();n&&r(n);const u=T=>r(T.detail);return window.addEventListener("sm:select-persona",u),()=>window.removeEventListener("sm:select-persona",u)},[]);const O=e.jsx(Ce,{options:[{key:"personas",label:"Personas"},{key:"tags",label:"Tags"}],active:t,onChange:s});if(t==="tags")return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("div",{className:"px-3 py-1.5 border-b border-line",children:O}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Le,{onOpenPersona:n=>{r(n),c(null),h(!1),s("personas")}})})]});if(a===null)return e.jsx(K,{title:"loading…"});const F=o.toLowerCase(),B=a.filter(n=>!F||n.name.toLowerCase().includes(F)||(n.description??"").toLowerCase().includes(F)),f=a.find(n=>n.name===l)??a[0]??null,x=b??(f?_(f):null),M=!!b&&!!f&&JSON.stringify(b)!==JSON.stringify(_(f)),m=v,I=n=>{c(null),h(!1),S(!1),C(null),r(n)},de=n=>c(u=>({...u??(f?_(f):J),...n})),ce=()=>{c({...J}),h(!0),S(!1)},fe=()=>{x&&(c({...x,name:x.name+"-copy"}),h(!0))},xe=()=>{c(null),h(!1)},me=async()=>{if(x){if(!/^[a-z][a-z0-9-]*$/.test(x.name)){N.error('agent name must be lowercase, hyphenated (e.g. "my-agent")');return}k(!0);try{const n=m?null:f,u={name:x.name,originalName:n==null?void 0:n.name,description:x.description,tools:x.tools,model:x.model,effort:x.effort,color:x.color,tags:oe(x.tags),body:x.body},T=n?Te(n,u):u;await window.api.agents.savePersona(T),N.info(m?`created ${x.name}`:`saved ${x.name}`),c(null),h(!1),await j(x.name)}catch(n){N.error(n.message||"failed to save agent persona")}finally{k(!1)}}},ge=async()=>{if(f){k(!0);try{await window.api.agents.deletePersona({name:f.name}),N.info(`deleted ${f.name}`),S(!1),c(null),h(!1),await j()}catch(n){N.error(n.message||"failed to delete agent persona")}finally{k(!1)}}},he=async n=>{k(!0);try{await window.api.agents.deletePersona({name:n}),N.info(`deleted ${n}`),C(null),l===n&&(c(null),h(!1)),await j()}catch(u){N.error(u.message||"failed to delete agent persona")}finally{k(!1)}},pe=async n=>{if(f)try{await window.api.agents.removeOverride({name:f.name,projectName:n}),N.info(`removed ${n}'s override of ${f.name}`),await j(f.name)}catch(u){N.error(u.message||"failed to remove override")}},ue=async n=>{if(!(!f||!w)){k(!0);try{n.model==="inherit"&&n.effort==="inherit"?(await window.api.agents.removeOverride({name:f.name,projectName:w}),N.info(`cleared ${w}'s override of ${f.name}`)):(await window.api.agents.savePersona({name:f.name,projectName:w,description:"",tools:[],color:"",tags:[],body:"",model:n.model,effort:n.effort}),N.info(`saved ${w}'s override of ${f.name}`)),await j(f.name)}catch(u){N.error(u.message||"failed to save project override")}finally{k(!1)}}};return e.jsx(te,{toolbar:e.jsxs(e.Fragment,{children:[O,e.jsxs("span",{className:"text-fg-faint",children:[a.length," persona",a.length===1?"":"s"]}),e.jsx("input",{value:o,onChange:n=>p(n.target.value),placeholder:"filter…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-40"}),e.jsx("div",{className:"flex-1"}),e.jsx(R,{variant:"primary",onClick:ce,children:"+ New agent"})]}),children:e.jsx(ne,{sidebar:e.jsxs("div",{className:"py-1",children:[m&&e.jsx("div",{className:"w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 bg-bg-hi text-fg border-l-2 border-accent",children:e.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[e.jsx("span",{className:"truncate font-mono",children:x==null?void 0:x.name}),e.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"new"})]})}),B.length===0&&!m?e.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no agent personas found"}):B.map(n=>{const u=!m&&n.name===l,T=u&&M,be=g===n.name;return e.jsxs("div",{"data-agent-row":n.name,className:`group w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 border-l-2 cursor-pointer ${u?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,onClick:()=>I(n.name),children:[e.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{background:n.color?re[n.color]??n.color:"var(--fg-faint, #999)",opacity:n.color?1:.35}}),e.jsx("span",{className:"truncate font-mono",children:n.name})]}),e.jsxs("span",{className:"shrink-0 flex items-center gap-1.5",children:[T&&e.jsx("span",{className:"text-[10px] font-semibold text-accent",children:"unsaved"}),!T&&n.overridingProjects.length>0&&e.jsx("span",{title:Me(n),children:e.jsxs(V,{tone:"dim",children:[n.overridingProjects.length," override",n.overridingProjects.length>1?"s":""]})}),be?e.jsxs("span",{className:"flex items-center gap-1",onClick:W=>W.stopPropagation(),children:[e.jsx("button",{onClick:()=>he(n.name),disabled:L,title:`Delete ${n.name}`,className:"text-[10px] font-semibold text-red-400 hover:text-red-300",children:"confirm"}),e.jsx("button",{onClick:()=>C(null),title:"Cancel",className:"text-[10px] text-fg-faint hover:text-fg",children:"cancel"})]}):e.jsx("button",{onClick:W=>{W.stopPropagation(),C(n.name)},title:`Delete ${n.name}`,className:"opacity-0 group-hover:opacity-100 text-fg-faint hover:text-red-400 transition-opacity",children:"×"})]})]}),n.description&&e.jsx("span",{className:"truncate text-fg-faint",children:n.description})]},n.name)})]}),detail:x?e.jsx(Ie,{obj:x,set:de,saved:f,dirty:M,isNew:m,busy:L,confirmDelete:$,setConfirmDelete:S,onDuplicate:fe,onRevert:xe,onSave:me,onDelete:ge,onDropOverride:pe,activeProject:w,activeCwd:i,onSaveOverride:ue}):e.jsx(K,{title:"select an agent"})})})}const qe=y.memo(Ve);function Ie({obj:t,set:s,saved:a,dirty:d,isNew:l,busy:r,confirmDelete:o,setConfirmDelete:p,onDuplicate:b,onRevert:c,onSave:v,onDelete:h,onDropOverride:$,activeProject:S,activeCwd:g,onSaveOverride:C}){const L=X(),k=!l&&a?a.path:`${L??"~"}/.claude/agents/${t.name}.md`,E=d||l;return e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-line flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-semibold text-fg font-mono",children:t.name}),l?e.jsx(V,{tone:"accent",children:"unsaved draft"}):d?e.jsx(V,{tone:"warn",children:"edited"}):e.jsx(V,{tone:"good",children:"saved"}),e.jsx("span",{className:"ml-auto min-w-0",children:e.jsx(se,{path:k})})]}),e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsx(D,{label:"name",hint:"Filename on disk — lowercase, hyphenated.",children:e.jsx("input",{value:t.name,onChange:i=>s({name:i.target.value.toLowerCase()}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg font-mono"})}),e.jsx(D,{label:"description",hint:"Shown in the list and in agent pickers.",children:e.jsx("input",{value:t.description,onChange:i=>s({description:i.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg"})}),e.jsx(ie,{value:t.model,onChange:i=>s({model:i})}),e.jsx(le,{value:t.effort,model:t.model,onChange:i=>s({effort:i})}),!l&&a&&e.jsx(We,{saved:a,activeProject:S,activeCwd:g,busy:r,onSave:C}),e.jsx(D,{label:"tools",hint:`${t.tools.length} of ${H.length} granted. Anything not ticked is refused at call time.`,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:H.map(i=>{const w=t.tools.includes(i);return e.jsx("button",{onClick:()=>s({tools:w?t.tools.filter(j=>j!==i):[...t.tools,i]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${w?"bg-sage/15 text-sage-dark border-sage/30":"bg-bg-hi text-fg-faint border-line"}`,children:i},i)})})}),e.jsx(D,{label:"color",children:e.jsx("div",{className:"flex gap-1.5",children:Be.map(i=>e.jsx("button",{title:i||"none",onClick:()=>s({color:i}),className:"w-5 h-5 rounded",style:{background:i?re[i]:"transparent",border:t.color===i?"2px solid var(--accent, #b85c34)":"1px solid var(--line, #555)"}},i||"none"))})}),e.jsx(D,{label:"tags",hint:"Session mission tags this persona is associated with — shown as the default agent on the Tags tab.",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(i=>{const w=t.tags.includes(i.tag),j=z(i.tag);return e.jsxs("button",{onClick:()=>s({tags:w?t.tags.filter(O=>O!==i.tag):[...t.tags,i.tag]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${w?`${j.bg} ${j.text} ${j.border?"border-current/30":"border-transparent"}`:"bg-bg-hi text-fg-faint border-line"}`,children:["#",i.tag]},i.tag)})})}),e.jsx(D,{label:"definition",hint:"The system prompt this persona runs under.",children:e.jsx("textarea",{rows:9,value:t.body,onChange:i=>s({body:i.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono leading-relaxed resize-y"})}),e.jsx(D,{label:"project overrides",hint:"Open projects that shadow this definition with a local copy.",children:a&&a.overridingProjects.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.overridingProjects.map(i=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[i,e.jsx("button",{onClick:()=>$(i),title:"Drop the local copy",className:"text-fg-faint hover:text-fg",children:"×"})]},i))}):e.jsx("div",{className:"text-xs text-fg-faint italic",children:l?"save first to see project overrides.":"no open project overlays this agent — the global definition applies everywhere."})})]}),e.jsx("div",{className:"px-4 py-2.5 border-t border-line flex items-center gap-2 flex-wrap",children:o?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-xs text-fg-dim",children:["Delete ",e.jsx("strong",{className:"font-mono",children:t.name})," and its file?"]}),e.jsx(R,{variant:"danger",onClick:h,disabled:r,children:"Delete"}),e.jsx(R,{onClick:()=>p(!1),children:"Keep"})]}):e.jsxs(e.Fragment,{children:[e.jsx(R,{onClick:b,disabled:r,children:"Duplicate"}),!l&&e.jsx(R,{variant:"danger",onClick:()=>p(!0),disabled:r,children:"Delete"}),e.jsx("div",{className:"flex-1"}),E&&e.jsx("span",{className:"text-[11px] text-fg-faint",children:"unsaved changes"}),e.jsx(R,{onClick:c,disabled:!E||r,children:"Revert"}),e.jsx(R,{variant:"primary",onClick:v,disabled:!E||r,children:r?"Saving…":l?"Create":"Save"})]})})]})}function D({label:t,hint:s,children:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:t}),a,s&&e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:s})]})}const G="latest",U="Blocked by the availableModels allowlist in your Claude settings";function ie({value:t,onChange:s,label:a="default model",hint:d,testIdPrefix:l="",inheritLabel:r}){var x,M;const{catalog:o,loading:p,degraded:b,refresh:c}=ee(null),v=o?["inherit",...o.aliases]:[...ye],h=(o==null?void 0:o.availableModels)??null,$=m=>!!h&&m!=="inherit"&&!h.includes(m),S=(m,I)=>!!h&&!h.includes(m)&&!(I&&h.includes(I)),g=t||"inherit",C=((x=/\[[^\]]*\]$/.exec(g))==null?void 0:x[0])??"",L=v.includes(g),k=!L&&o&&A(g)&&v.includes(A(g)+C)?A(g)+C:null,E=L?g:k??g,i=A(E),w=((M=/\[[^\]]*\]$/.exec(E))==null?void 0:M[0])??"",j=!!o&&g!=="inherit"&&!!i&&v.includes(E),O=j?o.models.filter(m=>A(m)===i).map(m=>m+w):[],F=L?G:g,B={};if(o)for(const m of v)$(m)&&(B[m]=U);const f={};for(const m of O)S(m,i)&&(f[m]=U);return e.jsxs(D,{label:a,hint:d??"This persona's default model for its Epics — sets the --model an Epic launches with (Terminal + Chat both honor it). 'inherit' falls back to each view's own default, not this Settings page. Cheap models for read-only personas; opus for judgement calls.",children:[e.jsx("div",{"data-testid":`${l}model-row`,children:e.jsx(Y,{options:v,value:E,onChange:s,mono:!0,blocked:B,labels:r?{inherit:r}:void 0})}),j&&e.jsxs("div",{className:"mt-2","data-testid":`${l}model-version-row`,children:[e.jsx("div",{className:"text-[10.5px] text-fg-faint mb-1 font-mono",children:"version"}),e.jsx(Y,{options:[G,...O],value:F,onChange:m=>s(m===G?E:m),mono:!0,blocked:f})]}),e.jsxs("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug flex items-center gap-2",children:[e.jsx("span",{children:o?`Models are live-read from the installed claude CLI${b?" (cached — CLI probe unavailable)":""}. "latest" keeps the floating alias.`:p?"Loading model catalog…":"catalog unavailable — showing the standard list."}),e.jsx("button",{"data-testid":`${l}model-catalog-refresh`,onClick:()=>{c()},disabled:p,className:"underline text-fg-dim disabled:opacity-40",children:"refresh"})]})]})}function le({value:t,model:s,onChange:a,label:d="effort",testIdPrefix:l="",inheritLabel:r}){const{catalog:o}=ee(null),p=o&&o.effortLevels.length?["inherit",...o.effortLevels]:[...$e],b=(o==null?void 0:o.settingsEffortLevels)??[],c=o?p.filter($=>$!=="inherit"&&!b.includes($)):[],v=t||"inherit",h=v!=="inherit"&&Fe(s)===!1;return e.jsxs(D,{label:d,hint:o?`Effort levels are live-read from the installed claude CLI (what /effort accepts). ${c.length?`${c.join(", ")} ${c.length>1?"are":"is"} session-only — settings.json accepts ${b.join(", ")}. `:""}'inherit' writes no effort: line.`:"catalog unavailable — showing the standard list. 'inherit' writes no effort: line.",children:[e.jsx("div",{"data-testid":`${l}effort-row`,children:e.jsx(Y,{options:p,value:v,onChange:a,mono:!0,labels:r?{inherit:r}:void 0})}),c.length>0&&e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 font-mono","data-testid":`${l}effort-session-only`,children:c.map($=>`${$} (session-only)`).join(" · ")}),h&&e.jsx("div",{className:"text-[11px] text-amber-400 mt-1 leading-snug","data-testid":`${l}effort-unsupported-note`,children:"The selected model does not support effort — the CLI will ignore this setting."})]})}function We({saved:t,activeProject:s,activeCwd:a,busy:d,onSave:l}){var h,$,S;if(!s)return e.jsxs("div",{"data-testid":"project-override-none",className:"border border-dashed border-line rounded p-3 text-[11px] text-fg-faint",children:[e.jsx("div",{className:"text-[10.5px] font-semibold uppercase tracking-wide mb-1 font-mono",children:"project override"}),"No active project — open a project tab to override this persona's model or effort for that project only."]});const r=(h=t.overrideDetails)==null?void 0:h.find(g=>g.project===s),o=!!(r!=null&&r.bodyOverridden),p=(($=r==null?void 0:r.values)==null?void 0:$.model)??"inherit",b=((S=r==null?void 0:r.values)==null?void 0:S.effort)??"inherit",c=t.model??"inherit",v=t.effort??"inherit";return e.jsxs("div",{"data-testid":"project-override",className:"border border-accent/40 rounded p-3 space-y-3 bg-accent/5",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-accent font-mono",children:"project override"}),e.jsxs(V,{tone:"accent",children:[s," only"]}),e.jsx("span",{className:"ml-auto min-w-0",children:e.jsx(se,{path:`${(a??"").replace(/\/+$/,"")}/.claude/agents/${t.name}.md`})})]}),e.jsxs("div",{className:"text-[11px] text-fg-faint leading-snug",children:["Changes what the SCHEDULER (and new Epics) spawn for ",e.jsx("strong",{children:s})," only — a frontmatter-only overlay with just the keys you set; the persona's body stays the global one. The global model/effort rows edit the machine-wide persona and are never touched here."]}),o&&e.jsxs("div",{"data-testid":"project-override-fullbody",className:"text-[11px] text-amber-400 leading-snug",children:[s,' already has a FULL-BODY override of this persona (its own definition text). It is shown as-is and not converted to a frontmatter-only overlay — edit that file directly, or drop it with × under "project overrides" below.']}),e.jsxs("fieldset",{disabled:d||o,className:"space-y-3 border-0 p-0 m-0 min-w-0",children:[e.jsx(ie,{value:p,onChange:g=>{o||l({model:g,effort:b})},label:"project model",hint:"'use global' writes no model: line in the overlay.",testIdPrefix:"override-",inheritLabel:"use global"}),e.jsx(le,{value:b,model:p!=="inherit"?p:c,onChange:g=>{o||l({model:p,effort:g})},label:"project effort",testIdPrefix:"override-",inheritLabel:"use global"})]}),e.jsx("div",{"data-testid":"override-provenance",className:"text-[11px] font-mono text-fg-dim space-y-0.5",children:[["model",c,p],["effort",v,b]].map(([g,C,L])=>e.jsxs("div",{"data-testid":`override-provenance-${g}`,children:[g,": ",L!=="inherit"?e.jsxs(e.Fragment,{children:[C," ",e.jsx("span",{className:"text-fg-faint",children:"(global)"})," → ",e.jsx("span",{className:"text-accent",children:L})," ",e.jsx("span",{className:"text-fg-faint",children:"(this project)"})]}):e.jsxs(e.Fragment,{children:[C," ",e.jsx("span",{className:"text-fg-faint",children:"(global — not overridden)"})]})]},g))})]})}export{qe as AgentLibrary};