pi-odd-worktree 2.0.0 → 3.0.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 (160) hide show
  1. package/README.md +54 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -711
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2569 -308
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +477 -93
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+ // S12: the one entry this package may write in the user's MCP configuration.
3
+ //
4
+ // `ensureCodegraphServer` makes `mcpServers.codegraph` of `<agent dir>/mcp.json` carry the three fields CodeGraph's
5
+ // explore tool needs (`command`, `args`, `toolExposure.codegraph_explore`). It adds the entry when it is missing, fixes
6
+ // only the fields that differ, and keeps every other server, key and field. The file is rewritten only when something
7
+ // changed, atomically (a temp file in the same directory, then a rename) and with its permission bits; a file that is
8
+ // not valid JSON, or whose `mcpServers` is not an object, is left untouched and reported. The configuration may hold
9
+ // secrets, so nothing here logs or returns its contents: a result carries a status and the names of the fields changed.
10
+
11
+ const nodeFs = require('node:fs');
12
+ const nodePath = require('node:path');
13
+
14
+ const CONFIG_FILE = 'mcp.json';
15
+
16
+ /** The entry CodeGraph's explore tool needs; the format of the file around it is irrelevant. */
17
+ const CODEGRAPH_SERVER = Object.freeze({
18
+ command: 'codegraph',
19
+ args: Object.freeze(['serve', '--mcp']),
20
+ toolExposure: Object.freeze({ codegraph_explore: 'direct' }),
21
+ });
22
+
23
+ function mcpConfigPath(agentDir) {
24
+ return nodePath.join(agentDir, CONFIG_FILE);
25
+ }
26
+
27
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ const sameArgs = (value) =>
29
+ Array.isArray(value) && value.length === CODEGRAPH_SERVER.args.length && value.every((arg, i) => arg === CODEGRAPH_SERVER.args[i]);
30
+
31
+ /** The indentation of an existing document, so a rewrite keeps the shape the user chose. */
32
+ function indentOf(text) {
33
+ const match = /\n([ \t]+)"/.exec(text);
34
+ return match ? match[1] : 2;
35
+ }
36
+
37
+ /**
38
+ * The entry as it must be, and the names of the fields that changed to get there. Every field the user added is kept;
39
+ * only the three CodeGraph needs are set.
40
+ */
41
+ function repairedEntry(current) {
42
+ const changes = [];
43
+ const entry = isObject(current) ? { ...current } : {};
44
+ if (entry.command !== CODEGRAPH_SERVER.command) {
45
+ entry.command = CODEGRAPH_SERVER.command;
46
+ changes.push('command');
47
+ }
48
+ if (!sameArgs(entry.args)) {
49
+ entry.args = [...CODEGRAPH_SERVER.args];
50
+ changes.push('args');
51
+ }
52
+ const exposure = isObject(entry.toolExposure) ? { ...entry.toolExposure } : {};
53
+ if (exposure.codegraph_explore !== CODEGRAPH_SERVER.toolExposure.codegraph_explore) {
54
+ exposure.codegraph_explore = CODEGRAPH_SERVER.toolExposure.codegraph_explore;
55
+ entry.toolExposure = exposure;
56
+ changes.push('toolExposure.codegraph_explore');
57
+ }
58
+ return { entry, changes };
59
+ }
60
+
61
+ async function readText(fs, file) {
62
+ try {
63
+ return { text: await fs.readFile(file, 'utf8') };
64
+ } catch (error) {
65
+ return { error };
66
+ }
67
+ }
68
+
69
+ async function writeAtomically(fs, file, text, mode) {
70
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
71
+ try {
72
+ await fs.writeFile(temp, text, { mode });
73
+ // writeFile keeps the umask on a new file, so the mode is applied again: the original's bits, or owner-only.
74
+ await fs.chmod(temp, mode);
75
+ await fs.rename(temp, file);
76
+ } catch (error) {
77
+ await fs.rm(temp, { force: true }).catch(() => {});
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Ensures the CodeGraph entry of the global MCP configuration. Resolves, never throws:
84
+ * `unchanged` | `added` | `fixed` (with `changes`) | `skipped` (no agent directory) | `invalid` (left untouched) |
85
+ * `unreadable` (left untouched) | `failed` (the write failed; the original is intact).
86
+ */
87
+ async function ensureCodegraphServer(options = {}) {
88
+ const fs = options.fs || nodeFs.promises;
89
+ const agentDir = options.agentDir;
90
+ try {
91
+ if (typeof agentDir !== 'string' || agentDir.length === 0) return { status: 'skipped' };
92
+ const file = mcpConfigPath(agentDir);
93
+ const read = await readText(fs, file);
94
+
95
+ let config;
96
+ let indent = 2;
97
+ let mode = 0o600;
98
+ if (read.error) {
99
+ if (read.error.code !== 'ENOENT') return { status: 'unreadable' };
100
+ const directory = await fs.stat(agentDir).catch(() => undefined);
101
+ if (!directory || !directory.isDirectory()) return { status: 'skipped' };
102
+ config = {};
103
+ } else {
104
+ try {
105
+ config = JSON.parse(read.text);
106
+ } catch {
107
+ return { status: 'invalid' };
108
+ }
109
+ if (!isObject(config)) return { status: 'invalid' };
110
+ indent = indentOf(read.text);
111
+ const stat = await fs.stat(file).catch(() => undefined);
112
+ if (stat) mode = stat.mode & 0o777;
113
+ }
114
+
115
+ const servers = config.mcpServers;
116
+ if (servers !== undefined && !isObject(servers)) return { status: 'invalid' };
117
+
118
+ const had = isObject(servers) && servers.codegraph !== undefined;
119
+ const { entry, changes } = repairedEntry(had ? servers.codegraph : undefined);
120
+ if (had && changes.length === 0) return { status: 'unchanged' };
121
+
122
+ const next = { ...config, mcpServers: { ...(isObject(servers) ? servers : {}), codegraph: entry } };
123
+ try {
124
+ await writeAtomically(fs, file, `${JSON.stringify(next, null, indent)}\n`, mode);
125
+ } catch {
126
+ return { status: 'failed' };
127
+ }
128
+ return had ? { status: 'fixed', changes } : { status: 'added', changes };
129
+ } catch {
130
+ return { status: 'failed' };
131
+ }
132
+ }
133
+
134
+ module.exports = { CODEGRAPH_SERVER, CONFIG_FILE, mcpConfigPath, ensureCodegraphServer };
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+ // The MCP side of CodeGraph: read the configuration, say what would hide the explore tool and whether a server
3
+ // is registered at all. This module never writes it — the user's mcp.json stays the user's — and MCP is optional:
4
+ // no server means a warning, not a failure, and a registered entry never proves a daemon is reachable (the
5
+ // registry in codegraph-daemon.js answers that).
6
+
7
+ const nodeFs = require('node:fs');
8
+ const { join } = require('node:path');
9
+
10
+ const EXPLORE = 'codegraph_explore';
11
+
12
+ function matchingExposure(entry) {
13
+ const tools = entry.toolExposure;
14
+ if (!tools || typeof tools !== 'object' || Array.isArray(tools)) return undefined;
15
+ if (typeof tools[EXPLORE] === 'string') return tools[EXPLORE];
16
+ for (const [pattern, exposure] of Object.entries(tools)) {
17
+ if (!pattern.includes('*') || typeof exposure !== 'string') continue;
18
+ const regex = new RegExp(`^${pattern.split('*').map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`);
19
+ if (regex.test(EXPLORE)) return exposure;
20
+ }
21
+ return undefined;
22
+ }
23
+
24
+ function codegraphServer(text) {
25
+ try {
26
+ const config = JSON.parse(text);
27
+ const entry = config?.mcpServers?.codegraph;
28
+ return entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : undefined;
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ /** Missing is distinct from disabled, invalid configuration and servers registered by extensions. */
35
+ function isCodegraphServerMissing(globalText, projectText, registered = false) {
36
+ if (registered === true) return false;
37
+ const read = (text) => {
38
+ try {
39
+ const value = JSON.parse(text);
40
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ };
45
+ const global = read(globalText);
46
+ const project = projectText === undefined ? undefined : read(projectText);
47
+ if (!global || (projectText !== undefined && !project)) return false;
48
+ const hasServer = (config) => {
49
+ const servers = config.mcpServers;
50
+ return !!servers && typeof servers === 'object' && !Array.isArray(servers)
51
+ && Object.prototype.hasOwnProperty.call(servers, 'codegraph');
52
+ };
53
+ if (hasServer(global)) return false;
54
+ if (!project || !hasServer(project)) return true;
55
+ const entry = project.mcpServers.codegraph;
56
+ // A project-only override cannot create a server without a transport definition.
57
+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
58
+ return !('command' in entry || 'url' in entry || 'type' in entry);
59
+ }
60
+ return false; // Let Pi report an invalid server entry instead of claiming it is absent.
61
+ }
62
+
63
+ /** Explicit restrictions must be respected, not overridden silently. */
64
+ function inspectMcpExposure(text) {
65
+ const entry = codegraphServer(text);
66
+ if (!entry) return undefined;
67
+ if (entry.enabled === false) return 'disabled';
68
+ const selected = matchingExposure(entry);
69
+ if (entry.exposure === 'hidden' && selected === 'direct') return 'hidden-with-direct';
70
+ if (selected !== undefined) return selected === 'direct' ? undefined : selected;
71
+ const exposure = typeof entry.exposure === 'string' ? entry.exposure : 'codemode';
72
+ return exposure === 'direct' ? undefined : exposure;
73
+ }
74
+
75
+ /** Inspect the effective file configuration, including a trusted project's override when supplied. */
76
+ function inspectEffectiveMcpExposure(globalText, projectText) {
77
+ const global = codegraphServer(globalText);
78
+ const project = projectText === undefined ? undefined : codegraphServer(projectText);
79
+ if (!project) return inspectMcpExposure(globalText);
80
+ const replacement = 'command' in project || 'url' in project || 'type' in project;
81
+ const entry = replacement ? project : { ...global, ...project };
82
+ return inspectMcpExposure(JSON.stringify({ mcpServers: { codegraph: entry } }));
83
+ }
84
+
85
+ const codeOf = (error) => error?.code;
86
+
87
+ /**
88
+ * What would hide the shipped explore tool, or undefined when it is reachable. Reads the effective file
89
+ * configuration only — untrusted project configuration is not loaded by Pi — and changes neither file.
90
+ */
91
+ function readExposureWarning(agentDir, cwd, projectTrusted, options = {}) {
92
+ const readFile = options.readFile ?? nodeFs.readFileSync;
93
+ const read = (path) => {
94
+ try {
95
+ return readFile(path, 'utf8');
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ };
100
+ const global = read(join(agentDir, 'mcp.json')) ?? '{}';
101
+ const project = projectTrusted === true ? read(join(cwd, '.pi', 'mcp.json')) : undefined;
102
+ return inspectEffectiveMcpExposure(global, project);
103
+ }
104
+
105
+ /**
106
+ * Whether no CodeGraph server is registered anywhere it would count. Reads the files without creating them; a
107
+ * read that fails for a reason other than "not there" is an invalid configuration, not an absent server.
108
+ */
109
+ function readMissingServerWarning(agentDir, cwd, projectTrusted, registered = false, options = {}) {
110
+ const readFile = options.readFile ?? nodeFs.readFileSync;
111
+ const read = (path) => {
112
+ try {
113
+ return readFile(path, 'utf8');
114
+ } catch (error) {
115
+ return codeOf(error) === 'ENOENT' ? undefined : 'invalid';
116
+ }
117
+ };
118
+ const global = read(join(agentDir, 'mcp.json')) ?? '{}';
119
+ const project = projectTrusted === true ? read(join(cwd, '.pi', 'mcp.json')) : undefined;
120
+ return isCodegraphServerMissing(global, project, registered === true);
121
+ }
122
+
123
+ module.exports = { readExposureWarning, readMissingServerWarning, isCodegraphServerMissing };
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+ // One root identity and one way to start codegraph (shared by the index, lock and daemon modules).
3
+ //
4
+ // Windows spells a network folder two ways, the mapped drive (Y:\...) and the UNC path behind it
5
+ // (\\server\share\...), and cmd.exe, which the npm `.cmd` shim needs, does not accept a UNC working
6
+ // directory. So roots are compared in one canonical form, and codegraph always runs from the temp
7
+ // directory with the project passed as an argument. The project path never goes into the command line
8
+ // itself on Windows (cmd.exe would expand %VAR% in it): it travels in PROJECT_ENV. Elsewhere it is a plain
9
+ // argv element and no shell is involved. A path neither realpath form can resolve keeps the resolved
10
+ // identity of its nearest resolvable parent, with the rest appended.
11
+
12
+ const { realpathSync } = require('node:fs');
13
+ const { tmpdir } = require('node:os');
14
+ const { basename, dirname, join, resolve } = require('node:path');
15
+
16
+ /** Lower case and no trailing separator on Windows; only the trailing separator elsewhere. */
17
+ function foldRoot(path, platform = process.platform) {
18
+ let out = path;
19
+ while (out.length > 1 && (out.endsWith('\\') || out.endsWith('/')) && !/^[A-Za-z]:[\\/]$/.test(out)) {
20
+ out = out.slice(0, -1);
21
+ }
22
+ return platform === 'win32' ? out.toLowerCase() : out;
23
+ }
24
+
25
+ function unfoldRoot(path) {
26
+ try {
27
+ return realpathSync.native(path);
28
+ } catch {
29
+ try {
30
+ return realpathSync(path);
31
+ } catch {
32
+ const parent = dirname(path);
33
+ if (parent === path) return path;
34
+ return join(unfoldRoot(parent), basename(path));
35
+ }
36
+ }
37
+ }
38
+
39
+ /** The identity of a project root: symlinks resolved, and on Windows the mapped drive as its UNC path. */
40
+ function canonicalRoot(path, platform = process.platform) {
41
+ return foldRoot(unfoldRoot(resolve(path)), platform);
42
+ }
43
+
44
+ /** The environment variable that carries the project path to a Windows shell command line. */
45
+ const PROJECT_ENV = 'ODD_WORKTREE_CODEGRAPH_PROJECT';
46
+
47
+ function projectArg(project, platform) {
48
+ if (platform === 'win32') {
49
+ return { command: `"%${PROJECT_ENV}%"`, env: { [PROJECT_ENV]: project.endsWith('\\') ? `${project}.` : project } };
50
+ }
51
+ return { command: `"$${PROJECT_ENV}"`, env: { [PROJECT_ENV]: project } };
52
+ }
53
+
54
+ /** `codegraph <args> <project>` from the temp dir: through cmd.exe on Windows, without a shell elsewhere. */
55
+ function codegraphSpawn(args, project, platform = process.platform) {
56
+ if (platform === 'win32') {
57
+ const arg = projectArg(project, platform);
58
+ return { command: ['codegraph', ...args, arg.command].join(' '), args: [], cwd: tmpdir(), shell: true, env: arg.env };
59
+ }
60
+ return { command: 'codegraph', args: [...args, project], cwd: tmpdir(), shell: false, env: {} };
61
+ }
62
+
63
+ /** The warm-up server command with the project named by -p. */
64
+ function serveCommand(command, project, platform = process.platform) {
65
+ const arg = projectArg(project, platform);
66
+ return { command: `${command} -p ${arg.command}`, env: arg.env };
67
+ }
68
+
69
+ module.exports = { foldRoot, canonicalRoot, PROJECT_ENV, codegraphSpawn, serveCommand };
@@ -0,0 +1,11 @@
1
+ ## CodeGraph
2
+
3
+ Run a `codegraph` `query` for symbols or `explore` for source plus call paths before you search or read
4
+ code — `fd`, `find`, `rg`, `grep`, `read` or `cat`. Start with `explore`: one call returns the source of
5
+ the relevant symbols and the call paths between them, so it answers where a behaviour lives, who calls it,
6
+ what it calls and what an error passes through, in place of the chain of greps and reads that would. Use
7
+ `query` when you only need to know whether and where a symbol is defined. Follow the call paths it returns
8
+ instead of grepping for callers, and run `explore` again on a symbol it surfaced when the next layer is
9
+ what the question needs, then stop. Read what it points at before you report: the answer says where code
10
+ lives, not what it does. The other tools stay available after the first call, for exact strings and what
11
+ the graph does not index.
@@ -0,0 +1,6 @@
1
+ ## CodeGraph
2
+
3
+ Run one `mcp__codegraph__codegraph_explore` — source plus call paths in one call — before you search or
4
+ read code: `fd`, `find`, `rg`, `grep`, `read` or `cat`. Call it with the symbol behind the finding: the
5
+ code, its callers and what it calls are the whole reach of the patch, so the fix stays inside them. The
6
+ other tools stay available after the first call, and you read the file before editing it.
@@ -0,0 +1,8 @@
1
+ ## CodeGraph
2
+
3
+ Run one call to the CodeGraph tool you hold before you search or read code — `fd`, `find`, `rg`, `grep`,
4
+ `read` or `cat` — when the task needs structure rather than a lookup: where something lives, who calls it,
5
+ what a change reaches. Exact strings, filenames and a known file may skip it, and the other tools stay
6
+ available after the first call.
7
+
8
+ The answer is a map, not proof: confirm it in the source, and read a file before editing it.
@@ -0,0 +1,9 @@
1
+ ## CodeGraph
2
+
3
+ Run one `mcp__codegraph__codegraph_explore` — source plus call paths in one call — before you search or
4
+ read code: `fd`, `find`, `rg`, `grep`, `read` or `cat`. Call it with the symbols the change touches: their
5
+ callers and callees show how far a regression could reach and which relationships the change bends, so the
6
+ sweep covers that radius and not only the diff. The other tools stay available after the first call.
7
+
8
+ The answer is a map, never proof: confirm every finding in the source before reporting it, and an answer on
9
+ its own is not a finding.
@@ -0,0 +1,17 @@
1
+ ## CodeGraph
2
+
3
+ Run a `codegraph` `query` for symbols or `explore` for source plus call paths before you search or read
4
+ code — `fd`, `find`, `rg`, `grep`, `read` or `cat` — and before you plan or size a change that one read
5
+ batch does not already explain: one `explore` on the change's subject shows the files and callers it
6
+ reaches, which is what scope, size and any handoff depend on, and `query` locates a symbol. Exact strings,
7
+ a file or location you already know and a run that only executes commands or tests need no call. The call
8
+ comes first, not instead: the other tools stay for what the graph does not index, and its answer is a map
9
+ — a verdict comes from the source and from tests.
10
+
11
+ `codegraph` answers only for the checkout the session runs in, and each worktree is its own workspace with
12
+ its own index. An ODD works in its own worktree: when the session runs elsewhere, look at that worktree, at
13
+ a sibling worktree or at another git project by calling `mcp__codegraph__codegraph_explore` with
14
+ `projectPath` set to that checkout, when that tool is available. That one look is enough to settle a doubt
15
+ and to size the work. If it does not settle it, or the work there is more than a look, delegate an explorer
16
+ to that checkout and hand it that map. An answer is only ever about the checkout it came from: never
17
+ present one workspace's answer as another's.
@@ -0,0 +1,10 @@
1
+ ## CodeGraph
2
+
3
+ Run one `mcp__codegraph__codegraph_explore` — source plus call paths in one call — before you search or
4
+ read code: `fd`, `find`, `rg`, `grep`, `read` or `cat`. Call it with the name of a symbol the change
5
+ touches: the callers and dependents it returns are what you choose interaction and regression probes from,
6
+ and you call it again on a caller it surfaces when a probe needs the next layer. The other tools stay
7
+ available after the first call.
8
+
9
+ The answer is a map, never evidence: a verdict comes from the source you read and the checks you run, and
10
+ a probe that contradicts the graph is the one that is right.
@@ -0,0 +1,7 @@
1
+ ## CodeGraph
2
+
3
+ Run one `mcp__codegraph__codegraph_explore` — source plus call paths in one call — before you search or
4
+ read code: `fd`, `find`, `rg`, `grep`, `read` or `cat`. Call it with the symbol you are about to change:
5
+ what calls it and what it calls are what the edit has to keep working, and after a refactor you call it
6
+ again to find anything that still points at what moved. The other tools stay available after the first
7
+ call, and you read a file before editing it — the answer says where code lives, not what it does.
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+ // What a session may do with the project's index, read from the tool list the host requested for a subagent
3
+ // child (a child carries no agent name in its environment, only that list). The explorer reads only; verify and
4
+ // the judges read and run commands but write no file, so they never initiate an `init` or a `sync`; a worker or
5
+ // the primary session may. Navigation is not proof, and a read-only role must not change the index it reads.
6
+
7
+ const { holdsCodegraph } = require('./codegraph-rules.js');
8
+
9
+ const CHILD_ENV = 'GENTLE_PI_AGENTS_CHILD';
10
+ const REQUESTED_TOOLS_ENV = 'GENTLE_PI_AGENTS_REQUESTED_TOOLS';
11
+
12
+ /** Tools that write a file of the project: a role holding one of them may write the index too. */
13
+ const FILE_WRITING_TOOLS = ['edit', 'write', 'bash_background'];
14
+
15
+ /** Tools that run a command without writing a file through it: verify and the judges hold `bash`. */
16
+ const COMMAND_TOOLS = ['bash', 'bash_background'];
17
+
18
+ /** The tool list the host requested for a child, as one array; empty for the primary session. */
19
+ function requestedTools(env = process.env) {
20
+ return String((env && env[REQUESTED_TOOLS_ENV]) || '')
21
+ .split(',')
22
+ .map((tool) => tool.trim())
23
+ .filter((tool) => tool.length > 0);
24
+ }
25
+
26
+ /**
27
+ * The role of one declared tool list: `writer` (a file-writing tool wins), `read-only` (a command tool),
28
+ * `explorer` (a CodeGraph tool and nothing else) or `unknown` (the list says nothing about CodeGraph).
29
+ */
30
+ function indexRole(tools) {
31
+ const list = Array.isArray(tools) ? tools : [];
32
+ if (list.length === 0) return 'unknown';
33
+ if (list.some((tool) => FILE_WRITING_TOOLS.includes(tool))) return 'writer';
34
+ if (list.some((tool) => COMMAND_TOOLS.includes(tool))) return 'read-only';
35
+ return holdsCodegraph(list) ? 'explorer' : 'unknown';
36
+ }
37
+
38
+ /** The role of this session: undefined in the primary session, which is not a subagent role. */
39
+ function sessionIndexRole(env = process.env) {
40
+ return env && env[CHILD_ENV] === '1' ? indexRole(requestedTools(env)) : undefined;
41
+ }
42
+
43
+ /** Whether this role may start an index write at all: a read-only role (verify, the judges) may not. */
44
+ function mayInitiateIndexWrite(role) {
45
+ return role !== 'read-only';
46
+ }
47
+
48
+ module.exports = {
49
+ indexRole,
50
+ sessionIndexRole,
51
+ requestedTools,
52
+ mayInitiateIndexWrite,
53
+ FILE_WRITING_TOOLS,
54
+ COMMAND_TOOLS,
55
+ };
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+ // The `## CodeGraph` section of a session's system prompt, one text per role.
3
+ //
4
+ // It rides `systemPromptOptions.appendSystemPrompt` like the `## ODD worktrees`
5
+ // block: appended after the harness's own text, never returned as a replacement
6
+ // `systemPrompt` (a host may drop it and it would erase the harness text), and
7
+ // skipped when the heading is already there. Nothing here probes, runs or writes
8
+ // CodeGraph: the section only tells a session that already holds a CodeGraph
9
+ // tool how to use it. A session with no such tool, and a `review-*` agent, get
10
+ // nothing. The text of each role is a Markdown file under `codegraph-prompt/`,
11
+ // so it can be read and edited as prose.
12
+
13
+ const fs = require('node:fs');
14
+ const path = require('node:path');
15
+
16
+ const SECTION_MARKER = '## CodeGraph';
17
+ const PROMPT_DIR = path.join(__dirname, 'codegraph-prompt');
18
+
19
+ const NATIVE_TOOL = 'codegraph';
20
+ const MCP_TOOL = 'mcp__codegraph__codegraph_explore';
21
+
22
+ const VARIANTS = ['orchestrator', 'explore', 'verify', 'worker', 'fix', 'judge', 'generic'];
23
+
24
+ // The gentle-shell agents that have a text of their own. Both judges share one.
25
+ const VARIANT_BY_AGENT = {
26
+ 'gentle-ai-explore': 'explore',
27
+ 'gentle-ai-verify': 'verify',
28
+ 'gentle-ai-worker': 'worker',
29
+ 'jd-fix-agent': 'fix',
30
+ 'jd-judge-a': 'judge',
31
+ 'jd-judge-b': 'judge',
32
+ };
33
+
34
+ const SUBAGENT_DIR_PREFIX = 'gentle-pi-subagent-';
35
+
36
+ // The agent name of a subagent child, read from its own argv
37
+ // (`gentle-pi-subagent-<agent>-<random>/...`). Undefined in the primary
38
+ // session. A name outside the table keeps the directory's spelling, so a
39
+ // `review-*` child is still recognised by its prefix. Never throws.
40
+ function agentNameFromArgv(argv) {
41
+ if (!Array.isArray(argv)) return undefined;
42
+ for (const arg of argv) {
43
+ if (typeof arg !== 'string') continue;
44
+ const at = arg.lastIndexOf(SUBAGENT_DIR_PREFIX);
45
+ if (at < 0) continue;
46
+ const rest = arg.slice(at + SUBAGENT_DIR_PREFIX.length);
47
+ const end = rest.search(/[\\/]/);
48
+ const directory = (end < 0 ? rest : rest.slice(0, end)).trim();
49
+ if (directory.length === 0) continue;
50
+ for (const name of Object.keys(VARIANT_BY_AGENT)) {
51
+ if (directory === name || directory.startsWith(`${name}-`)) return name;
52
+ }
53
+ return directory;
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ // The session's tools: the selected ones plus, in a child, the ones the host
59
+ // requested for it (MCP tools are not in the selected list yet when
60
+ // `before_agent_start` runs).
61
+ function sessionTools(selectedTools, requestedEnv, child) {
62
+ const selected = Array.isArray(selectedTools) ? selectedTools.filter((tool) => typeof tool === 'string') : [];
63
+ const requested = child && typeof requestedEnv === 'string'
64
+ ? requestedEnv.split(',').map((tool) => tool.trim()).filter(Boolean)
65
+ : [];
66
+ return [...new Set([...selected, ...requested])];
67
+ }
68
+
69
+ function holdsCodegraph(tools) {
70
+ return tools.includes(NATIVE_TOOL) || tools.some((tool) => tool === MCP_TOOL || tool === 'mcp__codegraph__*');
71
+ }
72
+
73
+ function isReviewer(agent) {
74
+ return typeof agent === 'string' && agent.startsWith('review-');
75
+ }
76
+
77
+ // A primary session gets the orchestrator's text, a named gentle-shell agent its
78
+ // own, and any other child (unknown or unreadable name) the generic one.
79
+ function variantFor({ child, agent }) {
80
+ if (child !== true) return 'orchestrator';
81
+ if (typeof agent !== 'string' || agent.length === 0) return 'generic';
82
+ return VARIANT_BY_AGENT[agent] || 'generic';
83
+ }
84
+
85
+ function readVariant(variant, dir) {
86
+ try {
87
+ const text = fs.readFileSync(path.join(dir, `${variant}.md`), 'utf8').trim();
88
+ return text.startsWith(SECTION_MARKER) ? text : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ // A file that cannot be used falls back to the generic text; a generic text
95
+ // that cannot be used is no section, never a broken session.
96
+ function sectionText(variant, dir = PROMPT_DIR) {
97
+ return readVariant(variant, dir) || (variant === 'generic' ? null : readVariant('generic', dir));
98
+ }
99
+
100
+ function separatorFor(existing) {
101
+ if (existing.endsWith('\n\n')) return '';
102
+ if (existing.endsWith('\n')) return '\n';
103
+ return '\n\n';
104
+ }
105
+
106
+ // Append the section for this session to
107
+ // `event.systemPromptOptions.appendSystemPrompt`. Returns nothing: the mutation
108
+ // is the whole contract. `ODD_WORKTREE_PROMPT=0` turns it off together with the
109
+ // worktrees block.
110
+ function appendCodegraphSection(event, deps = {}) {
111
+ try {
112
+ const env = (deps && deps.env) || process.env;
113
+ if (env.ODD_WORKTREE_PROMPT === '0') return;
114
+ const options = event && event.systemPromptOptions;
115
+ if (!options || typeof options !== 'object') return;
116
+
117
+ const child = env.GENTLE_PI_AGENTS_CHILD === '1';
118
+ const agent = child ? agentNameFromArgv((deps && deps.argv) || process.argv) : undefined;
119
+ if (isReviewer(agent)) return;
120
+ const tools = sessionTools(options.selectedTools, env.GENTLE_PI_AGENTS_REQUESTED_TOOLS, child);
121
+ if (!holdsCodegraph(tools)) return;
122
+
123
+ const section = sectionText(variantFor({ child, agent }), deps && deps.dir);
124
+ if (section === null || section === undefined) return;
125
+ const existing = typeof options.appendSystemPrompt === 'string' ? options.appendSystemPrompt : '';
126
+ if (existing.includes(SECTION_MARKER)) return;
127
+ options.appendSystemPrompt = existing.length === 0
128
+ ? section
129
+ : `${existing}${separatorFor(existing)}${section}`;
130
+ } catch {
131
+ // The prompt block must never break a session.
132
+ }
133
+ }
134
+
135
+ module.exports = {
136
+ appendCodegraphSection,
137
+ sessionTools,
138
+ holdsCodegraph,
139
+ agentNameFromArgv,
140
+ variantFor,
141
+ sectionText,
142
+ VARIANTS,
143
+ VARIANT_BY_AGENT,
144
+ PROMPT_DIR,
145
+ SECTION_MARKER,
146
+ };