@indigoai-us/hq-cli 5.345.217 → 5.345.218

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 (50) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +1 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/dist/commands/cloud.d.ts +1 -1
  6. package/dist/commands/cloud.js +1 -1
  7. package/dist/commands/core-hq-session-native.js +3 -0
  8. package/dist/commands/install-global.js +1 -1
  9. package/dist/commands/members.js +1 -1
  10. package/dist/commands/pack-start-bot.d.ts +1 -1
  11. package/dist/commands/pack-start-bot.js +2 -2
  12. package/dist/commands/pkg-update.js +1 -1
  13. package/dist/commands/sync-narrow.js +1 -1
  14. package/dist/commands/team-sync.js +1 -1
  15. package/dist/data/command-states.json +8 -1
  16. package/dist/lib/billing/usage-cost.js +5 -2
  17. package/dist/lib/bot/pack-link.d.ts +2 -2
  18. package/dist/lib/bot/pack-link.js +2 -2
  19. package/dist/lib/daemon/hook-env.d.ts +32 -0
  20. package/dist/lib/daemon/hook-env.js +51 -0
  21. package/dist/lib/daemon/ops/policy.js +5 -3
  22. package/dist/lib/daemon/run.js +7 -1
  23. package/dist/lib/doctor/checks/host-core.d.ts +2 -0
  24. package/dist/lib/doctor/checks/host-core.js +78 -10
  25. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  26. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  27. package/dist/lib/environment/credential-shapes.js +333 -0
  28. package/dist/lib/environment/profile.js +4 -16
  29. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  30. package/dist/lib/hook-engine/coverage.js +124 -0
  31. package/dist/lib/hook-engine/reconcile.js +294 -114
  32. package/dist/lib/hook-engine/registration.d.ts +10 -3
  33. package/dist/lib/hook-engine/registration.js +52 -16
  34. package/dist/lib/install/claude-targets.js +28 -15
  35. package/dist/lib/install/codex-pack-contributions.js +1 -1
  36. package/dist/lib/install/codex-targets.js +24 -11
  37. package/dist/lib/install/hook-target.d.ts +2 -2
  38. package/dist/lib/install/hook-target.js +7 -5
  39. package/dist/lib/packages/setup-block.d.ts +2 -2
  40. package/dist/lib/packages/setup-block.js +2 -2
  41. package/dist/lib/packages/start-bot.d.ts +1 -1
  42. package/dist/lib/packages/start-bot.js +1 -1
  43. package/dist/main.js +1 -1
  44. package/dist/types.d.ts +1 -1
  45. package/dist/utils/callback-port-busy.d.ts +1 -1
  46. package/dist/utils/callback-port-busy.js +4 -4
  47. package/dist/utils/hook-trust.js +4 -1
  48. package/dist/utils/host-registration.d.ts +57 -4
  49. package/dist/utils/host-registration.js +140 -13
  50. package/package.json +7 -7
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Credential shapes in environment profile text.
3
+ *
4
+ * What counts as a credential is decided by SECRET_PATTERNS in
5
+ * src/lib/core-utils/secret-patterns.ts, the list `hq core secret-scan` uses.
6
+ * This module does not keep a second set of shapes. It applies the shared
7
+ * expressions, unchanged, to bounded windows of the text, so that:
8
+ *
9
+ * - the result for a string is the result the shared list gives for it
10
+ * (`sharedShapesIn`, checked against `matchingSecretPatterns` in
11
+ * credential-equivalence.test.ts), and
12
+ * - the time is linear in the length of the string. Applied to one long
13
+ * string as a whole, the JWT expression restarts at every candidate and
14
+ * rescans to the end, which took 29 s for a 320 KB note.
15
+ *
16
+ * Windows.
17
+ *
18
+ * - Every expression except JWT is run on consecutive chunks of CHUNK
19
+ * characters that overlap by OVERLAP. A match of any of those expressions
20
+ * has a shortest form of at most 41 characters from its start (a prefix
21
+ * and a minimum count), so every match start lies in a chunk that holds
22
+ * that shortest form. The cost of one chunk is bounded by its size.
23
+ * - A JWT match is three dot-separated runs of [A-Za-z0-9_-]. Only the
24
+ * minimum counts (20, 20, 10) matter to the expression, so a long run can
25
+ * be cut after 64 characters without changing the answer. Each window is
26
+ * one piece of a first segment (at most 320 characters), the first 64
27
+ * characters of the next segment and the first 64 of the one after.
28
+ *
29
+ * Exemptions. Profile text is sentences, hostnames and labels, and a match
30
+ * rejects the profile. Three exemptions accept ordinary text that matches the
31
+ * shared list: a Slack prefix named in a sentence, a host name that starts
32
+ * with the key prefix letters, and an Authorization header followed by a
33
+ * secret's NAME. Each fails closed: it reads the whole white-space-delimited
34
+ * token and accepts only a closed form. Nothing else the shared list rejects
35
+ * is accepted here, and some ordinary text is rejected as the price of that.
36
+ *
37
+ * There is no exemption for a private key header. Any string that holds a
38
+ * BEGIN ... PRIVATE KEY line is rejected, as on main, with or without key
39
+ * material after it, because the body can sit in another string of the same
40
+ * profile. To mention a key in a profile, name its type in words.
41
+ *
42
+ * One rule is added to the shared list: a URL with an inline password.
43
+ */
44
+ import { SECRET_PATTERNS } from "../core-utils/secret-patterns.js";
45
+ type SharedShapeName = (typeof SECRET_PATTERNS)[number]["name"];
46
+ declare const URL_PASSWORD = "URL with an inline password";
47
+ export type CredentialShapeName = SharedShapeName | typeof URL_PASSWORD;
48
+ export declare const CREDENTIAL_SHAPE_NAMES: CredentialShapeName[];
49
+ /**
50
+ * The shared shape names that match `text`, in the shared list's order: the
51
+ * same answer as `matchingSecretPatterns(text)`, computed on bounded windows.
52
+ */
53
+ export declare function sharedShapesIn(text: string): SharedShapeName[];
54
+ /**
55
+ * The credential shapes present in `text` for the profile loader: the shared
56
+ * shapes, less the six ordinary-text exemptions, plus a URL with an inline
57
+ * password. Returns names, never the matched text.
58
+ */
59
+ export declare function credentialShapesIn(text: string): CredentialShapeName[];
60
+ export {};
61
+ //# sourceMappingURL=credential-shapes.d.ts.map
@@ -0,0 +1,333 @@
1
+ /**
2
+ * Credential shapes in environment profile text.
3
+ *
4
+ * What counts as a credential is decided by SECRET_PATTERNS in
5
+ * src/lib/core-utils/secret-patterns.ts, the list `hq core secret-scan` uses.
6
+ * This module does not keep a second set of shapes. It applies the shared
7
+ * expressions, unchanged, to bounded windows of the text, so that:
8
+ *
9
+ * - the result for a string is the result the shared list gives for it
10
+ * (`sharedShapesIn`, checked against `matchingSecretPatterns` in
11
+ * credential-equivalence.test.ts), and
12
+ * - the time is linear in the length of the string. Applied to one long
13
+ * string as a whole, the JWT expression restarts at every candidate and
14
+ * rescans to the end, which took 29 s for a 320 KB note.
15
+ *
16
+ * Windows.
17
+ *
18
+ * - Every expression except JWT is run on consecutive chunks of CHUNK
19
+ * characters that overlap by OVERLAP. A match of any of those expressions
20
+ * has a shortest form of at most 41 characters from its start (a prefix
21
+ * and a minimum count), so every match start lies in a chunk that holds
22
+ * that shortest form. The cost of one chunk is bounded by its size.
23
+ * - A JWT match is three dot-separated runs of [A-Za-z0-9_-]. Only the
24
+ * minimum counts (20, 20, 10) matter to the expression, so a long run can
25
+ * be cut after 64 characters without changing the answer. Each window is
26
+ * one piece of a first segment (at most 320 characters), the first 64
27
+ * characters of the next segment and the first 64 of the one after.
28
+ *
29
+ * Exemptions. Profile text is sentences, hostnames and labels, and a match
30
+ * rejects the profile. Three exemptions accept ordinary text that matches the
31
+ * shared list: a Slack prefix named in a sentence, a host name that starts
32
+ * with the key prefix letters, and an Authorization header followed by a
33
+ * secret's NAME. Each fails closed: it reads the whole white-space-delimited
34
+ * token and accepts only a closed form. Nothing else the shared list rejects
35
+ * is accepted here, and some ordinary text is rejected as the price of that.
36
+ *
37
+ * There is no exemption for a private key header. Any string that holds a
38
+ * BEGIN ... PRIVATE KEY line is rejected, as on main, with or without key
39
+ * material after it, because the body can sit in another string of the same
40
+ * profile. To mention a key in a profile, name its type in words.
41
+ *
42
+ * One rule is added to the shared list: a URL with an inline password.
43
+ */
44
+ import { SECRET_PATTERN_BOUNDARY, SECRET_PATTERNS } from "../core-utils/secret-patterns.js";
45
+ const URL_PASSWORD = "URL with an inline password";
46
+ const CHUNK = 4096;
47
+ const OVERLAP = 256;
48
+ const JWT_NAME = "JWT";
49
+ const JWT_PIECE = 256;
50
+ const JWT_EXTENSION = 64;
51
+ const JWT_SEGMENT_CAP = 64;
52
+ // "(^|[^a-zA-Z0-9])" without the start-of-text alternative.
53
+ const BOUNDARY_CHARACTER = SECRET_PATTERN_BOUNDARY.replace("^|", "");
54
+ const COMPILED = SECRET_PATTERNS.map(({ pattern, name }) => ({
55
+ name,
56
+ whole: new RegExp(`${SECRET_PATTERN_BOUNDARY}${pattern}`),
57
+ first: new RegExp(`${SECRET_PATTERN_BOUNDARY}(?:${pattern})`, "g"),
58
+ later: new RegExp(`${BOUNDARY_CHARACTER}(?:${pattern})`, "g"),
59
+ afterCharacter: new RegExp(`${BOUNDARY_CHARACTER}(?:${pattern})`),
60
+ }));
61
+ /**
62
+ * Call `visit` with the start and end of each match of one shared expression,
63
+ * found chunk by chunk. `start` is the first character of the token, after the
64
+ * boundary character. Stops when `visit` returns true and returns true.
65
+ */
66
+ function someChunkedMatch(shape, text, visit) {
67
+ for (let from = 0;; from += CHUNK - OVERLAP) {
68
+ const expression = from === 0 ? shape.first : shape.later;
69
+ // A later chunk begins one character early so its first position has a real boundary character.
70
+ const base = from === 0 ? 0 : from - 1;
71
+ const chunk = text.slice(base, from + CHUNK);
72
+ expression.lastIndex = 0;
73
+ for (let match = expression.exec(chunk); match !== null; match = expression.exec(chunk)) {
74
+ const boundary = match[1]?.length ?? 0;
75
+ if (visit(base + match.index + boundary, base + match.index + match[0].length))
76
+ return true;
77
+ if (match[0].length === 0)
78
+ expression.lastIndex += 1;
79
+ }
80
+ if (from + CHUNK >= text.length)
81
+ return false;
82
+ }
83
+ }
84
+ const isDigit = (c) => c >= 48 && c <= 57;
85
+ const isUpper = (c) => c >= 65 && c <= 90;
86
+ const isLower = (c) => c >= 97 && c <= 122;
87
+ const isAlnum = (c) => isDigit(c) || isUpper(c) || isLower(c);
88
+ const DOT = 46;
89
+ const DASH = 45;
90
+ const UNDERSCORE = 95;
91
+ const isJwtSegmentCharacter = (c) => isAlnum(c) || c === UNDERSCORE || c === DASH;
92
+ /** Whether the shared JWT expression matches anywhere in `text`, using bounded windows. */
93
+ function jwtPresent(shape, text) {
94
+ let at = 0;
95
+ while (at < text.length) {
96
+ // One maximal run of JWT characters and dots.
97
+ while (at < text.length && !isJwtSegmentCharacter(text.charCodeAt(at)) && text.charCodeAt(at) !== DOT)
98
+ at += 1;
99
+ const runStart = at;
100
+ const segments = [];
101
+ let segmentStart = at;
102
+ for (; at < text.length; at += 1) {
103
+ const c = text.charCodeAt(at);
104
+ if (c === DOT) {
105
+ segments.push([segmentStart, at]);
106
+ segmentStart = at + 1;
107
+ }
108
+ else if (!isJwtSegmentCharacter(c))
109
+ break;
110
+ }
111
+ if (at > runStart)
112
+ segments.push([segmentStart, at]);
113
+ // The expression has two literal dots, so a match needs two segments after its first.
114
+ for (let index = 0; index + 2 < segments.length; index += 1) {
115
+ const [firstStart, firstEnd] = segments[index];
116
+ const [secondStart, secondEnd] = segments[index + 1];
117
+ const [thirdStart, thirdEnd] = segments[index + 2];
118
+ const tail = `.${text.slice(secondStart, Math.min(secondEnd, secondStart + JWT_SEGMENT_CAP))}.${text.slice(thirdStart, Math.min(thirdEnd, thirdStart + JWT_SEGMENT_CAP))}`;
119
+ for (let piece = firstStart; piece < firstEnd; piece += JWT_PIECE) {
120
+ const before = piece > 0 ? text[piece - 1] : "";
121
+ const window = before + text.slice(piece, Math.min(firstEnd, piece + JWT_PIECE + JWT_EXTENSION)) + tail;
122
+ // With a character in front, the start of the window is not the start of the text.
123
+ if ((before === "" ? shape.whole : shape.afterCharacter).test(window))
124
+ return true;
125
+ }
126
+ }
127
+ }
128
+ return false;
129
+ }
130
+ /** Read the run of characters satisfying `inClass` from `from`, at most `cap` characters. null when the run is longer. */
131
+ function runFrom(text, from, inClass, cap) {
132
+ let end = from;
133
+ while (end < text.length && end - from <= cap && inClass(text.charCodeAt(end)))
134
+ end += 1;
135
+ return end - from > cap ? null : text.slice(from, end);
136
+ }
137
+ /*
138
+ * Exemptions fail closed. Each one is decided on the whole white-space
139
+ * delimited token the match starts and accepts only a closed form. Anything
140
+ * else the shared list rejects is rejected, at the cost of some ordinary text
141
+ * being rejected too.
142
+ */
143
+ const CLOSERS = ".,;\"')`";
144
+ /**
145
+ * The text from `start` to the next white space or the end, without one
146
+ * closing punctuation mark at its very end. null when it is longer than 255
147
+ * characters. Punctuation anywhere else stays in the token, so "joined to more
148
+ * characters" is always visible to the rule that reads it.
149
+ */
150
+ function tokenFrom(text, start) {
151
+ let end = start;
152
+ while (end < text.length && end - start <= 255 && text.charCodeAt(end) > 32)
153
+ end += 1;
154
+ if (end - start > 255)
155
+ return null;
156
+ const token = text.slice(start, end);
157
+ return token.length > 1 && CLOSERS.includes(token[token.length - 1]) ? token.slice(0, -1) : token;
158
+ }
159
+ const SLACK_PROSE_WORDS = new Set([
160
+ "style", "styled", "prefix", "prefixed", "type", "typed", "token", "tokens", "format", "kind", "like", "shaped", "based", "family",
161
+ ]);
162
+ /**
163
+ * Exemption 1. A sentence that names a Slack token prefix, such as the prefix,
164
+ * a hyphen and the word "style". Exempt only when the whole token is the
165
+ * prefix, a hyphen and one word from a closed list.
166
+ */
167
+ function slackPrefixInProse(text, start) {
168
+ const token = tokenFrom(text, start);
169
+ return token !== null && SLACK_PROSE_WORDS.has(token.slice(5));
170
+ }
171
+ const HOST_SUFFIXES = new Set([
172
+ "example", "internal", "local", "localhost", "test", "invalid", "lan", "corp", "arpa", "svc",
173
+ "com", "net", "org", "io", "dev", "ai", "co", "app", "cloud",
174
+ ]);
175
+ /**
176
+ * Exemptions 2 and 3. A host name that starts with the letters and hyphen of
177
+ * the OpenAI key prefix, in free text or in an identifier field such as
178
+ * declared.aliases. Exempt only when the whole token is a dotted host name in
179
+ * lower case whose last label is in a closed list of suffixes, with at least
180
+ * two plain words and no piece that could be key material: letters only up to
181
+ * 15 characters, digits only up to 5, letters and digits mixed up to 8.
182
+ *
183
+ * Known limit: material deliberately shaped as such a host name and ending in
184
+ * a listed suffix is accepted, for example the prefix, two random 15-letter
185
+ * pieces and ".com". No key format is written that way. The behaviour is
186
+ * pinned by a test named as a known limit in credential-exemptions.test.ts.
187
+ */
188
+ function hostnameWithKeyPrefix(text, start) {
189
+ const token = tokenFrom(text, start);
190
+ if (token === null || !/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(token))
191
+ return false;
192
+ const labels = token.split(".");
193
+ if (labels.length < 2 || !HOST_SUFFIXES.has(labels[labels.length - 1]))
194
+ return false;
195
+ let words = 0;
196
+ for (const piece of token.split(/[.-]/).slice(1)) {
197
+ const letters = /[a-z]/.test(piece);
198
+ const digits = /[0-9]/.test(piece);
199
+ if (piece.length > (letters && digits ? 8 : letters ? 15 : 5))
200
+ return false;
201
+ if (letters && !digits && piece.length >= 3)
202
+ words += 1;
203
+ }
204
+ return words >= 2;
205
+ }
206
+ /**
207
+ * Exemption 4. An Authorization header whose value is a secret's NAME and not
208
+ * a value. Exempt only when the whole token after the scheme word is upper
209
+ * snake case: capitals, digits and underscores, starting with a letter, with
210
+ * at least one underscore, at most 64 characters, and every piece between
211
+ * underscores either at most 4 characters or holding a letter from G to Z and
212
+ * at most 24 characters. Hex with underscores is therefore not a NAME. A NAME
213
+ * joined to anything (plus, slash, equals, dot, hyphen, colon, more
214
+ * characters) is not exempt, because the token is read up to white space.
215
+ *
216
+ * Known limit: material deliberately written as upper snake case with pieces
217
+ * that fit this rule is accepted, for example 32 upper-case hex in groups of
218
+ * four joined by underscores. No token format is written that way. The
219
+ * behaviour is pinned by a test named as a known limit in
220
+ * credential-exemptions.test.ts.
221
+ *
222
+ * There is no placeholder list. A header followed by a lower-case placeholder
223
+ * of hyphen-joined words was exempt in an earlier version; it cannot be told
224
+ * from token material without guessing, so it is rejected.
225
+ */
226
+ function bearerSecretName(text, start) {
227
+ const token = tokenFrom(text, start + "Bearer ".length);
228
+ if (token === null || token.length > 64 || !/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(token))
229
+ return false;
230
+ return token.split("_").every((piece) => piece.length <= 4 || (piece.length <= 24 && /[G-Z]/.test(piece)));
231
+ }
232
+ const EXEMPTIONS = {
233
+ "Slack token": slackPrefixInProse,
234
+ "OpenAI/Stripe key": hostnameWithKeyPrefix,
235
+ "Bearer token": bearerSecretName,
236
+ };
237
+ const isHostCharacter = (c) => isAlnum(c) || c === DOT || c === DASH;
238
+ /** Whether a host-like name starts at `from`: letters, digits, dots and hyphens, with a dot, or "localhost". */
239
+ function hostAt(text, from) {
240
+ const host = runFrom(text, from, isHostCharacter, 253);
241
+ if (host === null)
242
+ return true;
243
+ return host === "localhost" || (host.length >= 3 && host.includes(".") && isAlnum(host.charCodeAt(0)));
244
+ }
245
+ /**
246
+ * scheme://user:password@host, including an empty user name. A user name
247
+ * alone, a port, and a colon or at-sign in the path or query are not
248
+ * passwords.
249
+ *
250
+ * The authority normally ends at a slash, question mark, hash, comma, space,
251
+ * quote or angle bracket. A password may itself contain one of those. So when
252
+ * the text up to that point has a colon that is not followed by a port
253
+ * number, the scan looks up to 128 characters further for an at-sign followed
254
+ * by a host name, and allows at most one space on the way, so that a sentence
255
+ * with an email address later in it is not taken for a password.
256
+ *
257
+ * Not covered: a URL with no scheme (two slashes alone), and a token used as
258
+ * the user name with no colon, which is reported only when it has a shape
259
+ * from the shared list.
260
+ */
261
+ function urlWithPassword(text) {
262
+ for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 3)) {
263
+ const start = at + 3;
264
+ let end = start;
265
+ let colon = -1;
266
+ let lastAt = -1;
267
+ for (; end < text.length; end += 1) {
268
+ const c = text.charCodeAt(end);
269
+ if (c === 47 || c === 63 || c === 35 || c === 44 || c <= 32 || c === 34 || c === 39 || c === 60 || c === 62)
270
+ break;
271
+ if (c === 58 && colon === -1)
272
+ colon = end;
273
+ if (c === 64)
274
+ lastAt = end;
275
+ }
276
+ if (lastAt !== -1) {
277
+ // user:password@host inside the authority. The password is not empty.
278
+ if (colon !== -1 && colon < lastAt - 1)
279
+ return true;
280
+ continue;
281
+ }
282
+ if (colon === -1 || text.charCodeAt(start) === 91)
283
+ continue; // no colon, or an IPv6 literal
284
+ const afterColon = text.slice(colon + 1, end);
285
+ if (afterColon === "" || /^[0-9]{1,5}$/.test(afterColon))
286
+ continue; // nothing, or a port
287
+ let spaces = 0;
288
+ const limit = Math.min(text.length, colon + 1 + 128);
289
+ for (let index = end; index < limit; index += 1) {
290
+ const c = text.charCodeAt(index);
291
+ if (c === 10 || c === 13)
292
+ break;
293
+ if (c === 32 && (spaces += 1) > 1)
294
+ break;
295
+ if (c === 64) {
296
+ if (hostAt(text, index + 1))
297
+ return true;
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ return false;
303
+ }
304
+ export const CREDENTIAL_SHAPE_NAMES = [...COMPILED.map((shape) => shape.name), URL_PASSWORD];
305
+ function sharedShapePresent(shape, text, withExemptions) {
306
+ if (shape.name === JWT_NAME)
307
+ return jwtPresent(shape, text);
308
+ const exempt = withExemptions ? EXEMPTIONS[shape.name] : undefined;
309
+ if (!exempt)
310
+ return someChunkedMatch(shape, text, () => true);
311
+ return someChunkedMatch(shape, text, (start, end) => !exempt(text, start, end));
312
+ }
313
+ /**
314
+ * The shared shape names that match `text`, in the shared list's order: the
315
+ * same answer as `matchingSecretPatterns(text)`, computed on bounded windows.
316
+ */
317
+ export function sharedShapesIn(text) {
318
+ return COMPILED.filter((shape) => sharedShapePresent(shape, text, false)).map((shape) => shape.name);
319
+ }
320
+ /**
321
+ * The credential shapes present in `text` for the profile loader: the shared
322
+ * shapes, less the six ordinary-text exemptions, plus a URL with an inline
323
+ * password. Returns names, never the matched text.
324
+ */
325
+ export function credentialShapesIn(text) {
326
+ if (text.length < 6)
327
+ return [];
328
+ const found = COMPILED.filter((shape) => sharedShapePresent(shape, text, true)).map((shape) => shape.name);
329
+ if (urlWithPassword(text))
330
+ found.push(URL_PASSWORD);
331
+ return found;
332
+ }
333
+ //# sourceMappingURL=credential-shapes.js.map
@@ -17,7 +17,7 @@ import { readFileSync } from "node:fs";
17
17
  import { dirname, join } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import Ajv2020 from "ajv/dist/2020.js";
20
- import { SECRET_PATTERN_BOUNDARY, SECRET_PATTERNS } from "../core-utils/secret-patterns.js";
20
+ import { credentialShapesIn } from "./credential-shapes.js";
21
21
  const HERE = dirname(fileURLToPath(import.meta.url));
22
22
  export const ENVIRONMENT_PROFILE_SCHEMA_VERSION = "hq-environment-profile.v1";
23
23
  export const ENVIRONMENT_PROFILE_SCHEMA_ID = "urn:hq:schema:hq-environment-profile:v1";
@@ -101,18 +101,6 @@ function printable(value, limit) {
101
101
  }
102
102
  /** A property name is printed only when it looks like a field name. */
103
103
  const PLAIN_FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,40}$/;
104
- // The shapes `hq core secret-scan` uses (src/lib/core-utils/secret-patterns.ts),
105
- // compiled once. Each needs a known credential prefix, so ordinary sentences
106
- // that mention a token or a key do not match.
107
- const CREDENTIAL_SHAPES = SECRET_PATTERNS.map(({ pattern, name }) => ({
108
- name,
109
- expression: new RegExp(`${SECRET_PATTERN_BOUNDARY}${pattern}`),
110
- }));
111
- function credentialShapes(text) {
112
- if (text.length < 6)
113
- return [];
114
- return CREDENTIAL_SHAPES.flatMap(({ name, expression }) => (expression.test(text) ? [name] : []));
115
- }
116
104
  function pointerSegment(key) {
117
105
  return key.replace(/~/g, "~0").replace(/\//g, "~1");
118
106
  }
@@ -123,7 +111,7 @@ function pointerSegment(key) {
123
111
  */
124
112
  function credentialIssues(value, at, out) {
125
113
  if (typeof value === "string") {
126
- const shapes = credentialShapes(value);
114
+ const shapes = credentialShapesIn(value);
127
115
  if (shapes.length > 0)
128
116
  out.push({ path: at, message: `holds a string shaped like a credential (${shapes.join(", ")})` });
129
117
  return;
@@ -135,7 +123,7 @@ function credentialIssues(value, at, out) {
135
123
  if (value === null || typeof value !== "object")
136
124
  return;
137
125
  for (const [key, child] of Object.entries(value)) {
138
- const shapes = credentialShapes(key);
126
+ const shapes = credentialShapesIn(key);
139
127
  if (shapes.length > 0) {
140
128
  out.push({ path: at, message: `has a property name shaped like a credential (${shapes.join(", ")})` });
141
129
  continue;
@@ -164,7 +152,7 @@ function issueFrom(error) {
164
152
  const params = error.params;
165
153
  const extra = params.additionalProperty ?? params.unevaluatedProperty;
166
154
  if (typeof extra === "string") {
167
- message = PLAIN_FIELD_NAME.test(extra) && credentialShapes(extra).length === 0
155
+ message = PLAIN_FIELD_NAME.test(extra) && credentialShapesIn(extra).length === 0
168
156
  ? `must not have property "${extra}"`
169
157
  : "must not have an unexpected property";
170
158
  }
@@ -0,0 +1,13 @@
1
+ import type { CoreNextHost, CoreNextTarget } from '../../utils/host-registration.js';
2
+ /** Stands for the hook list when it cannot be read; never covered. */
3
+ export declare const UNREADABLE = "(the old dispatcher hook list could not be read)";
4
+ /** The hooks the old dispatcher runs for `event` on `host` in this HQ root; null when they cannot be read exactly. */
5
+ export declare function shellHooks(root: string, host: CoreNextHost, event: string): string[] | null;
6
+ /** The old dispatcher's hooks for `event` on `host` that the engine does not cover. */
7
+ export declare function uncoveredHooks(root: string, host: CoreNextHost, event: string, covers: Readonly<Record<string, readonly string[]>> | undefined): string[];
8
+ /**
9
+ * `target` narrowed to the events it covers in full on `host` in this HQ
10
+ * root; null when none is covered (every event stays on the old dispatcher).
11
+ */
12
+ export declare function forHost(target: CoreNextTarget | null, root: string, host: CoreNextHost): CoreNextTarget | null;
13
+ //# sourceMappingURL=coverage.d.ts.map
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Coverage gate of the registration switch (hq-core-rust US-017).
3
+ *
4
+ * A switched event's new-core entry replaces the shell registration, so the
5
+ * new core must do everything the old dispatcher does for that event on that
6
+ * host. Both sides come from data, not from a list kept in the CLI:
7
+ *
8
+ * - The old dispatcher's hooks are read from this HQ root, the way
9
+ * `.claude/hooks/master-hook.sh` finds them: every `hook-registry.json`
10
+ * entry for the event (all matchers), and every `*.sh` in
11
+ * `core/hooks/<Event>`, `personal/hooks/<Event>`,
12
+ * `core/packages/<pack>/hooks/<Event>` and `companies/<co>/hooks/<Event>`
13
+ * (any company, since the active one is chosen at run time). Folder hooks
14
+ * are named by their path under the root. `master-hook:<Event>` stands for
15
+ * the dispatcher's own work for the event. On Codex and Grok the adapter's
16
+ * own work (`codex-adapter:<Event>`, `grok-adapter:<Event>`) and every
17
+ * other command `.claude/settings.json` registers for the event
18
+ * (`settings:<command>`) are added, because the adapters run those too.
19
+ * - What the new core does in full is what the installed engine reports in
20
+ * `hq-hook capabilities --json` under `covers`.
21
+ *
22
+ * An event switches only when every old hook is covered. A hook list that
23
+ * cannot be read counts as not covered, and an engine that reports no
24
+ * `covers` covers nothing, so the event stays on the old dispatcher.
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
28
+ import { isCoreNextEntry } from './registration.js';
29
+ /** Stands for the hook list when it cannot be read; never covered. */
30
+ export const UNREADABLE = '(the old dispatcher hook list could not be read)';
31
+ /** Folder hook that master-hook.sh never dispatches (retired; `hq rescue` can leave it on disk). */
32
+ const RETIRED = new Set(['Stop/70-work-mesh-done.sh']);
33
+ function listDir(dir) {
34
+ try {
35
+ return fs.readdirSync(dir).sort();
36
+ }
37
+ catch {
38
+ // Absent folder: no hooks there.
39
+ return [];
40
+ }
41
+ }
42
+ /** The hooks the old dispatcher runs for `event` on `host` in this HQ root; null when they cannot be read exactly. */
43
+ export function shellHooks(root, host, event) {
44
+ const out = [`master-hook:${event}`];
45
+ let registry;
46
+ try {
47
+ registry = JSON.parse(fs.readFileSync(path.join(root, '.claude', 'hooks', 'hook-registry.json'), 'utf8'));
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ const hooks = registry?.hooks;
53
+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks))
54
+ return null;
55
+ const groups = hooks[event] ?? [];
56
+ if (!Array.isArray(groups))
57
+ return null;
58
+ for (const group of groups) {
59
+ const entries = group?.hooks;
60
+ if (!Array.isArray(entries))
61
+ return null;
62
+ for (const entry of entries) {
63
+ const id = entry?.id;
64
+ if (typeof id !== 'string' || id === '')
65
+ return null;
66
+ out.push(id);
67
+ }
68
+ }
69
+ const folders = [`core/hooks/${event}`, `personal/hooks/${event}`];
70
+ for (const base of ['core/packages', 'companies']) {
71
+ for (const name of listDir(path.join(root, base)))
72
+ folders.push(`${base}/${name}/hooks/${event}`);
73
+ }
74
+ for (const folder of folders) {
75
+ for (const file of listDir(path.join(root, folder))) {
76
+ if (!file.endsWith('.sh'))
77
+ continue;
78
+ if (folder === `core/hooks/${event}` && RETIRED.has(`${event}/${file}`))
79
+ continue;
80
+ out.push(`${folder}/${file}`);
81
+ }
82
+ }
83
+ if (host !== 'claude') {
84
+ out.push(`${host}-adapter:${event}`);
85
+ let settings;
86
+ try {
87
+ settings = JSON.parse(fs.readFileSync(path.join(root, '.claude', 'settings.json'), 'utf8'));
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ const registered = (settings?.hooks ?? {})[event];
93
+ for (const group of Array.isArray(registered) ? registered : []) {
94
+ for (const entry of Array.isArray(group?.hooks) ? group.hooks : []) {
95
+ const command = entry?.command;
96
+ // HQ's own entry for the event (master-hook, or the Claude Code
97
+ // new-core entry that took its place) is the dispatcher counted above.
98
+ if (typeof command !== 'string' || command.includes('master-hook.sh') || isCoreNextEntry(entry, root))
99
+ continue;
100
+ out.push(`settings:${command}`);
101
+ }
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+ /** The old dispatcher's hooks for `event` on `host` that the engine does not cover. */
107
+ export function uncoveredHooks(root, host, event, covers) {
108
+ const hooks = shellHooks(root, host, event);
109
+ if (!hooks)
110
+ return [UNREADABLE];
111
+ const covered = covers?.[event] ?? [];
112
+ return hooks.filter((hook) => !covered.includes(hook));
113
+ }
114
+ /**
115
+ * `target` narrowed to the events it covers in full on `host` in this HQ
116
+ * root; null when none is covered (every event stays on the old dispatcher).
117
+ */
118
+ export function forHost(target, root, host) {
119
+ if (!target)
120
+ return null;
121
+ const events = target.events.filter((event) => uncoveredHooks(root, host, event, target.covers).length === 0);
122
+ return events.length ? { ...target, events } : null;
123
+ }
124
+ //# sourceMappingURL=coverage.js.map