@indigoai-us/hq-cli 5.111.2 → 5.113.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/bin/hq-auth-refresh.d.ts +2 -0
  3. package/dist/bin/hq-auth-refresh.js +12 -6
  4. package/dist/command-catalog.generated.d.ts +6399 -0
  5. package/dist/command-catalog.generated.js +8275 -0
  6. package/dist/command-registration-plan.d.ts +394 -0
  7. package/dist/command-registration-plan.js +103 -0
  8. package/dist/commands/core.js +18 -0
  9. package/dist/commands/index-cmd.d.ts +2 -0
  10. package/dist/commands/index-cmd.js +15 -0
  11. package/dist/lazy-commands.d.ts +20 -44
  12. package/dist/lazy-commands.js +57 -58
  13. package/dist/lib/core-utils/qmd-reindex-after-sync.d.ts +1 -0
  14. package/dist/lib/core-utils/qmd-reindex-after-sync.js +12 -0
  15. package/dist/lib/core-utils/sentry-report.d.ts +76 -0
  16. package/dist/lib/core-utils/sentry-report.js +255 -0
  17. package/dist/lib/search-index/background.d.ts +2 -0
  18. package/dist/lib/search-index/background.js +28 -0
  19. package/dist/lib/search-index/max-doc-bytes.d.ts +220 -0
  20. package/dist/lib/search-index/max-doc-bytes.js +463 -0
  21. package/dist/main.d.ts +6 -0
  22. package/dist/main.js +87 -29
  23. package/dist/register-all.d.ts +4 -29
  24. package/dist/register-all.js +4 -235
  25. package/dist/sentry.d.ts +8 -2
  26. package/dist/sentry.js +17 -1
  27. package/dist/utils/cli-telemetry.d.ts +2 -1
  28. package/dist/utils/cli-telemetry.js +5 -5
  29. package/dist/utils/contribution-table.d.ts +1 -1
  30. package/dist/utils/version-check.d.ts +4 -1
  31. package/dist/utils/version-check.js +2 -2
  32. package/dist/utils/version-gate.d.ts +5 -1
  33. package/dist/utils/version-gate.js +4 -4
  34. package/package.json +3 -2
@@ -1,55 +1,31 @@
1
- /**
2
- * Hot-command manifest for the entrypoint's lazy registration.
3
- *
4
- * main.ts used to import the entire ~60-module command graph at module scope,
5
- * so every invocation paid for every command. That is fine for a human typing
6
- * one command and ruinous for the calls automation makes in a loop: the
7
- * hq-sentry agent fleet on an outpost runs `hq secrets` about 39 times a minute
8
- * (each worker resolves credentials before every external command it executes),
9
- * and each of those processes spent ~0.75 CPU-seconds importing commands it
10
- * never ran — around half a core, continuously. Measured on Outpost 2
11
- * (i-09424eff61920a4ac) 2026-09-05; see register-all.ts for the numbers.
12
- *
13
- * A command listed here registers ITSELF and nothing else. Anything not listed
14
- * — `--help`, a bare `hq`, an unknown command, every other command — falls back
15
- * to `registerAllCommands`, the complete unchanged graph. That fallback is what
16
- * makes this safe to extend one command at a time: an entry is a performance
17
- * opt-in, never a behaviour change, and a command that is absent here is simply
18
- * as fast as it was before.
19
- *
20
- * This mirrors commands/scaffold-fast.ts, which does the same thing for the
21
- * relocated `hq core …` scripts, and carries the same anti-drift discipline: a
22
- * parity test registers each entry BOTH ways and asserts the resulting command
23
- * shape is identical, so a manifest entry cannot silently diverge from the real
24
- * registration.
25
- *
26
- * TO ADD A COMMAND: it must register exactly one top-level command, be
27
- * registered onto `program` (not onto a subcommand group), and have no other
28
- * module contributing subcommands to it. The parity test enforces the shape;
29
- * these three conditions are what make the entry correct in the first place.
30
- */
31
- import type { Command } from "commander";
1
+ import { Command } from "commander";
32
2
  export type LazyCommand = {
33
- /** The top-level token this matches `hq <name> …`. */
3
+ /** Canonical top-level name; aliases resolve to this name. */
34
4
  name: string;
35
- /** Registers this one command onto `program`, importing only its module. */
5
+ /** Registers every contributor for this root and no unrelated root. */
36
6
  register: (program: Command) => Promise<void>;
37
7
  };
38
8
  /**
39
- * The hot paths, in descending order of how often automation calls them.
40
- *
41
- * `secrets` and `run` are the two commands HQ's own tooling puts on the inner
42
- * loop: every fleet worker shells through one of them before each external
43
- * command, which is exactly the shape that makes eager import expensive.
9
+ * One entry for every root, including groups that are assembled by several
10
+ * registrar modules. The routing metadata itself is generated from the eager
11
+ * command graph and checked in tests and the build.
44
12
  */
45
13
  export declare const LAZY_COMMANDS: readonly LazyCommand[];
46
14
  /**
47
- * Resolve `process.argv` to a manifest entry, or null to use the full graph.
48
- *
49
- * argv is `[node, hq, <name>, ...rest]`. `hq` declares no program-level options
50
- * before the command name, so argv[2] is the command token when there is one;
51
- * `--help`, `--version`, and a bare `hq` all fail the lookup and take the
52
- * fallback, which is the intended behaviour — help must list every command.
15
+ * Keep the registration seam at register-all.js. Besides making one place own
16
+ * the graph, this lets the torn-install recovery wrap failures while an update
17
+ * replaces the installed tree between startup and command registration.
18
+ */
19
+ export declare function registerCommandRoot(program: Command, root: string): Promise<boolean>;
20
+ /**
21
+ * Register only generated root metadata. This is enough for root help and
22
+ * Commander suggestions, without evaluating an implementation module.
23
+ */
24
+ export declare function registerCommandCatalog(program: Command): void;
25
+ /**
26
+ * Resolve the root requested by Commander argv. Root help, a bare invocation,
27
+ * and unknown tokens deliberately return null so the lightweight catalog can
28
+ * preserve the complete help and unknown-command recovery surfaces.
53
29
  */
54
30
  export declare function findLazyCommand(argv: readonly string[]): LazyCommand | null;
55
31
  //# sourceMappingURL=lazy-commands.d.ts.map
@@ -1,68 +1,67 @@
1
+ import { Command } from "commander";
2
+ import { COMMAND_CATALOG } from "./command-catalog.generated.js";
3
+ const commandCatalog = COMMAND_CATALOG;
1
4
  /**
2
- * Hot-command manifest for the entrypoint's lazy registration.
3
- *
4
- * main.ts used to import the entire ~60-module command graph at module scope,
5
- * so every invocation paid for every command. That is fine for a human typing
6
- * one command and ruinous for the calls automation makes in a loop: the
7
- * hq-sentry agent fleet on an outpost runs `hq secrets` about 39 times a minute
8
- * (each worker resolves credentials before every external command it executes),
9
- * and each of those processes spent ~0.75 CPU-seconds importing commands it
10
- * never ran — around half a core, continuously. Measured on Outpost 2
11
- * (i-09424eff61920a4ac) 2026-09-05; see register-all.ts for the numbers.
12
- *
13
- * A command listed here registers ITSELF and nothing else. Anything not listed
14
- * — `--help`, a bare `hq`, an unknown command, every other command — falls back
15
- * to `registerAllCommands`, the complete unchanged graph. That fallback is what
16
- * makes this safe to extend one command at a time: an entry is a performance
17
- * opt-in, never a behaviour change, and a command that is absent here is simply
18
- * as fast as it was before.
19
- *
20
- * This mirrors commands/scaffold-fast.ts, which does the same thing for the
21
- * relocated `hq core …` scripts, and carries the same anti-drift discipline: a
22
- * parity test registers each entry BOTH ways and asserts the resulting command
23
- * shape is identical, so a manifest entry cannot silently diverge from the real
24
- * registration.
25
- *
26
- * TO ADD A COMMAND: it must register exactly one top-level command, be
27
- * registered onto `program` (not onto a subcommand group), and have no other
28
- * module contributing subcommands to it. The parity test enforces the shape;
29
- * these three conditions are what make the entry correct in the first place.
5
+ * One entry for every root, including groups that are assembled by several
6
+ * registrar modules. The routing metadata itself is generated from the eager
7
+ * command graph and checked in tests and the build.
30
8
  */
9
+ export const LAZY_COMMANDS = commandCatalog.map((command) => ({
10
+ name: command.name,
11
+ register: async (program) => {
12
+ const registered = await registerCommandRoot(program, command.name);
13
+ if (!registered)
14
+ throw new Error(`No registration plan for '${command.name}'`);
15
+ },
16
+ }));
31
17
  /**
32
- * The hot paths, in descending order of how often automation calls them.
33
- *
34
- * `secrets` and `run` are the two commands HQ's own tooling puts on the inner
35
- * loop: every fleet worker shells through one of them before each external
36
- * command, which is exactly the shape that makes eager import expensive.
18
+ * Keep the registration seam at register-all.js. Besides making one place own
19
+ * the graph, this lets the torn-install recovery wrap failures while an update
20
+ * replaces the installed tree between startup and command registration.
37
21
  */
38
- export const LAZY_COMMANDS = [
39
- {
40
- name: "secrets",
41
- register: async (program) => {
42
- const { registerSecretsCommand } = await import("./commands/secrets.js");
43
- registerSecretsCommand(program);
44
- },
45
- },
46
- {
47
- name: "run",
48
- register: async (program) => {
49
- const { registerRunCommand } = await import("./commands/run.js");
50
- registerRunCommand(program);
51
- },
52
- },
53
- ];
22
+ export async function registerCommandRoot(program, root) {
23
+ const registration = await import("./register-all.js");
24
+ return registration.registerCommandRoot(program, root);
25
+ }
26
+ function commandDefinition(command) {
27
+ const stub = new Command(command.name)
28
+ .description(command.description);
29
+ for (const alias of command.aliases)
30
+ stub.alias(alias);
31
+ for (const argument of command.arguments) {
32
+ const name = `${argument.name}${argument.variadic ? "..." : ""}`;
33
+ stub.argument(argument.required ? `<${name}>` : `[${name}]`);
34
+ }
35
+ for (const option of command.options)
36
+ stub.option(option.flags, option.description);
37
+ if (command.hidden)
38
+ stub._hidden = true;
39
+ return stub;
40
+ }
54
41
  /**
55
- * Resolve `process.argv` to a manifest entry, or null to use the full graph.
56
- *
57
- * argv is `[node, hq, <name>, ...rest]`. `hq` declares no program-level options
58
- * before the command name, so argv[2] is the command token when there is one;
59
- * `--help`, `--version`, and a bare `hq` all fail the lookup and take the
60
- * fallback, which is the intended behaviour — help must list every command.
42
+ * Register only generated root metadata. This is enough for root help and
43
+ * Commander suggestions, without evaluating an implementation module.
44
+ */
45
+ export function registerCommandCatalog(program) {
46
+ for (const command of commandCatalog)
47
+ program.addCommand(commandDefinition(command));
48
+ }
49
+ function commandForToken(token) {
50
+ return commandCatalog.find((candidate) => candidate.name === token || candidate.aliases.includes(token));
51
+ }
52
+ /**
53
+ * Resolve the root requested by Commander argv. Root help, a bare invocation,
54
+ * and unknown tokens deliberately return null so the lightweight catalog can
55
+ * preserve the complete help and unknown-command recovery surfaces.
61
56
  */
62
57
  export function findLazyCommand(argv) {
63
- const name = argv[2];
64
- if (typeof name !== "string")
58
+ const first = argv[2];
59
+ const token = first === "help" ? argv[3] : first;
60
+ if (typeof token !== "string" || token.startsWith("-"))
61
+ return null;
62
+ const command = commandForToken(token);
63
+ if (!command)
65
64
  return null;
66
- return LAZY_COMMANDS.find((candidate) => candidate.name === name) ?? null;
65
+ return LAZY_COMMANDS.find((candidate) => candidate.name === command.name) ?? null;
67
66
  }
68
67
  //# sourceMappingURL=lazy-commands.js.map
@@ -10,6 +10,7 @@ export type QmdReindexOptions = UtilityIo & {
10
10
  bin: string;
11
11
  cwd: string;
12
12
  }) => unknown;
13
+ sizeLimit?: (hqRoot: string) => unknown;
13
14
  };
14
15
  export declare function qmdReindexAfterSync(args?: string[], options?: QmdReindexOptions): number;
15
16
  //# sourceMappingURL=qmd-reindex-after-sync.d.ts.map
@@ -12,6 +12,7 @@
12
12
  import * as fs from "node:fs";
13
13
  import * as path from "node:path";
14
14
  import { reconcileCollections, resolveQmdBin, runQmd } from "../search-index/index.js";
15
+ import { applyIndexSizeLimit } from "../search-index/max-doc-bytes.js";
15
16
  export function qmdReindexAfterSync(args = [], options = {}) {
16
17
  let hqRoot = "";
17
18
  let embed = false;
@@ -36,6 +37,7 @@ export function qmdReindexAfterSync(args = [], options = {}) {
36
37
  return 0;
37
38
  const reconcile = options.reconcile ?? ((root, opts) => reconcileCollections(root, opts));
38
39
  const run = options.run ?? ((argv, opts) => runQmd(argv, opts));
40
+ const sizeLimit = options.sizeLimit ?? ((root) => applyIndexSizeLimit(root));
39
41
  // Every qmd interaction is best-effort: the shell suffixed each with `|| true`.
40
42
  try {
41
43
  reconcile(hqRoot, { bin });
@@ -43,6 +45,16 @@ export function qmdReindexAfterSync(args = [], options = {}) {
43
45
  catch {
44
46
  /* registration is advisory; an update still helps */
45
47
  }
48
+ // The cap has to land before the update, not after: qmd decides what to read
49
+ // at glob time, so an ignore entry written afterwards saves nothing on this
50
+ // pass. This is the post-sync entry point, which reaches `qmd update` without
51
+ // going through `hq index sync` at all.
52
+ try {
53
+ sizeLimit(hqRoot);
54
+ }
55
+ catch {
56
+ /* an uncapped index is worse than none, but still better than a failed sync */
57
+ }
46
58
  try {
47
59
  run(["update"], { bin, cwd: hqRoot });
48
60
  }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `hq core sentry report` — constrained diagnostic transport for HQ hooks.
3
+ *
4
+ * The stdin event schema is deliberately closed. Hook payloads can contain
5
+ * commands, prompts, source content, transcript locations, and credentials, so
6
+ * this module accepts only a small set of scalar diagnostics and never reads a
7
+ * hook payload or the process environment. The owner-approved `hook_path`
8
+ * diagnostic is the narrow exception: it names the slow hook script and may
9
+ * include its company directory, but never carries the hook payload itself.
10
+ *
11
+ * Invalid top-level input and structurally rich metadata are rejected rather
12
+ * than truncated. Unknown scalar metadata is dropped instead: the allowlist,
13
+ * not a caller version match, determines what may leave the machine.
14
+ */
15
+ import type { CaptureContext, SeverityLevel } from "@sentry/node";
16
+ export declare const DEFAULT_SENTRY_REPORT_TIMEOUT_MS = 750;
17
+ export declare const MAX_SENTRY_REPORT_TIMEOUT_MS = 5000;
18
+ export declare const MAX_SENTRY_REPORT_PAYLOAD_BYTES = 2048;
19
+ export declare const MAX_SENTRY_REPORT_METADATA_VALUE_BYTES = 256;
20
+ /**
21
+ * The only hook diagnostics that can be attached as metadata. The list omits
22
+ * command text, prompts, payloads, company names, and repositories. `hook_path`
23
+ * is owner-approved telemetry for the exact hook script and may include a
24
+ * company directory; it is never a substitute for hook input or a transcript.
25
+ */
26
+ export declare const ALLOWED_SENTRY_REPORT_METADATA_KEYS: readonly ["hook_name", "hook_path", "hook_event", "tool_name", "session_id", "declared_timeout_ms", "elapsed_ms", "remaining_ms", "watchdog_timeout_ms", "hook_timeout_ms", "hq_version", "platform", "load_average"];
27
+ export declare const MAX_SENTRY_REPORT_METADATA_KEYS: number;
28
+ export type SentryReportMetadata = Record<string, string | number | boolean>;
29
+ export type SentryReportEvent = {
30
+ type: string;
31
+ message: string;
32
+ fingerprint: string;
33
+ level: SeverityLevel;
34
+ metadata: SentryReportMetadata;
35
+ };
36
+ export type SentryReportOptions = {
37
+ dryRun?: boolean;
38
+ /** Total time reserved for the report flush after validation. */
39
+ timeoutMs?: number;
40
+ };
41
+ export type SentryReportDependencies = {
42
+ sentry: {
43
+ captureMessage: (message: string, context?: CaptureContext | SeverityLevel) => string;
44
+ flush: (timeout?: number) => PromiseLike<boolean>;
45
+ };
46
+ stdout: Pick<NodeJS.WriteStream, "write">;
47
+ stderr: Pick<NodeJS.WriteStream, "write">;
48
+ };
49
+ export type SentryReportResult = {
50
+ code: 0 | 1;
51
+ event?: SentryReportEvent;
52
+ droppedMetadataKeys?: number;
53
+ };
54
+ /**
55
+ * Read no more than the accepted event size. Returning early keeps a malformed
56
+ * pipe from making a watchdog retain an unbounded hook payload in memory.
57
+ */
58
+ export declare function readSentryReportStdin(stdin: AsyncIterable<Buffer | string>): Promise<string | null>;
59
+ /** Unknown metadata is ignored before this cap is evaluated. */
60
+ export declare function exceedsSentryReportMetadataKeyCap(keys: Iterable<string>): boolean;
61
+ /**
62
+ * Parse and validate the closed report schema without touching Sentry. The
63
+ * function intentionally returns an ordinary result instead of throwing so a
64
+ * hook can ignore the CLI exit code without creating an unhandled rejection.
65
+ */
66
+ export declare function parseSentryReportEvent(stdin: string): SentryReportResult;
67
+ /**
68
+ * Capture one validated Sentry message and wait only for the supplied bounded
69
+ * flush budget. A zero result means the event entered the local transport and
70
+ * its queue drained in time, not that ingest accepted it. Normal reports are
71
+ * silent on stdout; dry-runs print the same scrubbed event projection used by
72
+ * the live path. All failures use a generic stderr line so malformed input and
73
+ * transport errors cannot echo event data back to a hook.
74
+ */
75
+ export declare function reportSentryEvent(stdin: string, options?: SentryReportOptions, dependencies?: SentryReportDependencies): Promise<SentryReportResult>;
76
+ //# sourceMappingURL=sentry-report.d.ts.map
@@ -0,0 +1,255 @@
1
+ /**
2
+ * `hq core sentry report` — constrained diagnostic transport for HQ hooks.
3
+ *
4
+ * The stdin event schema is deliberately closed. Hook payloads can contain
5
+ * commands, prompts, source content, transcript locations, and credentials, so
6
+ * this module accepts only a small set of scalar diagnostics and never reads a
7
+ * hook payload or the process environment. The owner-approved `hook_path`
8
+ * diagnostic is the narrow exception: it names the slow hook script and may
9
+ * include its company directory, but never carries the hook payload itself.
10
+ *
11
+ * Invalid top-level input and structurally rich metadata are rejected rather
12
+ * than truncated. Unknown scalar metadata is dropped instead: the allowlist,
13
+ * not a caller version match, determines what may leave the machine.
14
+ */
15
+ import * as Sentry from "@sentry/node";
16
+ import { beforeSend } from "../../sentry-before-send.js";
17
+ export const DEFAULT_SENTRY_REPORT_TIMEOUT_MS = 750;
18
+ export const MAX_SENTRY_REPORT_TIMEOUT_MS = 5_000;
19
+ export const MAX_SENTRY_REPORT_PAYLOAD_BYTES = 2_048;
20
+ export const MAX_SENTRY_REPORT_METADATA_VALUE_BYTES = 256;
21
+ const MAX_SENTRY_REPORT_TYPE_BYTES = 64;
22
+ const MAX_SENTRY_REPORT_MESSAGE_BYTES = 1_024;
23
+ const MAX_SENTRY_REPORT_FINGERPRINT_BYTES = 128;
24
+ const SENTRY_REPORT_LEVELS = new Set([
25
+ "fatal",
26
+ "error",
27
+ "warning",
28
+ "log",
29
+ "info",
30
+ "debug",
31
+ ]);
32
+ /**
33
+ * The only hook diagnostics that can be attached as metadata. The list omits
34
+ * command text, prompts, payloads, company names, and repositories. `hook_path`
35
+ * is owner-approved telemetry for the exact hook script and may include a
36
+ * company directory; it is never a substitute for hook input or a transcript.
37
+ */
38
+ export const ALLOWED_SENTRY_REPORT_METADATA_KEYS = [
39
+ "hook_name",
40
+ "hook_path",
41
+ "hook_event",
42
+ "tool_name",
43
+ "session_id",
44
+ "declared_timeout_ms",
45
+ "elapsed_ms",
46
+ "remaining_ms",
47
+ "watchdog_timeout_ms",
48
+ "hook_timeout_ms",
49
+ "hq_version",
50
+ "platform",
51
+ "load_average",
52
+ ];
53
+ const ALLOWED_METADATA_KEYS = new Set(ALLOWED_SENTRY_REPORT_METADATA_KEYS);
54
+ const SENTRY_REPORT_METADATA_KEY_HEADROOM = 2;
55
+ // This tracks the schema rather than a separately-maintained literal. A caller
56
+ // can send every recognised key with room for two later recognised fields,
57
+ // while unknown keys are deliberately dropped.
58
+ export const MAX_SENTRY_REPORT_METADATA_KEYS = ALLOWED_SENTRY_REPORT_METADATA_KEYS.length + SENTRY_REPORT_METADATA_KEY_HEADROOM;
59
+ const defaultDependencies = {
60
+ sentry: Sentry,
61
+ stdout: process.stdout,
62
+ stderr: process.stderr,
63
+ };
64
+ /**
65
+ * Read no more than the accepted event size. Returning early keeps a malformed
66
+ * pipe from making a watchdog retain an unbounded hook payload in memory.
67
+ */
68
+ export async function readSentryReportStdin(stdin) {
69
+ const chunks = [];
70
+ let totalBytes = 0;
71
+ for await (const chunk of stdin) {
72
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
73
+ totalBytes += bytes.length;
74
+ if (totalBytes > MAX_SENTRY_REPORT_PAYLOAD_BYTES)
75
+ return null;
76
+ chunks.push(bytes);
77
+ }
78
+ return Buffer.concat(chunks).toString("utf8");
79
+ }
80
+ function isRecord(value) {
81
+ return value !== null && typeof value === "object" && !Array.isArray(value);
82
+ }
83
+ function byteLength(value) {
84
+ return Buffer.byteLength(value, "utf8");
85
+ }
86
+ function isBoundedString(value, maxBytes) {
87
+ return typeof value === "string" && value.length > 0 && byteLength(value) <= maxBytes;
88
+ }
89
+ function isScalarMetadataValue(value) {
90
+ if (typeof value === "string")
91
+ return byteLength(value) <= MAX_SENTRY_REPORT_METADATA_VALUE_BYTES;
92
+ if (typeof value === "boolean")
93
+ return true;
94
+ return typeof value === "number" && Number.isFinite(value);
95
+ }
96
+ function isAllowedMetadataValue(key, value) {
97
+ if (!isScalarMetadataValue(value))
98
+ return false;
99
+ if (key === "tool_name" || key === "session_id" || key === "hook_path") {
100
+ return typeof value === "string";
101
+ }
102
+ return true;
103
+ }
104
+ /** Unknown metadata is ignored before this cap is evaluated. */
105
+ export function exceedsSentryReportMetadataKeyCap(keys) {
106
+ let recognisedKeys = 0;
107
+ for (const key of keys) {
108
+ if (!ALLOWED_METADATA_KEYS.has(key))
109
+ continue;
110
+ recognisedKeys++;
111
+ if (recognisedKeys > MAX_SENTRY_REPORT_METADATA_KEYS)
112
+ return true;
113
+ }
114
+ return false;
115
+ }
116
+ function invalidInput() {
117
+ return { code: 1 };
118
+ }
119
+ /**
120
+ * Parse and validate the closed report schema without touching Sentry. The
121
+ * function intentionally returns an ordinary result instead of throwing so a
122
+ * hook can ignore the CLI exit code without creating an unhandled rejection.
123
+ */
124
+ export function parseSentryReportEvent(stdin) {
125
+ if (byteLength(stdin) > MAX_SENTRY_REPORT_PAYLOAD_BYTES)
126
+ return invalidInput();
127
+ let parsed;
128
+ try {
129
+ parsed = JSON.parse(stdin);
130
+ }
131
+ catch {
132
+ return invalidInput();
133
+ }
134
+ if (!isRecord(parsed))
135
+ return invalidInput();
136
+ const allowedTopLevel = new Set(["type", "message", "fingerprint", "level", "metadata"]);
137
+ if (Object.keys(parsed).some((key) => !allowedTopLevel.has(key)))
138
+ return invalidInput();
139
+ if (!isBoundedString(parsed.type, MAX_SENTRY_REPORT_TYPE_BYTES))
140
+ return invalidInput();
141
+ if (!isBoundedString(parsed.message, MAX_SENTRY_REPORT_MESSAGE_BYTES))
142
+ return invalidInput();
143
+ if (!isBoundedString(parsed.fingerprint, MAX_SENTRY_REPORT_FINGERPRINT_BYTES))
144
+ return invalidInput();
145
+ if (typeof parsed.level !== "string" || !SENTRY_REPORT_LEVELS.has(parsed.level)) {
146
+ return invalidInput();
147
+ }
148
+ const rawMetadata = "metadata" in parsed ? parsed.metadata : {};
149
+ if (!isRecord(rawMetadata))
150
+ return invalidInput();
151
+ const metadataKeys = Object.keys(rawMetadata);
152
+ if (exceedsSentryReportMetadataKeyCap(metadataKeys))
153
+ return invalidInput();
154
+ const metadata = {};
155
+ let droppedMetadataKeys = 0;
156
+ for (const key of metadataKeys) {
157
+ if (!isScalarMetadataValue(rawMetadata[key]))
158
+ return invalidInput();
159
+ if (!ALLOWED_METADATA_KEYS.has(key)) {
160
+ droppedMetadataKeys++;
161
+ continue;
162
+ }
163
+ if (!isAllowedMetadataValue(key, rawMetadata[key]))
164
+ return invalidInput();
165
+ metadata[key] = rawMetadata[key];
166
+ }
167
+ return {
168
+ code: 0,
169
+ event: {
170
+ type: parsed.type,
171
+ message: parsed.message,
172
+ fingerprint: parsed.fingerprint,
173
+ level: parsed.level,
174
+ metadata,
175
+ },
176
+ droppedMetadataKeys,
177
+ };
178
+ }
179
+ function resolveTimeout(timeoutMs) {
180
+ const timeout = timeoutMs ?? DEFAULT_SENTRY_REPORT_TIMEOUT_MS;
181
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_SENTRY_REPORT_TIMEOUT_MS)
182
+ return null;
183
+ return timeout;
184
+ }
185
+ function sentryEnvelope(event) {
186
+ return {
187
+ level: event.level,
188
+ fingerprint: [event.fingerprint],
189
+ tags: { sentry_event_type: event.type },
190
+ extra: event.metadata,
191
+ };
192
+ }
193
+ /** Build the same scrubbed event projection that the live SDK path uses. */
194
+ function scrubbedSentryEnvelope(event) {
195
+ return beforeSend({
196
+ message: event.message,
197
+ ...sentryEnvelope(event),
198
+ }, {});
199
+ }
200
+ /**
201
+ * Resolve true only when the local transport queue drains within the budget.
202
+ * This does not confirm that the ingest service accepted the event.
203
+ */
204
+ async function flushWithin(sentry, timeoutMs) {
205
+ return new Promise((resolve) => {
206
+ const timer = setTimeout(() => resolve(false), timeoutMs);
207
+ void Promise.resolve()
208
+ .then(() => sentry.flush(timeoutMs))
209
+ .then((flushed) => {
210
+ clearTimeout(timer);
211
+ resolve(flushed === true);
212
+ }, () => {
213
+ clearTimeout(timer);
214
+ resolve(false);
215
+ });
216
+ });
217
+ }
218
+ /**
219
+ * Capture one validated Sentry message and wait only for the supplied bounded
220
+ * flush budget. A zero result means the event entered the local transport and
221
+ * its queue drained in time, not that ingest accepted it. Normal reports are
222
+ * silent on stdout; dry-runs print the same scrubbed event projection used by
223
+ * the live path. All failures use a generic stderr line so malformed input and
224
+ * transport errors cannot echo event data back to a hook.
225
+ */
226
+ export async function reportSentryEvent(stdin, options = {}, dependencies = defaultDependencies) {
227
+ const timeoutMs = resolveTimeout(options.timeoutMs);
228
+ const result = parseSentryReportEvent(stdin);
229
+ if (timeoutMs === null || result.code !== 0 || !result.event) {
230
+ dependencies.stderr.write("Invalid Sentry report input.\n");
231
+ return invalidInput();
232
+ }
233
+ if (result.droppedMetadataKeys) {
234
+ const noun = result.droppedMetadataKeys === 1 ? "key" : "keys";
235
+ dependencies.stderr.write(`Dropped ${result.droppedMetadataKeys} unsupported Sentry report metadata ${noun}.\n`);
236
+ }
237
+ const envelope = sentryEnvelope(result.event);
238
+ if (options.dryRun) {
239
+ const scrubbed = scrubbedSentryEnvelope(result.event);
240
+ if (scrubbed)
241
+ dependencies.stdout.write(`${JSON.stringify(scrubbed)}\n`);
242
+ return result;
243
+ }
244
+ try {
245
+ dependencies.sentry.captureMessage(result.event.message, envelope);
246
+ if (await flushWithin(dependencies.sentry, timeoutMs))
247
+ return result;
248
+ }
249
+ catch {
250
+ // Report failure below without exposing event fields or transport details.
251
+ }
252
+ dependencies.stderr.write("Sentry report failed.\n");
253
+ return invalidInput();
254
+ }
255
+ //# sourceMappingURL=sentry-report.js.map
@@ -15,6 +15,8 @@ export type BackgroundDependencies = {
15
15
  isProcessAlive: (pid: number) => boolean;
16
16
  resolveQmdBin: () => string;
17
17
  reconcileCollections: (hqRoot: string) => unknown;
18
+ /** Apply the per-document size cap to qmd's config before the update reads anything. */
19
+ applyIndexSizeLimit: (hqRoot: string) => unknown;
18
20
  runQmd: (args: string[], options?: RunQmdOptions) => QmdProcessResult;
19
21
  spawnWorker: (options: {
20
22
  logPath: string;
@@ -3,6 +3,7 @@ import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { Sentry } from '../../sentry.js';
5
5
  import { reconcileCollections as defaultReconcileCollections, resolveQmdBin as defaultResolveQmdBin, runQmd as defaultRunQmd, } from './index.js';
6
+ import { applyIndexSizeLimit as defaultApplyIndexSizeLimit } from './max-doc-bytes.js';
6
7
  const LOCK_NAME = 'qmd-reindex-bg.lock';
7
8
  const COMPLETE_NAME = 'qmd-reindex-bg.completed';
8
9
  function errnoInfo(error) {
@@ -119,6 +120,7 @@ export function defaultBackgroundDependencies(hqRoot) {
119
120
  isProcessAlive: alive,
120
121
  resolveQmdBin: defaultResolveQmdBin,
121
122
  reconcileCollections: defaultReconcileCollections,
123
+ applyIndexSizeLimit: defaultApplyIndexSizeLimit,
122
124
  runQmd: defaultRunQmd,
123
125
  spawnWorker: defaultSpawnWorker,
124
126
  };
@@ -420,6 +422,21 @@ function capWorkerLog(logPath, env) {
420
422
  function stepOutput(result) {
421
423
  return `${result.stdout ?? ''}${result.stderr ?? ''}`;
422
424
  }
425
+ /**
426
+ * One worker-log line summarising the size cap, so an operator reading the log
427
+ * can see WHY a file stopped being indexed. Shaped defensively because the
428
+ * dependency is typed `unknown` at the seam.
429
+ */
430
+ function sizeLimitOutput(result) {
431
+ const r = result;
432
+ if (typeof r?.maxBytes !== 'number')
433
+ return '';
434
+ if (r.maxBytes === 0)
435
+ return '[qmd-reindex-bg] size cap disabled\n';
436
+ const collections = r.collections ?? [];
437
+ const files = collections.reduce((total, collection) => total + collection.ignored.length, 0);
438
+ return `[qmd-reindex-bg] size cap ${r.maxBytes}B — ${files} file(s) skipped across ${collections.length} collection(s)\n`;
439
+ }
423
440
  function errorOutput(error) {
424
441
  const e = error;
425
442
  return `${e.stdout ?? ''}${e.stderr ?? ''}` || (e.message ?? '');
@@ -500,6 +517,17 @@ export async function runBackgroundWorker(dependencies) {
500
517
  // The shell worker has no collection-registration step. Keep this #306
501
518
  // integration best-effort so it cannot suppress a later index update.
502
519
  }
520
+ // The size cap rewrites qmd's ignore lists, so it MUST land before the
521
+ // update below — an oversized file is skipped at glob time or not at all.
522
+ // Best-effort for the same reason as reconciliation: a capping failure must
523
+ // not suppress an otherwise healthy index update.
524
+ try {
525
+ const capped = dependencies.applyIndexSizeLimit(dependencies.hqRoot);
526
+ appendWorkerLog(logPath, sizeLimitOutput(capped));
527
+ }
528
+ catch (error) {
529
+ appendWorkerLog(logPath, errorOutput(error));
530
+ }
503
531
  if (await signalWindow())
504
532
  return { state: 'terminated' };
505
533
  try {