pi-odd-worktree 3.7.1 → 3.8.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.
@@ -22,10 +22,9 @@ const nodeOs = require('node:os');
22
22
  const nodePath = require('node:path');
23
23
 
24
24
  const index = require('./codegraph-index.js');
25
- const { createCodegraphCardResolver } = require('./codegraph-card.js');
25
+ const { createCodegraphGuard } = require('./codegraph-guard.js');
26
26
  const { compactionSync } = require('./codegraph-compaction.js');
27
27
  const { createEditSync } = require('./codegraph-edit-sync.js');
28
- const { createCodegraphGuard } = require('./codegraph-guard.js');
29
28
  const { liveDaemon } = require('./codegraph-daemon.js');
30
29
  const { ensureCodegraphServer } = require('./codegraph-mcp-config.js');
31
30
  const { sessionIndexRole } = require('./codegraph-role.js');
@@ -119,7 +118,6 @@ function registerCodegraph(pi, deps = {}) {
119
118
  createEditSync,
120
119
  createCodegraphGuard,
121
120
  warmUpDaemon,
122
- createCodegraphCardResolver,
123
121
  ...(deps.impl || {}),
124
122
  };
125
123
  if (typeof pi?.on !== 'function') return { registered: false };
@@ -128,9 +126,6 @@ function registerCodegraph(pi, deps = {}) {
128
126
  const child = env.GENTLE_PI_AGENTS_CHILD === '1';
129
127
  const role = sessionIndexRole(env);
130
128
  const registryDir = deps.registryDir;
131
- // S6: the card's cwd seam reads the session this wiring belongs to; unknown until
132
- // the host names it at session_start, and then the segment is shown, not guessed.
133
- let sessionDir;
134
129
  let mcpChecked = false;
135
130
  // S2: the index writes this process already asked for, per checkout. Registering one here is what lets a
136
131
  // search join it; nothing in this map starts work of its own.
@@ -140,17 +135,9 @@ function registerCodegraph(pi, deps = {}) {
140
135
  if (timer && typeof timer.unref === 'function') timer.unref();
141
136
  });
142
137
 
143
- // The CodeGraph card goes through the host's renderer hook, looked up when it is used: an older host without it draws
144
- // nothing of ours and loses nothing. No tool, command or execution is registered by it.
145
- try {
146
- impl.createCodegraphCardResolver({
147
- metrics: deps.metrics || (() => null),
148
- cwd: () => sessionDir,
149
- registerToolRenderer: (resolver) => (typeof pi.registerToolRenderer === 'function' ? pi.registerToolRenderer(resolver) : undefined),
150
- });
151
- } catch {
152
- // The card is cosmetic.
153
- }
138
+ // The CodeGraph CARD is not registered here (modular-tools S11): it is a design, so its switch is
139
+ // the bridge's `Card activity` line and the extension registers it beside the file and jobs cards,
140
+ // outside this module. What CodeGraph does is never decided by what is drawn.
154
141
 
155
142
  // The two reminders own their own state: a compaction, a `/warp` and a new session are its facts to keep.
156
143
  const guards = impl.createCodegraphGuard({ env, argv: deps.argv, toplevel: deps.toplevel, isDirectory: deps.isDirectory });
@@ -254,12 +241,6 @@ function registerCodegraph(pi, deps = {}) {
254
241
  }
255
242
 
256
243
  pi.on('session_start', (event, ctx) => {
257
- try {
258
- // The card names the explored checkout against the session's own directory.
259
- sessionDir = sessionCwd(event, ctx);
260
- } catch {
261
- // An unknown cwd only means the explicit projectPath is shown.
262
- }
263
244
  try {
264
245
  // A new, resumed or forked session is a new session; a `/reload` keeps this one and what it was told.
265
246
  if (!event || event.reason !== 'reload') guards.onNewSession();
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // ONE line, `diff`, covers the two tools that change a file. `/gentle:customize` -> `Cards` draws
12
12
  // it as `Card diff`, keeps the host's own card first as `default` (stored `native`) and shows this
13
- // design's value as `color`. The line is UNSCOPED: the path scope belongs to the `Card tags`
13
+ // design's value as `color`. The line is UNSCOPED: the path scope belongs to the `Card activity`
14
14
  // line's own claim on the same two tools (gentle-shell-bridge 0.9.0 maps a scope to ONE
15
15
  // (`line`, `tool`) claim, so one unscoped claim and any number of scoped ones coexist), and a call
16
16
  // that line owns is painted by it before this one is asked.
@@ -434,6 +434,10 @@ const LEADING_CHROME = new Set([' ', '│', '▎', '|', '┃', '║']);
434
434
  // The closing run is dropped only while it CLEARS a state, because a frame cell's own paint starts
435
435
  // there too (`\u001b[32m│`) and is the host's to keep.
436
436
  const TRAILING_SGR = /(?:\u001b\[[0-9;]*m)+$/u;
437
+ // A row whose first cell is the host's frame rule, and the skip marker the host draws between hunks:
438
+ // neither is the rest of a wrapped diff line.
439
+ const WRAP_BREAK_CELLS = new Set(['╭', '╰', '╮', '╯', '─']);
440
+ const SKIP_MARKER = /^\.\.\./u;
437
441
  const SGR_CLEARS = new Set(['0', '22', '23', '24', '25', '27', '28', '29', '39', '49', '55', '59']);
438
442
 
439
443
  /** Whether one SGR escape CLEARS a state rather than opening one. */
@@ -547,11 +551,14 @@ function recolourDiffRow(row, spec) {
547
551
  const paintedCode = code === '' ? '' : highlightRow(code, 'muted', spec.language, spec.seam, spec.theme);
548
552
  return `${before}${paint(spec.theme, 'muted', token)}${paintedCode}${after}`;
549
553
  }
550
- const match = ADDED.exec(rest) ?? REMOVED.exec(rest) ?? CONTEXT.exec(rest);
554
+ // The number's trailing space is the row's padding when the row states no code of its own (the host
555
+ // flushed it before a word wider than the row), so the row is read with that space restored.
556
+ const probe = `${rest} `;
557
+ const match = ADDED.exec(probe) ?? REMOVED.exec(probe) ?? CONTEXT.exec(probe);
551
558
  if (match === null) return row;
552
559
  // `undefined` marks a context row, whose marker is a space and already part of the row's chrome.
553
- const added = ADDED.test(rest);
554
- const role = added ? 'toolDiffAdded' : REMOVED.test(rest) ? 'toolDiffRemoved' : undefined;
560
+ const added = ADDED.test(probe);
561
+ const role = added ? 'toolDiffAdded' : REMOVED.test(probe) ? 'toolDiffRemoved' : undefined;
555
562
  const gutter = role === undefined ? match[1] : `${rest[0]}${match[1]}`;
556
563
  const head = `${gutter}${DIVIDER_RUN}`;
557
564
  const headColumns = textColumns(head);
@@ -564,8 +571,14 @@ function recolourDiffRow(row, spec) {
564
571
  // A row this design already divided wears the rule right after its number: read it back, so the
565
572
  // second pass rebuilds the same row instead of adding a second divider (S14).
566
573
  const code = tailText.startsWith(DIVIDER_TAIL) ? tailText.slice(DIVIDER_TAIL.length) : tailText;
567
- const clipped = headColumns + textColumns(code) > room;
568
- const shown = clipped ? clipPlain(code, room - headColumns) : code;
574
+ // S15: a line the host wrapped states the rest of it on rows this design drops. The row is drawn
575
+ // from the WHOLE line, so it fills its width like the write pane's and ends in the ellipsis that
576
+ // pane writes for a line that did not fit.
577
+ const whole = joinWrapped(code, rest, spec.rest ?? [], room);
578
+ const base = whole;
579
+ const overflow = headColumns + textColumns(base) > room;
580
+ const clipped = overflow;
581
+ const shown = overflow ? clipPlain(base, room - headColumns) : base;
569
582
  let body;
570
583
  if (role !== undefined) {
571
584
  body = paint(spec.theme, role, `${head}${shown}`);
@@ -593,17 +606,179 @@ function highlightRow(code, fallback, language, seam, theme) {
593
606
  return paint(theme, fallback === 'muted' ? 'text' : fallback, code);
594
607
  }
595
608
 
609
+ /** Whether a row states a numbered diff line (a hunk header and a skip marker state none). */
610
+ function statesLine(row) {
611
+ const chars = visibleChars(row);
612
+ const start = diffStart(chars);
613
+ if (start < 0) return false;
614
+ const rest = chars.slice(start).map((entry) => entry.char).join('');
615
+ return !HUNK.test(rest) && (ADDED.test(rest) || REMOVED.test(rest) || CONTEXT.test(rest));
616
+ }
617
+
618
+ /**
619
+ * Whether a row is the REST of a diff line the host wrapped: text with no number, at the row's own
620
+ * left column. A blank band row, a frame rule, a skip marker and the host's expand hint are the
621
+ * host's own rows and never the rest of a line.
622
+ */
623
+ function wrappedRest(row) {
624
+ if (typeof row !== 'string' || statesLine(row)) return undefined;
625
+ const chars = visibleChars(row);
626
+ const first = chars.findIndex((entry) => !LEADING_CHROME.has(entry.char));
627
+ const last = contentLast(chars);
628
+ if (first < 0 || last < first) return undefined;
629
+ if (WRAP_BREAK_CELLS.has(chars[first].char)) return undefined;
630
+ const text = chars.slice(first, last + 1).map((entry) => entry.char).join('');
631
+ return HUNK.test(text) || SKIP_MARKER.test(text) || EXPAND_HINT.test(plainOf(row)) ? undefined : text;
632
+ }
633
+
634
+ /**
635
+ * The code of a wrapped diff line put back together: the numbered row's code and the rows the host
636
+ * wrapped it onto. The host broke each row at a space it then ate, or — for a word longer than the
637
+ * width — through the word, which leaves the row FULL and with no space to break at. `room` is the
638
+ * width the host wrapped at.
639
+ */
640
+ function joinWrapped(code, rowText, rest, room) {
641
+ let whole = code;
642
+ let previous = rowText;
643
+ let previousCode = code;
644
+ for (const piece of rest) {
645
+ const hardBreak = textColumns(previous) >= room && !previousCode.trim().includes(' ');
646
+ // A numbered row with no code of its own (the host flushed it before a word wider than the row)
647
+ // has nothing to separate the rest from.
648
+ whole += `${hardBreak || whole === '' ? '' : ' '}${piece}`;
649
+ previous = piece;
650
+ previousCode = piece;
651
+ }
652
+ return whole;
653
+ }
654
+
655
+ // ---- the edit heading: what the call changed ----
656
+
657
+ // The heading the host draws for an `edit`: its frame cells, an optional icon, the tool and the path.
658
+ const EDIT_HEADING = /^[╭─\s▎│]*(?:✎\s*)?edit\s+\S+/u;
659
+ // The most cells the line comparison may fill; a bigger block is counted without one.
660
+ const MAX_DIFF_CELLS = 4_000_000;
661
+
662
+ function textLines(text) {
663
+ return text === '' ? [] : text.split('\n');
664
+ }
665
+
666
+ /** How many lines of `before` a change to `after` deletes and adds, by the longest common subsequence. */
667
+ function lineDelta(before, after) {
668
+ const a = textLines(before);
669
+ const b = textLines(after);
670
+ let head = 0;
671
+ while (head < a.length && head < b.length && a[head] === b[head]) head += 1;
672
+ let tail = 0;
673
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1;
674
+ const left = a.slice(head, a.length - tail);
675
+ const right = b.slice(head, b.length - tail);
676
+ if (left.length === 0 || right.length === 0 || left.length * right.length > MAX_DIFF_CELLS) {
677
+ return { added: right.length, removed: left.length };
678
+ }
679
+ let previous = new Array(right.length + 1).fill(0);
680
+ for (let i = 1; i <= left.length; i += 1) {
681
+ const current = new Array(right.length + 1).fill(0);
682
+ for (let j = 1; j <= right.length; j += 1) {
683
+ current[j] = left[i - 1] === right[j - 1] ? previous[j - 1] + 1 : Math.max(previous[j], current[j - 1]);
684
+ }
685
+ previous = current;
686
+ }
687
+ const common = previous[right.length];
688
+ return { added: right.length - common, removed: left.length - common };
689
+ }
690
+
691
+ /** The `(+added · -removed)` an edit call states, or `undefined` when it changes no line. A zero is not written. */
692
+ function changeCount(args) {
693
+ if (args === null || typeof args !== 'object') return undefined;
694
+ const edits = Array.isArray(args.edits) ? [...args.edits] : [];
695
+ if (typeof args.oldText === 'string' && typeof args.newText === 'string') edits.push(args);
696
+ let added = 0;
697
+ let removed = 0;
698
+ for (const entry of edits) {
699
+ if (entry === null || typeof entry !== 'object') continue;
700
+ if (typeof entry.oldText !== 'string' || typeof entry.newText !== 'string') continue;
701
+ const delta = lineDelta(entry.oldText, entry.newText);
702
+ added += delta.added;
703
+ removed += delta.removed;
704
+ }
705
+ const parts = [added > 0 ? `+${added}` : '', removed > 0 ? `-${removed}` : ''].filter((part) => part !== '');
706
+ return parts.length === 0 ? undefined : `(${parts.join(' · ')})`;
707
+ }
708
+
709
+ /** The SGR escapes in force at the end of `text`: every one since the last full reset. */
710
+ function sgrInForce(text) {
711
+ let state = [];
712
+ for (const escape of text.matchAll(/\u001b\[([0-9;]*)m/gu)) {
713
+ if (escape[1] === '' || escape[1] === '0') state = [];
714
+ else state.push(escape[0]);
715
+ }
716
+ return state.join('');
717
+ }
718
+
719
+ /**
720
+ * The host's heading row with `count` written after the path, in the `muted` role. The columns come
721
+ * out of the rule (or the padding) that follows the path, so the row keeps its width and the frame
722
+ * does not move; a heading with no room for it, or whose filler carries a paint of its own, is the
723
+ * host's. A heading that already wears a count has no filler right after its path, so it is a no-op.
724
+ */
725
+ function headingWithCount(row, count, theme) {
726
+ const chars = visibleChars(row);
727
+ const matched = EDIT_HEADING.exec(chars.map((entry) => entry.char).join(''));
728
+ if (matched === null) return row;
729
+ const end = Array.from(matched[0]).length;
730
+ let filler = 0;
731
+ while (end + filler < chars.length && (chars[end + filler].char === ' ' || chars[end + filler].char === '─')) filler += 1;
732
+ const need = textColumns(count) + 1;
733
+ if (chars[end]?.char !== ' ' || filler < need + 3) return row;
734
+ const from = chars[end + 1].raw;
735
+ const to = chars[end + 1 + need].raw;
736
+ if (row.slice(from, to).includes('\u001b')) return row;
737
+ const at = chars[end].raw;
738
+ const before = row.slice(0, at);
739
+ return `${before} ${paint(theme, 'muted', count)}${sgrInForce(before)}${row.slice(at, from)}${row.slice(to)}`;
740
+ }
741
+
596
742
  /**
597
743
  * Every row of an `edit` card, recoloured and divided. Idempotent (S8b/S14): each row is read as its
598
744
  * PLAIN text and rebuilt from it, divider included, so a row already wearing this drawing states the
599
745
  * same visible characters and comes back byte for byte — never with a second copy of an escape, a
600
746
  * reset or the divider.
747
+ *
748
+ * S15: the host wraps a long diff line onto rows that carry no number and no gutter, which would
749
+ * draw at the frame's left column with no divider. This design draws ONE row per line, like the
750
+ * write pane: the rows after a numbered one that are the rest of its line are dropped, and that row
751
+ * ends in `…`. A row that fit is never marked.
601
752
  */
602
753
  function editRows(lines, render, ctx, seam) {
603
754
  const language = languageOf(callPath(render?.args), seam);
604
- return lines.map((row) => (typeof row === 'string'
605
- ? recolourDiffRow(row, { theme: ctx.theme, language, seam })
606
- : String(row)));
755
+ const count = render?.isError === true ? undefined : changeCount(render?.args);
756
+ let headed = count === undefined;
757
+ const out = [];
758
+ let index = 0;
759
+ while (index < lines.length) {
760
+ const row = lines[index];
761
+ index += 1;
762
+ if (typeof row !== 'string') {
763
+ out.push(String(row));
764
+ continue;
765
+ }
766
+ if (!headed && statesLine(row)) headed = true;
767
+ if (!headed && EDIT_HEADING.test(plainOf(row))) {
768
+ headed = true;
769
+ out.push(headingWithCount(row, count, ctx.theme));
770
+ continue;
771
+ }
772
+ const rest = [];
773
+ if (render?.isError !== true && statesLine(row)) {
774
+ while (index < lines.length && wrappedRest(lines[index]) !== undefined) {
775
+ rest.push(wrappedRest(lines[index]));
776
+ index += 1;
777
+ }
778
+ }
779
+ out.push(recolourDiffRow(row, { theme: ctx.theme, language, seam, rest }));
780
+ }
781
+ return out;
607
782
  }
608
783
 
609
784
  // ---- the design's entry point ----
@@ -656,8 +831,11 @@ function applyDiffDesign(lines, ctx, seam) {
656
831
 
657
832
  // The read-only picture `/gentle:customize` draws while `color` is highlighted. ONE row, like every
658
833
  // other Cards value: the gutter, a diff's two kinds and a hunk header on a single line.
834
+ // S4 (modular-tools): the preview's TITLE is the line's own name — what the bridge shows for the
835
+ // `default` value — so both options of `Card diff` read as one line and only the SAMPLE tells them
836
+ // apart. The bridge derives the row from the line key (`Card <line>`), and so does this title.
659
837
  const DIFF_DESIGN_PREVIEW = {
660
- title: `Cards · ${DIFF_DESIGN_LABEL}`,
838
+ title: `Cards · Card ${LINE_NAME}`,
661
839
  sample: ' 12 │ const total = items.length + 3 added − 1 removed @@ -1,4 +1,4 @@',
662
840
  };
663
841
 
@@ -13,7 +13,7 @@
13
13
  // * WHICH ROWS IT CLAIMS. `read`, `edit` and `write` only, and only when the host
14
14
  // offers a usable measurement seam. Whether one particular CALL is this card's is
15
15
  // decided per call, inside the slots (`lib/file-card.js`): the path's identity and
16
- // the bridge's `Card tags` line are read on every paint, so a row whose path names
16
+ // the bridge's `Card activity` line are read on every paint, so a row whose path names
17
17
  // neither is the chain's own drawing and a switch flipped while the transcript is
18
18
  // on screen repaints the row already there.
19
19
  // * THE SEAMS. Text measurement and Pi's Markdown renderer are injected, so a host
@@ -38,7 +38,7 @@ const { loadMarkdownClass } = require('./file-card-markdown.js');
38
38
  // ---- the one switch (S1/S7) ----
39
39
  //
40
40
  // The file card no longer owns a preference: it is painted while the bridge's
41
- // `Card tags` line answers that this package's activity design draws the tool being
41
+ // `Card activity` line answers that this package's activity design draws the tool being
42
42
  // drawn, and the host's own card is painted for every other value (the bridge's
43
43
  // `native`, a design that has left the line, and a design that does not cover this
44
44
  // tool alike).
@@ -161,7 +161,7 @@ function createFileCardResolver(options) {
161
161
  }
162
162
  },
163
163
  /**
164
- * The one switch, read now (S1/S7): the bridge's `Card tags` line answers with the
164
+ * The one switch, read now (S1/S7): the bridge's `Card activity` line answers with the
165
165
  * activity design for `tool` — and, since a claim can be scoped, for THIS call: the
166
166
  * call's `args` are handed over with the question (S4). A bridge with no reader —
167
167
  * older than 0.7.0, or none at all — paints the card, which is the behaviour it had
package/lib/file-card.js CHANGED
@@ -536,7 +536,7 @@ function fileResultRows(input) {
536
536
  /**
537
537
  * The call slot. The identity and the ONE switch are both decided INSIDE the
538
538
  * component's build, so the host's `render(width)` re-reads them on every frame: a card
539
- * already on screen repaints when the bridge's `Card tags` line changes (L6), and the
539
+ * already on screen repaints when the bridge's `Card activity` line changes (L6), and the
540
540
  * measurement seam is asked for at paint time rather than at construction.
541
541
  *
542
542
  * A path that names neither identity returns the chain's own component straight away,
@@ -15,7 +15,7 @@
15
15
  // activity design hands back exactly what the chain resolved, and Pi draws what it always drew.
16
16
  // A switch flipped while a card is already on screen reaches the next job card, not that one.
17
17
  //
18
- // THE SWITCH is the bridge's `Card tags` line, read through its published reader, never a
18
+ // THE SWITCH is the bridge's `Card activity` line, read through its published reader, never a
19
19
  // store path. It is strict: only the answer `design` carrying this package's activity design
20
20
  // paints. No bridge, a bridge older than the reader, a reader that throws, `native`,
21
21
  // `not-covered`, `missing`, another plugin's design and an answer nothing can read all leave
package/lib/jobs-card.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // Gentle Shell registers those four tools with no renderer of their own, so Pi draws its
6
6
  // plain default box and the conversation's card style (neon or float) never reaches them.
7
7
  // This module is the drawing half; `lib/jobs-card-resolver.js` decides WHEN it is used — only
8
- // while the bridge's `Card tags` line answers `activity` for the tool being drawn.
8
+ // while the bridge's `Card activity` line answers `activity` for the tool being drawn.
9
9
  //
10
10
  // It is shaped exactly like `lib/file-card.js` and shares its helpers (tone, expand hint,
11
11
  // theme fallback, result text, the bounded body preview), so the two cards read as one family.
@@ -40,7 +40,7 @@ const { PREVIEW_ROWS, cardTone, component, expandHint, fileResultRows, optionFla
40
40
  // The one reader of text as a card draws it: no terminal sequences, however the model wrote it.
41
41
  const { cardText } = require('./codegraph-card-preview.js');
42
42
 
43
- /** The four tools this card owns, in the order the bridge's `Card tags` line declares them. */
43
+ /** The four tools this card owns, in the order the bridge's `Card activity` line declares them. */
44
44
  const JOB_TOOLS = Object.freeze(['bash_background', 'monitor', 'job_stop', 'job_list']);
45
45
 
46
46
  // Each tool's mark, its label, the theme role the heading wears and the role the call's own text
@@ -33,7 +33,7 @@
33
33
  //
34
34
  // THE SWITCH (S1). Both alerts are selected by the SAME value that already draws this package's
35
35
  // tool cards, and this module owns no switch of its own: each design FOLLOWS the tool design line
36
- // this package registers — `follows: { line: TOOLS_LINE, id: BASH_DESIGN_ID }` — so `Card tags`
36
+ // this package registers — `follows: { line: TOOLS_LINE, id: BASH_DESIGN_ID }` — so `Card activity`
37
37
  // answering `activity` is what paints them. The bridge resolves that LIVE on every pass, reading
38
38
  // the tool document and never writing it: a flip on the line repaints a message already on screen
39
39
  // and turns it off again, with no re-registration, no seed and no second store. A following design
@@ -300,7 +300,7 @@ function bridgeTakesFollows(api) {
300
300
 
301
301
  /**
302
302
  * `registerMessageCards({ metrics, theme })` — the extension's one wiring point, shaped like
303
- * `registerJobsCard`. Both designs follow `Card tags` → `activity`, so the human's existing choice
303
+ * `registerJobsCard`. Both designs follow `Card activity` → `activity`, so the human's existing choice
304
304
  * is the switch and the bridge decides per pass; this module registers whenever the bridge can
305
305
  * express that follow, and NOTHING at all on an older one (a bridge that ignores `follows` would
306
306
  * silently create a `Message <type>` switch of its own).
package/lib/modules.js ADDED
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+ // The module switches (modular-tools): which of this package's two optional halves a
3
+ // user wants. `Codegraph+` is everything CodeGraph (the prompt text, the two reminders
4
+ // and the session wiring); `Worktrees+` is everything worktree (the prompt text, the
5
+ // two tools, `/warp` and the guards). Everything else — issues, cards, `/odd`,
6
+ // `/files`, the skill-read guard — is transversal and has no switch here.
7
+ //
8
+ // One persisted document, through the bridge's own store: `odd-worktree` →
9
+ // `modules` → `{ codegraph?: boolean, worktrees?: boolean }`. A module is ON unless its
10
+ // stored value is exactly `false`, so a missing, malformed or unreadable document keeps
11
+ // the package whole. The extension reads it ONCE, when it registers: a change made on
12
+ // the `Tools` page lands on the next load, which is why a change says so.
13
+ //
14
+ // The rows are a plain bridge provider (`registerRows`): two consecutive rows sharing
15
+ // one `choice.setting` make one `Off On` line. Pure over the injected bridge and
16
+ // notifier; nothing here touches the host.
17
+
18
+ const OWN_STORE = 'odd-worktree';
19
+ const MODULES_KEY = 'modules';
20
+ const CATEGORY = 'Tools';
21
+ const PROVIDER_ID = 'odd-worktree.tools';
22
+
23
+ // The two switches, in the order the page lists them. `setting` is the row name the bridge
24
+ // validates (one to three plain words, no structural mark: `+` is allowed).
25
+ const MODULES = Object.freeze([
26
+ Object.freeze({ key: 'codegraph', setting: 'Codegraph+' }),
27
+ Object.freeze({ key: 'worktrees', setting: 'Worktrees+' }),
28
+ ]);
29
+ const VALUES = Object.freeze([
30
+ Object.freeze({ value: 'Off', on: false }),
31
+ Object.freeze({ value: 'On', on: true }),
32
+ ]);
33
+
34
+ function storeOf(api) {
35
+ if (api === null || typeof api !== 'object' || typeof api.createStore !== 'function') return null;
36
+ return api.createStore(OWN_STORE);
37
+ }
38
+
39
+ function storedDocument(store) {
40
+ const stored = store.get(MODULES_KEY, undefined);
41
+ return stored !== null && typeof stored === 'object' && !Array.isArray(stored) ? stored : {};
42
+ }
43
+
44
+ /** `{ codegraph, worktrees }`: ON unless the stored value is exactly `false`. Never throws. */
45
+ function readModules(api) {
46
+ const state = {};
47
+ let stored = {};
48
+ try {
49
+ const store = storeOf(api);
50
+ if (store !== null) stored = storedDocument(store);
51
+ } catch {
52
+ stored = {};
53
+ }
54
+ for (const { key } of MODULES) state[key] = stored[key] !== false;
55
+ return state;
56
+ }
57
+
58
+ /** Persist one switch, keeping the other module and every other key. True when it wrote. Never throws. */
59
+ function writeModule(api, key, on) {
60
+ try {
61
+ if (!MODULES.some((module) => module.key === key)) return false;
62
+ const store = storeOf(api);
63
+ if (store === null) return false;
64
+ store.set(MODULES_KEY, { ...storedDocument(store), [key]: on === true });
65
+ return true;
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ /** The one short line a change says: it lands on the next load, in a NEW session. */
72
+ function restartNotice(setting, value) {
73
+ return `${setting} ${value} · run /reload and start a new session to apply`;
74
+ }
75
+
76
+ /**
77
+ * The bridge provider for the `Tools` page. `notify(text)` carries the restart notice to
78
+ * the session's UI; a change to the value a module already has writes nothing and says
79
+ * nothing, and a store that cannot write says nothing either, so the notice is never
80
+ * promised for a change that was not kept.
81
+ */
82
+ function moduleRowsProvider({ api, notify }) {
83
+ const say = (text) => {
84
+ try {
85
+ if (typeof notify === 'function') notify(text);
86
+ } catch {
87
+ // A dead UI never fails the row.
88
+ }
89
+ };
90
+ return {
91
+ id: PROVIDER_ID,
92
+ category: CATEGORY,
93
+ rows() {
94
+ const rows = [];
95
+ for (const { key, setting } of MODULES) {
96
+ for (const { value, on } of VALUES) {
97
+ rows.push({
98
+ category: CATEGORY,
99
+ label: () => setting,
100
+ choice: {
101
+ setting,
102
+ value,
103
+ current: () => readModules(api)[key] === on,
104
+ },
105
+ action: () => {
106
+ if (readModules(api)[key] === on) return;
107
+ if (writeModule(api, key, on)) say(restartNotice(setting, value));
108
+ },
109
+ });
110
+ }
111
+ }
112
+ return rows;
113
+ },
114
+ };
115
+ }
116
+
117
+ module.exports = {
118
+ MODULES,
119
+ CATEGORY,
120
+ PROVIDER_ID,
121
+ readModules,
122
+ writeModule,
123
+ restartNotice,
124
+ moduleRowsProvider,
125
+ };
@@ -1,43 +1,31 @@
1
1
  'use strict';
2
- // The `## ODD worktrees` section of the primary session's system prompt (S7), and
3
- // (T3, S5) the one short block a CHILD that writes gets.
2
+ // The `## ODD worktrees` section of the primary session's system prompt (S7).
4
3
  //
5
4
  // It is appended to `systemPromptOptions.appendSystemPrompt` and nowhere else:
6
5
  // a handler-returned `systemPrompt` is dropped by pi-claude-bridge, and
7
6
  // replacing the option would erase the harness's own text. The block is only
8
7
  // ever added after the existing text, is skipped when it is already there, and
9
8
  // reaches a primary session only — a named agent gets the primary text of its
10
- // own session, never this one.
9
+ // own session, never this one, and a `GENTLE_PI_AGENTS_CHILD` session gets none
10
+ // of it: a child works where the primary session's handoff put it (its
11
+ // `workspace_root`), so the rule is the primary session's to apply.
11
12
  //
12
- // S5: a `GENTLE_PI_AGENTS_CHILD` session is not skipped any more. A child that
13
- // WRITES — `gentle-ai-worker`, `jd-fix-agent`, and any child whose agent name the
14
- // argv cannot name, which is the generic child — gets one short line telling it to
15
- // work in its workspace root's worktree and to stop and report on the primary. The
16
- // children that only look or judge (explore, verify, the two judges, every
17
- // `review-*`) get nothing, exactly as before. The agent name comes from
18
- // `lib/codegraph-rules.js` (`agentNameFromArgv`), which already reads it from the
19
- // child's own argv; the argv parsing is never duplicated here.
20
- //
21
- // `ODD_WORKTREE_PROMPT=0` turns both blocks off.
13
+ // `ODD_WORKTREE_PROMPT=0` turns the block off.
22
14
 
23
15
  const fs = require('node:fs');
24
16
  const path = require('node:path');
25
- const { agentNameFromArgv, variantFor } = require('./codegraph-rules.js');
26
17
 
27
18
  // The heading is the identity of the block, so an already-injected section is
28
19
  // never added twice.
29
20
  const SECTION_MARKER = '## ODD worktrees';
30
21
 
31
22
  // The section text lives in its own Markdown file so it can be read, reviewed
32
- // and edited as prose: `lib/odd-prompt/odd-worktrees.md`, and — one short line for a
33
- // child that writes — `lib/odd-prompt/odd-worktrees-child.md`. A missing or empty
23
+ // and edited as prose: `lib/odd-prompt/odd-worktrees.md`. A missing or empty
34
24
  // file falls back to the heading alone: the block still injects, never crashes the
35
25
  // session, and the idempotency marker still works.
36
26
  const PROMPT_DIR = path.join(__dirname, 'odd-prompt');
37
27
  const PROMPT_FILE = path.join(PROMPT_DIR, 'odd-worktrees.md');
38
- const CHILD_PROMPT_FILE = path.join(PROMPT_DIR, 'odd-worktrees-child.md');
39
28
  const FALLBACK = `${SECTION_MARKER}\n\nEach ODD feature has its own worktree.`;
40
- const CHILD_FALLBACK = `${SECTION_MARKER}\n`;
41
29
 
42
30
  function readPromptFile(file) {
43
31
  try {
@@ -54,25 +42,6 @@ function sectionFromFile(file, fallback) {
54
42
  }
55
43
 
56
44
  const SECTION = sectionFromFile(PROMPT_FILE, FALLBACK);
57
- const CHILD_SECTION = sectionFromFile(CHILD_PROMPT_FILE, CHILD_FALLBACK);
58
-
59
- // S5: the children that WRITE, by the name `agentNameFromArgv` reports for them.
60
- const CHILD_WRITER_AGENTS = new Set(['gentle-ai-worker', 'jd-fix-agent']);
61
- const REVIEWER_PREFIX = 'review-';
62
-
63
- /**
64
- * S5: whether this child gets the block. A worker or the fix agent does; a child whose
65
- * name cannot be read is the generic one and does too; a child that only looks or
66
- * judges — explore, verify, the judges, every `review-*` — never does. An unknown but
67
- * READ name is generic exactly as `lib/codegraph-rules.js` decides it, so the two
68
- * blocks can never call the same child two different things.
69
- */
70
- function childGetsSection(agent) {
71
- if (typeof agent !== 'string' || agent.length === 0) return true;
72
- if (CHILD_WRITER_AGENTS.has(agent)) return true;
73
- if (agent.startsWith(REVIEWER_PREFIX)) return false;
74
- return variantFor({ child: true, agent }) === 'generic';
75
- }
76
45
 
77
46
  // The names a named-agent event may carry. `agent` itself is listed because a
78
47
  // plain string there is a named agent too; an object is read through `.name`.
@@ -100,32 +69,26 @@ function separatorFor(existing) {
100
69
  // Append the section for this session to
101
70
  // `event.systemPromptOptions.appendSystemPrompt`. Returns nothing: the mutation
102
71
  // is the whole contract, so a host that awaits the handler receives no
103
- // replacement prompt. `deps.env` and `deps.argv` are the seams: the environment the
104
- // session runs with, and the argv a child's agent name is read from.
72
+ // replacement prompt. `deps.env` is the seam: the environment the session runs with.
105
73
  function appendOddWorktreesSection(event, deps = {}) {
106
74
  try {
107
75
  const effectiveDeps = deps || {};
108
76
  const env = effectiveDeps.env || process.env;
109
77
  if (env.ODD_WORKTREE_PROMPT === '0') return;
110
78
 
111
- // S5: a child is judged by the agent name its own argv carries, and gets the child
112
- // block only when it writes. A primary session keeps the one section it always had,
113
- // and a named-agent event still gets none of it.
114
- const child = env.GENTLE_PI_AGENTS_CHILD === '1';
115
- if (child) {
116
- if (!childGetsSection(agentNameFromArgv(effectiveDeps.argv || process.argv))) return;
117
- } else if (namedAgentOf(event) !== null) return;
79
+ // A child and a named-agent event get none of it.
80
+ if (env.GENTLE_PI_AGENTS_CHILD === '1') return;
81
+ if (namedAgentOf(event) !== null) return;
118
82
 
119
83
  const options = event && event.systemPromptOptions;
120
84
  if (!options || typeof options !== 'object') return;
121
85
 
122
- const section = child ? CHILD_SECTION : SECTION;
123
86
  const existing = typeof options.appendSystemPrompt === 'string' ? options.appendSystemPrompt : '';
124
87
  if (existing.includes(SECTION_MARKER)) return;
125
88
  // Append-only: every existing byte stays the prefix of the new value.
126
89
  options.appendSystemPrompt = existing.length === 0
127
- ? section
128
- : `${existing}${separatorFor(existing)}${section}`;
90
+ ? SECTION
91
+ : `${existing}${separatorFor(existing)}${SECTION}`;
129
92
  } catch {
130
93
  // The prompt block must never break session start.
131
94
  }
@@ -133,10 +96,7 @@ function appendOddWorktreesSection(event, deps = {}) {
133
96
 
134
97
  module.exports = {
135
98
  appendOddWorktreesSection,
136
- childGetsSection,
137
99
  readPromptFile,
138
100
  sectionFromFile,
139
101
  SECTION,
140
- CHILD_SECTION,
141
- CHILD_FALLBACK,
142
102
  };