pi-odd-worktree 2.1.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 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  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 -712
  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 +2565 -309
  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 +419 -199
  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
@@ -1,758 +1,467 @@
1
1
  'use strict';
2
- // Creation hooks for the worktree tools (P2-S3).
2
+ // The preparation hooks of `worktree_create` (S19, S20).
3
3
  //
4
- // `runCreationHooks({principalRoot, worktreePath, ...})` runs, in order:
5
- // (a) copy unversioned env files from the principal checkout,
6
- // (a2) link the principal's git-ignored agent/ODD entries (S3/L4: `.agents`,
7
- // `.pi`, `.claude`, `odd` — never a copy, never over an existing path),
8
- // (b) dependency install by lockfile-detected stack,
9
- // (c) `codegraph init` when the CLI is available.
4
+ // An ordered chain that runs once Git has created the worktree and before the output
5
+ // is rendered: the submodules, the copy of the untracked inputs, `copy_changes` (S18),
6
+ // the links of build caches and local asset directories, and the slot the setup chain
7
+ // takes. Every step reports `applied`, `skipped: <reason>` or `failed: <reason>`, and a
8
+ // failing step never aborts the chain or the creation: the worktree stays created and
9
+ // usable, and the summary names what failed.
10
10
  //
11
- // Both `worktree_upsert` (sync runner) and the panel create path (async
12
- // twin) reach these hooks, so the link policy is applied by ONE shared
13
- // implementation in `lib/worktree-symlinks.js` and both creation routes
14
- // behave identically.
11
+ // The chain reaches the world only through the injected seams — filesystem, Git and
12
+ // platform — so a test answers for a machine it invents and no case depends on the
13
+ // host's link privileges. No hook reads a file's contents: an input is copied by the
14
+ // filesystem and never decoded, so nothing secret can reach a log or a summary.
15
15
  //
16
- // A worktree reaches a checked-in `odd/` because the repository tracks it: a
17
- // tracked entry arrives with the checkout, which is why the link step refuses
18
- // every name git already tracks.
19
- //
20
- // Every external process is spawned with a fixed argv array (never a shell
21
- // string) and a bounded timeout. A missing binary is a `skipped` step with
22
- // a recorded reason, never a failure. A non-zero exit is a `failed` step
23
- // plus a warning, and never aborts the remaining steps. Missing sources
24
- // never fail the hook.
25
- //
26
- // The candidate list (`unversionedCandidates`) and the command table
27
- // (`installTable`) are injectable so tests never touch the network and
28
- // never need real package managers. Defaults match S8 exactly. The `run`
29
- // and `hasBinary` hooks are injectable for the same reason.
30
-
31
- const codegraphSession = require('./codegraph-session.js');
32
-
33
- const { spawnSync } = require('node:child_process');
34
- const fs = require('node:fs');
35
- const path = require('node:path');
36
- const symlinksLib = require('./worktree-symlinks.js');
37
-
38
- // Shared pure plan helpers (S63): the sync and async hook runners use the
39
- // SAME detection/format/classification pipeline so the two implementations
40
- // cannot drift. Detection stays sync lstat (constant-time, millisecond
41
- // scale, never a 120s subprocess); only subprocesses and file copies go
42
- // async in the async twin.
43
-
44
- const DEFAULT_UNVERSIONED_FILES = [
45
- '.env',
46
- '.env.local',
47
- '.env.development',
48
- '.env.production',
49
- '.env.test',
50
- ];
16
+ // The lists are fixed here and extend them from `<git-common-dir>/gentle-ai/worktree-hooks.json`,
17
+ // which is local to the clone and never versioned. That file extends the copy and link
18
+ // lists and enables setup for the repository; it carries no command, because a command
19
+ // read from a file must never run.
20
+
21
+ const { dirname, isAbsolute, join } = require('node:path');
22
+
23
+ const WORKTREE_HOOKS_FILENAME = 'worktree-hooks.json';
51
24
 
52
- // Order is the execution order when several markers are present (monorepo:
53
- // every detected stack runs). `markers` is OR: any present file triggers
54
- // the entry. `fallbackArgv` runs only when `argv` exits non-zero.
55
- const DEFAULT_INSTALL_TABLE = [
56
- { key: 'bun', markers: ['bun.lockb', 'bun.lock'], argv: ['bun', 'install'] },
57
- { key: 'pnpm', markers: ['pnpm-lock.yaml'], argv: ['pnpm', 'install', '--frozen-lockfile'] },
58
- { key: 'yarn', markers: ['yarn.lock'], argv: ['yarn', 'install', '--frozen-lockfile'] },
59
- { key: 'npm', markers: ['package-lock.json'], argv: ['npm', 'ci'], fallbackArgv: ['npm', 'install'] },
60
- { key: 'uv', markers: ['uv.lock', 'pyproject.toml'], argv: ['uv', 'sync'] },
61
- { key: 'cargo', markers: ['Cargo.toml'], argv: ['cargo', 'fetch'] },
62
- { key: 'go', markers: ['go.mod'], argv: ['go', 'mod', 'download'] },
25
+ /** S20: the clone-local directory, inside the common directory Git never versions. */
26
+ const WORKTREE_LOCAL_DIRECTORY = 'gentle-ai';
27
+
28
+ /** S20: the clone-local file, inside the common directory Git never versions. */
29
+ function worktreeHooksFilePath(commonDir) {
30
+ return join(commonDir, WORKTREE_LOCAL_DIRECTORY, WORKTREE_HOOKS_FILENAME);
31
+ }
32
+
33
+ /** S19: directories a package manager owns. No list can make one of these a link. */
34
+ const WORKTREE_NEVER_LINKED = [
35
+ 'node_modules',
36
+ 'vendor',
37
+ '.venv',
38
+ 'target',
39
+ 'deps',
40
+ '.pi/gentle-ai',
41
+ '.gentle-ai',
63
42
  ];
64
43
 
65
- const DEFAULT_TIMEOUT_MS = 120000;
44
+ /** S19: build caches, linked only when main has them untracked. */
45
+ const WORKTREE_BUILD_CACHE_LINKS = ['.turbo', '.next/cache', '.parcel-cache', '.pytest_cache', '.ruff_cache'];
46
+
47
+ /** S19: local asset directories, linked only when main has them untracked. */
48
+ const WORKTREE_ASSET_LINKS = ['.agents', '.atl', '.claude', 'odd'];
66
49
 
67
- function resolvePrincipal(opts) {
68
- return opts.principalRoot || opts.root || opts.principal || null;
50
+ /** S19: the untracked input family copied by default. */
51
+ const WORKTREE_INPUT_PREFIX = '.env';
52
+
53
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
54
+
55
+ // ---- The local configuration (S20) ----
56
+
57
+ function emptyWorktreeHooksConfig() {
58
+ return { copy: [], link: [], setup: false };
69
59
  }
70
60
 
71
- function resolveWorktree(opts) {
72
- return opts.worktreePath || opts.worktreeRoot || opts.path || null;
61
+ /** One relative path, so no configured entry can reach outside the worktree. */
62
+ function isSafeRelativePath(value) {
63
+ if (typeof value !== 'string' || value.length === 0 || CONTROL_CHARACTER.test(value) || isAbsolute(value)) return false;
64
+ const segments = value.replaceAll('\\', '/').split('/');
65
+ return !segments.some((segment) => segment === '' || segment === '.' || segment === '..');
73
66
  }
74
67
 
75
- // True when the path exists, including a dangling symlink (lstat, not stat).
76
- function pathExists(p) {
77
- try {
78
- fs.lstatSync(p);
79
- return true;
80
- } catch {
81
- return false;
82
- }
68
+ function relativePath(value) {
69
+ return value.replaceAll('\\', '/').replace(/\/+$/, '');
83
70
  }
84
71
 
85
- // Default PATH lookup: search each PATH entry for an executable file.
86
- // Never spawns anything, never a shell string.
87
- function defaultHasBinary(bin, env) {
88
- if (typeof bin !== 'string' || bin === '') return false;
89
- if (bin.includes(path.sep) || bin.includes('/')) {
90
- try {
91
- fs.accessSync(bin, fs.constants.X_OK);
92
- return true;
93
- } catch {
94
- return false;
95
- }
96
- }
97
- const rawPath = (env || {}).PATH || (env || {}).Path || '';
98
- const dirs = String(rawPath).split(path.delimiter).filter((d) => d.length > 0);
99
- for (const dir of dirs) {
100
- try {
101
- fs.accessSync(path.join(dir, bin), fs.constants.X_OK);
102
- return true;
103
- } catch {
104
- // Not here; keep searching.
105
- }
106
- }
107
- return false;
72
+ function unique(values) {
73
+ return [...new Set(values)];
108
74
  }
109
75
 
110
- // Default runner: fixed argv via spawnSync, bounded timeout, no shell.
111
- function defaultRun(bin, args, opts = {}) {
112
- const result = spawnSync(bin, args, {
113
- cwd: opts.cwd,
114
- env: opts.env,
115
- timeout: opts.timeoutMs,
116
- encoding: 'utf8',
117
- windowsHide: true,
118
- });
119
- if (result.error) {
120
- return {
121
- status: result.status ?? null,
122
- stdout: result.stdout || '',
123
- stderr: result.stderr || '',
124
- error: String((result.error && result.error.message) || result.error),
125
- };
126
- }
127
- return {
128
- status: result.status,
129
- stdout: result.stdout || '',
130
- stderr: result.stderr || '',
131
- error: null,
132
- };
76
+ function configuredPaths(value) {
77
+ if (!Array.isArray(value)) return [];
78
+ const safe = value.filter((entry) => isSafeRelativePath(entry)).map((entry) => relativePath(entry));
79
+ return unique(safe);
133
80
  }
134
81
 
135
- // True when <candidate> (relative, e.g. `.env`) is tracked by git in the
136
- // principal checkout: `git ls-files --error-unmatch` exits 0. Fixed argv,
137
- // bounded timeout, never a shell string.
138
- function isTrackedByGit(run, principalRoot, candidate, timeoutMs, env) {
139
- let res;
140
- try {
141
- res = run('git', ['ls-files', '--error-unmatch', candidate], {
142
- cwd: principalRoot,
143
- timeoutMs,
144
- env,
145
- });
146
- } catch {
147
- // A runner failure must never mark a file untracked (fail closed
148
- // would copy a tracked file); treat as tracked so the copy is refused.
149
- return true;
150
- }
151
- if (!res) return true;
152
- if (res.status === 0) return true;
153
- // A spawn-level failure (missing git, timeout) fails closed: refuse
154
- // the copy rather than risk copying a tracked file.
155
- if (res.status === null || res.status === undefined || res.error) return true;
156
- return false;
82
+ /**
83
+ * S20: an absent or unreadable file keeps the defaults, because a bad local file must
84
+ * never break a create. Only the two lists and the boolean flag are read: a key naming
85
+ * a command reaches nothing, and neither does a `version` this code does not know.
86
+ */
87
+ function parseWorktreeHooksConfig(text) {
88
+ const config = emptyWorktreeHooksConfig();
89
+ if (text === undefined) return config;
90
+ let value;
91
+ try {
92
+ value = JSON.parse(text);
93
+ } catch {
94
+ return config;
95
+ }
96
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return config;
97
+ config.copy = configuredPaths(value.copy);
98
+ config.link = configuredPaths(value.link);
99
+ config.setup = value.setup === true;
100
+ return config;
157
101
  }
158
102
 
159
- // The `codegraph init` decision (S3): the session gate answers once per
160
- // process, so creation no longer re-probes. An injected `hasBinary` stays
161
- // authoritative for callers that already supply one (tests, embedders), and
162
- // only the default path consults the gate.
163
- function codegraphDecision(opts, env, hasBinary) {
164
- if (typeof opts.hasBinary === 'function') {
165
- return hasBinary('codegraph')
166
- ? { available: true }
167
- : { available: false, detail: 'codegraph not on PATH' };
168
- }
169
- return codegraphSession.hasCodegraph(env)
170
- ? { available: true }
171
- : { available: false, detail: 'codegraph session gate: CLI not detected in this session' };
103
+ // ---- The seams ----
104
+ //
105
+ // Everything a hook may touch. Nothing else is importable from here, so a hook cannot
106
+ // open a file, spawn a process or read the environment on its own: `git` runs Git in
107
+ // `cwd` with the same shape the create flow already uses, `kind` answers from `lstat`
108
+ // what stands at a path, `readdir` lists a directory, `readText` reads the local S20
109
+ // file, `copyFile` is a byte copy, `mkdir` creates with parents, `symlink` creates one
110
+ // link of the given type and `platform` names the host.
111
+
112
+ // ---- The chain ----
113
+
114
+ /**
115
+ * Runs the chain in order, one hook at a time, and never lets one stop the next. A hook
116
+ * that throws is recorded as failed with its own name, because a chain that reported
117
+ * nothing would read as a chain that did nothing.
118
+ *
119
+ * `input.mainRoot` is the canonical main worktree, which the main-relative steps (the
120
+ * submodules, the inputs, the links) read. `input.changesRoot` is the checkout whose
121
+ * uncommitted delta `copy_changes` copies — the one the caller stands in, which is not
122
+ * necessarily main — and falls back to `mainRoot` only when a caller names none.
123
+ */
124
+ async function runWorktreeHooks(input) {
125
+ const config = parseWorktreeHooksConfig(await input.seams.readText(input.configPath));
126
+ const context = {
127
+ mainRoot: input.mainRoot,
128
+ changesRoot: input.changesRoot ?? input.mainRoot,
129
+ path: input.path,
130
+ odd: input.odd,
131
+ copyChanges: input.copyChanges === true,
132
+ config,
133
+ };
134
+ const results = [];
135
+ for (const hook of input.hooks ?? defaultWorktreeHooks()) {
136
+ try {
137
+ results.push(...(await hook.run(context, input.seams)));
138
+ } catch (error) {
139
+ results.push({ name: hook.name, status: 'failed', detail: reasonFor(error) });
140
+ }
141
+ }
142
+ const summary = worktreeHooksSummary(results);
143
+ return summary === undefined ? { results, config } : { results, config, summary };
172
144
  }
173
145
 
174
- // --- Shared pure pipeline (S63): sync + async runners use these ---
175
- // Detection: which install entries fire for the worktree (markers OR).
176
- // Sync lstat only (constant-time); never a subprocess, never the loop blocker.
177
- function selectInstallEntries(worktreePath, table) {
178
- const list = Array.isArray(table) ? table : DEFAULT_INSTALL_TABLE;
179
- return list.filter((entry) => Array.isArray(entry.markers)
180
- && entry.markers.some((marker) => pathExists(path.join(worktreePath, marker))));
146
+ /**
147
+ * S19 in order, with `copy_changes` (S18) between the inputs and the links so the setup
148
+ * chain installs against the copied manifests. Every caller runs this same list, so no
149
+ * caller reorders it.
150
+ */
151
+ function defaultWorktreeHooks() {
152
+ return [submodulesHook, inputsHook, copyChangesHook, symlinksHook];
181
153
  }
182
154
 
183
- // Split an install entry argv into fixed bin + args (never a shell string).
184
- // Returns null when the entry carries no command.
185
- function installEntryArgv(entry) {
186
- const argv = (entry && entry.argv) || [];
187
- const bin = argv[0];
188
- if (typeof bin !== 'string' || bin === '') return null;
189
- return { bin, args: argv.slice(1) };
155
+ // ---- Shared Git questions ----
156
+
157
+ async function isTracked(seams, mainRoot, path) {
158
+ const tracked = await seams.git(mainRoot, ['ls-files', '--error-unmatch', '--', path]);
159
+ return tracked !== undefined && tracked.code === 0;
190
160
  }
191
161
 
192
- // Classify a finished run: { ok } when status 0, else a short cause.
193
- function runCause(res) {
194
- if (res && res.status === 0) return null;
195
- if (res && (res.stderr || res.error)) return String(res.stderr || res.error).trim();
196
- const code = res && res.status !== null && res.status !== undefined ? res.status : 'non-zero';
197
- return `exit ${code}`;
162
+ async function isIgnored(seams, mainRoot, path) {
163
+ const ignored = await seams.git(mainRoot, ['check-ignore', '--quiet', '--', path]);
164
+ return ignored !== undefined && ignored.code === 0;
198
165
  }
199
166
 
200
- // Copy outcome formatting shared by both runners.
201
- function formatCopyOutcome(copied, skipped, copyError) {
202
- if (copyError && copied.length === 0) {
203
- const message = `copy unversioned files failed: ${(copyError && copyError.message) || copyError}`;
204
- return { status: 'failed', detail: `copied none; ${skipped.join('; ')}`, warning: message };
205
- }
206
- const warning = copyError
207
- ? `copy unversioned files partially failed: ${(copyError && copyError.message) || copyError}`
208
- : null;
209
- const detail = copied.length > 0
210
- ? `copied ${copied.join(', ')}${skipped.length > 0 ? `; skipped ${skipped.join('; ')}` : ''}`
211
- : `copied none; ${skipped.join('; ') || 'nothing to copy'}`;
212
- return { status: copied.length > 0 ? 'done' : 'skipped', detail, warning };
167
+ /** S19: the rule a reader can add to silence this path, only while Git really does not ignore it. */
168
+ async function gitignoreWarning(context, seams, path) {
169
+ if (await isIgnored(seams, context.mainRoot, path)) return undefined;
170
+ return `${path} is not ignored; add ${path} to .gitignore`;
213
171
  }
214
172
 
215
- // Link outcome formatting shared by both runners. `created` means "links in
216
- // place after this call" (the create tool surfaces it), `existing` the ones
217
- // that were already correct, and `errors` the ones whose symlink failed — a
218
- // failed link is reported, never silent, and never fails the creation.
219
- function formatLinkOutcome(applied, error) {
220
- if (!applied) {
221
- const message = `link principal entries failed: ${(error && error.message) || error || 'unknown error'}`;
222
- return { status: 'failed', detail: message, warning: message };
223
- }
224
- const created = applied.created || [];
225
- const existing = applied.existing || [];
226
- const skipped = applied.skipped || [];
227
- const errors = applied.errors || [];
228
- const parts = [];
229
- if (created.length > 0) parts.push(`linked ${created.join(', ')}`);
230
- if (existing.length > 0) parts.push(`already linked ${existing.join(', ')}`);
231
- if (skipped.length > 0) parts.push(`skipped ${skipped.join('; ')}`);
232
- const detail = parts.join('; ') || 'nothing to link';
233
- if (errors.length === 0) {
234
- return {
235
- status: created.length > 0 ? 'done' : 'skipped',
236
- detail,
237
- warning: null,
238
- };
239
- }
240
- const message = `link principal entries failed: ${errors.join('; ')}`;
241
- return { status: 'failed', detail, warning: message };
173
+ function isNeverLinked(path) {
174
+ return WORKTREE_NEVER_LINKED.some((forbidden) => path === forbidden || path.startsWith(`${forbidden}/`));
242
175
  }
243
176
 
244
- // Default async runner: SHARED with `lib/worktree-git.js` runArgvAsync
245
- // (the wizard's effective production runner) — one ownership
246
- // implementation, never two divergent kill paths. Fixed argv, never a
247
- // shell string, never the main-thread blocker; bounded timeout with
248
- // SIGTERM-then-SIGKILL escalation and owned-group reaping (POSIX), plus
249
- // AbortSignal support. Forwards cwd/env/spawnFn/signal/timeoutMs/killGraceMs
250
- // and resolves the same `{status, stdout, stderr, error}` shape.
251
- function defaultRunAsync(bin, args, opts = {}) {
252
- let gitAsync = null;
253
- try {
254
- gitAsync = require('./worktree-git.js').runArgvAsync;
255
- } catch {
256
- gitAsync = null;
257
- }
258
- if (typeof gitAsync === 'function') {
259
- return gitAsync(bin, args, opts);
260
- }
261
- return Promise.resolve({
262
- status: null,
263
- stdout: '',
264
- stderr: '',
265
- error: 'async runner unavailable: lib/worktree-git.js could not be loaded',
266
- });
177
+ function reasonFor(error) {
178
+ return error instanceof Error ? error.message : String(error);
267
179
  }
268
180
 
269
- // Async existence via lstat (dangling symlink counts as exists, like sync).
270
- async function pathExistsAsync(p, existsAsync) {
271
- if (typeof existsAsync === 'function') return !!(await existsAsync(p));
272
- try {
273
- await fs.promises.lstat(p);
274
- return true;
275
- } catch {
276
- return false;
277
- }
181
+ // ---- S19 step 1: submodules ----
182
+
183
+ const submodulesHook = {
184
+ name: 'submodules',
185
+ async run(context, seams) {
186
+ if ((await seams.kind(join(context.mainRoot, '.gitmodules'))) === undefined) {
187
+ return [{ name: 'submodules', status: 'skipped', detail: 'no submodules' }];
188
+ }
189
+ const args = ['submodule', 'update', '--init', '--recursive'];
190
+ const updated = await seams.git(context.path, args);
191
+ if (updated === undefined || updated.code !== 0) {
192
+ const outcome = updated === undefined ? 'without a result' : updated.code;
193
+ return [{ name: 'submodules', status: 'failed', detail: `git ${args.join(' ')} exited ${outcome}` }];
194
+ }
195
+ return [{ name: 'submodules', status: 'applied' }];
196
+ },
197
+ };
198
+
199
+ // ---- S19 step 2: the untracked inputs ----
200
+
201
+ const inputsHook = {
202
+ name: 'inputs',
203
+ async run(context, seams) {
204
+ const present = (await seams.readdir(context.mainRoot)).filter((name) => name.startsWith(WORKTREE_INPUT_PREFIX));
205
+ const candidates = unique([...present.sort(), ...context.config.copy]);
206
+ if (candidates.length === 0) {
207
+ return [{ name: 'inputs', status: 'skipped', detail: `no ${WORKTREE_INPUT_PREFIX} files in main` }];
208
+ }
209
+ const results = [];
210
+ for (const path of candidates) results.push(await copyInput(context, seams, path));
211
+ return results;
212
+ },
213
+ };
214
+
215
+ /** Copies one input by bytes. A directory, a link and a path already in the worktree are refused. */
216
+ async function copyInput(context, seams, path) {
217
+ const name = `copy ${path}`;
218
+ if (!isSafeRelativePath(path)) return { name, status: 'skipped', detail: `${path} is not a relative path` };
219
+ const source = join(context.mainRoot, path);
220
+ const destination = join(context.path, path);
221
+ const kind = await seams.kind(source);
222
+ if (kind === undefined) return { name, status: 'skipped', detail: `${path} not in main` };
223
+ if (await isTracked(seams, context.mainRoot, path)) return { name, status: 'skipped', detail: 'tracked' };
224
+ if (kind !== 'file') return { name, status: 'skipped', detail: `${path} is not a file` };
225
+ if ((await seams.kind(destination)) !== undefined) return { name, status: 'skipped', detail: `${path} already exists in the worktree` };
226
+ try {
227
+ await seams.mkdir(dirname(destination));
228
+ await seams.copyFile(source, destination);
229
+ } catch (error) {
230
+ return { name, status: 'failed', detail: `could not copy ${path}: ${reasonFor(error)}` };
231
+ }
232
+ const warning = await gitignoreWarning(context, seams, path);
233
+ return warning === undefined ? { name, status: 'applied' } : { name, status: 'applied', warning };
278
234
  }
279
235
 
280
- async function copyFileAsyncDefault(src, dest, copyAsync) {
281
- if (typeof copyAsync === 'function') return copyAsync(src, dest);
282
- return fs.promises.copyFile(src, dest);
236
+ // ---- S18: the uncommitted changes ----
237
+ //
238
+ // The delta belongs to the checkout the create was asked from (`context.changesRoot`),
239
+ // never to the canonical main worktree: a session standing in another checkout copies
240
+ // its own line of work, exactly as the panel's path-selection transfer does. The patch
241
+ // is still applied in the new worktree, so the source keeps every change it had.
242
+
243
+ /**
244
+ * The patch file Git writes for this step. It lives in the worktree's administrative
245
+ * directory — never in the worktree, so a copied change is the only thing a reader sees
246
+ * — and a fixed name makes it deterministic and overwritten instead of accumulating.
247
+ */
248
+ const COPY_CHANGES_PATCH_FILENAME = 'gentle-ai-copy-changes.patch';
249
+
250
+ const copyChangesHook = {
251
+ name: 'copy_changes',
252
+ async run(context, seams) {
253
+ // S18: omitted or false copies nothing and prints nothing, so the step neither
254
+ // applies, skips nor fails — it never happened.
255
+ if (!context.copyChanges) return [];
256
+ const changed = await gitPaths(seams, context.changesRoot, ['diff', '--name-only', '--no-renames', '-z', 'HEAD']);
257
+ const untracked = await gitPaths(seams, context.changesRoot, ['ls-files', '--others', '--exclude-standard', '-z']);
258
+ if (changed === undefined || untracked === undefined) {
259
+ return [{ name: 'copy_changes', status: 'failed', detail: 'could not read the uncommitted changes' }];
260
+ }
261
+ if (changed.length === 0 && untracked.length === 0) {
262
+ return [
263
+ {
264
+ name: 'copy_changes',
265
+ status: 'skipped',
266
+ detail: 'no uncommitted changes',
267
+ copyChanges: { copied: 0, failed: [] },
268
+ },
269
+ ];
270
+ }
271
+ const patchPath = await copyChangesPatchPath(context, seams);
272
+ if (patchPath === undefined) {
273
+ return [
274
+ {
275
+ name: 'copy_changes',
276
+ status: 'failed',
277
+ detail: "could not read the worktree's administrative directory",
278
+ copyChanges: { copied: 0, failed: [...changed, ...untracked] },
279
+ },
280
+ ];
281
+ }
282
+
283
+ let copied = 0;
284
+ const failedTracked = [];
285
+ const failedUntracked = [];
286
+ for (const path of changed) {
287
+ if (await applyChangedFile(context, seams, patchPath, path)) copied += 1;
288
+ else failedTracked.push(path);
289
+ }
290
+ for (const path of untracked) {
291
+ const outcome = await copyUntrackedFile(context, seams, path);
292
+ if (outcome === 'copied') copied += 1;
293
+ else if (outcome === 'failed') failedUntracked.push(path);
294
+ }
295
+ // S18: a conflicting patch leaves the worktree exactly as Git created it; the
296
+ // failing paths are reported instead of aborting the creation.
297
+ if (failedTracked.length > 0) await discardFailedChanges(context, seams, failedTracked);
298
+ const failed = [...failedTracked, ...failedUntracked];
299
+ if (failed.length > 0) {
300
+ return [
301
+ {
302
+ name: 'copy_changes',
303
+ status: 'failed',
304
+ detail: `could not copy: ${failed.join(', ')}`,
305
+ copyChanges: { copied, failed },
306
+ },
307
+ ];
308
+ }
309
+ return [{ name: 'copy_changes', status: 'applied', copyChanges: { copied, failed: [] } }];
310
+ },
311
+ };
312
+
313
+ /** One Git query whose answer is a NUL-separated path list, or nothing when it failed. */
314
+ async function gitPaths(seams, cwd, args) {
315
+ const result = await seams.git(cwd, args);
316
+ if (result === undefined || result.code !== 0) return undefined;
317
+ return result.stdout.split('\0').filter((path) => path.length > 0);
283
318
  }
284
319
 
285
- // Async tracked check: same fail-closed classification as the sync twin.
286
- async function isTrackedByGitAsync(runAsync, principalRoot, candidate, timeoutMs, env) {
287
- let res;
288
- try {
289
- res = await runAsync('git', ['ls-files', '--error-unmatch', candidate], { cwd: principalRoot, timeoutMs, env });
290
- } catch {
291
- return true;
292
- }
293
- if (!res) return true;
294
- if (res.status === 0) return true;
295
- if (res.status === null || res.status === undefined || res.error) return true;
296
- return false;
320
+ /** Git writes the patch, so no hook ever handles its bytes or its encoding. */
321
+ async function copyChangesPatchPath(context, seams) {
322
+ const gitDir = await seams.git(context.path, ['rev-parse', '--path-format=absolute', '--git-dir']);
323
+ if (gitDir === undefined || gitDir.code !== 0) return undefined;
324
+ const path = gitDir.stdout.trim();
325
+ return path.length === 0 ? undefined : join(path, COPY_CHANGES_PATCH_FILENAME);
297
326
  }
298
327
 
299
- // Async counterpart of runCreationHooks (S63): same order, same steps,
300
- // same warnings, same fail-closed gates — but subprocesses run on a
301
- // spawned child with a killing timeout and copies run on async fs, so
302
- // Pi input/render/event-loop work advances WHILE hooks are pending.
303
- // Never detaches orphan jobs: every child is owned until settle (close /
304
- // error / timeout / abort kills it). Never skips installs/codegraph as
305
- // a speed fix; no extra retries beyond the npm fallback. Fixed argv only.
306
- //
307
- // `deferSetup: true` splits the run for BOTH create fronts (the `worktree_create`
308
- // tool and the panel): the file-level steps (unversioned copies, principal links)
309
- // still settle before it returns, while the slow half (dependency install,
310
- // `codegraph init`) travels back as `setup()` — one callable, run once, never
311
- // rejecting — so the caller hands the checkout back as soon as it exists.
312
- // Nothing is skipped: the deferred phases still run, just after the caller has
313
- // handed control back.
314
- async function runCreationHooksAsync(opts = {}) {
315
- const principalRoot = resolvePrincipal(opts);
316
- const worktreePath = resolveWorktree(opts);
317
- if (typeof principalRoot !== 'string' || principalRoot === '') {
318
- throw new TypeError('runCreationHooksAsync requires principalRoot (or root)');
319
- }
320
- if (typeof worktreePath !== 'string' || worktreePath === '') {
321
- throw new TypeError('runCreationHooksAsync requires worktreePath');
322
- }
323
- const env = opts.env || process.env;
324
- const timeoutMs = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
325
- const signal = opts.signal || null;
326
- const candidates = Array.isArray(opts.unversionedCandidates)
327
- ? opts.unversionedCandidates
328
- : DEFAULT_UNVERSIONED_FILES;
329
- const table = Array.isArray(opts.installTable) ? opts.installTable : DEFAULT_INSTALL_TABLE;
330
- const spawnFn = opts.spawnFn;
331
- const killGraceMs = opts.killGraceMs;
332
- // Preferred async runner; else await a promise-returning `run`; else the
333
- // owned default that kills on timeout/abort. A purely sync blocking `run`
334
- // must not be passed here (it would re-block the loop).
335
- let runAsync;
336
- if (typeof opts.runAsync === 'function') {
337
- runAsync = (bin, args, o) => opts.runAsync(bin, args, o);
338
- } else if (typeof opts.run === 'function') {
339
- runAsync = (bin, args, o) => {
340
- const out = opts.run(bin, args, o);
341
- if (out && typeof out.then === 'function') return out;
342
- return Promise.resolve(out);
343
- };
344
- } else {
345
- runAsync = (bin, args, o) => defaultRunAsync(bin, args, { ...o, env, spawnFn, signal });
346
- }
347
- const defaultedRunAsync = runAsync;
348
- const runWithDefaults = (bin, args, o) => defaultedRunAsync(bin, args, { ...o, env, spawnFn, signal, killGraceMs });
349
- const hasBinary = typeof opts.hasBinary === 'function'
350
- ? (bin) => opts.hasBinary(bin, env)
351
- : (bin) => defaultHasBinary(bin, env);
352
- const existsAsync = opts.existsAsync;
353
- const copyAsync = opts.copyAsync;
354
-
355
- const steps = [];
356
- const warnings = [];
357
- let failed = false;
358
- const addStep = (name, status, detail) => {
359
- steps.push({ name, status, detail: String(detail || '') });
360
- if (status === 'failed') failed = true;
361
- };
362
-
363
- // (a) Copy unversioned files on async fs (heartbeat advances mid-copy).
364
- {
365
- const copied = [];
366
- const skipped = [];
367
- let copyError = null;
368
- for (const candidate of candidates) {
369
- const src = path.join(principalRoot, candidate);
370
- const dest = path.join(worktreePath, candidate);
371
- if (!(await pathExistsAsync(src, existsAsync))) {
372
- skipped.push(`${candidate}: missing source`);
373
- continue;
374
- }
375
- if (await pathExistsAsync(dest, existsAsync)) {
376
- skipped.push(`${candidate}: target exists`);
377
- continue;
378
- }
379
- if (await isTrackedByGitAsync(runWithDefaults, principalRoot, candidate, timeoutMs, env)) {
380
- skipped.push(`${candidate}: tracked`);
381
- continue;
382
- }
383
- try {
384
- await copyFileAsyncDefault(src, dest, copyAsync);
385
- copied.push(candidate);
386
- } catch (err) {
387
- copyError = err;
388
- skipped.push(`${candidate}: copy failed`);
389
- }
390
- }
391
- const outcome = formatCopyOutcome(copied, skipped, copyError);
392
- if (outcome.warning) warnings.push(outcome.warning);
393
- addStep('copy-unversioned', outcome.status, outcome.detail);
394
- }
395
-
396
- // (a2) Link git-ignored principal entries: the async twin of the sync
397
- // step, sharing the one classifier in lib/worktree-symlinks.js so the tool
398
- // path and the panel create path cannot disagree. The git reads and the
399
- // link writes are awaited, so the event loop keeps running.
400
- //
401
- // Policy (round-3 S3/L4): `.agents`, `.pi`, `.claude` and `odd` become
402
- // symlinks to the principal ONLY when git ignores them there. A tracked
403
- // entry arrives with the checkout, an untracked-but-not-ignored one is not
404
- // eligible, and an occupied target is preserved — never copied, never
405
- // deleted, never fatal.
406
- {
407
- let applied = null;
408
- let linkError = null;
409
- try {
410
- applied = await symlinksLib.applyWorktreeSymlinksAsync({
411
- principalRoot, worktreePath, env, timeoutMs, runAsync: runWithDefaults,
412
- });
413
- } catch (err) {
414
- linkError = err;
415
- }
416
- const outcome = formatLinkOutcome(applied, linkError);
417
- if (outcome.warning) warnings.push(outcome.warning);
418
- addStep('link-principal-entries', outcome.status, outcome.detail);
419
- }
420
-
421
- // (b) Dependency install by detected stack (shared detection pipeline) and
422
- // (c) `codegraph init` when the CLI is available. These two are the SLOW
423
- // half — a package manager can run for minutes — so they are one unit that
424
- // the interactive create can defer instead of awaiting.
425
- const runSetupPhases = async () => {
426
- const setupSteps = [];
427
- const setupWarnings = [];
428
- let setupFailed = false;
429
- const addSetupStep = (name, status, detail) => {
430
- setupSteps.push({ name, status, detail: String(detail || '') });
431
- if (status === 'failed') setupFailed = true;
432
- };
433
-
434
- {
435
- const detected = selectInstallEntries(worktreePath, table);
436
- if (detected.length === 0) {
437
- addSetupStep('install', 'skipped', 'no lockfile detected');
438
- }
439
- for (const entry of detected) {
440
- const name = `install:${entry.key}`;
441
- const parsed = installEntryArgv(entry);
442
- if (!parsed) {
443
- addSetupStep(name, 'skipped', 'no command configured');
444
- continue;
445
- }
446
- const { bin, args } = parsed;
447
- if (!hasBinary(bin)) {
448
- addSetupStep(name, 'skipped', `${bin} not on PATH`);
449
- continue;
450
- }
451
- let res;
452
- try {
453
- res = await runWithDefaults(bin, args, { cwd: worktreePath, timeoutMs, env });
454
- } catch (err) {
455
- res = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
456
- }
457
- if (res && res.status === 0) {
458
- addSetupStep(name, 'done', `${bin} ${args.join(' ')} exited 0`);
459
- continue;
460
- }
461
- if (Array.isArray(entry.fallbackArgv) && entry.fallbackArgv.length > 0) {
462
- const fbBin = entry.fallbackArgv[0];
463
- const fbArgs = entry.fallbackArgv.slice(1);
464
- if (!hasBinary(fbBin)) {
465
- const message = `${name}: ${bin} ${args.join(' ')} failed and fallback ${fbBin} not on PATH`;
466
- setupWarnings.push(message);
467
- addSetupStep(name, 'failed', message);
468
- continue;
469
- }
470
- let fb;
471
- try {
472
- fb = await runWithDefaults(fbBin, fbArgs, { cwd: worktreePath, timeoutMs, env });
473
- } catch (err) {
474
- fb = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
475
- }
476
- if (fb && fb.status === 0) {
477
- addSetupStep(name, 'done', `${bin} ${args.join(' ')} failed, ${fbBin} ${fbArgs.join(' ')} exited 0`);
478
- continue;
479
- }
480
- const message = `${name}: ${bin} ${args.join(' ')} failed (${((res && (res.stderr || res.error)) || 'exit non-zero').trim()}), `
481
- + `fallback ${fbBin} ${fbArgs.join(' ')} failed (${((fb && (fb.stderr || fb.error)) || 'exit non-zero').trim()})`;
482
- setupWarnings.push(message);
483
- addSetupStep(name, 'failed', message);
484
- continue;
485
- }
486
- const cause = runCause(res);
487
- const message = `${name}: ${bin} ${args.join(' ')} failed (${cause})`;
488
- setupWarnings.push(message);
489
- addSetupStep(name, 'failed', message);
490
- }
491
- }
492
-
493
- {
494
- const codegraph = codegraphDecision(opts, env, hasBinary);
495
- if (!codegraph.available) {
496
- addSetupStep('codegraph-init', 'skipped', codegraph.detail);
497
- } else {
498
- let res;
499
- try {
500
- res = await runWithDefaults('codegraph', ['init'], { cwd: worktreePath, timeoutMs, env });
501
- } catch (err) {
502
- res = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
503
- }
504
- if (res && res.status === 0) {
505
- addSetupStep('codegraph-init', 'done', 'codegraph init exited 0');
506
- } else {
507
- const cause = runCause(res);
508
- const message = `codegraph-init: codegraph init failed (${cause})`;
509
- setupWarnings.push(message);
510
- addSetupStep('codegraph-init', 'failed', message);
511
- }
512
- }
513
- }
514
-
515
- return { ok: !setupFailed, steps: setupSteps, warnings: setupWarnings };
516
- };
517
-
518
- // Deferred setup: the caller wants the checkout usable NOW and the slow
519
- // phases later. Nothing is skipped — the phases travel as ONE callable that
520
- // runs them exactly once (a second call returns the same promise, so a
521
- // retry can never install twice) and never rejects: a thrown phase becomes a
522
- // failed step, so a deferred caller can always report an outcome.
523
- let setupPromise = null;
524
- const runSetupOnce = () => {
525
- if (setupPromise === null) {
526
- setupPromise = (async () => {
527
- try {
528
- return await runSetupPhases();
529
- } catch (err) {
530
- const message = `creation setup failed: ${(err && err.message) || err}`;
531
- return { ok: false, steps: [{ name: 'setup', status: 'failed', detail: message }], warnings: [message] };
532
- }
533
- })();
534
- }
535
- return setupPromise;
536
- };
537
-
538
- if (opts.deferSetup === true) {
539
- // The steps the deferred half WILL report are named as pending, so the
540
- // caller's own report is honest about what has not happened yet instead of
541
- // claiming a skipped or a completed setup.
542
- addStep('install', 'pending', 'setup runs in the background');
543
- addStep('codegraph-init', 'pending', 'setup runs in the background');
544
- return { ok: !failed, steps, warnings, deferred: true, setup: runSetupOnce };
545
- }
546
-
547
- const setupOutcome = await runSetupOnce();
548
- for (const step of setupOutcome.steps) steps.push(step);
549
- for (const warning of setupOutcome.warnings) warnings.push(warning);
550
- if (!setupOutcome.ok) failed = true;
551
-
552
- return { ok: !failed, steps, warnings };
328
+ /** S18: one tracked path, patched from the asking checkout and applied with `--3way` in the worktree. */
329
+ async function applyChangedFile(context, seams, patchPath, path) {
330
+ const patch = await seams.git(context.changesRoot, ['diff', '--binary', '--no-renames', `--output=${patchPath}`, 'HEAD', '--', path]);
331
+ if (patch === undefined || patch.code !== 0) return false;
332
+ const applied = await seams.git(context.path, ['apply', '--3way', patchPath]);
333
+ return applied !== undefined && applied.code === 0;
334
+ }
335
+
336
+ /** A byte copy; a path another hook already carried over is left as that hook wrote it. */
337
+ async function copyUntrackedFile(context, seams, path) {
338
+ if (!isSafeRelativePath(path)) return 'failed';
339
+ const destination = join(context.path, path);
340
+ if ((await seams.kind(destination)) !== undefined) return 'present';
341
+ try {
342
+ await seams.mkdir(dirname(destination));
343
+ await seams.copyFile(join(context.changesRoot, path), destination);
344
+ return 'copied';
345
+ } catch {
346
+ return 'failed';
347
+ }
348
+ }
349
+
350
+ /**
351
+ * S18: `--3way` implies `--index`, so a conflict leaves unmerged entries and conflict
352
+ * markers behind. The index is reset to the worktree's own HEAD and the failing paths
353
+ * are written back from it; both are plumbing over a checkout this hook never owned,
354
+ * so the worktree is usable and clean again.
355
+ */
356
+ async function discardFailedChanges(context, seams, failed) {
357
+ await seams.git(context.path, ['read-tree', 'HEAD']);
358
+ await seams.git(context.path, ['checkout-index', '-f', '--', ...failed]);
359
+ }
360
+
361
+ // ---- S19 step 4: the build caches and the local asset directories ----
362
+
363
+ const symlinksHook = {
364
+ name: 'symlinks',
365
+ async run(context, seams) {
366
+ const results = [];
367
+ const candidates = unique([...WORKTREE_BUILD_CACHE_LINKS, ...WORKTREE_ASSET_LINKS, ...context.config.link]);
368
+ for (const path of candidates) results.push(await linkPath(context, seams, path));
369
+ return results;
370
+ },
371
+ };
372
+
373
+ /**
374
+ * Links one directory from main. A refused link is retried as a junction, which Windows
375
+ * grants without the developer mode, and a second refusal is reported: the failure is
376
+ * never replaced by a copy that would silently duplicate a cache.
377
+ */
378
+ async function linkPath(context, seams, path) {
379
+ const name = `symlink ${path}`;
380
+ if (!isSafeRelativePath(path)) return { name, status: 'skipped', detail: `${path} is not a relative path` };
381
+ const relative = relativePath(path);
382
+ if (isNeverLinked(relative)) return { name, status: 'skipped', detail: `${relative} is never linked` };
383
+ const target = join(context.mainRoot, relative);
384
+ if ((await seams.kind(target)) === undefined) return { name, status: 'skipped', detail: `${relative} not in main` };
385
+ if (await isTracked(seams, context.mainRoot, relative)) return { name, status: 'skipped', detail: 'tracked' };
386
+ const link = join(context.path, relative);
387
+ if ((await seams.kind(link)) !== undefined) return { name, status: 'skipped', detail: `${relative} already exists in the worktree` };
388
+
389
+ const attempts = seams.platform === 'win32' ? ['junction', 'dir'] : ['dir', 'junction'];
390
+ let firstFailure;
391
+ for (const type of attempts) {
392
+ try {
393
+ await seams.mkdir(dirname(link));
394
+ await seams.symlink(target, link, type);
395
+ const warning = await gitignoreWarning(context, seams, relative);
396
+ const applied = { name, status: 'applied' };
397
+ if (type === 'junction') applied.detail = 'junction';
398
+ if (warning !== undefined) applied.warning = warning;
399
+ return applied;
400
+ } catch (error) {
401
+ if (firstFailure === undefined) firstFailure = reasonFor(error);
402
+ }
403
+ }
404
+ return { name, status: 'failed', detail: `could not link ${relative}: ${firstFailure ?? 'no link type was attempted'}` };
405
+ }
406
+
407
+ // ---- S16 and S7: what the output prints and the record stores ----
408
+
409
+ /**
410
+ * S16: the one `hooks:` line. It summarises the counts, names everything that failed and
411
+ * carries the `.gitignore` advice, and it is absent when nothing applied and nothing
412
+ * failed, because an empty line would claim a chain that never ran.
413
+ */
414
+ function worktreeHooksSummary(results) {
415
+ const applied = results.filter((result) => result.status === 'applied').length;
416
+ const skipped = results.filter((result) => result.status === 'skipped').length;
417
+ const failed = results.filter((result) => result.status === 'failed');
418
+ if (applied === 0 && failed.length === 0) return undefined;
419
+ const parts = [];
420
+ if (applied > 0) parts.push(`${applied} applied`);
421
+ if (skipped > 0) parts.push(`${skipped} skipped`);
422
+ if (failed.length > 0) parts.push(`${failed.length} failed: ${failed.map((result) => `${result.name} (${result.detail ?? 'no reason'})`).join(', ')}`);
423
+ const warnings = results.map((result) => result.warning).filter((warning) => warning !== undefined);
424
+ if (warnings.length > 0) parts.push(`warning: ${warnings.join('; ')}`);
425
+ return `hooks: ${parts.join(', ')}`;
426
+ }
427
+
428
+ /** S18: the one dedicated line, present only when the request passed copy_changes. */
429
+ function worktreeCopyChangesLine(results) {
430
+ const result = results.find((entry) => entry.name === 'copy_changes');
431
+ if (result === undefined) return undefined;
432
+ const outcome = result.copyChanges;
433
+ if (outcome === undefined) return `copy_changes: ${result.detail ?? 'could not copy the uncommitted changes'}`;
434
+ if (outcome.failed.length > 0) {
435
+ return `copy_changes: ${outcome.copied} changes copied; failed: ${outcome.failed.join(', ')}`;
436
+ }
437
+ if (outcome.copied === 0) return 'copy_changes: no uncommitted changes to copy';
438
+ return `copy_changes: ${outcome.copied} changes copied`;
553
439
  }
554
440
 
555
- function runCreationHooks(opts = {}) {
556
- const principalRoot = resolvePrincipal(opts);
557
- const worktreePath = resolveWorktree(opts);
558
- if (typeof principalRoot !== 'string' || principalRoot === '') {
559
- throw new TypeError('runCreationHooks requires principalRoot (or root)');
560
- }
561
- if (typeof worktreePath !== 'string' || worktreePath === '') {
562
- throw new TypeError('runCreationHooks requires worktreePath');
563
- }
564
- const env = opts.env || process.env;
565
- const timeoutMs = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
566
- const candidates = Array.isArray(opts.unversionedCandidates)
567
- ? opts.unversionedCandidates
568
- : DEFAULT_UNVERSIONED_FILES;
569
- const table = Array.isArray(opts.installTable) ? opts.installTable : DEFAULT_INSTALL_TABLE;
570
- const run = typeof opts.run === 'function'
571
- ? (bin, args, o) => opts.run(bin, args, o)
572
- : (bin, args, o) => defaultRun(bin, args, { ...o, env });
573
- const hasBinary = typeof opts.hasBinary === 'function'
574
- ? (bin) => opts.hasBinary(bin, env)
575
- : (bin) => defaultHasBinary(bin, env);
576
-
577
- const steps = [];
578
- const warnings = [];
579
- let failed = false;
580
- const addStep = (name, status, detail) => {
581
- steps.push({ name, status, detail: String(detail || '') });
582
- if (status === 'failed') failed = true;
583
- };
584
-
585
- // (a) Copy unversioned files. Each candidate is copied from the
586
- // principal checkout ONLY when it exists there, is NOT tracked by git,
587
- // and does NOT already exist in the worktree. Never overwrite, never
588
- // copy a tracked file, never fail for a missing source.
589
- {
590
- const copied = [];
591
- const skipped = [];
592
- let copyError = null;
593
- for (const candidate of candidates) {
594
- const src = path.join(principalRoot, candidate);
595
- const dest = path.join(worktreePath, candidate);
596
- if (!pathExists(src)) {
597
- skipped.push(`${candidate}: missing source`);
598
- continue;
599
- }
600
- if (pathExists(dest)) {
601
- skipped.push(`${candidate}: target exists`);
602
- continue;
603
- }
604
- if (isTrackedByGit(run, principalRoot, candidate, timeoutMs, env)) {
605
- skipped.push(`${candidate}: tracked`);
606
- continue;
607
- }
608
- try {
609
- fs.copyFileSync(src, dest);
610
- copied.push(candidate);
611
- } catch (err) {
612
- copyError = err;
613
- skipped.push(`${candidate}: copy failed`);
614
- }
615
- }
616
- if (copyError && copied.length === 0) {
617
- // A copy error with nothing copied is a failed step plus a warning,
618
- // but never aborts the remaining hooks.
619
- const message = `copy unversioned files failed: ${(copyError && copyError.message) || copyError}`;
620
- warnings.push(message);
621
- addStep('copy-unversioned', 'failed', `copied none; ${skipped.join('; ')}`);
622
- } else {
623
- if (copyError) warnings.push(`copy unversioned files partially failed: ${(copyError && copyError.message) || copyError}`);
624
- addStep(
625
- 'copy-unversioned',
626
- copied.length > 0 ? 'done' : 'skipped',
627
- copied.length > 0
628
- ? `copied ${copied.join(', ')}${skipped.length > 0 ? `; skipped ${skipped.join('; ')}` : ''}`
629
- : `copied none; ${skipped.join('; ') || 'nothing to copy'}`,
630
- );
631
- }
632
- }
633
-
634
- // (a2) Link git-ignored principal entries (round-3 S3/L4). One shared
635
- // policy for both creation routes: `.agents`, `.pi`, `.claude` and `odd`
636
- // become symlinks to the principal ONLY when git ignores them there. A
637
- // tracked entry arrives with the checkout, an untracked-but-not-ignored
638
- // one is not eligible, and an occupied target is preserved — this step
639
- // never copies, never deletes and never aborts the creation.
640
- {
641
- let applied = null;
642
- let linkError = null;
643
- try {
644
- applied = symlinksLib.applyWorktreeSymlinks({
645
- principalRoot, worktreePath, env, timeoutMs, run,
646
- });
647
- } catch (err) {
648
- linkError = err;
649
- }
650
- const outcome = formatLinkOutcome(applied, linkError);
651
- if (outcome.warning) warnings.push(outcome.warning);
652
- addStep('link-principal-entries', outcome.status, outcome.detail);
653
- }
654
-
655
- // (b) Dependency install by detected stack. Every detected stack runs in
656
- // table order. A missing binary is skipped; a non-zero exit is failed
657
- // plus a warning and never aborts the remaining steps. `npm ci` falls
658
- // back to `npm install` only when `ci` fails.
659
- {
660
- const detected = table.filter((entry) => Array.isArray(entry.markers)
661
- && entry.markers.some((marker) => pathExists(path.join(worktreePath, marker))));
662
- if (detected.length === 0) {
663
- addStep('install', 'skipped', 'no lockfile detected');
664
- }
665
- for (const entry of detected) {
666
- const name = `install:${entry.key}`;
667
- const argv = entry.argv || [];
668
- const bin = argv[0];
669
- const args = argv.slice(1);
670
- if (typeof bin !== 'string' || bin === '') {
671
- addStep(name, 'skipped', 'no command configured');
672
- continue;
673
- }
674
- if (!hasBinary(bin)) {
675
- addStep(name, 'skipped', `${bin} not on PATH`);
676
- continue;
677
- }
678
- let res;
679
- try {
680
- res = run(bin, args, { cwd: worktreePath, timeoutMs, env });
681
- } catch (err) {
682
- res = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
683
- }
684
- if (res && res.status === 0) {
685
- addStep(name, 'done', `${bin} ${args.join(' ')} exited 0`);
686
- continue;
687
- }
688
- // Non-zero: npm alone gets exactly one fallback to `npm install`.
689
- if (Array.isArray(entry.fallbackArgv) && entry.fallbackArgv.length > 0) {
690
- const fbBin = entry.fallbackArgv[0];
691
- const fbArgs = entry.fallbackArgv.slice(1);
692
- if (!hasBinary(fbBin)) {
693
- const message = `${name}: ${bin} ${args.join(' ')} failed and fallback ${fbBin} not on PATH`;
694
- warnings.push(message);
695
- addStep(name, 'failed', message);
696
- continue;
697
- }
698
- let fb;
699
- try {
700
- fb = run(fbBin, fbArgs, { cwd: worktreePath, timeoutMs, env });
701
- } catch (err) {
702
- fb = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
703
- }
704
- if (fb && fb.status === 0) {
705
- addStep(name, 'done', `${bin} ${args.join(' ')} failed, ${fbBin} ${fbArgs.join(' ')} exited 0`);
706
- continue;
707
- }
708
- const message = `${name}: ${bin} ${args.join(' ')} failed (${((res && (res.stderr || res.error)) || 'exit non-zero').trim()}), `
709
- + `fallback ${fbBin} ${fbArgs.join(' ')} failed (${((fb && (fb.stderr || fb.error)) || 'exit non-zero').trim()})`;
710
- warnings.push(message);
711
- addStep(name, 'failed', message);
712
- continue;
713
- }
714
- const cause = res && (res.stderr || res.error)
715
- ? String(res.stderr || res.error).trim()
716
- : `exit ${res && res.status !== null && res.status !== undefined ? res.status : 'non-zero'}`;
717
- const message = `${name}: ${bin} ${args.join(' ')} failed (${cause})`;
718
- warnings.push(message);
719
- addStep(name, 'failed', message);
720
- }
721
- }
722
-
723
- // (c) codegraph init when the CLI is available. Skipped with a reason
724
- // when absent; a non-zero exit is failed plus a warning. Never fatal.
725
- {
726
- const codegraph = codegraphDecision(opts, env, hasBinary);
727
- if (!codegraph.available) {
728
- addStep('codegraph-init', 'skipped', codegraph.detail);
729
- } else {
730
- let res;
731
- try {
732
- res = run('codegraph', ['init'], { cwd: worktreePath, timeoutMs, env });
733
- } catch (err) {
734
- res = { status: null, stdout: '', stderr: '', error: String((err && err.message) || err) };
735
- }
736
- if (res && res.status === 0) {
737
- addStep('codegraph-init', 'done', 'codegraph init exited 0');
738
- } else {
739
- const cause = res && (res.stderr || res.error)
740
- ? String(res.stderr || res.error).trim()
741
- : `exit ${res && res.status !== null && res.status !== undefined ? res.status : 'non-zero'}`;
742
- const message = `codegraph-init: codegraph init failed (${cause})`;
743
- warnings.push(message);
744
- addStep('codegraph-init', 'failed', message);
745
- }
746
- }
747
- }
748
-
749
- return { ok: !failed, steps, warnings };
441
+ /** S7: the outcome as the record stores it, with the advice folded into its detail. */
442
+ function worktreeHookRecords(results) {
443
+ return results.map((result) => {
444
+ const detail = [result.detail, result.warning].filter((part) => part !== undefined).join('; ');
445
+ return detail.length === 0 ? { name: result.name, status: result.status } : { name: result.name, status: result.status, detail };
446
+ });
750
447
  }
751
448
 
752
449
  module.exports = {
753
- runCreationHooks,
754
- runCreationHooksAsync,
755
- DEFAULT_UNVERSIONED_FILES,
756
- DEFAULT_INSTALL_TABLE,
757
- DEFAULT_TIMEOUT_MS,
450
+ WORKTREE_HOOKS_FILENAME,
451
+ worktreeHooksFilePath,
452
+ WORKTREE_NEVER_LINKED,
453
+ WORKTREE_BUILD_CACHE_LINKS,
454
+ WORKTREE_ASSET_LINKS,
455
+ WORKTREE_INPUT_PREFIX,
456
+ emptyWorktreeHooksConfig,
457
+ parseWorktreeHooksConfig,
458
+ runWorktreeHooks,
459
+ defaultWorktreeHooks,
460
+ submodulesHook,
461
+ inputsHook,
462
+ copyChangesHook,
463
+ symlinksHook,
464
+ worktreeHooksSummary,
465
+ worktreeCopyChangesLine,
466
+ worktreeHookRecords,
758
467
  };