@indigoai-us/hq-cli 5.345.215 → 5.345.217

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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * hq-environment-profile.v1: one profile per place that can do work (the
3
+ * local machine, an Outpost, a MicroVM, a bot, a fleet box), published as a
4
+ * company-scoped view.
5
+ *
6
+ * This module holds the TypeScript shape, and a loader that validates a
7
+ * document against src/schemas/hq-environment-profile.v1.schema.json and
8
+ * refuses any other schema_version. It reads; it does not write a profile and
9
+ * it does not match work to an environment.
10
+ *
11
+ * Failure text never contains a value taken from the document, apart from a
12
+ * shortened schema_version. A rejected field may be holding a credential, so
13
+ * issues carry the path, the rule that failed and at most a property name,
14
+ * and a property name is printed only when it looks like a plain field name.
15
+ */
16
+ import type { Availability } from "../capacity/available.js";
17
+ export declare const ENVIRONMENT_PROFILE_SCHEMA_VERSION = "hq-environment-profile.v1";
18
+ export declare const ENVIRONMENT_PROFILE_SCHEMA_ID = "urn:hq:schema:hq-environment-profile:v1";
19
+ export declare const ENVIRONMENT_PROFILE_SCHEMA_PATH: string;
20
+ export type EnvironmentKind = "local" | "outpost" | "microvm" | "bot" | "fleet-box";
21
+ export type EnvironmentState = "running" | "template" | "stopped";
22
+ export type EnvironmentEngine = "claude" | "codex" | "grok";
23
+ export type EnvironmentDispatchMethod = "lane-local" | "lane-ssm" | "lane-endpoint" | "dm" | "fleet-task";
24
+ export interface EnvironmentProvenance {
25
+ source: string;
26
+ /** true only when read from the live system at observed time. */
27
+ verified: boolean;
28
+ }
29
+ export interface EnvironmentTaint {
30
+ /** key:value; work tolerates it by listing the same string. */
31
+ key: string;
32
+ effect: "no-place" | "prefer-not";
33
+ reason: string;
34
+ }
35
+ export interface EnvironmentImage {
36
+ name: string;
37
+ version: string;
38
+ /** Registry or snapshot reference; null when the image is not built yet. */
39
+ ref: string | null;
40
+ contents?: string[];
41
+ }
42
+ export interface EnvironmentDeclared {
43
+ kind: EnvironmentKind;
44
+ /** kind:native-id. */
45
+ id: string;
46
+ aliases?: string[];
47
+ /** Companies this environment may do work for. */
48
+ companies: string[];
49
+ state: EnvironmentState;
50
+ lifecycle: {
51
+ type: "persistent" | "ephemeral";
52
+ /** 0 for a running environment; null when unknown. */
53
+ start_seconds_estimate: number | null;
54
+ provenance?: EnvironmentProvenance;
55
+ };
56
+ limits: {
57
+ vcpu?: number | null;
58
+ memory_mb?: number | null;
59
+ disk_gb?: number | null;
60
+ max_concurrent?: number | null;
61
+ /** Hard ceiling on one run. null means no ceiling. */
62
+ max_run_seconds: number | null;
63
+ workspace_survives: boolean;
64
+ provenance?: EnvironmentProvenance;
65
+ };
66
+ /** key:value labels, for example os:macos, tool:git, engine:claude. */
67
+ labels: string[];
68
+ image?: EnvironmentImage | null;
69
+ dispatch: {
70
+ method: EnvironmentDispatchMethod;
71
+ target?: string;
72
+ /** false when the method is proposed and not built. */
73
+ exists_today: boolean;
74
+ };
75
+ cost: {
76
+ model: "owned" | "fixed" | "metered";
77
+ marginal_usd_per_hour: number | null;
78
+ fixed_usd_per_month?: number | null;
79
+ suspend_usd_per_hour?: number | null;
80
+ basis?: string;
81
+ provenance: EnvironmentProvenance;
82
+ };
83
+ taints: EnvironmentTaint[];
84
+ }
85
+ /** Carried by every reading. */
86
+ export interface EnvironmentReadingMeta {
87
+ /** RFC 3339 date-time. */
88
+ observed_at: string;
89
+ ttl_seconds: number;
90
+ source: string;
91
+ }
92
+ export interface EnvironmentComputeReading extends EnvironmentReadingMeta {
93
+ vcpu_online: number;
94
+ load_1m?: number | null;
95
+ load_per_vcpu?: number | null;
96
+ mem_total_mb?: number;
97
+ mem_available_mb: number;
98
+ disk_total_gb?: number;
99
+ disk_free_gb: number;
100
+ }
101
+ export interface EnvironmentSlotsReading extends EnvironmentReadingMeta {
102
+ host_ref: {
103
+ kind: string;
104
+ id: string;
105
+ };
106
+ providers: Array<{
107
+ engine: EnvironmentEngine;
108
+ max_running: number;
109
+ max_queued?: number;
110
+ running: number;
111
+ queued: number;
112
+ }>;
113
+ queued_lanes?: number;
114
+ }
115
+ export interface EnvironmentAccountReading extends EnvironmentReadingMeta {
116
+ engine: EnvironmentEngine;
117
+ /** Lane-config account label. */
118
+ account_id: string;
119
+ provider_account_id?: string | null;
120
+ provider_account_join_verified?: boolean;
121
+ /** Company slug, "personal" or "unknown". */
122
+ owning_company: string;
123
+ owning_company_source?: string;
124
+ /**
125
+ * Who holds the login. An owner-held login may be used for any of the
126
+ * owner's businesses, so owning_company is a reporting and ranking input
127
+ * for it and not a filter. A login held by another person is never an
128
+ * account; it is an EnvironmentForeignAccount.
129
+ */
130
+ holder: "owner" | "unknown";
131
+ holder_source?: string;
132
+ /**
133
+ * Whether work may be paired with this login. true only when holder is
134
+ * "owner", enabled is true and signed_in is true.
135
+ */
136
+ usable: boolean;
137
+ /** Companies the owner explicitly designated; a record, not a limit. */
138
+ usable_for_companies?: string[];
139
+ enabled: boolean;
140
+ /** null when sources disagree or no reading exists. */
141
+ signed_in: boolean | null;
142
+ sign_in_evidence?: string[];
143
+ slots?: {
144
+ max_running?: number;
145
+ running?: number;
146
+ queued?: number;
147
+ quota_held?: boolean;
148
+ };
149
+ room: {
150
+ left_percent: number | null;
151
+ /** The hq-available-ai.v1 word, unchanged; null when there is no reading. */
152
+ availability: Availability | null;
153
+ back_at?: string | null;
154
+ tranche?: string;
155
+ usage_ref?: string | null;
156
+ observed_at: string | null;
157
+ ttl_seconds: number;
158
+ };
159
+ }
160
+ /**
161
+ * A login held by a person other than the owner: its existence, engine and
162
+ * holder only. It has no account id and is never paired with work.
163
+ */
164
+ export interface EnvironmentForeignAccount {
165
+ engine: EnvironmentEngine;
166
+ /** "other", or "other:<person-slug>" when the person is known. */
167
+ holder: string;
168
+ observed_at: string;
169
+ ttl_seconds: number;
170
+ source: string;
171
+ }
172
+ export interface EnvironmentAccessProbe extends EnvironmentReadingMeta {
173
+ /** kind:name, for example secret:NAME or repo:hq-pro. A name, never a value. */
174
+ name: string;
175
+ result: "pass" | "fail" | "unknown";
176
+ /** What the probe proves. */
177
+ checks: string;
178
+ }
179
+ export interface EnvironmentBaseReadiness extends EnvironmentReadingMeta {
180
+ result: "ready" | "degraded" | "not-ready" | "unknown";
181
+ document_ref?: string | null;
182
+ }
183
+ export interface EnvironmentReadings {
184
+ compute?: EnvironmentComputeReading;
185
+ slots?: EnvironmentSlotsReading;
186
+ accounts: EnvironmentAccountReading[];
187
+ foreign_accounts: EnvironmentForeignAccount[];
188
+ access: EnvironmentAccessProbe[];
189
+ base_readiness?: EnvironmentBaseReadiness;
190
+ }
191
+ export interface EnvironmentProfile {
192
+ schema_version: typeof ENVIRONMENT_PROFILE_SCHEMA_VERSION;
193
+ view: {
194
+ company: string;
195
+ generated_at: string;
196
+ generated_by: string;
197
+ };
198
+ declared: EnvironmentDeclared;
199
+ readings: EnvironmentReadings;
200
+ notes?: string[];
201
+ }
202
+ export interface EnvironmentProfileIssue {
203
+ /** JSON pointer into the document; "" is the document itself. */
204
+ path: string;
205
+ message: string;
206
+ }
207
+ export type EnvironmentProfileFailureCode = "invalid_json" | "not_an_object" | "missing_schema_version" | "unsupported_schema_version" | "invalid";
208
+ export interface EnvironmentProfileSuccess {
209
+ ok: true;
210
+ profile: EnvironmentProfile;
211
+ }
212
+ export interface EnvironmentProfileFailure {
213
+ ok: false;
214
+ code: EnvironmentProfileFailureCode;
215
+ message: string;
216
+ /** At most ENVIRONMENT_PROFILE_MAX_ISSUES entries. */
217
+ issues: EnvironmentProfileIssue[];
218
+ /** How many further issues were found and not listed. */
219
+ issues_omitted: number;
220
+ }
221
+ export type EnvironmentProfileResult = EnvironmentProfileSuccess | EnvironmentProfileFailure;
222
+ /** RFC 3339 date-time with a real calendar date and in-range clock fields. */
223
+ export declare function isRfc3339DateTime(value: string): boolean;
224
+ /** At most this many issues are listed; the rest are counted. */
225
+ export declare const ENVIRONMENT_PROFILE_MAX_ISSUES = 100;
226
+ /**
227
+ * Validate a parsed document. The schema_version is checked first, so a
228
+ * document from a later major version is refused by name and is not reported
229
+ * as a list of field errors against the v1 schema.
230
+ *
231
+ * Beyond the schema, two rules are checked here because JSON Schema cannot
232
+ * express them: view.company is one of declared.companies, and no string is
233
+ * shaped like a credential. At most ENVIRONMENT_PROFILE_MAX_ISSUES issues are
234
+ * returned; issues_omitted counts the rest.
235
+ */
236
+ export declare function validateEnvironmentProfile(value: unknown): EnvironmentProfileResult;
237
+ /** Parse JSON text and validate it. The text is never echoed in a failure. */
238
+ export declare function parseEnvironmentProfile(text: string): EnvironmentProfileResult;
239
+ //# sourceMappingURL=profile.d.ts.map
@@ -0,0 +1,251 @@
1
+ /**
2
+ * hq-environment-profile.v1: one profile per place that can do work (the
3
+ * local machine, an Outpost, a MicroVM, a bot, a fleet box), published as a
4
+ * company-scoped view.
5
+ *
6
+ * This module holds the TypeScript shape, and a loader that validates a
7
+ * document against src/schemas/hq-environment-profile.v1.schema.json and
8
+ * refuses any other schema_version. It reads; it does not write a profile and
9
+ * it does not match work to an environment.
10
+ *
11
+ * Failure text never contains a value taken from the document, apart from a
12
+ * shortened schema_version. A rejected field may be holding a credential, so
13
+ * issues carry the path, the rule that failed and at most a property name,
14
+ * and a property name is printed only when it looks like a plain field name.
15
+ */
16
+ import { readFileSync } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import Ajv2020 from "ajv/dist/2020.js";
20
+ import { SECRET_PATTERN_BOUNDARY, SECRET_PATTERNS } from "../core-utils/secret-patterns.js";
21
+ const HERE = dirname(fileURLToPath(import.meta.url));
22
+ export const ENVIRONMENT_PROFILE_SCHEMA_VERSION = "hq-environment-profile.v1";
23
+ export const ENVIRONMENT_PROFILE_SCHEMA_ID = "urn:hq:schema:hq-environment-profile:v1";
24
+ export const ENVIRONMENT_PROFILE_SCHEMA_PATH = join(HERE, "..", "..", "schemas", "hq-environment-profile.v1.schema.json");
25
+ const TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-](\d{2}):(\d{2}))$/;
26
+ /** RFC 3339 date-time with a real calendar date and in-range clock fields. */
27
+ export function isRfc3339DateTime(value) {
28
+ const match = TIMESTAMP.exec(value);
29
+ if (!match)
30
+ return false;
31
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
32
+ if (month < 1 || month > 12 || day < 1)
33
+ return false;
34
+ // Day 0 of the next month is the last day of this one.
35
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
36
+ if (day > daysInMonth)
37
+ return false;
38
+ // 60 is allowed for a leap second.
39
+ if (hour > 23 || minute > 59 || second > 60)
40
+ return false;
41
+ if (match[9] !== undefined && (Number(match[9]) > 23 || Number(match[10]) > 59))
42
+ return false;
43
+ return true;
44
+ }
45
+ /** At most this many issues are listed; the rest are counted. */
46
+ export const ENVIRONMENT_PROFILE_MAX_ISSUES = 100;
47
+ /**
48
+ * Replace every local `#/$defs/...` reference with the schema it names.
49
+ *
50
+ * Ajv compiles a `$ref` that itself contains a `$ref` as a function call, and
51
+ * with allErrors it copies the whole error list after each call. A document
52
+ * with many invalid readings then costs time in the square of their number
53
+ * (16,000 invalid probes took 1.3 s). The schema has no recursive reference,
54
+ * so it can be flattened, and the compiled validator appends errors in place.
55
+ */
56
+ function inlineLocalRefs(node, defs, depth = 0) {
57
+ if (depth > 32)
58
+ throw new Error("hq-environment-profile.v1 schema has a recursive $ref");
59
+ if (Array.isArray(node))
60
+ return node.map((entry) => inlineLocalRefs(entry, defs, depth));
61
+ if (node === null || typeof node !== "object")
62
+ return node;
63
+ const record = node;
64
+ const out = {};
65
+ for (const [key, value] of Object.entries(record)) {
66
+ if (key === "$ref" || key === "$defs")
67
+ continue;
68
+ out[key] = inlineLocalRefs(value, defs, depth);
69
+ }
70
+ const ref = record.$ref;
71
+ if (typeof ref !== "string")
72
+ return out;
73
+ const name = /^#\/\$defs\/([A-Za-z0-9_]+)$/.exec(ref)?.[1];
74
+ if (!name || !(name in defs))
75
+ throw new Error(`hq-environment-profile.v1 schema has an unresolved $ref ${ref}`);
76
+ const target = inlineLocalRefs(defs[name], defs, depth + 1);
77
+ const siblings = Object.keys(out).filter((key) => key !== "description");
78
+ if (siblings.length === 0)
79
+ return { ...target, ...out };
80
+ const existing = Array.isArray(out.allOf) ? out.allOf : [];
81
+ return { ...out, allOf: [...existing, target] };
82
+ }
83
+ let cachedValidate;
84
+ function validator() {
85
+ if (cachedValidate)
86
+ return cachedValidate;
87
+ const schema = JSON.parse(readFileSync(ENVIRONMENT_PROFILE_SCHEMA_PATH, "utf8"));
88
+ const defs = (schema.$defs ?? {});
89
+ const ajv = new Ajv2020({
90
+ allErrors: true,
91
+ strict: false,
92
+ formats: { "date-time": isRfc3339DateTime },
93
+ });
94
+ cachedValidate = ajv.compile(inlineLocalRefs(schema, defs));
95
+ return cachedValidate;
96
+ }
97
+ /** A short printable form of a string from the document. */
98
+ function printable(value, limit) {
99
+ const short = value.length > limit ? `${value.slice(0, limit)}...` : value;
100
+ return short.replace(/[^\x20-\x7e]/g, "?");
101
+ }
102
+ /** A property name is printed only when it looks like a field name. */
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
+ function pointerSegment(key) {
117
+ return key.replace(/~/g, "~0").replace(/\//g, "~1");
118
+ }
119
+ /**
120
+ * Every string in a profile is a name, a label or a sentence about where a
121
+ * value came from. None may hold a credential, so a string or property name
122
+ * shaped like one is an issue. The shape is named; the string is not printed.
123
+ */
124
+ function credentialIssues(value, at, out) {
125
+ if (typeof value === "string") {
126
+ const shapes = credentialShapes(value);
127
+ if (shapes.length > 0)
128
+ out.push({ path: at, message: `holds a string shaped like a credential (${shapes.join(", ")})` });
129
+ return;
130
+ }
131
+ if (Array.isArray(value)) {
132
+ value.forEach((entry, index) => credentialIssues(entry, `${at}/${index}`, out));
133
+ return;
134
+ }
135
+ if (value === null || typeof value !== "object")
136
+ return;
137
+ for (const [key, child] of Object.entries(value)) {
138
+ const shapes = credentialShapes(key);
139
+ if (shapes.length > 0) {
140
+ out.push({ path: at, message: `has a property name shaped like a credential (${shapes.join(", ")})` });
141
+ continue;
142
+ }
143
+ credentialIssues(child, `${at}/${pointerSegment(key)}`, out);
144
+ }
145
+ }
146
+ /** view.company must be one of declared.companies. */
147
+ function companyIssues(value) {
148
+ const view = value.view;
149
+ const declared = value.declared;
150
+ const company = view && typeof view === "object" ? view.company : undefined;
151
+ const companies = declared && typeof declared === "object" ? declared.companies : undefined;
152
+ if (typeof company !== "string" || !Array.isArray(companies))
153
+ return [];
154
+ if (companies.includes(company))
155
+ return [];
156
+ return [{ path: "/view/company", message: "must be one of declared.companies" }];
157
+ }
158
+ function issueFrom(error) {
159
+ // An "if" error only says that the paired "then" failed; the "then" errors
160
+ // carry the path and the rule.
161
+ if (error.keyword === "if")
162
+ return null;
163
+ let message = error.message ?? "is not valid";
164
+ const params = error.params;
165
+ const extra = params.additionalProperty ?? params.unevaluatedProperty;
166
+ if (typeof extra === "string") {
167
+ message = PLAIN_FIELD_NAME.test(extra) && credentialShapes(extra).length === 0
168
+ ? `must not have property "${extra}"`
169
+ : "must not have an unexpected property";
170
+ }
171
+ else if (error.keyword === "false schema") {
172
+ message = "is not allowed here";
173
+ }
174
+ return { path: error.instancePath, message };
175
+ }
176
+ function failure(code, message, issues = [], omitted = 0) {
177
+ return { ok: false, code, message, issues, issues_omitted: omitted };
178
+ }
179
+ /**
180
+ * Validate a parsed document. The schema_version is checked first, so a
181
+ * document from a later major version is refused by name and is not reported
182
+ * as a list of field errors against the v1 schema.
183
+ *
184
+ * Beyond the schema, two rules are checked here because JSON Schema cannot
185
+ * express them: view.company is one of declared.companies, and no string is
186
+ * shaped like a credential. At most ENVIRONMENT_PROFILE_MAX_ISSUES issues are
187
+ * returned; issues_omitted counts the rest.
188
+ */
189
+ export function validateEnvironmentProfile(value) {
190
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
191
+ return failure("not_an_object", "an environment profile must be a JSON object");
192
+ }
193
+ const version = value.schema_version;
194
+ if (version === undefined) {
195
+ return failure("missing_schema_version", `schema_version is missing; this CLI reads ${ENVIRONMENT_PROFILE_SCHEMA_VERSION}`);
196
+ }
197
+ if (version !== ENVIRONMENT_PROFILE_SCHEMA_VERSION) {
198
+ const named = typeof version === "string" ? `"${printable(version, 80)}"` : `of type ${typeof version}`;
199
+ return failure("unsupported_schema_version", `unsupported schema_version ${named}; this CLI reads ${ENVIRONMENT_PROFILE_SCHEMA_VERSION}`);
200
+ }
201
+ const validate = validator();
202
+ const schemaValid = validate(value);
203
+ const kept = [];
204
+ const seen = new Set();
205
+ let total = 0;
206
+ const add = (issue) => {
207
+ if (!issue)
208
+ return;
209
+ // Duplicates come from two branches reporting the same rule at the same
210
+ // path, close together, so remembering a bounded number of keys is enough.
211
+ const key = `${issue.path}\u0000${issue.message}`;
212
+ if (seen.has(key))
213
+ return;
214
+ if (seen.size < ENVIRONMENT_PROFILE_MAX_ISSUES * 100)
215
+ seen.add(key);
216
+ total += 1;
217
+ if (kept.length < ENVIRONMENT_PROFILE_MAX_ISSUES)
218
+ kept.push(issue);
219
+ };
220
+ // Rules outside the schema first, so a credential-shaped string is always
221
+ // among the listed issues however many schema errors follow.
222
+ const credentials = [];
223
+ credentialIssues(value, "", credentials);
224
+ for (const issue of credentials)
225
+ add(issue);
226
+ for (const issue of companyIssues(value))
227
+ add(issue);
228
+ if (!schemaValid)
229
+ for (const error of validate.errors ?? [])
230
+ add(issueFrom(error));
231
+ if (total === 0)
232
+ return { ok: true, profile: value };
233
+ kept.sort((a, b) => (a.path === b.path ? a.message.localeCompare(b.message) : a.path < b.path ? -1 : 1));
234
+ const omitted = total - kept.length;
235
+ const count = total === 1 ? "1 issue" : `${total} issues`;
236
+ const listed = omitted > 0 ? `; the first ${kept.length} are listed` : "";
237
+ return failure("invalid", `not a valid ${ENVIRONMENT_PROFILE_SCHEMA_VERSION} document (${count}${listed})`, kept, omitted);
238
+ }
239
+ /** Parse JSON text and validate it. The text is never echoed in a failure. */
240
+ export function parseEnvironmentProfile(text) {
241
+ let value;
242
+ try {
243
+ // A leading UTF-8 byte-order mark is not part of the JSON.
244
+ value = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
245
+ }
246
+ catch {
247
+ return failure("invalid_json", "the document is not valid JSON");
248
+ }
249
+ return validateEnvironmentProfile(value);
250
+ }
251
+ //# sourceMappingURL=profile.js.map
@@ -3,9 +3,10 @@ import { writeConfigAtomic, jsonFormat } from '../../commands/mcp-registration.j
3
3
  import { join } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { addHqHooks, removeHqHooks } from '../install/claude-targets.js';
6
- import { hookTargetFor } from '../install/hook-target.js';
6
+ import { legacyHookTarget } from '../install/hook-target.js';
7
7
  import { addCodexHooks, removeCodexHooks, codexHookEntry, codexHookTrustKeys } from '../install/codex-targets.js';
8
- import { engineArgs, isNativeEntry, registrationEngine } from './registration.js';
8
+ import { engineArgs, isCoreNextEntry, isNativeEntry, registrationEngine } from './registration.js';
9
+ import { coreNextArgs, coreNextTargetOrWarn } from '../../utils/host-registration.js';
9
10
  /** The project master-hook command shipped in HQ's .claude/settings.json. */
10
11
  function projectClaudeCommand(event) {
11
12
  return 'env BASH_ENV=/dev/null bash "$CLAUDE_PROJECT_DIR/.claude/hooks/master-hook.sh" ' + event;
@@ -24,7 +25,7 @@ function rewriteEntries(doc, convert) {
24
25
  return group;
25
26
  return { ...group, hooks: group.hooks.map((entry) => {
26
27
  const next = entry && typeof entry === 'object' ? convert(entry, event) : undefined;
27
- if (!next)
28
+ if (!next || JSON.stringify(next) === JSON.stringify(entry))
28
29
  return entry;
29
30
  changed = true;
30
31
  return next;
@@ -36,12 +37,23 @@ function rewriteEntries(doc, convert) {
36
37
  /** Reconcile existing registrations only; reindex must not install a runtime. */
37
38
  export function reconcileHookRegistrations(root, home = homedir(), env = process.env, daemonInstalled) {
38
39
  const result = { codexUserKeys: [], failures: [] };
39
- const engine = registrationEngine(home, env);
40
+ // `core.next` (hq-core-rust US-017) wins over the pinned launcher flag. Both
41
+ // off: registrations are left exactly as they are, or rolled back to the
42
+ // bash target when an earlier pass wrote a native entry.
43
+ // With `core.next` on, only the events the engine has every guard for
44
+ // switch (`coreNext.events`); the others keep the flag-off registration. A
45
+ // failure to set up the new core is one warning and the flag-off path.
46
+ const coreNext = coreNextTargetOrWarn(home, env);
47
+ const launcher = registrationEngine(home, env);
48
+ const native = coreNext ?? (launcher ? { engine: launcher } : null);
49
+ const ours = (entry) => isNativeEntry(entry, root) || isCoreNextEntry(entry, root);
40
50
  // Flag-off rollback restores the same bash target install would choose (the
41
51
  // hqd shim when the daemon serves this root). Resolved only when a
42
52
  // registration is rewritten, so the default-off path reads no daemon state.
43
53
  let target;
44
- const globalTarget = () => (target ??= engine ? { engine } : hookTargetFor(root, home, daemonInstalled, env));
54
+ const globalTarget = () => (target ??= coreNext
55
+ ? { ...coreNext, fallback: legacyHookTarget(root, home, daemonInstalled, env) }
56
+ : legacyHookTarget(root, home, daemonInstalled, env));
45
57
  const codexBash = (event) => [codexHookEntry(root, event, 'master').command, codexHookEntry(root, event, 'shim').command];
46
58
  for (const [file, runtime, global] of [
47
59
  [join(root, '.claude/settings.json'), 'claude', false],
@@ -57,7 +69,7 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
57
69
  // Default-off must not acquire a write lock or create backups for a legacy
58
70
  // registration. The merge below repeats this check under the lock when a
59
71
  // native entry was found, so a concurrent writer still wins safely.
60
- if (!engine) {
72
+ if (!native) {
61
73
  let current;
62
74
  // A file we cannot parse holds no native entry of ours; leave it untouched.
63
75
  try {
@@ -69,7 +81,7 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
69
81
  const entries = current?.hooks && typeof current.hooks === 'object'
70
82
  ? Object.values(current.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : [])
71
83
  : [];
72
- if (!entries.some(e => e && isNativeEntry(e, root)))
84
+ if (!entries.some(e => e && ours(e)))
73
85
  continue;
74
86
  }
75
87
  let expected;
@@ -84,7 +96,7 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
84
96
  if (!doc || typeof doc !== 'object' || !doc.hooks || typeof doc.hooks !== 'object')
85
97
  return doc;
86
98
  const entries = Object.values(doc.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : []);
87
- if (!engine && !entries.some(e => e && isNativeEntry(e, root)))
99
+ if (!native && !entries.some(e => e && ours(e)))
88
100
  return doc;
89
101
  if (global && (runtime === 'codex' ? removeCodexHooks(doc, root) : removeHqHooks(doc, root)) === doc)
90
102
  return doc;
@@ -95,10 +107,17 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
95
107
  // Only an entry install itself writes is converted. HQ's own project
96
108
  // file routes through hook-gate.sh and has none, so it stays as is.
97
109
  next = rewriteEntries(doc, (entry, event) => {
98
- if (!isNativeEntry(entry, root) && !codexBash(event).includes(entry.command))
110
+ if (!ours(entry) && !codexBash(event).includes(entry.command))
99
111
  return undefined;
100
112
  const { command: _command, commandWindows: _windows, ...rest } = entry;
101
113
  const { command, commandWindows } = codexHookEntry(root, event, globalTarget());
114
+ // To or from the new core (US-017), `command` keeps its place so
115
+ // switching back restores the original bytes. The launcher path
116
+ // keeps its existing key order.
117
+ if (isCoreNextEntry(entry, root) || coreNext) {
118
+ const { commandWindows: _old, ...inPlace } = entry;
119
+ return { ...inPlace, command, ...(commandWindows ? { commandWindows } : {}) };
120
+ }
102
121
  return { ...rest, command, ...(commandWindows ? { commandWindows } : {}) };
103
122
  });
104
123
  }
@@ -106,12 +125,19 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
106
125
  // Only the exact shipped master-hook command is converted; a wrapped
107
126
  // or extended invocation is someone's edit and is left alone.
108
127
  next = rewriteEntries(doc, (entry, event) => {
109
- if (!isNativeEntry(entry, root) && entry.command !== projectClaudeCommand(event))
128
+ if (!ours(entry) && entry.command !== projectClaudeCommand(event))
110
129
  return undefined;
111
130
  const { args, commandWindows: _windows, ...rest } = entry;
112
- if (engine)
113
- return { ...rest, command: engine, args: engineArgs(root, event, 'claude') };
114
- return { ...rest, command: projectClaudeCommand(Array.isArray(args) && typeof args[0] === 'string' ? args[0] : event) };
131
+ // The event an existing native entry was written for: the first
132
+ // launcher argument, or the one after `run --host claude`.
133
+ const written = Array.isArray(args) ? (args[0] === 'run' ? args[3] : args[0]) : undefined;
134
+ const original = typeof written === 'string' ? written : event;
135
+ // The new core only for an event it has every guard for.
136
+ if (coreNext?.events.includes(original))
137
+ return { ...rest, command: coreNext.coreNext, args: coreNextArgs('claude', original, root, 'project') };
138
+ if (launcher)
139
+ return { ...rest, command: launcher, args: engineArgs(root, original, 'claude') };
140
+ return { ...rest, command: projectClaudeCommand(original) };
115
141
  });
116
142
  }
117
143
  expected = JSON.stringify(next);
@@ -12,6 +12,15 @@ export declare function launcherRoot(root: string): string;
12
12
  export declare function engineArgs(root: string, event: string, runtime: 'claude' | 'codex', global?: boolean): string[];
13
13
  /** Recognize only our pinned executable with the exact root argument. */
14
14
  export declare function isNativeEntry(entry: Record<string, unknown>, root: string): boolean;
15
+ /**
16
+ * A registration that calls the new core's entry point, `hq-hook run --host
17
+ * <host> <Event> --hq-root <root>`, through the release-stable link
18
+ * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
19
+ * words and the exact root argument, in exec form (`args`) or as a command
20
+ * string (Codex, Grok).
21
+ */
22
+ export declare const CORE_NEXT_LINK: RegExp;
23
+ export declare function isCoreNextEntry(entry: Record<string, unknown>, root: string): boolean;
15
24
  export declare function quotePosix(value: string): string;
16
25
  export declare function quoteWindows(value: string): string;
17
26
  //# sourceMappingURL=registration.d.ts.map
@@ -40,6 +40,25 @@ export function isNativeEntry(entry, root) {
40
40
  }
41
41
  return entry.command.includes(quotePosix('--hq-root') + ' ' + quotePosix(spelling));
42
42
  }
43
+ /**
44
+ * A registration that calls the new core's entry point, `hq-hook run --host
45
+ * <host> <Event> --hq-root <root>`, through the release-stable link
46
+ * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
47
+ * words and the exact root argument, in exec form (`args`) or as a command
48
+ * string (Codex, Grok).
49
+ */
50
+ export const CORE_NEXT_LINK = /[\\/]\.hq[\\/]bin[\\/]hq-hook[\\/]stable[\\/]/;
51
+ export function isCoreNextEntry(entry, root) {
52
+ if (typeof entry.command !== 'string' || !CORE_NEXT_LINK.test(entry.command))
53
+ return false;
54
+ const spelling = launcherRoot(root);
55
+ if (Array.isArray(entry.args)) {
56
+ const i = entry.args.indexOf('--hq-root');
57
+ return entry.args[0] === 'run' && entry.args[1] === '--host' && i >= 0 && entry.args[i + 1] === spelling;
58
+ }
59
+ return entry.command.includes(`${quotePosix('run')} ${quotePosix('--host')}`)
60
+ && entry.command.includes(`${quotePosix('--hq-root')} ${quotePosix(spelling)}`);
61
+ }
43
62
  export function quotePosix(value) { return "'" + value.replace(/'/g, "'\\''") + "'"; }
44
63
  export function quoteWindows(value) {
45
64
  // Codex 0.162.1 uses its Windows PowerShell runtime shell for hooks.