@indigoai-us/hq-cli 5.77.6 → 5.77.8
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 +16 -0
- package/dist/commands/group-grants.d.ts +1 -1
- package/dist/commands/group-grants.js +6 -6
- package/dist/commands/integrations.js +24 -1
- package/dist/commands/reindex.d.ts +5 -23
- package/dist/commands/reindex.js +206 -1
- package/dist/commands/secrets.js +2 -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/group-grants.test.ts +41 -2
- package/src/commands/group-grants.ts +11 -8
- 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/commands/secrets.test.ts +40 -0
- package/src/commands/secrets.ts +11 -2
- package/src/utils/version-gate.test.ts +176 -0
- package/src/utils/version-gate.ts +127 -1
|
@@ -189,15 +189,18 @@ export async function revokeGroupGrant(
|
|
|
189
189
|
export async function listOutboundGrants(
|
|
190
190
|
token: string,
|
|
191
191
|
sourceCompanyUid: string,
|
|
192
|
-
groupId
|
|
192
|
+
groupId: string,
|
|
193
193
|
): Promise<GroupGrant[]> {
|
|
194
|
-
|
|
195
|
-
|
|
194
|
+
if (!GROUP_ID_PATTERN.test(groupId)) {
|
|
195
|
+
throw new Error(
|
|
196
|
+
`Invalid group id '${groupId}': must match grp_<alphanumeric, underscore, hyphen>`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
196
199
|
|
|
197
200
|
const res = await vaultApiFetch({
|
|
198
201
|
token,
|
|
199
202
|
path: "/group-grants/outbound",
|
|
200
|
-
query,
|
|
203
|
+
query: { sourceCompanyUid, groupId },
|
|
201
204
|
});
|
|
202
205
|
|
|
203
206
|
if (!res.ok) {
|
|
@@ -385,13 +388,13 @@ export function registerGroupGrantsCommand(program: Command): void {
|
|
|
385
388
|
grants
|
|
386
389
|
.command("outbound")
|
|
387
390
|
.description(
|
|
388
|
-
"List grants
|
|
391
|
+
"List grants a source-company group holds on other companies",
|
|
389
392
|
)
|
|
390
|
-
.
|
|
393
|
+
.requiredOption(
|
|
391
394
|
"--group <groupId>",
|
|
392
|
-
"
|
|
395
|
+
"Group id to inspect",
|
|
393
396
|
)
|
|
394
|
-
.action(async (opts: { group
|
|
397
|
+
.action(async (opts: { group: string }) => {
|
|
395
398
|
try {
|
|
396
399
|
const token = await ensureCognitoToken();
|
|
397
400
|
const sourceSlug = grants.opts().company as string | undefined;
|
|
@@ -513,3 +513,121 @@ describe("integration gateway 401 → AuthError (HQ-CLI-9)", () => {
|
|
|
513
513
|
expect((err as Error).message).toMatch(/monday rejected the board id/);
|
|
514
514
|
});
|
|
515
515
|
});
|
|
516
|
+
|
|
517
|
+
// HQ-CLI-B: `hq integrations tools|call … --provider …` against a connection the
|
|
518
|
+
// caller has NOT been granted returned HTTP 200 with a JSON-RPC error
|
|
519
|
+
// { code: -32003, message: "You do not have access to this integration. Ask its
|
|
520
|
+
// owner to share it with you.", data: { code: "IntegrationAccessDenied" } }.
|
|
521
|
+
// `callGateway` threw an IntegrationsCliError WITHOUT `expected`, so it defaulted
|
|
522
|
+
// to `expected === false` and the top-level handler shipped a GOVERNED, correct
|
|
523
|
+
// access denial to Sentry as an error-level fatal — 40 identical, unfixable
|
|
524
|
+
// events for one user. A caller-side JSON-RPC code (UNAUTHORIZED / INVALID_PARAMS)
|
|
525
|
+
// is the analog of a client 4xx and must be printed to the user, not captured;
|
|
526
|
+
// genuine server/provider/protocol faults must still report.
|
|
527
|
+
describe("gateway JSON-RPC error classification (HQ-CLI-B)", () => {
|
|
528
|
+
function gatewayJsonRpcError(code: number | undefined, message: string, data?: unknown) {
|
|
529
|
+
return jsonResponse({
|
|
530
|
+
jsonrpc: "2.0",
|
|
531
|
+
id: "x",
|
|
532
|
+
error: { ...(code == null ? {} : { code }), message, ...(data ? { data } : {}) },
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function runGatewayCall(): Promise<unknown> {
|
|
537
|
+
return runCli([
|
|
538
|
+
"integrations",
|
|
539
|
+
"call",
|
|
540
|
+
"get_board_info",
|
|
541
|
+
"--provider",
|
|
542
|
+
"linear",
|
|
543
|
+
"--args",
|
|
544
|
+
"{}",
|
|
545
|
+
]).then(
|
|
546
|
+
() => {
|
|
547
|
+
throw new Error("expected runCli to throw");
|
|
548
|
+
},
|
|
549
|
+
(e: unknown) => e,
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
it("marks the access-denied gateway error (-32003) as expected and preserves its actionable message", async () => {
|
|
554
|
+
vaultApiFetchMock
|
|
555
|
+
.mockResolvedValueOnce(connectionsResponse())
|
|
556
|
+
.mockResolvedValueOnce(
|
|
557
|
+
gatewayJsonRpcError(
|
|
558
|
+
-32003,
|
|
559
|
+
"You do not have access to this integration. Ask its owner to share it with you.",
|
|
560
|
+
{ code: "IntegrationAccessDenied" },
|
|
561
|
+
),
|
|
562
|
+
);
|
|
563
|
+
|
|
564
|
+
const err = await runGatewayCall();
|
|
565
|
+
|
|
566
|
+
expect(err).toBeInstanceOf(IntegrationsCliError);
|
|
567
|
+
// The regression: this was `false` and flooded Sentry with a governed denial.
|
|
568
|
+
expect((err as IntegrationsCliError).expected).toBe(true);
|
|
569
|
+
// A connection-level denial is NOT an expired session — never an AuthError.
|
|
570
|
+
expect(isAuthError(err)).toBe(false);
|
|
571
|
+
expect((err as Error).message).toContain("do not have access to this integration");
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
it("also marks access-denied as expected on the `tools` path (same callGateway seam)", async () => {
|
|
575
|
+
vaultApiFetchMock
|
|
576
|
+
.mockResolvedValueOnce(connectionsResponse())
|
|
577
|
+
.mockResolvedValueOnce(
|
|
578
|
+
gatewayJsonRpcError(
|
|
579
|
+
-32003,
|
|
580
|
+
"You do not have access to this integration. Ask its owner to share it with you.",
|
|
581
|
+
),
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
const err = await runCli(["integrations", "tools", "--provider", "linear"]).then(
|
|
585
|
+
() => {
|
|
586
|
+
throw new Error("expected runCli to throw");
|
|
587
|
+
},
|
|
588
|
+
(e: unknown) => e,
|
|
589
|
+
);
|
|
590
|
+
|
|
591
|
+
expect(err).toBeInstanceOf(IntegrationsCliError);
|
|
592
|
+
expect((err as IntegrationsCliError).expected).toBe(true);
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
it("marks an invalid-params gateway error (-32602) as expected", async () => {
|
|
596
|
+
vaultApiFetchMock
|
|
597
|
+
.mockResolvedValueOnce(connectionsResponse())
|
|
598
|
+
.mockResolvedValueOnce(gatewayJsonRpcError(-32602, "Unknown integration tool: get_board_info"));
|
|
599
|
+
|
|
600
|
+
const err = await runGatewayCall();
|
|
601
|
+
|
|
602
|
+
expect(err).toBeInstanceOf(IntegrationsCliError);
|
|
603
|
+
expect((err as IntegrationsCliError).expected).toBe(true);
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
it("still reports genuine provider/internal/conflict gateway faults (expected === false)", async () => {
|
|
607
|
+
// -32050 PROVIDER_ERROR, -32603 INTERNAL_ERROR, and -32009 CONFLICT (which the
|
|
608
|
+
// gateway raises for a confirm queue being unavailable or an owner
|
|
609
|
+
// notification failing) are real faults that must keep reaching Sentry.
|
|
610
|
+
for (const code of [-32050, -32603, -32009]) {
|
|
611
|
+
vaultApiFetchMock
|
|
612
|
+
.mockResolvedValueOnce(connectionsResponse())
|
|
613
|
+
.mockResolvedValueOnce(gatewayJsonRpcError(code, "gateway fault"));
|
|
614
|
+
|
|
615
|
+
const err = await runGatewayCall();
|
|
616
|
+
|
|
617
|
+
expect(err).toBeInstanceOf(IntegrationsCliError);
|
|
618
|
+
expect((err as IntegrationsCliError).expected).toBe(false);
|
|
619
|
+
vaultApiFetchMock.mockClear();
|
|
620
|
+
}
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
it("reports a gateway error with no JSON-RPC code (unclassified → expected === false)", async () => {
|
|
624
|
+
vaultApiFetchMock
|
|
625
|
+
.mockResolvedValueOnce(connectionsResponse())
|
|
626
|
+
.mockResolvedValueOnce(gatewayJsonRpcError(undefined, "codeless failure"));
|
|
627
|
+
|
|
628
|
+
const err = await runGatewayCall();
|
|
629
|
+
|
|
630
|
+
expect(err).toBeInstanceOf(IntegrationsCliError);
|
|
631
|
+
expect((err as IntegrationsCliError).expected).toBe(false);
|
|
632
|
+
});
|
|
633
|
+
});
|
|
@@ -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
|
}
|