@indigoai-us/hq-cli 5.77.6 → 5.77.7
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 +7 -0
- package/dist/commands/integrations.js +24 -1
- package/dist/commands/reindex.d.ts +5 -23
- package/dist/commands/reindex.js +206 -1
- package/dist/utils/version-gate.d.ts +36 -0
- package/dist/utils/version-gate.js +102 -1
- package/package.json +2 -2
- package/pnpm-workspace.yaml +1 -1
- package/src/commands/integrations.test.ts +118 -0
- package/src/commands/integrations.ts +26 -0
- package/src/commands/reindex.test.ts +168 -3
- package/src/commands/reindex.ts +207 -1
- package/src/utils/version-gate.test.ts +176 -0
- package/src/utils/version-gate.ts +127 -1
|
@@ -76,6 +76,31 @@ function isClientError(status: number): boolean {
|
|
|
76
76
|
return status >= 400 && status < 500;
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
// The integration gateway answers `POST /v1/integrations/mcp` JSON-RPC-style: a
|
|
80
|
+
// transport failure is a non-2xx HTTP status, but a GOVERNED refusal arrives as
|
|
81
|
+
// HTTP 200 carrying a JSON-RPC `error` object (mirrors hq-pro's
|
|
82
|
+
// integration-mcp/server.ts error mapping). These caller-side codes are the
|
|
83
|
+
// JSON-RPC analog of a client 4xx — the caller's request/state/permission,
|
|
84
|
+
// expected and actionable, not an hq-cli defect — so they are printed to the
|
|
85
|
+
// user and skipped for Sentry capture (HQ-CLI-B):
|
|
86
|
+
// -32003 UNAUTHORIZED — connection-level access denial, e.g. the
|
|
87
|
+
// "You do not have access to this integration. Ask its
|
|
88
|
+
// owner to share it with you." (IntegrationAccessDenied)
|
|
89
|
+
// that flooded Sentry, plus ConnectionNotFound / a
|
|
90
|
+
// read-only share rejecting a write.
|
|
91
|
+
// -32602 INVALID_PARAMS — an unknown tool or unsupported provider for the
|
|
92
|
+
// connection (a bad request the caller can correct).
|
|
93
|
+
// Everything else stays unexpected so a genuine fault still reaches Sentry:
|
|
94
|
+
// PROVIDER_ERROR (-32050, an upstream provider fault), INTERNAL_ERROR (-32603),
|
|
95
|
+
// CONFLICT (-32009, which the gateway also raises for a confirm queue being
|
|
96
|
+
// unavailable or an owner notification failing — real backend faults worth a
|
|
97
|
+
// report), METHOD_NOT_FOUND / PARSE_ERROR, and any absent or unrecognized code.
|
|
98
|
+
const EXPECTED_GATEWAY_ERROR_CODES = new Set<number>([-32003, -32602]);
|
|
99
|
+
|
|
100
|
+
function isExpectedGatewayError(code: number | undefined): boolean {
|
|
101
|
+
return code != null && EXPECTED_GATEWAY_ERROR_CODES.has(code);
|
|
102
|
+
}
|
|
103
|
+
|
|
79
104
|
// A 401 from ANY integration-gateway vault call means the caller's HQ session
|
|
80
105
|
// is expired or missing — an expected auth state fixed by `hq login`, not an
|
|
81
106
|
// hq-cli defect. Raise the same typed AuthError the vault company-resolution
|
|
@@ -196,6 +221,7 @@ export async function callGateway(
|
|
|
196
221
|
if (message.error) {
|
|
197
222
|
throw new IntegrationsCliError(
|
|
198
223
|
message.error.message ?? "Integration gateway returned an error.",
|
|
224
|
+
{ expected: isExpectedGatewayError(message.error.code) },
|
|
199
225
|
);
|
|
200
226
|
}
|
|
201
227
|
return message;
|
|
@@ -7,17 +7,62 @@ import {
|
|
|
7
7
|
vi,
|
|
8
8
|
type MockInstance,
|
|
9
9
|
} from "vitest";
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as os from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
10
13
|
|
|
11
|
-
// Mock the hq-cloud
|
|
14
|
+
// Mock the hq-cloud commands so the command only touches its temporary HQ roots.
|
|
12
15
|
vi.mock("@indigoai-us/hq-cloud", () => ({
|
|
13
16
|
reindex: vi.fn(() => ({ status: 0 })),
|
|
17
|
+
rescue: vi.fn(() => ({ status: 0 })),
|
|
14
18
|
}));
|
|
15
19
|
|
|
16
20
|
import { Command } from "commander";
|
|
17
|
-
import { reindex } from "@indigoai-us/hq-cloud";
|
|
21
|
+
import { reindex, rescue } from "@indigoai-us/hq-cloud";
|
|
18
22
|
import { registerReindexCommand } from "./reindex.js";
|
|
19
23
|
|
|
20
24
|
const reindexMock = reindex as unknown as MockInstance<typeof reindex>;
|
|
25
|
+
const rescueMock = rescue as unknown as MockInstance<typeof rescue>;
|
|
26
|
+
|
|
27
|
+
const HEALTHY_SETTINGS = {
|
|
28
|
+
hooks: Object.fromEntries(
|
|
29
|
+
["SessionStart", "UserPromptSubmit", "PreToolUse"].map((event) => [
|
|
30
|
+
event,
|
|
31
|
+
[{ matcher: "", hooks: [{ type: "command", command: `echo ${event}` }] }],
|
|
32
|
+
])
|
|
33
|
+
),
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
let tempRoots: string[] = [];
|
|
37
|
+
let defaultRoot: string;
|
|
38
|
+
|
|
39
|
+
function writeSettings(root: string, settings: unknown): void {
|
|
40
|
+
fs.mkdirSync(path.join(root, ".claude"), { recursive: true });
|
|
41
|
+
fs.writeFileSync(path.join(root, ".claude", "settings.json"), JSON.stringify(settings, null, 2));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function makeHqRoot(settings: unknown = HEALTHY_SETTINGS): string {
|
|
45
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "hq-reindex-"));
|
|
46
|
+
tempRoots.push(root);
|
|
47
|
+
fs.mkdirSync(path.join(root, ".claude"), { recursive: true });
|
|
48
|
+
fs.mkdirSync(path.join(root, "companies"), { recursive: true });
|
|
49
|
+
fs.mkdirSync(path.join(root, "personal"), { recursive: true });
|
|
50
|
+
fs.mkdirSync(path.join(root, "core"), { recursive: true });
|
|
51
|
+
fs.writeFileSync(path.join(root, "core", "core.yaml"), 'version: 1\nhqVersion: "15.0.56"\n');
|
|
52
|
+
if (settings !== undefined) writeSettings(root, settings);
|
|
53
|
+
return root;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function restoreShippedHookConfig(options: { hqRoot?: string }): { status: number } {
|
|
57
|
+
const root = options.hqRoot;
|
|
58
|
+
if (!root) throw new Error("rescue requires hqRoot");
|
|
59
|
+
const settings = path.join(root, ".claude", "settings.json");
|
|
60
|
+
if (fs.existsSync(settings)) {
|
|
61
|
+
fs.copyFileSync(settings, path.join(root, "personal", "settings.json"));
|
|
62
|
+
}
|
|
63
|
+
writeSettings(root, HEALTHY_SETTINGS);
|
|
64
|
+
return { status: 0 };
|
|
65
|
+
}
|
|
21
66
|
|
|
22
67
|
function buildProgram(): Command {
|
|
23
68
|
const program = new Command();
|
|
@@ -31,9 +76,10 @@ function buildProgram(): Command {
|
|
|
31
76
|
}
|
|
32
77
|
|
|
33
78
|
async function run(...args: string[]): Promise<void> {
|
|
79
|
+
const commandArgs = args.includes("--repo-root") ? args : ["--repo-root", defaultRoot, ...args];
|
|
34
80
|
// process.exit is spied to throw; swallow that so parseAsync resolves.
|
|
35
81
|
try {
|
|
36
|
-
await buildProgram().parseAsync(["node", "hq", "reindex", ...
|
|
82
|
+
await buildProgram().parseAsync(["node", "hq", "reindex", ...commandArgs]);
|
|
37
83
|
} catch (err) {
|
|
38
84
|
if (!(err instanceof Error) || !err.message.startsWith("__EXIT__:")) throw err;
|
|
39
85
|
}
|
|
@@ -41,18 +87,26 @@ async function run(...args: string[]): Promise<void> {
|
|
|
41
87
|
|
|
42
88
|
let exitSpy: MockInstance<typeof process.exit>;
|
|
43
89
|
let savedLockTimeout: string | undefined;
|
|
90
|
+
let logSpy: MockInstance<typeof console.log>;
|
|
91
|
+
let warnSpy: MockInstance<typeof console.warn>;
|
|
44
92
|
|
|
45
93
|
beforeEach(() => {
|
|
46
94
|
vi.clearAllMocks();
|
|
47
95
|
savedLockTimeout = process.env.HQ_OP_LOCK_TIMEOUT;
|
|
48
96
|
delete process.env.HQ_OP_LOCK_TIMEOUT;
|
|
97
|
+
tempRoots = [];
|
|
98
|
+
defaultRoot = makeHqRoot();
|
|
99
|
+
rescueMock.mockImplementation(restoreShippedHookConfig as never);
|
|
49
100
|
exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
|
|
50
101
|
throw new Error(`__EXIT__:${code ?? 0}`);
|
|
51
102
|
}) as never);
|
|
103
|
+
logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
|
104
|
+
warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
|
52
105
|
});
|
|
53
106
|
|
|
54
107
|
afterEach(() => {
|
|
55
108
|
vi.restoreAllMocks();
|
|
109
|
+
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
|
|
56
110
|
if (savedLockTimeout === undefined) delete process.env.HQ_OP_LOCK_TIMEOUT;
|
|
57
111
|
else process.env.HQ_OP_LOCK_TIMEOUT = savedLockTimeout;
|
|
58
112
|
});
|
|
@@ -92,3 +146,114 @@ describe("hq reindex lock-wait policy", () => {
|
|
|
92
146
|
expect(process.env.HQ_OP_LOCK_TIMEOUT).toBeUndefined();
|
|
93
147
|
});
|
|
94
148
|
});
|
|
149
|
+
|
|
150
|
+
describe("hq reindex hook health", () => {
|
|
151
|
+
it("does not warn when all lifecycle hooks are declared", async () => {
|
|
152
|
+
await run();
|
|
153
|
+
|
|
154
|
+
expect(rescueMock).not.toHaveBeenCalled();
|
|
155
|
+
expect(warnSpy).not.toHaveBeenCalled();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("leaves a healthy root alone across repeated reindexes", async () => {
|
|
159
|
+
const root = makeHqRoot();
|
|
160
|
+
|
|
161
|
+
await run("--repo-root", root);
|
|
162
|
+
await run("--repo-root", root);
|
|
163
|
+
|
|
164
|
+
expect(rescueMock).not.toHaveBeenCalled();
|
|
165
|
+
expect(warnSpy).not.toHaveBeenCalled();
|
|
166
|
+
expect(logSpy).not.toHaveBeenCalledWith("reindex: repaired HQ hook config");
|
|
167
|
+
expect(reindexMock).toHaveBeenCalledTimes(2);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("warns and repairs missing settings.json non-interactively", async () => {
|
|
171
|
+
const root = makeHqRoot();
|
|
172
|
+
fs.rmSync(path.join(root, ".claude", "settings.json"));
|
|
173
|
+
|
|
174
|
+
await run("--repo-root", root);
|
|
175
|
+
|
|
176
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(".claude/settings.json is missing"));
|
|
177
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("hq rescue -y --paths .claude"));
|
|
178
|
+
expect(rescueMock).toHaveBeenCalledWith(
|
|
179
|
+
expect.objectContaining({
|
|
180
|
+
hqRoot: root,
|
|
181
|
+
source: "indigoai-us/hq-core",
|
|
182
|
+
ref: "v15.0.56",
|
|
183
|
+
paths: [".claude"],
|
|
184
|
+
assumeYes: true,
|
|
185
|
+
})
|
|
186
|
+
);
|
|
187
|
+
expect(JSON.parse(fs.readFileSync(path.join(root, ".claude", "settings.json"), "utf8"))).toEqual(
|
|
188
|
+
HEALTHY_SETTINGS
|
|
189
|
+
);
|
|
190
|
+
expect(logSpy).toHaveBeenCalledWith("reindex: repaired HQ hook config");
|
|
191
|
+
expect(exitSpy).toHaveBeenCalledWith(0);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("warns and repairs settings.json when it declares none of the lifecycle hooks", async () => {
|
|
195
|
+
const root = makeHqRoot({ hooks: { Stop: [{ hooks: [{ type: "command", command: "echo stop" }] }] } });
|
|
196
|
+
|
|
197
|
+
await run("--repo-root", root);
|
|
198
|
+
|
|
199
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("no SessionStart, UserPromptSubmit, or PreToolUse command hook"));
|
|
200
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("hq rescue -y --paths .claude"));
|
|
201
|
+
expect(rescueMock).toHaveBeenCalledTimes(1);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it("preserves settings.local.json and personal drift while restoring hook wiring", async () => {
|
|
205
|
+
const root = makeHqRoot({ customSetting: true, hooks: {} });
|
|
206
|
+
const localSettings = '{"localOnly":true}\n';
|
|
207
|
+
const personalEdit = "keep this user policy\n";
|
|
208
|
+
fs.writeFileSync(path.join(root, ".claude", "settings.local.json"), localSettings);
|
|
209
|
+
fs.writeFileSync(path.join(root, "personal", "policy.md"), personalEdit);
|
|
210
|
+
|
|
211
|
+
await run("--repo-root", root);
|
|
212
|
+
|
|
213
|
+
expect(fs.readFileSync(path.join(root, ".claude", "settings.local.json"), "utf8")).toBe(localSettings);
|
|
214
|
+
expect(fs.readFileSync(path.join(root, "personal", "policy.md"), "utf8")).toBe(personalEdit);
|
|
215
|
+
expect(JSON.parse(fs.readFileSync(path.join(root, "personal", "settings.json"), "utf8"))).toEqual({
|
|
216
|
+
customSetting: true,
|
|
217
|
+
hooks: {},
|
|
218
|
+
});
|
|
219
|
+
expect(logSpy).toHaveBeenCalledWith("reindex: repaired HQ hook config");
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("warns without changing partial hook wiring", async () => {
|
|
223
|
+
const root = makeHqRoot({
|
|
224
|
+
hooks: {
|
|
225
|
+
SessionStart: [{ hooks: [{ type: "command", command: "echo start" }] }],
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
await run("--repo-root", root);
|
|
230
|
+
|
|
231
|
+
expect(rescueMock).not.toHaveBeenCalled();
|
|
232
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("missing command hook wiring"));
|
|
233
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("settingSources"));
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("uses the shipped hook checker when the resolved HQ root contains it", async () => {
|
|
237
|
+
const root = makeHqRoot();
|
|
238
|
+
const checker = path.join(root, "core", "scripts", "check-hq-hooks.sh");
|
|
239
|
+
fs.mkdirSync(path.dirname(checker), { recursive: true });
|
|
240
|
+
fs.writeFileSync(checker, 'printf checked > "$2/.claude/checker-ran"\n');
|
|
241
|
+
|
|
242
|
+
await run("--repo-root", root);
|
|
243
|
+
|
|
244
|
+
expect(fs.readFileSync(path.join(root, ".claude", "checker-ran"), "utf8")).toBe("checked");
|
|
245
|
+
expect(warnSpy).not.toHaveBeenCalled();
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("surfaces diagnostics when the shipped hook checker fails", async () => {
|
|
249
|
+
const root = makeHqRoot();
|
|
250
|
+
const checker = path.join(root, "core", "scripts", "check-hq-hooks.sh");
|
|
251
|
+
fs.mkdirSync(path.dirname(checker), { recursive: true });
|
|
252
|
+
fs.writeFileSync(checker, 'echo "scaffold detected drift" >&2\nexit 2\n');
|
|
253
|
+
|
|
254
|
+
await run("--repo-root", root);
|
|
255
|
+
|
|
256
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("scaffold detected drift"));
|
|
257
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("hq rescue -y --paths .claude"));
|
|
258
|
+
});
|
|
259
|
+
});
|
package/src/commands/reindex.ts
CHANGED
|
@@ -22,8 +22,213 @@
|
|
|
22
22
|
* operation lock honors, so it works even against an installed hq-cloud build
|
|
23
23
|
* that predates a typed lock-timeout option.
|
|
24
24
|
*/
|
|
25
|
+
import { spawnSync } from 'node:child_process';
|
|
26
|
+
import * as fs from 'node:fs';
|
|
27
|
+
import * as path from 'node:path';
|
|
25
28
|
import { Command } from 'commander';
|
|
26
|
-
import
|
|
29
|
+
import * as yaml from 'js-yaml';
|
|
30
|
+
import { reindex, rescue } from '@indigoai-us/hq-cloud';
|
|
31
|
+
import { findHqRoot } from '../utils/manifest.js';
|
|
32
|
+
|
|
33
|
+
const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse'] as const;
|
|
34
|
+
const HOOK_CHECK_RELATIVE_PATH = path.join('core', 'scripts', 'check-hq-hooks.sh');
|
|
35
|
+
|
|
36
|
+
type HookHealth =
|
|
37
|
+
| { state: 'healthy' }
|
|
38
|
+
| { state: 'extreme'; reason: string }
|
|
39
|
+
| { state: 'minor'; reason: string };
|
|
40
|
+
|
|
41
|
+
type HookCheckResult = { status: number; output: string };
|
|
42
|
+
|
|
43
|
+
/** Resolve the same root the repair/check commands must operate on. */
|
|
44
|
+
function resolveHqRoot(repoRoot?: string): string {
|
|
45
|
+
const root = repoRoot ?? findHqRoot();
|
|
46
|
+
try {
|
|
47
|
+
return fs.realpathSync(root);
|
|
48
|
+
} catch {
|
|
49
|
+
return path.resolve(root);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isHqRoot(hqRoot: string): boolean {
|
|
54
|
+
return (
|
|
55
|
+
fs.existsSync(path.join(hqRoot, 'companies')) &&
|
|
56
|
+
(fs.existsSync(path.join(hqRoot, '.claude')) ||
|
|
57
|
+
fs.existsSync(path.join(hqRoot, 'core')) ||
|
|
58
|
+
fs.existsSync(path.join(hqRoot, 'personal')))
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function hasCommandHook(value: unknown): boolean {
|
|
63
|
+
if (!Array.isArray(value)) return false;
|
|
64
|
+
return value.some((entry) => {
|
|
65
|
+
if (!entry || typeof entry !== 'object') return false;
|
|
66
|
+
const hooks = (entry as { hooks?: unknown }).hooks;
|
|
67
|
+
if (!Array.isArray(hooks)) return false;
|
|
68
|
+
return hooks.some(
|
|
69
|
+
(hook) =>
|
|
70
|
+
!!hook &&
|
|
71
|
+
typeof hook === 'object' &&
|
|
72
|
+
(hook as { type?: unknown }).type === 'command' &&
|
|
73
|
+
typeof (hook as { command?: unknown }).command === 'string' &&
|
|
74
|
+
(hook as { command: string }).command.trim().length > 0
|
|
75
|
+
);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Run the release health checker when it is available. Its diagnostics cover
|
|
81
|
+
* runtime/configuration issues outside the safe repair scope; the JSON check
|
|
82
|
+
* below additionally recognizes UserPromptSubmit, which older checkers omit.
|
|
83
|
+
*/
|
|
84
|
+
function runShippedHookCheck(hqRoot: string): HookCheckResult | undefined {
|
|
85
|
+
const checker = path.join(hqRoot, HOOK_CHECK_RELATIVE_PATH);
|
|
86
|
+
if (!fs.existsSync(checker)) return undefined;
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
const result = spawnSync('bash', [checker, '--root', hqRoot], {
|
|
90
|
+
encoding: 'utf8',
|
|
91
|
+
stdio: 'pipe',
|
|
92
|
+
});
|
|
93
|
+
if (result.error) return undefined;
|
|
94
|
+
return {
|
|
95
|
+
status: result.status ?? 1,
|
|
96
|
+
output: `${result.stderr ?? ''}${result.stdout ?? ''}`.trim(),
|
|
97
|
+
};
|
|
98
|
+
} catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function inspectHookHealth(hqRoot: string): HookHealth {
|
|
104
|
+
const checkerResult = runShippedHookCheck(hqRoot);
|
|
105
|
+
const settingsPath = path.join(hqRoot, '.claude', 'settings.json');
|
|
106
|
+
if (!fs.existsSync(settingsPath)) {
|
|
107
|
+
return { state: 'extreme', reason: '.claude/settings.json is missing' };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let settings: unknown;
|
|
111
|
+
try {
|
|
112
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
|
113
|
+
} catch {
|
|
114
|
+
return { state: 'minor', reason: '.claude/settings.json is not valid JSON' };
|
|
115
|
+
}
|
|
116
|
+
if (!settings || typeof settings !== 'object') {
|
|
117
|
+
return { state: 'minor', reason: '.claude/settings.json is not an object' };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const hooks = (settings as { hooks?: unknown }).hooks;
|
|
121
|
+
if (!hooks || typeof hooks !== 'object') {
|
|
122
|
+
return { state: 'extreme', reason: 'no command hooks are declared' };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const commandEvents = HOOK_EVENTS.filter((event) =>
|
|
126
|
+
hasCommandHook((hooks as Record<string, unknown>)[event])
|
|
127
|
+
);
|
|
128
|
+
if (commandEvents.length === 0) {
|
|
129
|
+
return { state: 'extreme', reason: 'no SessionStart, UserPromptSubmit, or PreToolUse command hook is declared' };
|
|
130
|
+
}
|
|
131
|
+
if (commandEvents.length !== HOOK_EVENTS.length) {
|
|
132
|
+
return {
|
|
133
|
+
state: 'minor',
|
|
134
|
+
reason: `missing command hook wiring for ${HOOK_EVENTS.filter((event) => !commandEvents.includes(event)).join(', ')}`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (checkerResult !== undefined && checkerResult.status !== 0) {
|
|
139
|
+
return {
|
|
140
|
+
state: 'minor',
|
|
141
|
+
reason: checkerResult.output || 'the shipped core/scripts/check-hq-hooks.sh check failed',
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
return { state: 'healthy' };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function printHookHealthWarning(hqRoot: string, reason: string): void {
|
|
148
|
+
console.warn(`
|
|
149
|
+
HQ hook health warning: lifecycle hooks may not fire in ${hqRoot}.
|
|
150
|
+
- ${reason}
|
|
151
|
+
|
|
152
|
+
Repair the project settings with:
|
|
153
|
+
hq rescue -y --paths .claude
|
|
154
|
+
|
|
155
|
+
If the repair is unavailable, update HQ and re-run \`hq reindex\`.
|
|
156
|
+
For Claude Desktop, open the HQ root itself as the project (not a parent or child folder).
|
|
157
|
+
For an SDK launch, set both \`cwd\` to the HQ root and \`settingSources: ["project"]\`.
|
|
158
|
+
See core/docs/hq/HOOKS-NOT-FIRING.md for the recovery procedure.`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function installedCoreRef(hqRoot: string): string | undefined {
|
|
162
|
+
for (const relativePath of [path.join('core', 'core.yaml'), 'core.yaml']) {
|
|
163
|
+
try {
|
|
164
|
+
const core = yaml.load(fs.readFileSync(path.join(hqRoot, relativePath), 'utf8')) as
|
|
165
|
+
| { hqVersion?: unknown }
|
|
166
|
+
| undefined;
|
|
167
|
+
if (typeof core?.hqVersion === 'string' && core.hqVersion.trim()) {
|
|
168
|
+
return core.hqVersion.startsWith('v') ? core.hqVersion : `v${core.hqVersion}`;
|
|
169
|
+
}
|
|
170
|
+
} catch {
|
|
171
|
+
// The installed version is optional; rescue will use the production default.
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Rescue writes detailed progress directly to stdio. Reindex only needs a one-line notice. */
|
|
178
|
+
function runSilently<T>(operation: () => T): T {
|
|
179
|
+
const writeStdout = process.stdout.write;
|
|
180
|
+
const writeStderr = process.stderr.write;
|
|
181
|
+
const discard = (() => true) as typeof process.stdout.write;
|
|
182
|
+
process.stdout.write = discard;
|
|
183
|
+
process.stderr.write = discard;
|
|
184
|
+
try {
|
|
185
|
+
return operation();
|
|
186
|
+
} finally {
|
|
187
|
+
process.stdout.write = writeStdout;
|
|
188
|
+
process.stderr.write = writeStderr;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Check hook health without relying on lifecycle hooks. A fully disabled
|
|
194
|
+
* configuration is repaired only after a successful reindex; partial and
|
|
195
|
+
* malformed configurations remain untouched and receive recovery guidance.
|
|
196
|
+
*/
|
|
197
|
+
export function repairExtremeHookDrift(hqRoot: string, allowRepair = true): void {
|
|
198
|
+
// `hq reindex` can still be invoked from an arbitrary directory. Never turn
|
|
199
|
+
// an absent settings file there into a rescue attempt.
|
|
200
|
+
if (!isHqRoot(hqRoot)) return;
|
|
201
|
+
|
|
202
|
+
const health = inspectHookHealth(hqRoot);
|
|
203
|
+
if (health.state === 'healthy') return;
|
|
204
|
+
|
|
205
|
+
printHookHealthWarning(hqRoot, health.reason);
|
|
206
|
+
if (health.state === 'minor' || !allowRepair) return;
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
const result = runSilently(() =>
|
|
210
|
+
rescue({
|
|
211
|
+
hqRoot,
|
|
212
|
+
source: 'indigoai-us/hq-core',
|
|
213
|
+
ref: installedCoreRef(hqRoot),
|
|
214
|
+
paths: ['.claude'],
|
|
215
|
+
assumeYes: true,
|
|
216
|
+
})
|
|
217
|
+
);
|
|
218
|
+
const afterRepair = inspectHookHealth(hqRoot);
|
|
219
|
+
if (result.status === 0 && afterRepair.state === 'healthy') {
|
|
220
|
+
console.log('reindex: repaired HQ hook config');
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
printHookHealthWarning(
|
|
224
|
+
hqRoot,
|
|
225
|
+
afterRepair.state === 'healthy' ? `rescue exited ${result.status}` : afterRepair.reason
|
|
226
|
+
);
|
|
227
|
+
} catch {
|
|
228
|
+
// A transient clone/transport failure must not turn reindex into a fatal command.
|
|
229
|
+
printHookHealthWarning(hqRoot, 'hook configuration repair could not run');
|
|
230
|
+
}
|
|
231
|
+
}
|
|
27
232
|
|
|
28
233
|
export function registerReindexCommand(program: Command): void {
|
|
29
234
|
program
|
|
@@ -63,6 +268,7 @@ export function registerReindexCommand(program: Command): void {
|
|
|
63
268
|
}
|
|
64
269
|
|
|
65
270
|
const { status } = reindex({ repoRoot: opts.repoRoot });
|
|
271
|
+
repairExtremeHookDrift(resolveHqRoot(opts.repoRoot), status === 0);
|
|
66
272
|
process.exit(status);
|
|
67
273
|
});
|
|
68
274
|
}
|
|
@@ -436,4 +436,180 @@ describe("enforceVersionGate — hard-update path", () => {
|
|
|
436
436
|
expect(exitSpy).toHaveBeenCalledWith(75);
|
|
437
437
|
expect(runner).toHaveBeenCalledWith("sudo", expect.arrayContaining(["-n"]));
|
|
438
438
|
});
|
|
439
|
+
|
|
440
|
+
it("cleans a stale partial install and retries once when the unprivileged install fails with ENOTEMPTY", async () => {
|
|
441
|
+
vi.spyOn(console, "error").mockImplementation(() => {});
|
|
442
|
+
const exitSpy = vi
|
|
443
|
+
.spyOn(process, "exit")
|
|
444
|
+
.mockImplementation(((code?: number) => {
|
|
445
|
+
throw new Error(`__process_exit__:${code ?? 0}`);
|
|
446
|
+
}) as never);
|
|
447
|
+
// The reported failure: `npm install -g --prefix <toolchain> …` fails with
|
|
448
|
+
// ENOTEMPTY renaming a partial `hq-cli`. sudo does NOT fix a corrupt dir —
|
|
449
|
+
// only removing the stale artifacts and reinstalling does. Before this fix
|
|
450
|
+
// the gate exhausted npm→sudo→exit 75, leaving `hq` broken (ENOENT).
|
|
451
|
+
let npmCalls = 0;
|
|
452
|
+
const runner = vi.fn().mockImplementation((cmd: string) => {
|
|
453
|
+
if (cmd === "sudo") return { ok: false, detail: "ENOTEMPTY" };
|
|
454
|
+
npmCalls += 1;
|
|
455
|
+
return npmCalls === 1 ? { ok: false, detail: "ENOTEMPTY" } : { ok: true };
|
|
456
|
+
});
|
|
457
|
+
const prefix =
|
|
458
|
+
"/Users/x/Library/Application Support/Indigo HQ/toolchain/npm-global";
|
|
459
|
+
const cleanStale = vi
|
|
460
|
+
.fn()
|
|
461
|
+
.mockReturnValue([`${prefix}/lib/node_modules/@indigoai-us/.hq-cli-0DY3ww6z`]);
|
|
462
|
+
const { __test__ } = await loadModule();
|
|
463
|
+
|
|
464
|
+
expect(() =>
|
|
465
|
+
__test__.enforceUpdateRequired(
|
|
466
|
+
{
|
|
467
|
+
clientId: "hq-cli",
|
|
468
|
+
currentVersion: "5.10.0",
|
|
469
|
+
minVersion: "5.20.0",
|
|
470
|
+
latestVersion: "5.24.0",
|
|
471
|
+
updateRequired: true,
|
|
472
|
+
updateRecommended: false,
|
|
473
|
+
updateCommand: "npm install -g @indigoai-us/hq-cli@latest",
|
|
474
|
+
},
|
|
475
|
+
{ resolvePrefix: () => prefix, runner, cleanStale },
|
|
476
|
+
),
|
|
477
|
+
).toThrow(/__process_exit__:0/); // recovers after the cleanup + retry
|
|
478
|
+
|
|
479
|
+
expect(exitSpy).toHaveBeenCalledWith(0);
|
|
480
|
+
expect(cleanStale).toHaveBeenCalledWith(prefix);
|
|
481
|
+
const installArgs = [
|
|
482
|
+
"install",
|
|
483
|
+
"-g",
|
|
484
|
+
"--prefix",
|
|
485
|
+
prefix,
|
|
486
|
+
"@indigoai-us/hq-cli@latest",
|
|
487
|
+
];
|
|
488
|
+
// primary attempt + one retry after the stale artifacts were removed
|
|
489
|
+
expect(
|
|
490
|
+
runner.mock.calls.filter((c) => c[0] === "npm").length,
|
|
491
|
+
).toBe(2);
|
|
492
|
+
expect(runner).toHaveBeenCalledWith("npm", installArgs);
|
|
493
|
+
// sudo must NOT be reached — the ENOTEMPTY was fixed by cleanup, not perms
|
|
494
|
+
expect(runner).not.toHaveBeenCalledWith("sudo", expect.anything());
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
it("does NOT reinstall-after-clean when nothing stale exists (plain EACCES falls straight to sudo)", async () => {
|
|
498
|
+
vi.spyOn(console, "error").mockImplementation(() => {});
|
|
499
|
+
const exitSpy = vi
|
|
500
|
+
.spyOn(process, "exit")
|
|
501
|
+
.mockImplementation(((code?: number) => {
|
|
502
|
+
throw new Error(`__process_exit__:${code ?? 0}`);
|
|
503
|
+
}) as never);
|
|
504
|
+
const runner = vi
|
|
505
|
+
.fn()
|
|
506
|
+
.mockImplementation((cmd: string) =>
|
|
507
|
+
cmd === "sudo" ? { ok: true } : { ok: false, detail: "EACCES" },
|
|
508
|
+
);
|
|
509
|
+
const cleanStale = vi.fn().mockReturnValue([]); // healthy prefix, nothing to remove
|
|
510
|
+
const { __test__ } = await loadModule();
|
|
511
|
+
|
|
512
|
+
expect(() =>
|
|
513
|
+
__test__.enforceUpdateRequired(
|
|
514
|
+
{
|
|
515
|
+
clientId: "hq-cli",
|
|
516
|
+
currentVersion: "5.10.0",
|
|
517
|
+
minVersion: "5.20.0",
|
|
518
|
+
latestVersion: "5.24.0",
|
|
519
|
+
updateRequired: true,
|
|
520
|
+
updateRecommended: false,
|
|
521
|
+
updateCommand: "npm install -g @indigoai-us/hq-cli@latest",
|
|
522
|
+
},
|
|
523
|
+
{ resolvePrefix: () => "/usr", runner, cleanStale },
|
|
524
|
+
),
|
|
525
|
+
).toThrow(/__process_exit__:0/); // sudo retry succeeds
|
|
526
|
+
|
|
527
|
+
expect(exitSpy).toHaveBeenCalledWith(0);
|
|
528
|
+
expect(cleanStale).toHaveBeenCalledWith("/usr");
|
|
529
|
+
// exactly ONE npm attempt (no redundant reinstall), then sudo
|
|
530
|
+
expect(runner.mock.calls.filter((c) => c[0] === "npm").length).toBe(1);
|
|
531
|
+
expect(runner).toHaveBeenCalledWith("sudo", expect.arrayContaining(["-n"]));
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
describe("cleanStalePartialInstall", () => {
|
|
536
|
+
type FakeTree = {
|
|
537
|
+
dirs: Record<string, string[]>;
|
|
538
|
+
packageJson: Record<string, string | null>;
|
|
539
|
+
existing: Set<string>;
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
function makeFakeFs(tree: FakeTree) {
|
|
543
|
+
const removed: string[] = [];
|
|
544
|
+
const fs = {
|
|
545
|
+
readdirSync: (dir: string) => {
|
|
546
|
+
if (dir in tree.dirs) return tree.dirs[dir]!;
|
|
547
|
+
throw new Error(`ENOENT: ${dir}`);
|
|
548
|
+
},
|
|
549
|
+
existsSync: (target: string) => tree.existing.has(target),
|
|
550
|
+
readFileSync: (target: string) => {
|
|
551
|
+
const pkgDir = target.replace(/\/package\.json$/, "");
|
|
552
|
+
const content = tree.packageJson[pkgDir];
|
|
553
|
+
if (content == null) throw new Error(`ENOENT: ${target}`);
|
|
554
|
+
return content;
|
|
555
|
+
},
|
|
556
|
+
rmSync: (target: string) => {
|
|
557
|
+
removed.push(target);
|
|
558
|
+
},
|
|
559
|
+
};
|
|
560
|
+
return { fs, removed };
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
it("removes the npm staging dir and a partial package dir, but keeps unrelated entries", async () => {
|
|
564
|
+
const { __test__ } = await loadModule();
|
|
565
|
+
const prefix = "/p";
|
|
566
|
+
const scopeDir = "/p/lib/node_modules/@indigoai-us";
|
|
567
|
+
const { fs, removed } = makeFakeFs({
|
|
568
|
+
dirs: {
|
|
569
|
+
[scopeDir]: [".hq-cli-0DY3ww6z", "hq-cli", "some-other-pkg"],
|
|
570
|
+
},
|
|
571
|
+
packageJson: { [`${scopeDir}/hq-cli`]: null }, // partial: package.json unreadable
|
|
572
|
+
existing: new Set([`${scopeDir}/hq-cli`]),
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
const result = __test__.cleanStalePartialInstall(prefix, fs);
|
|
576
|
+
|
|
577
|
+
expect(result).toContain(`${scopeDir}/.hq-cli-0DY3ww6z`);
|
|
578
|
+
expect(result).toContain(`${scopeDir}/hq-cli`);
|
|
579
|
+
expect(removed).not.toContain(`${scopeDir}/some-other-pkg`);
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
it("never touches a healthy install (valid package.json with matching name)", async () => {
|
|
583
|
+
const { __test__ } = await loadModule();
|
|
584
|
+
const scopeDir = "/p/lib/node_modules/@indigoai-us";
|
|
585
|
+
const { fs, removed } = makeFakeFs({
|
|
586
|
+
dirs: { [scopeDir]: ["hq-cli"] }, // no staging leftovers
|
|
587
|
+
packageJson: {
|
|
588
|
+
[`${scopeDir}/hq-cli`]: JSON.stringify({
|
|
589
|
+
name: "@indigoai-us/hq-cli",
|
|
590
|
+
version: "5.24.0",
|
|
591
|
+
}),
|
|
592
|
+
},
|
|
593
|
+
existing: new Set([`${scopeDir}/hq-cli`]),
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
const result = __test__.cleanStalePartialInstall("/p", fs);
|
|
597
|
+
|
|
598
|
+
expect(result).toEqual([]);
|
|
599
|
+
expect(removed).toEqual([]);
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
it("also cleans a staging dir under the bare <prefix>/node_modules layout", async () => {
|
|
603
|
+
const { __test__ } = await loadModule();
|
|
604
|
+
const scopeDir = "/p/node_modules/@indigoai-us";
|
|
605
|
+
const { fs } = makeFakeFs({
|
|
606
|
+
dirs: { [scopeDir]: [".hq-cli-abc123"] },
|
|
607
|
+
packageJson: {},
|
|
608
|
+
existing: new Set(),
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
const result = __test__.cleanStalePartialInstall("/p", fs);
|
|
612
|
+
|
|
613
|
+
expect(result).toEqual([`${scopeDir}/.hq-cli-abc123`]);
|
|
614
|
+
});
|
|
439
615
|
});
|