@indigoai-us/hq-cli 5.103.34 → 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 +23 -0
- package/dist/commands/agents.d.ts +14 -0
- package/dist/commands/agents.js +91 -0
- package/dist/commands/reindex.d.ts +6 -0
- package/dist/commands/reindex.js +267 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,29 @@
|
|
|
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
|
+
|
|
15
|
+
## [5.104.0] — 2026-08-31
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- `hq agents terminal <agent>` — open an interactive terminal (real TTY over
|
|
20
|
+
SSM Session Manager) on a fleet agent's box using HQ identity alone: no SSH,
|
|
21
|
+
no local AWS credentials. Owner/admin only; auto-starts a dormant box and
|
|
22
|
+
waits for it to come online. `--forward <port>` (with optional
|
|
23
|
+
`--local-port`) tunnels a port on the box to your machine instead of opening
|
|
24
|
+
a shell. Requires the AWS `session-manager-plugin` installed locally.
|
|
25
|
+
- `hq outposts terminal` — the same interactive terminal for personal
|
|
26
|
+
Outposts (via `@indigoai-us/hq-cloud`).
|
|
27
|
+
|
|
5
28
|
## [5.103.34] — 2026-08-30
|
|
6
29
|
|
|
7
30
|
## [5.103.33] — 2026-08-30
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
* the caller's single active membership (same as `members.ts`).
|
|
26
26
|
*/
|
|
27
27
|
import { Command } from "commander";
|
|
28
|
+
import { type TerminalSessionPayload } from "@indigoai-us/hq-cloud/outposts/node";
|
|
28
29
|
import { type BillingErrorPayload } from "../utils/billing-gate.js";
|
|
29
30
|
/** Reasoning-effort values hq-pro accepts on `runtime-config`. */
|
|
30
31
|
export declare const VALID_EFFORTS: Set<string>;
|
|
@@ -201,6 +202,19 @@ export declare function startStopAgent(token: string, agentUid: string, action:
|
|
|
201
202
|
uid: string;
|
|
202
203
|
runtime?: Record<string, unknown>;
|
|
203
204
|
}>;
|
|
205
|
+
/** `POST /v1/agents/{uid}/terminal` wire shape: vended session or 202 starting. */
|
|
206
|
+
export type AgentTerminalResponse = ({
|
|
207
|
+
ok: true;
|
|
208
|
+
uid: string;
|
|
209
|
+
mode: "shell" | "port-forward";
|
|
210
|
+
} & TerminalSessionPayload) | {
|
|
211
|
+
ok: false;
|
|
212
|
+
step: "starting";
|
|
213
|
+
state: "starting-instance" | "awaiting-ssm";
|
|
214
|
+
retryAfterSeconds?: number;
|
|
215
|
+
uid: string;
|
|
216
|
+
};
|
|
217
|
+
export declare function openAgentTerminal(token: string, agentUid: string, body: Record<string, unknown>): Promise<AgentTerminalResponse>;
|
|
204
218
|
export declare function retryAgent(token: string, agentUid: string): Promise<Record<string, unknown>>;
|
|
205
219
|
export declare function deprovisionAgent(token: string, agentUid: string): Promise<{
|
|
206
220
|
uid: string;
|
package/dist/commands/agents.js
CHANGED
|
@@ -30,6 +30,7 @@ import * as readline from "node:readline";
|
|
|
30
30
|
import { resolveVaultCredential } from "../utils/resolve-vault-credential.js";
|
|
31
31
|
import { gateApiKeyCapabilities } from "../utils/api-key-command-gate.js";
|
|
32
32
|
import { vaultApiFetch, getCompanyUid } from "../utils/vault-api.js";
|
|
33
|
+
import { launchSessionManagerPlugin, SessionManagerPluginLaunchError, TerminalSessionTimeoutError, waitForTerminalSession, } from "@indigoai-us/hq-cloud/outposts/node";
|
|
33
34
|
import { peekIdToken } from "../utils/id-token.js";
|
|
34
35
|
import { isPlanGateError } from "../utils/plan-gate-error.js";
|
|
35
36
|
import { confirmChargeOrExit, formatUsd, parseBillingPayload, surfaceBillingBlocked, } from "../utils/billing-gate.js";
|
|
@@ -299,6 +300,14 @@ export async function startStopAgent(token, agentUid, action) {
|
|
|
299
300
|
method: "POST",
|
|
300
301
|
});
|
|
301
302
|
}
|
|
303
|
+
export async function openAgentTerminal(token, agentUid, body) {
|
|
304
|
+
return agentsRequest({
|
|
305
|
+
token,
|
|
306
|
+
path: `/v1/agents/${encodeURIComponent(agentUid)}/terminal`,
|
|
307
|
+
method: "POST",
|
|
308
|
+
body,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
302
311
|
export async function retryAgent(token, agentUid) {
|
|
303
312
|
return agentsRequest({
|
|
304
313
|
token,
|
|
@@ -540,6 +549,17 @@ function sleep(ms) {
|
|
|
540
549
|
// ---------------------------------------------------------------------------
|
|
541
550
|
// Command registration
|
|
542
551
|
// ---------------------------------------------------------------------------
|
|
552
|
+
/** Parse an optional port flag: integer 1..65535 or exit(1) with the flag name. */
|
|
553
|
+
function parsePortOption(value, flag) {
|
|
554
|
+
if (value === undefined)
|
|
555
|
+
return undefined;
|
|
556
|
+
const n = Number(value);
|
|
557
|
+
if (!Number.isInteger(n) || n < 1 || n > 65_535) {
|
|
558
|
+
console.error(chalk.red(`${flag} must be an integer between 1 and 65535.`));
|
|
559
|
+
process.exit(1);
|
|
560
|
+
}
|
|
561
|
+
return n;
|
|
562
|
+
}
|
|
543
563
|
function fail(err) {
|
|
544
564
|
// Let the CLI boundary render and offer the one shared Team checkout flow.
|
|
545
565
|
// Local exits would otherwise prevent interactive plan-limit remediation.
|
|
@@ -578,6 +598,9 @@ export function registerAgentsCommand(program) {
|
|
|
578
598
|
bySubcommand: {
|
|
579
599
|
message: { capability: "agents:use", routeAvailable: false },
|
|
580
600
|
thread: { capability: "agents:use", routeAvailable: false },
|
|
601
|
+
// Interactive terminals are for humans: hq-pro serves no keyed
|
|
602
|
+
// `/v1/keys/agents/{uid}/terminal` route, so machine keys fail closed.
|
|
603
|
+
terminal: { capability: "agents:use", routeAvailable: false },
|
|
581
604
|
},
|
|
582
605
|
});
|
|
583
606
|
// `--company` may live on the group or the subcommand; the subcommand value
|
|
@@ -667,6 +690,74 @@ export function registerAgentsCommand(program) {
|
|
|
667
690
|
fail(err);
|
|
668
691
|
}
|
|
669
692
|
});
|
|
693
|
+
agents
|
|
694
|
+
.command("terminal <agent>")
|
|
695
|
+
.description("Open an interactive terminal on an agent's box — a real TTY over SSM Session Manager (no SSH, no local AWS credentials). " +
|
|
696
|
+
"Owner/admin only; requires the AWS session-manager-plugin installed locally. With --forward, tunnels a port on the box instead.")
|
|
697
|
+
.option("--company <slug>", "Company slug (to resolve an agent by name/slug)")
|
|
698
|
+
.option("--forward <port>", "Forward this port on the box to your machine instead of opening a shell")
|
|
699
|
+
.option("--local-port <port>", "Local port for --forward (defaults to the forwarded port)")
|
|
700
|
+
.action(async function (agent, opts) {
|
|
701
|
+
try {
|
|
702
|
+
const forwardPort = parsePortOption(opts.forward, "--forward");
|
|
703
|
+
const localPort = parsePortOption(opts.localPort, "--local-port");
|
|
704
|
+
if (localPort !== undefined && forwardPort === undefined) {
|
|
705
|
+
console.error(chalk.red("--local-port requires --forward <port>."));
|
|
706
|
+
process.exit(1);
|
|
707
|
+
}
|
|
708
|
+
// A shell needs a real TTY on both ends; a port-forward does not.
|
|
709
|
+
if (forwardPort === undefined && !process.stdin.isTTY) {
|
|
710
|
+
console.error(chalk.red("hq agents terminal needs an interactive terminal (stdin is not a TTY)."));
|
|
711
|
+
process.exit(1);
|
|
712
|
+
}
|
|
713
|
+
const token = (await resolveVaultCredential()).token;
|
|
714
|
+
const agentUid = await resolveAgentUid(token, agent, companyOf(this));
|
|
715
|
+
const body = forwardPort !== undefined
|
|
716
|
+
? {
|
|
717
|
+
mode: "port-forward",
|
|
718
|
+
portNumber: forwardPort,
|
|
719
|
+
...(localPort !== undefined ? { localPortNumber: localPort } : {}),
|
|
720
|
+
}
|
|
721
|
+
: { mode: "shell" };
|
|
722
|
+
// 202-retry loop: a dormant box is auto-started server-side; SSM
|
|
723
|
+
// registration after a cold start takes ~30-90s. Status lines go to
|
|
724
|
+
// stderr (once per state) so stdout stays the session's.
|
|
725
|
+
let lastState;
|
|
726
|
+
const session = await waitForTerminalSession(async () => {
|
|
727
|
+
const result = await openAgentTerminal(token, agentUid, body);
|
|
728
|
+
if (result.ok)
|
|
729
|
+
return { kind: "ready", session: result };
|
|
730
|
+
return {
|
|
731
|
+
kind: "starting",
|
|
732
|
+
state: result.state,
|
|
733
|
+
...(result.retryAfterSeconds !== undefined
|
|
734
|
+
? { retryAfterSeconds: result.retryAfterSeconds }
|
|
735
|
+
: {}),
|
|
736
|
+
};
|
|
737
|
+
}, {
|
|
738
|
+
onStatus: (state) => {
|
|
739
|
+
if (state === lastState)
|
|
740
|
+
return;
|
|
741
|
+
lastState = state;
|
|
742
|
+
console.error(chalk.dim(state === "starting-instance"
|
|
743
|
+
? `${agent}'s box is starting — waiting for it to come online (Ctrl-C to cancel)…`
|
|
744
|
+
: `${agent}'s box is up — waiting for its agent to register (Ctrl-C to cancel)…`));
|
|
745
|
+
},
|
|
746
|
+
});
|
|
747
|
+
console.error(chalk.dim(forwardPort !== undefined
|
|
748
|
+
? `Forwarding box port ${forwardPort} to localhost:${localPort ?? forwardPort} — Ctrl-C to end.`
|
|
749
|
+
: `Connected to ${agent}'s box — type 'exit' or Ctrl-D to leave.`));
|
|
750
|
+
process.exitCode = await launchSessionManagerPlugin(session);
|
|
751
|
+
}
|
|
752
|
+
catch (err) {
|
|
753
|
+
if (err instanceof SessionManagerPluginLaunchError ||
|
|
754
|
+
err instanceof TerminalSessionTimeoutError) {
|
|
755
|
+
console.error(chalk.red(err.message));
|
|
756
|
+
process.exit(1);
|
|
757
|
+
}
|
|
758
|
+
fail(err);
|
|
759
|
+
}
|
|
760
|
+
});
|
|
670
761
|
agents
|
|
671
762
|
.command("provision <name>")
|
|
672
763
|
.alias("new")
|
|
@@ -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
|
package/dist/commands/reindex.js
CHANGED
|
@@ -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.
|
|
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": {
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"@aws-sdk/client-iot-data-plane": "^3.1096.0",
|
|
32
32
|
"@aws-sdk/client-s3": "^3.1049.0",
|
|
33
|
-
"@indigoai-us/hq-cloud": "~6.
|
|
33
|
+
"@indigoai-us/hq-cloud": "~6.16.0",
|
|
34
34
|
"@indigoai-us/hq-onboarding": "^0.1.0",
|
|
35
35
|
"@sentry/node": "^10.49.0",
|
|
36
36
|
"@tobilu/qmd": "2.5.3",
|