@indigoai-us/hq-cli 5.104.0 → 5.105.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.105.0] — 2026-08-31
6
+
7
+ ### Changed
8
+
9
+ - `hq reindex` now removes HQ-managed Git worktrees whose last Git-visible
10
+ activity is more than 12 hours old. It preserves the current worktree,
11
+ recently edited/deleted/renamed files, and the worktree's branch; ignored
12
+ dependency/build churn does not keep a worktree alive, and malformed or
13
+ uninspectable worktrees fail closed.
14
+
5
15
  ## [5.104.0] — 2026-08-31
6
16
 
7
17
  ### Added
@@ -1,4 +1,10 @@
1
1
  import { Command } from 'commander';
2
+ /**
3
+ * Remove inactive worktrees created by `hq worktree` without ever deleting
4
+ * directories directly. This runs on the hook path, so it uses a shallow
5
+ * layout scan and Git's status output rather than recursively walking trees.
6
+ */
7
+ export declare function removeStaleHqWorktrees(hqRoot: string, now?: number, deadline?: number): void;
2
8
  /**
3
9
  * Check hook health without relying on lifecycle hooks. A fully disabled
4
10
  * configuration is repaired only after a successful reindex; partial and
@@ -33,6 +33,9 @@ import { findHqRoot } from '../utils/manifest.js';
33
33
  import { guardLargeFiles } from '../utils/large-file-guard.js';
34
34
  const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse'];
35
35
  const HOOK_CHECK_RELATIVE_PATH = path.join('core', 'scripts', 'check-hq-hooks.sh');
36
+ const WORKTREE_STALE_AFTER_MS = 12 * 60 * 60 * 1_000;
37
+ const WORKTREE_GIT_TIMEOUT_MS = 2_000;
38
+ const WORKTREE_HOOK_SWEEP_BUDGET_MS = 5_000;
36
39
  /** Resolve the same root the repair/check commands must operate on. */
37
40
  function resolveHqRoot(repoRoot) {
38
41
  const root = repoRoot ?? findHqRoot();
@@ -43,6 +46,267 @@ function resolveHqRoot(repoRoot) {
43
46
  return path.resolve(root);
44
47
  }
45
48
  }
49
+ function runGit(cwd, args, deadline = Number.POSITIVE_INFINITY, finishStartedCommand = false) {
50
+ const remainingMs = deadline - Date.now();
51
+ if (remainingMs <= 0)
52
+ return undefined;
53
+ try {
54
+ const result = spawnSync('git', ['-C', cwd, ...args], {
55
+ encoding: 'utf8',
56
+ stdio: 'pipe',
57
+ ...(finishStartedCommand
58
+ ? {}
59
+ : { timeout: Math.max(1, Math.min(WORKTREE_GIT_TIMEOUT_MS, remainingMs)) }),
60
+ // `git status` may otherwise refresh its index while merely measuring
61
+ // activity, making this cleanup itself keep an old worktree alive.
62
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
63
+ });
64
+ if (result.error)
65
+ return undefined;
66
+ return {
67
+ status: result.status,
68
+ stdout: result.stdout ?? '',
69
+ stderr: result.stderr ?? '',
70
+ };
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ function latestMtime(paths) {
77
+ let latest = 0;
78
+ for (const candidate of paths) {
79
+ try {
80
+ latest = Math.max(latest, fs.lstatSync(candidate).mtimeMs);
81
+ }
82
+ catch {
83
+ // A concurrently removed administrative file is not activity.
84
+ }
85
+ }
86
+ return latest;
87
+ }
88
+ function latestContentChange(paths) {
89
+ let latest = 0;
90
+ for (const candidate of paths) {
91
+ try {
92
+ const stat = fs.lstatSync(candidate);
93
+ latest = Math.max(latest, stat.mtimeMs, stat.ctimeMs);
94
+ }
95
+ catch {
96
+ // Deleted paths are represented by their surviving parent directory.
97
+ }
98
+ }
99
+ return latest;
100
+ }
101
+ function changedWorktreePaths(status) {
102
+ const entries = status.split('\0');
103
+ const paths = [];
104
+ for (let index = 0; index < entries.length; index += 1) {
105
+ const entry = entries[index];
106
+ if (!entry || entry.length < 4 || entry[2] !== ' ')
107
+ continue;
108
+ paths.push(entry.slice(3));
109
+ // With -z, rename/copy records carry the second path in the next NUL
110
+ // field. Check both because either end may have recent activity.
111
+ if ((entry[0] === 'R' || entry[0] === 'C' || entry[1] === 'R' || entry[1] === 'C') && entries[index + 1]) {
112
+ paths.push(entries[index + 1]);
113
+ index += 1;
114
+ }
115
+ }
116
+ return paths;
117
+ }
118
+ function isDirectChild(parent, candidate) {
119
+ return path.dirname(candidate) === parent;
120
+ }
121
+ function currentProcessIsInside(worktree) {
122
+ let resolvedWorktree;
123
+ try {
124
+ resolvedWorktree = fs.realpathSync(worktree);
125
+ }
126
+ catch {
127
+ return true;
128
+ }
129
+ let currentCwd;
130
+ try {
131
+ currentCwd = process.cwd();
132
+ }
133
+ catch {
134
+ return true;
135
+ }
136
+ for (const processPath of [currentCwd, process.argv[1]]) {
137
+ if (!processPath)
138
+ continue;
139
+ try {
140
+ const resolvedProcessPath = fs.realpathSync(path.resolve(processPath));
141
+ if (resolvedProcessPath === resolvedWorktree ||
142
+ resolvedProcessPath.startsWith(`${resolvedWorktree}${path.sep}`)) {
143
+ return true;
144
+ }
145
+ }
146
+ catch {
147
+ // A missing argv path says nothing about whether this worktree is active.
148
+ }
149
+ }
150
+ return false;
151
+ }
152
+ function managedWorktreeCandidates(hqRoot) {
153
+ const worktreesRoot = path.join(hqRoot, 'workspace', 'worktrees');
154
+ let repositories;
155
+ try {
156
+ repositories = fs.readdirSync(worktreesRoot, { withFileTypes: true });
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ const candidates = [];
162
+ for (const repository of repositories) {
163
+ if (!repository.isDirectory())
164
+ continue;
165
+ const repositoryRoot = path.join(worktreesRoot, repository.name);
166
+ let worktrees;
167
+ try {
168
+ worktrees = fs.readdirSync(repositoryRoot, { withFileTypes: true });
169
+ }
170
+ catch {
171
+ continue;
172
+ }
173
+ for (const worktree of worktrees) {
174
+ if (!worktree.isDirectory())
175
+ continue;
176
+ const candidate = path.join(repositoryRoot, worktree.name);
177
+ // Keep the cleanup constrained to the layout that `hq worktree` owns.
178
+ if (isDirectChild(repositoryRoot, candidate))
179
+ candidates.push(candidate);
180
+ }
181
+ }
182
+ return candidates;
183
+ }
184
+ function linkedWorktreeGitDir(worktree, deadline = Number.POSITIVE_INFINITY) {
185
+ const gitFile = path.join(worktree, '.git');
186
+ try {
187
+ if (!fs.lstatSync(gitFile).isFile())
188
+ return undefined;
189
+ const match = /^gitdir:\s*(.+)\s*$/i.exec(fs.readFileSync(gitFile, 'utf8'));
190
+ if (!match)
191
+ return undefined;
192
+ const gitDir = path.resolve(worktree, match[1]);
193
+ if (!fs.statSync(gitDir).isDirectory())
194
+ return undefined;
195
+ // A submodule checkout also has a .git *file*. A linked worktree is
196
+ // distinguished by its per-worktree administrative commondir file.
197
+ if (!fs.lstatSync(path.join(gitDir, 'commondir')).isFile())
198
+ return undefined;
199
+ const topLevel = runGit(worktree, ['rev-parse', '--show-toplevel'], deadline);
200
+ if (topLevel?.status !== 0 || !topLevel.stdout.trim())
201
+ return undefined;
202
+ return fs.realpathSync(topLevel.stdout.trim()) === fs.realpathSync(worktree) ? gitDir : undefined;
203
+ }
204
+ catch {
205
+ return undefined;
206
+ }
207
+ }
208
+ function nearestExistingAncestor(candidate, worktree) {
209
+ let current = candidate;
210
+ while (current !== worktree && current.startsWith(`${worktree}${path.sep}`)) {
211
+ if (fs.existsSync(current))
212
+ return current;
213
+ current = path.dirname(current);
214
+ }
215
+ return worktree;
216
+ }
217
+ function hasRecentWorktreeActivity(worktree, gitDir, cutoff, deadline = Number.POSITIVE_INFINITY) {
218
+ const gitFile = path.join(worktree, '.git');
219
+ const administrativeActivity = latestMtime([
220
+ worktree,
221
+ gitFile,
222
+ gitDir,
223
+ path.join(gitDir, 'HEAD'),
224
+ path.join(gitDir, 'index'),
225
+ path.join(gitDir, 'logs', 'HEAD'),
226
+ ]);
227
+ if (administrativeActivity >= cutoff)
228
+ return true;
229
+ // Ask Git for only changed paths. `all` is necessary to see an untracked
230
+ // file inside an untracked directory; ignored dependency/build trees remain
231
+ // excluded, and we stat only the paths Git reports instead of walking trees.
232
+ const status = runGit(worktree, [
233
+ 'status',
234
+ '--porcelain=v1',
235
+ '-z',
236
+ '--untracked-files=all',
237
+ '--ignored=no',
238
+ ], deadline);
239
+ // A repository we cannot inspect is safer to retain than force-remove.
240
+ if (status?.status !== 0)
241
+ return true;
242
+ // Node replaces invalid UTF-8 bytes while decoding stdout. The resulting
243
+ // path is no longer safe to stat, so retain the worktree fail-closed.
244
+ if (status.stdout.includes('\uFFFD'))
245
+ return true;
246
+ const changedPaths = changedWorktreePaths(status.stdout);
247
+ // Git produced a record we do not understand. Fail closed instead of
248
+ // treating an unparsed dirty worktree as clean.
249
+ if (status.stdout.length > 0 && changedPaths.length === 0)
250
+ return true;
251
+ for (const relativePath of changedPaths) {
252
+ const candidate = path.resolve(worktree, relativePath);
253
+ if (candidate !== worktree && !candidate.startsWith(`${worktree}${path.sep}`))
254
+ continue;
255
+ try {
256
+ // Parent Git reports submodules and embedded repositories as aggregate
257
+ // directory paths. Descendant edits do not touch that directory's own
258
+ // timestamps, so retain these dirty aggregates rather than recurse into
259
+ // an unbounded tree on every reindex hook.
260
+ if (fs.lstatSync(candidate).isDirectory())
261
+ return true;
262
+ }
263
+ catch {
264
+ // Missing paths are deletions and are handled through their ancestors.
265
+ }
266
+ }
267
+ const dirtyPaths = changedPaths.flatMap((relativePath) => {
268
+ const candidate = path.resolve(worktree, relativePath);
269
+ if (candidate !== worktree && !candidate.startsWith(`${worktree}${path.sep}`))
270
+ return [];
271
+ return [candidate, nearestExistingAncestor(path.dirname(candidate), worktree)];
272
+ });
273
+ return latestContentChange(dirtyPaths) >= cutoff;
274
+ }
275
+ /**
276
+ * Remove inactive worktrees created by `hq worktree` without ever deleting
277
+ * directories directly. This runs on the hook path, so it uses a shallow
278
+ * layout scan and Git's status output rather than recursively walking trees.
279
+ */
280
+ export function removeStaleHqWorktrees(hqRoot, now = Date.now(), deadline = Number.POSITIVE_INFINITY) {
281
+ if (!isHqRoot(hqRoot))
282
+ return;
283
+ const cutoff = now - WORKTREE_STALE_AFTER_MS;
284
+ for (const worktree of managedWorktreeCandidates(hqRoot)) {
285
+ if (Date.now() >= deadline)
286
+ break;
287
+ if (currentProcessIsInside(worktree))
288
+ continue;
289
+ const gitDir = linkedWorktreeGitDir(worktree, deadline);
290
+ if (!gitDir || hasRecentWorktreeActivity(worktree, gitDir, cutoff, deadline))
291
+ continue;
292
+ // Narrow the destructive TOCTOU window: re-resolve the linked-worktree
293
+ // identity and re-measure activity immediately before asking Git to remove
294
+ // it. Git remains the only component that deletes the directory.
295
+ const confirmedGitDir = linkedWorktreeGitDir(worktree, deadline);
296
+ if (!confirmedGitDir || hasRecentWorktreeActivity(worktree, confirmedGitDir, cutoff, deadline))
297
+ continue;
298
+ // Recursive removal is not transactional. Only start it inside the sweep
299
+ // budget, then let Git finish so a timeout cannot leave a registered,
300
+ // partially deleted worktree behind.
301
+ const removal = runGit(worktree, ['worktree', 'remove', '--force', worktree], deadline, true);
302
+ if (removal?.status === 0) {
303
+ console.log(`reindex: removed stale worktree ${worktree} (branch preserved; stale uncommitted files are not recoverable)`);
304
+ continue;
305
+ }
306
+ const reason = removal?.stderr.trim() || removal?.stdout.trim() || 'Git could not remove it';
307
+ console.warn(`reindex: could not remove stale worktree ${worktree}: ${reason}`);
308
+ }
309
+ }
46
310
  function isHqRoot(hqRoot) {
47
311
  return (fs.existsSync(path.join(hqRoot, 'companies')) &&
48
312
  (fs.existsSync(path.join(hqRoot, '.claude')) ||
@@ -254,8 +518,10 @@ export function registerReindexCommand(program) {
254
518
  if (lockTimeoutSec !== undefined && process.env.HQ_OP_LOCK_TIMEOUT === undefined) {
255
519
  process.env.HQ_OP_LOCK_TIMEOUT = String(lockTimeoutSec);
256
520
  }
257
- const { status } = reindex({ repoRoot: opts.repoRoot });
258
521
  const hqRoot = resolveHqRoot(opts.repoRoot);
522
+ const sweepStartedAt = Date.now();
523
+ removeStaleHqWorktrees(hqRoot, sweepStartedAt, opts.fromHook ? sweepStartedAt + WORKTREE_HOOK_SWEEP_BUDGET_MS : Number.POSITIVE_INFINITY);
524
+ const { status } = reindex({ repoRoot: opts.repoRoot });
259
525
  repairExtremeHookDrift(hqRoot, status === 0);
260
526
  if (status === 0)
261
527
  await trustHqRuntimeHooks(hqRoot);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.104.0",
3
+ "version": "5.105.0",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {