@imdeadpool/guardex 7.1.0 → 7.1.1

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.
package/src/mcp/server.js CHANGED
@@ -19,7 +19,7 @@ const TOOLS = [
19
19
  {
20
20
  name: 'list_agents',
21
21
  description:
22
- 'List every active agent lane across all discovered repos: repo, branch, worktree, task, dirty (files changed RIGHT NOW), held file locks, last commit, ageDays, the PR it is shipping (with prLookupError set when the gh lookup itself failed, vs no open PR), stale (old + no PR + clean = a prune candidate), and warnings — e.g. a lane editing the primary checkout (the harness should act on that warning by moving to `gx branch start`). Use this to see who is working on what before you start. Read-only.',
22
+ 'List every active agent lane across all discovered repos. Returns a COMPACT radar by default — per lane: repo, branch, agent, task, dirty (count of files changed right now), locks (count), pr (number), last (commit date), and flags stale / onPrimary / unpushed when set. Use it to see who is working on what before you start. For full detail on a lane (worktree path, the actual dirty/lock file lists, full PR), call repo_state or my_context, or pass detail:true here (where the onPrimary flag appears as warning + onPrimaryCheckout instead). Read-only.',
23
23
  inputSchema: {
24
24
  type: 'object',
25
25
  properties: {
@@ -33,6 +33,7 @@ const TOOLS = [
33
33
  description: 'Override repo search roots. Default: ~/Documents, ~/code, ~/src, ~/projects.',
34
34
  },
35
35
  limit: { type: 'number', description: 'Max number of repos to scan.' },
36
+ detail: { type: 'boolean', description: 'Return full lane records (worktree path, dirty/lock file lists, full PR) instead of the compact radar. Default false.' },
36
37
  },
37
38
  },
38
39
  },
@@ -71,14 +72,19 @@ const TOOLS = [
71
72
 
72
73
  function callTool(name, args = {}) {
73
74
  switch (name) {
74
- case 'list_agents':
75
+ case 'list_agents': {
75
76
  // PRs on by default: one gh call per repo that has active lanes (most
76
77
  // repos have none, so they cost nothing). Pass include_prs:false to skip.
77
- return collect.collectAllAgents({
78
+ const full = collect.collectAllAgents({
78
79
  roots: args.roots,
79
80
  includePrs: args.include_prs !== false,
80
81
  limit: args.limit,
81
82
  });
83
+ // Compact radar by default (~80% fewer tokens); detail:true keeps the
84
+ // full records for callers that need worktree paths / file lists.
85
+ if (args.detail) return full;
86
+ return { ...full, agents: full.agents.map(collect.radarRecord) };
87
+ }
82
88
  case 'repo_state':
83
89
  return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs !== false });
84
90
  case 'who_owns':
@@ -118,7 +124,7 @@ function dispatch(msg) {
118
124
  const name = params && params.name;
119
125
  const args = (params && params.arguments) || {};
120
126
  const result = callTool(name, args);
121
- return ok(id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] });
127
+ return ok(id, { content: [{ type: 'text', text: JSON.stringify(result) }] });
122
128
  }
123
129
  if (method === 'ping') return ok(id, {});
124
130
  if (isNotification) return null; // e.g. notifications/initialized
@@ -20,6 +20,7 @@
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
22
  const { spawnSync } = require('child_process');
23
+ const { provisionFromConfig } = require('./provision-config');
23
24
 
24
25
  const ENV_FILE_CANDIDATES = [
25
26
  '.env',
@@ -190,10 +191,16 @@ function prepareAgentWorktree(repoRoot, worktreePath) {
190
191
  if (!repoRoot || !worktreePath) return [];
191
192
  if (repoRoot === worktreePath) return [];
192
193
  if (!fs.existsSync(worktreePath)) return [];
193
- const apps = detectAppPackages(repoRoot);
194
- if (apps.length === 0) return [];
195
194
 
196
195
  const operations = [];
196
+
197
+ // Declarative `.guardex.json` provisioning runs for ANY repo (monorepo or
198
+ // not) — copy/symlink gitignored files and run post_create hooks.
199
+ operations.push(...provisionFromConfig(repoRoot, worktreePath));
200
+
201
+ // Built-in apps/* monorepo convenience: env-file symlinks + a free dev port
202
+ // per app. Stays as the zero-config default for monorepos.
203
+ const apps = detectAppPackages(repoRoot);
197
204
  const takenPorts = new Set();
198
205
  for (const appName of apps) {
199
206
  operations.push(...symlinkAppEnvFiles(repoRoot, worktreePath, appName));
@@ -0,0 +1,314 @@
1
+ 'use strict';
2
+
3
+ // Declarative per-repo worktree provisioning (workmux W2).
4
+ //
5
+ // A repo may commit a `.guardex.json` at its root describing how to make a
6
+ // fresh agent worktree usable — which gitignored files to copy or symlink in,
7
+ // and which setup commands to run after creation:
8
+ //
9
+ // {
10
+ // "provision": {
11
+ // "files": {
12
+ // "copy": [".env", "apps/*/.env"], // per-worktree copies
13
+ // "symlink": ["node_modules", ".venv"] // shared via symlink
14
+ // },
15
+ // "postCreate": ["pnpm install --offline"]
16
+ // }
17
+ // }
18
+ //
19
+ // Parsed with jsonc-parser (comments allowed) — no new dependency. copy/symlink
20
+ // are pure filesystem ops. postCreate runs shell commands from the repo owner's
21
+ // committed config (same trust as package.json scripts); disable with
22
+ // GUARDEX_PROVISION_HOOKS=0. Everything is best-effort and never throws fatally.
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const { spawnSync } = require('child_process');
27
+ const jsonc = require('jsonc-parser');
28
+
29
+ const CONFIG_BASENAME = '.guardex.json';
30
+ const POST_CREATE_TIMEOUT_MS = 10 * 60 * 1000;
31
+
32
+ function toStringArray(value) {
33
+ if (!Array.isArray(value)) return [];
34
+ return value.filter((item) => typeof item === 'string' && item.trim() !== '');
35
+ }
36
+
37
+ // Read + normalize <repoRoot>/.guardex.json's `provision` block. Returns null
38
+ // when there is no config or no provision block; tolerant of malformed JSON.
39
+ function loadProvisionConfig(repoRoot, deps = {}) {
40
+ if (!repoRoot) return null;
41
+ const readFile = deps.readFile || ((p) => fs.readFileSync(p, 'utf8'));
42
+ const configPath = path.join(repoRoot, CONFIG_BASENAME);
43
+
44
+ let text;
45
+ try {
46
+ text = readFile(configPath);
47
+ } catch (error) {
48
+ if (error && error.code === 'ENOENT') return null;
49
+ return null;
50
+ }
51
+
52
+ const errors = [];
53
+ const parsed = jsonc.parse(text, errors, { allowTrailingComma: true });
54
+ if (errors.length > 0 || !parsed || typeof parsed !== 'object') {
55
+ return null;
56
+ }
57
+
58
+ const provision = parsed.provision;
59
+ if (!provision || typeof provision !== 'object' || Array.isArray(provision)) {
60
+ return null;
61
+ }
62
+
63
+ const files = provision.files && typeof provision.files === 'object' ? provision.files : {};
64
+ return {
65
+ source: configPath,
66
+ files: {
67
+ copy: toStringArray(files.copy),
68
+ symlink: toStringArray(files.symlink),
69
+ },
70
+ postCreate: toStringArray(provision.postCreate),
71
+ };
72
+ }
73
+
74
+ // A provisioning pattern must stay inside the repo: no absolute paths, no `..`.
75
+ function isUnsafePattern(pattern) {
76
+ if (typeof pattern !== 'string' || pattern.trim() === '') return true;
77
+ if (path.isAbsolute(pattern)) return true;
78
+ return pattern.split(/[\\/]/).some((segment) => segment === '..');
79
+ }
80
+
81
+ function segmentToRegExp(segment) {
82
+ // Only `*` is special (matches within a single path segment). Everything else
83
+ // is literal.
84
+ const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*');
85
+ return new RegExp(`^${escaped}$`);
86
+ }
87
+
88
+ // Minimal, dependency-free glob: literal segments plus a `*` wildcard within a
89
+ // single path segment (covers `.env`, `apps/*/.env`, `packages/*/.env`,
90
+ // `node_modules`). Returns repo-relative paths that exist.
91
+ function expandGlob(rootDir, pattern, deps = {}) {
92
+ if (isUnsafePattern(pattern)) return [];
93
+ const readdir = deps.readdir || ((p) => fs.readdirSync(p, { withFileTypes: true }));
94
+ const exists = deps.exists || ((p) => fs.existsSync(p));
95
+
96
+ const segments = pattern.split('/').filter((segment) => segment !== '' && segment !== '.');
97
+ let matches = [''];
98
+
99
+ for (const segment of segments) {
100
+ const next = [];
101
+ const hasWildcard = segment.includes('*');
102
+ for (const rel of matches) {
103
+ const absDir = path.join(rootDir, rel);
104
+ if (!hasWildcard) {
105
+ const candidate = rel ? `${rel}/${segment}` : segment;
106
+ if (exists(path.join(rootDir, candidate))) next.push(candidate);
107
+ continue;
108
+ }
109
+ let entries;
110
+ try {
111
+ entries = readdir(absDir);
112
+ } catch {
113
+ continue;
114
+ }
115
+ const re = segmentToRegExp(segment);
116
+ for (const entry of entries) {
117
+ const name = entry && entry.name ? entry.name : entry;
118
+ if (typeof name === 'string' && re.test(name)) {
119
+ next.push(rel ? `${rel}/${name}` : name);
120
+ }
121
+ }
122
+ }
123
+ matches = next;
124
+ }
125
+
126
+ return matches.filter((rel) => rel !== '');
127
+ }
128
+
129
+ function ensureParentDir(filePath) {
130
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
131
+ }
132
+
133
+ function safeRealpath(target) {
134
+ try {
135
+ return fs.realpathSync(target);
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ // True only when `target` (after resolving symlinks) stays inside `baseReal`.
142
+ // isUnsafePattern fences the pattern STRING; this fences the real filesystem so
143
+ // an in-repo symlink (e.g. `link -> /etc`) can't escape on read or write.
144
+ function withinReal(target, baseReal) {
145
+ if (!baseReal) return false;
146
+ const real = safeRealpath(target);
147
+ if (!real) return false;
148
+ return real === baseReal || real.startsWith(baseReal + path.sep);
149
+ }
150
+
151
+ function targetAlreadyPresent(destPath) {
152
+ try {
153
+ fs.lstatSync(destPath);
154
+ return true;
155
+ } catch (error) {
156
+ if (error && error.code !== 'ENOENT') throw error;
157
+ return false;
158
+ }
159
+ }
160
+
161
+ function applyCopy(repoRoot, worktreePath, patterns, deps = {}) {
162
+ const operations = [];
163
+ const repoReal = safeRealpath(repoRoot);
164
+ const worktreeReal = safeRealpath(worktreePath);
165
+ for (const pattern of patterns) {
166
+ const rels = expandGlob(repoRoot, pattern, deps);
167
+ if (rels.length === 0) {
168
+ operations.push({ status: 'skipped', file: pattern, note: 'no match in repo root' });
169
+ continue;
170
+ }
171
+ for (const rel of rels) {
172
+ const src = path.join(repoRoot, rel);
173
+ const dest = path.join(worktreePath, rel);
174
+ try {
175
+ // Source must resolve inside the repo (block in-repo symlink escapes).
176
+ if (!withinReal(src, repoReal)) {
177
+ operations.push({ status: 'skipped', file: rel, note: 'resolves outside repo root' });
178
+ continue;
179
+ }
180
+ if (fs.statSync(src).isDirectory()) {
181
+ operations.push({ status: 'skipped', file: rel, note: 'copy of a directory unsupported; use symlink' });
182
+ continue;
183
+ }
184
+ if (targetAlreadyPresent(dest)) {
185
+ operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
186
+ continue;
187
+ }
188
+ ensureParentDir(dest);
189
+ // Destination parent must resolve inside the worktree (block writes that
190
+ // tunnel through a symlink the worktree may already contain).
191
+ if (!withinReal(path.dirname(dest), worktreeReal)) {
192
+ operations.push({ status: 'skipped', file: rel, note: 'destination escapes worktree' });
193
+ continue;
194
+ }
195
+ fs.copyFileSync(src, dest);
196
+ operations.push({ status: 'copied', file: rel, note: 'copied from repo root' });
197
+ } catch (error) {
198
+ operations.push({ status: 'failed', file: rel, note: `copy failed: ${error.message}` });
199
+ }
200
+ }
201
+ }
202
+ return operations;
203
+ }
204
+
205
+ function applySymlink(repoRoot, worktreePath, patterns, deps = {}) {
206
+ const operations = [];
207
+ const repoReal = safeRealpath(repoRoot);
208
+ const worktreeReal = safeRealpath(worktreePath);
209
+ for (const pattern of patterns) {
210
+ const rels = expandGlob(repoRoot, pattern, deps);
211
+ if (rels.length === 0) {
212
+ operations.push({ status: 'skipped', file: pattern, note: 'no match in repo root' });
213
+ continue;
214
+ }
215
+ for (const rel of rels) {
216
+ const src = path.join(repoRoot, rel);
217
+ const dest = path.join(worktreePath, rel);
218
+ try {
219
+ // The symlink target must resolve inside the repo.
220
+ if (!withinReal(src, repoReal)) {
221
+ operations.push({ status: 'skipped', file: rel, note: 'resolves outside repo root' });
222
+ continue;
223
+ }
224
+ if (targetAlreadyPresent(dest)) {
225
+ operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
226
+ continue;
227
+ }
228
+ ensureParentDir(dest);
229
+ if (!withinReal(path.dirname(dest), worktreeReal)) {
230
+ operations.push({ status: 'skipped', file: rel, note: 'destination escapes worktree' });
231
+ continue;
232
+ }
233
+ fs.symlinkSync(src, dest);
234
+ operations.push({ status: 'linked', file: rel, note: `→ ${path.relative(worktreePath, src)}` });
235
+ } catch (error) {
236
+ operations.push({ status: 'failed', file: rel, note: `symlink failed: ${error.message}` });
237
+ }
238
+ }
239
+ }
240
+ return operations;
241
+ }
242
+
243
+ function hooksDisabled() {
244
+ const flag = String(process.env.GUARDEX_PROVISION_HOOKS || '').trim().toLowerCase();
245
+ return ['0', 'false', 'no', 'off'].includes(flag);
246
+ }
247
+
248
+ function applyPostCreate(repoRoot, worktreePath, commands, deps = {}) {
249
+ if (commands.length === 0) return [];
250
+ if (hooksDisabled()) {
251
+ return commands.map((command) => ({ status: 'skipped', file: command, note: 'GUARDEX_PROVISION_HOOKS disabled' }));
252
+ }
253
+ const run = deps.run || ((cmd, cwd, env) => spawnSync('sh', ['-lc', cmd], {
254
+ cwd,
255
+ env,
256
+ stdio: ['ignore', 'pipe', 'pipe'],
257
+ timeout: POST_CREATE_TIMEOUT_MS,
258
+ }));
259
+
260
+ const operations = [];
261
+ const env = { ...process.env, GUARDEX_WORKTREE: worktreePath, GUARDEX_REPO_ROOT: repoRoot };
262
+ for (const command of commands) {
263
+ let result;
264
+ try {
265
+ result = run(command, worktreePath, env);
266
+ } catch (error) {
267
+ operations.push({ status: 'failed', file: command, note: `hook error: ${error.message}` });
268
+ continue;
269
+ }
270
+ const ok = result && (result.status === 0 || result.status === undefined) && !result.error;
271
+ operations.push(
272
+ ok
273
+ ? { status: 'ran', file: command, note: 'post_create hook ok' }
274
+ : {
275
+ status: 'failed',
276
+ file: command,
277
+ note: `post_create exited ${result && result.status}${result && result.error ? `: ${result.error.message}` : ''}`,
278
+ },
279
+ );
280
+ }
281
+ return operations;
282
+ }
283
+
284
+ // Apply a normalized provision config to a worktree. Order: copy, symlink, then
285
+ // postCreate hooks (so hooks see the env/deps already in place). Best-effort.
286
+ function applyProvisionConfig(repoRoot, worktreePath, config, deps = {}) {
287
+ if (!config) return [];
288
+ const operations = [];
289
+ operations.push(...applyCopy(repoRoot, worktreePath, config.files.copy, deps));
290
+ operations.push(...applySymlink(repoRoot, worktreePath, config.files.symlink, deps));
291
+ operations.push(...applyPostCreate(repoRoot, worktreePath, config.postCreate, deps));
292
+ return operations;
293
+ }
294
+
295
+ // Convenience: load + apply for a freshly created worktree.
296
+ function provisionFromConfig(repoRoot, worktreePath, deps = {}) {
297
+ if (!repoRoot || !worktreePath || repoRoot === worktreePath) return [];
298
+ if (!fs.existsSync(worktreePath)) return [];
299
+ const config = loadProvisionConfig(repoRoot, deps);
300
+ if (!config) return [];
301
+ return applyProvisionConfig(repoRoot, worktreePath, config, deps);
302
+ }
303
+
304
+ module.exports = {
305
+ CONFIG_BASENAME,
306
+ loadProvisionConfig,
307
+ expandGlob,
308
+ isUnsafePattern,
309
+ applyCopy,
310
+ applySymlink,
311
+ applyPostCreate,
312
+ applyProvisionConfig,
313
+ provisionFromConfig,
314
+ };
@@ -304,6 +304,11 @@ function buildKittyCloseCommand(target, options = {}) {
304
304
  return commandShape(['@', 'close-window', '--match', targetMatch(target)], options);
305
305
  }
306
306
 
307
+ function buildKittySetWindowTitleCommand(target, title, options = {}) {
308
+ const value = title === undefined || title === null ? '' : String(title);
309
+ return commandShape(['@', 'set-window-title', '--match', targetMatch(target), value], options);
310
+ }
311
+
307
312
  function buildKittySendTextCommand(target, options = {}) {
308
313
  const shape = commandShape(['@', 'send-text', '--match', targetMatch(target), '--stdin'], options);
309
314
  if (Object.prototype.hasOwnProperty.call(options, 'input') || Object.prototype.hasOwnProperty.call(options, 'text') || options.submit) {
@@ -327,6 +332,10 @@ function buildSendTextCommand(target, config = {}) {
327
332
  return buildKittySendTextCommand(target, { kittyBin: kittyBin(config, { allowEnv: true }) });
328
333
  }
329
334
 
335
+ function buildSetWindowStatusCommand(target, title, config = {}) {
336
+ return buildKittySetWindowTitleCommand(target, title, { kittyBin: kittyBin(config, { allowEnv: true }) });
337
+ }
338
+
330
339
  function sendTextInput(value, options = {}) {
331
340
  const body = value === undefined || value === null ? '' : String(value);
332
341
  return options.submit ? `${body}\n` : body;
@@ -584,6 +593,16 @@ function createKittyBackend(config = {}) {
584
593
  'kitty could not send text',
585
594
  );
586
595
  },
596
+ setWindowStatus(target, label) {
597
+ // Non-destructive: relabel the lane window's title (a kitty window is one
598
+ // cockpit pane) to surface the W1 status icon.
599
+ return execute(
600
+ 'set-window-status',
601
+ buildSetWindowStatusCommand(target, label, config),
602
+ {},
603
+ 'kitty could not set window title',
604
+ );
605
+ },
587
606
  };
588
607
  }
589
608
 
@@ -600,6 +619,7 @@ module.exports = {
600
619
  buildKittyFocusCommand,
601
620
  buildKittyCloseCommand,
602
621
  buildKittySendTextCommand,
622
+ buildKittySetWindowTitleCommand,
603
623
  buildKittyLsCommand,
604
624
  buildKittyVersionCommand,
605
625
  buildVersionCommand,
@@ -109,6 +109,15 @@ function createBackend(options = {}) {
109
109
  focusPane(target) {
110
110
  return assertStatus(runTmux(['select-pane', '-t', targetId(target)]), 'tmux could not focus pane');
111
111
  },
112
+ setWindowStatus(target, label) {
113
+ // Non-destructive: set the pane title (shown via pane-border-format) instead
114
+ // of renaming the user's window/session. Surfaces the W1 status icon per lane.
115
+ const title = String(label === undefined || label === null ? '' : label);
116
+ return assertStatus(
117
+ runTmux(['select-pane', '-t', targetId(target), '-T', title]),
118
+ 'tmux could not set pane status',
119
+ );
120
+ },
112
121
  closePane(target) {
113
122
  return assertStatus(runTmux(['kill-pane', '-t', targetId(target)]), 'tmux could not close pane');
114
123
  },
@@ -151,6 +151,16 @@ Default: less word, same proof.
151
151
  - Keep raw terminal interaction out of long-lived context: retain only process, action sent, current result, next action.
152
152
  - Full commands/stdout belong in logs; prompt context keeps only the latest 1–2 checkpoints plus the newest tool-result summary.
153
153
 
154
+ ### Multi-agent token efficiency
155
+
156
+ Fan-out saves tokens only when each agent has a narrow job and returns a compact result. When reviewing or implementing here:
157
+
158
+ - **Scout, then implement.** A cheap-model subagent locates the 3-5 files that matter and returns a summary; edit those inline. Don't read 20+ files in the main context to find the 4 that count.
159
+ - **One agent, one job.** Each subagent gets a single objective and returns one output (analyze OR fix), not a muddle of both.
160
+ - **Review by parallel role.** Run correctness / security / consistency reviewers in parallel and synthesize — cheaper and sharper than one reviewer holding the whole diff. The finish review-gate is the place for it.
161
+ - **Route models to task weight.** scan/explore/draft → cheap (e.g. `haiku`); implement/debug → mid (`sonnet`); architecture/complex review → top (`opus`). `CLAUDE_CODE_SUBAGENT_MODEL` sets the subagent tier.
162
+ - **Don't fan out trivial work.** One-file tweaks and bounded edits stay direct (see Task-size routing) — a subagent's setup cost only pays off on a wide read or review surface.
163
+
154
164
  ### Version bumps
155
165
 
156
166
  If a change bumps a published version, the same PR records release notes in the appropriate OpenSpec artifact or release-note mechanism for the repo. Do not edit `CHANGELOG.md` directly unless the repo explicitly requires manual changelog edits.
@@ -145,8 +145,6 @@ WAIT_FOR_MERGE="$(normalize_bool "$WAIT_FOR_MERGE_RAW" "1")"
145
145
  WAIT_TIMEOUT_SECONDS="$(normalize_int "$WAIT_TIMEOUT_SECONDS_RAW" "1800" "30")"
146
146
  WAIT_POLL_SECONDS="$(normalize_int "$WAIT_POLL_SECONDS_RAW" "10" "0")"
147
147
  PARENT_GITLINK_AUTO_COMMIT="$(normalize_bool "$PARENT_GITLINK_AUTO_COMMIT_RAW" "1")"
148
- PREFLIGHT_ENABLED="$(normalize_bool "$PREFLIGHT_ENABLED_RAW" "1")"
149
- AUTO_PROMOTE_DRAFT="$(normalize_bool "$AUTO_PROMOTE_DRAFT_RAW" "1")"
150
148
 
151
149
  while [[ $# -gt 0 ]]; do
152
150
  case "$1" in
@@ -266,6 +264,14 @@ while [[ $# -gt 0 ]]; do
266
264
  esac
267
265
  done
268
266
 
267
+ # Normalize toggles whose flags set the RAW value DURING the parse loop
268
+ # (--no-preflight/--preflight, --no-auto-promote/--auto-promote). These MUST be
269
+ # normalized AFTER the loop — doing it before (as the env-only defaults above do)
270
+ # silently ignored the flags, leaving --no-preflight inert. Flags that set the
271
+ # normalized var directly in-loop (--cleanup, --wait-for-merge, ...) are unaffected.
272
+ PREFLIGHT_ENABLED="$(normalize_bool "$PREFLIGHT_ENABLED_RAW" "1")"
273
+ AUTO_PROMOTE_DRAFT="$(normalize_bool "$AUTO_PROMOTE_DRAFT_RAW" "1")"
274
+
269
275
  if [[ "$CLEANUP_AFTER_MERGE" -eq 1 && "$DELETE_REMOTE_BRANCH_EXPLICIT" -eq 0 ]]; then
270
276
  DELETE_REMOTE_BRANCH=1
271
277
  fi
@@ -485,7 +491,7 @@ stored_worktree_root_rel="$(git -C "$repo_root" config --get "branch.${SOURCE_BR
485
491
  if [[ -z "$stored_worktree_root_rel" ]]; then
486
492
  stored_worktree_root_rel=".omx/agent-worktrees"
487
493
  fi
488
- agent_worktree_root="${repo_common_root}/${stored_worktree_root_rel}"
494
+ agent_worktree_root="${repo_root}/${stored_worktree_root_rel}"
489
495
  runtime_state_root_rel="$(dirname "$stored_worktree_root_rel")"
490
496
  temp_worktree_root="${repo_common_root}/${runtime_state_root_rel}/.tmp-worktrees"
491
497
 
@@ -861,6 +861,20 @@ auto_transfer_message=""
861
861
  auto_transfer_source_branch=""
862
862
  auto_transfer_completed=0
863
863
 
864
+ # Preserve an un-appliable auto-transfer stash as a permanent ref instead of
865
+ # leaving it to pile up in the stash list forever. Stash entries are already
866
+ # commits, so we just point a ref at the same object and drop the stash entry;
867
+ # the work stays fully recoverable via `git stash apply <ref>`. Echoes the ref.
868
+ archive_auto_transfer_stash() {
869
+ local ref="$1"
870
+ local sha archive_ref
871
+ sha="$(git -C "$repo_root" rev-parse --verify "$ref" 2>/dev/null)" || return 1
872
+ archive_ref="refs/stash-archive/${auto_transfer_message:-auto-transfer}-${sha:0:8}"
873
+ git -C "$repo_root" update-ref "$archive_ref" "$sha" 2>/dev/null || return 1
874
+ git -C "$repo_root" stash drop "$ref" >/dev/null 2>&1 || true
875
+ printf '%s' "$archive_ref"
876
+ }
877
+
864
878
  restore_auto_transfer_stash_on_failure() {
865
879
  local exit_code="${1:-0}"
866
880
  if [[ "$exit_code" -eq 0 ]] || [[ -z "$auto_transfer_stash_ref" ]] || [[ "$auto_transfer_completed" -eq 1 ]]; then
@@ -868,13 +882,23 @@ restore_auto_transfer_stash_on_failure() {
868
882
  fi
869
883
 
870
884
  local transfer_label="${auto_transfer_source_branch:-$BASE_BRANCH}"
871
- if git -C "$repo_root" stash apply "$auto_transfer_stash_ref" >/dev/null 2>&1; then
885
+ # GUARDEX_TEST_FAIL_RESTORE_APPLY forces the restore-apply to fail so the
886
+ # archive path can be exercised deterministically in tests.
887
+ if ! env_flag_truthy "${GUARDEX_TEST_FAIL_RESTORE_APPLY:-}" \
888
+ && git -C "$repo_root" stash apply "$auto_transfer_stash_ref" >/dev/null 2>&1; then
872
889
  git -C "$repo_root" stash drop "$auto_transfer_stash_ref" >/dev/null 2>&1 || true
873
890
  auto_transfer_stash_ref=""
874
891
  echo "[agent-branch-start] Restored moved changes back to '${transfer_label}' after startup failure." >&2
875
892
  else
876
- echo "[agent-branch-start] Startup failed and auto-restore also failed." >&2
877
- echo "[agent-branch-start] Changes are preserved in ${auto_transfer_stash_ref} on ${transfer_label}." >&2
893
+ local archived_ref
894
+ if archived_ref="$(archive_auto_transfer_stash "$auto_transfer_stash_ref")"; then
895
+ auto_transfer_stash_ref=""
896
+ echo "[agent-branch-start] Startup failed and auto-restore also failed." >&2
897
+ echo "[agent-branch-start] Changes archived at ${archived_ref} on ${transfer_label} (recover with: git stash apply ${archived_ref})." >&2
898
+ else
899
+ echo "[agent-branch-start] Startup failed and auto-restore also failed." >&2
900
+ echo "[agent-branch-start] Changes are preserved in ${auto_transfer_stash_ref} on ${transfer_label}." >&2
901
+ fi
878
902
  fi
879
903
  }
880
904