@indigoai-us/hq-cli 5.345.230 → 5.345.232

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 (106) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +3 -2
  3. package/assets/lanes-reconcile/hq-lanes-reconcile.service +1 -1
  4. package/assets/scaffold/core/scripts/pipeline-conductor.sh +14 -14
  5. package/assets/scaffold/core/scripts/pipeline-driver.sh +7 -7
  6. package/assets/scaffold/core/scripts/session-project.sh +19 -4
  7. package/dist/command-catalog.generated.d.ts +213 -177
  8. package/dist/command-catalog.generated.js +263 -212
  9. package/dist/command-registration-plan.d.ts +6 -24
  10. package/dist/command-registration-plan.js +4 -8
  11. package/dist/commands/auth.js +3 -2
  12. package/dist/commands/core-pipeline-conductor-command.js +1 -1
  13. package/dist/commands/core-pipeline-conductor-native.js +5 -5
  14. package/dist/commands/core-pipeline-driver-native.js +5 -5
  15. package/dist/commands/crm.js +2 -1
  16. package/dist/commands/daemon.js +7 -36
  17. package/dist/commands/deploy-access.js +6 -13
  18. package/dist/commands/deploy-comments.js +5 -13
  19. package/dist/commands/deploy-domains.js +6 -13
  20. package/dist/commands/deploy-list.js +25 -11
  21. package/dist/commands/deploy-mutations.d.ts +3 -0
  22. package/dist/commands/deploy-mutations.js +147 -0
  23. package/dist/commands/link.js +29 -0
  24. package/dist/commands/mesh.js +3 -1
  25. package/dist/commands/packs.js +3 -2
  26. package/dist/commands/pkg-remove.js +2 -1
  27. package/dist/commands/report.js +12 -9
  28. package/dist/data/command-states.json +10 -7
  29. package/dist/lib/bot/fleet-bots-update-pass.d.ts +8 -0
  30. package/dist/lib/bot/fleet-bots-update-pass.js +40 -0
  31. package/dist/lib/bot/fleet-bots-update-task.d.ts +12 -0
  32. package/dist/lib/bot/fleet-bots-update-task.js +52 -0
  33. package/dist/lib/bot/fleet-bots-update-worker-v1.d.ts +2 -0
  34. package/dist/lib/bot/fleet-bots-update-worker-v1.js +5 -0
  35. package/dist/lib/daemon/catalog.d.ts +8 -5
  36. package/dist/lib/daemon/catalog.js +15 -8
  37. package/dist/lib/daemon/hook-requests-codex-settings.d.ts +26 -0
  38. package/dist/lib/daemon/hook-requests-codex-settings.js +185 -0
  39. package/dist/lib/daemon/hook-requests-conduct-link.d.ts +1 -0
  40. package/dist/lib/daemon/hook-requests-conduct-link.js +21 -4
  41. package/dist/lib/daemon/hook-requests.d.ts +3 -2
  42. package/dist/lib/daemon/hook-requests.js +16 -3
  43. package/dist/lib/daemon/lock.js +33 -37
  44. package/dist/lib/daemon/ops/skill-command.d.ts +99 -0
  45. package/dist/lib/daemon/ops/skill-command.js +260 -0
  46. package/dist/lib/daemon/protocol.d.ts +1 -1
  47. package/dist/lib/daemon/protocol.js +1 -0
  48. package/dist/lib/daemon/run.js +10 -18
  49. package/dist/lib/daemon/server.js +7 -0
  50. package/dist/lib/daemon/supervisor.d.ts +5 -0
  51. package/dist/lib/daemon/supervisor.js +17 -2
  52. package/dist/lib/db/app-ref.js +10 -15
  53. package/dist/lib/deploy-apps.d.ts +29 -0
  54. package/dist/lib/deploy-apps.js +37 -0
  55. package/dist/lib/doctor/checks/search-index.d.ts +16 -0
  56. package/dist/lib/doctor/checks/search-index.js +61 -0
  57. package/dist/lib/doctor/checks/stranded-lanes.js +1 -1
  58. package/dist/lib/doctor/registry.js +4 -0
  59. package/dist/lib/flag-registry.d.ts +7 -0
  60. package/dist/lib/flag-registry.js +20 -0
  61. package/dist/lib/hook-engine/coverage.d.ts +18 -0
  62. package/dist/lib/hook-engine/coverage.js +42 -1
  63. package/dist/lib/lanes/accounts.js +3 -3
  64. package/dist/lib/lanes/admission-host.js +1 -1
  65. package/dist/lib/lanes/admission.js +4 -4
  66. package/dist/lib/lanes/autopilot.js +2 -2
  67. package/dist/lib/lanes/blocker-freshness.js +1 -1
  68. package/dist/lib/lanes/compaction.js +5 -5
  69. package/dist/lib/lanes/delivery.js +1 -1
  70. package/dist/lib/lanes/depth-cap.js +1 -1
  71. package/dist/lib/lanes/disk-guard.js +1 -1
  72. package/dist/lib/lanes/dropbox.js +1 -1
  73. package/dist/lib/lanes/hooks-install.js +1 -1
  74. package/dist/lib/lanes/imported-question.js +1 -1
  75. package/dist/lib/lanes/keep-alive.d.ts +2 -2
  76. package/dist/lib/lanes/keep-alive.js +3 -3
  77. package/dist/lib/lanes/kr-freshness.js +1 -1
  78. package/dist/lib/lanes/links.js +92 -11
  79. package/dist/lib/lanes/loop.js +2 -2
  80. package/dist/lib/lanes/machine-identity.js +3 -3
  81. package/dist/lib/lanes/models.js +6 -6
  82. package/dist/lib/lanes/quota.js +1 -1
  83. package/dist/lib/lanes/reconcile-install.js +3 -3
  84. package/dist/lib/lanes/reconcile.js +16 -16
  85. package/dist/lib/lanes/remote-control-lane.js +6 -6
  86. package/dist/lib/lanes/reviews.js +2 -2
  87. package/dist/lib/lanes/spawn.js +24 -24
  88. package/dist/lib/lanes/status-fields.js +4 -4
  89. package/dist/lib/lanes/wait.js +4 -4
  90. package/dist/lib/lanes/watch.js +2 -2
  91. package/dist/lib/lanes/watcher-main.js +1 -1
  92. package/dist/lib/lanes/watcher.js +38 -38
  93. package/dist/lib/lanes/worker-process.js +5 -5
  94. package/dist/lib/mesh/live/daemon/pid-lock.d.ts +2 -4
  95. package/dist/lib/mesh/live/daemon/pid-lock.js +38 -55
  96. package/dist/utils/exclusive-lock.d.ts +60 -0
  97. package/dist/utils/exclusive-lock.js +65 -0
  98. package/dist/utils/exit-after-worker.d.ts +7 -0
  99. package/dist/utils/exit-after-worker.js +15 -0
  100. package/package.json +8 -7
  101. package/dist/commands/staff/listings.d.ts +0 -41
  102. package/dist/commands/staff/listings.js +0 -160
  103. package/dist/commands/staff/reset-test-account.d.ts +0 -121
  104. package/dist/commands/staff/reset-test-account.js +0 -285
  105. package/dist/commands/staff/test-account.d.ts +0 -51
  106. package/dist/commands/staff/test-account.js +0 -196
@@ -0,0 +1,185 @@
1
+ /**
2
+ * The `codex-settings` request note (hq-core-rust, codex-adapter:PostToolUse). On a Codex PostToolUse the native hook
3
+ * starts no `.claude/settings.json` command: it leaves the session id, the event, the command list it read from the
4
+ * settings file (the records of `hqad_iter_settings`) and the adapter's payload (the note's body), and the daemon runs
5
+ * the commands a moment later, as `dispatch_settings_hooks` in the released Codex adapter (hq-core v16.0.47,
6
+ * crates/hq-hook/tests/fixtures/codex-adapter-16.0.47/.codex/hooks/hq-codex-hook-adapter.sh) did in the hook.
7
+ *
8
+ * The command records and their programs are the same as a `fleet-local-settings` note's (`fleetLocalSettingsProgram`,
9
+ * `fleetLocalSettingsRefusal`). What differs is what the adapter exported for its hooks (adapter lines 5 and 86-100):
10
+ * `BASH_ENV=/dev/null` for every child, `HQ_ROOT` and `CLAUDE_PROJECT_DIR` set to the root,
11
+ * `HQ_CHECKPOINT_RUNTIME=codex`, `HQ_WORK_MESH_HARNESS=codex`, `HQ_HARNESS=codex` and `HQAD_EVENT_SESSION_ID` set to
12
+ * the session. The Codex adapter does not set `HQ_WORK_MESH_DISABLED`, so neither does this runner.
13
+ *
14
+ * PATH: before its first gated hook that the profile allows, the adapter runs `hq_augment_path` (from
15
+ * `hook-gate.sh --lib`) in its own shell (hook-adapter-core.sh `hqad_launch_registered_hook`), so that hook and every
16
+ * command after it see the augmented PATH. The runner does the same once, before the first gate command it starts.
17
+ *
18
+ * PostToolUse is advisory on Codex (`hqad_mode_for` answers advisory for every event but PreToolUse): a failing command
19
+ * does not stop the rest, and the note is done once the list has been run.
20
+ */
21
+ import * as path from "node:path";
22
+ import { FLEET_LOCAL_HOOK_GATE, FLEET_LOCAL_SETTINGS_MAX_COMMANDS, fleetLocalSettingsListed, fleetLocalSettingsProgram, fleetLocalSettingsRefusal, spawnRequestProgram, } from "./hook-requests.js";
23
+ /** What the released Codex adapter exported for the hooks it started (v16.0.47 adapter lines 5, 86-100). */
24
+ export const CODEX_SETTINGS_RUNTIME = "codex";
25
+ const plain = (value) => typeof value === "string" && !value.includes("\0");
26
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
27
+ /** The args of a `codex-settings` note: exactly `event` (PostToolUse) and 1 to 64 typed commands. Anything else: refused. */
28
+ export function parseCodexSettings(kind, args) {
29
+ if (kind !== "codex-settings")
30
+ return undefined;
31
+ const keys = Object.keys(args).sort();
32
+ if (keys.length !== 2 || keys[0] !== "commands" || keys[1] !== "event" || args.event !== "PostToolUse")
33
+ return undefined;
34
+ const list = args.commands;
35
+ if (!Array.isArray(list) || list.length === 0 || list.length > FLEET_LOCAL_SETTINGS_MAX_COMMANDS)
36
+ return undefined;
37
+ const commands = [];
38
+ const word = (s) => plain(s) && s.length > 0 && s.length <= 4096;
39
+ const script = (s) => word(s) && path.isAbsolute(s);
40
+ const exactly = (item, names) => {
41
+ const have = Object.keys(item).sort();
42
+ return have.length === names.length && have.every((name, i) => name === names[i]);
43
+ };
44
+ for (const entry of list) {
45
+ const item = record(entry);
46
+ if (!item)
47
+ return undefined;
48
+ if (item.type === "gate" && exactly(item, ["args", "id", "script", "type"])) {
49
+ if (!plain(item.id) || !/^[A-Za-z0-9._-]{1,128}$/.test(item.id) || !script(item.script))
50
+ return undefined;
51
+ if (!Array.isArray(item.args) || !item.args.every(arg => plain(arg) && arg.length <= 4096))
52
+ return undefined;
53
+ commands.push({ type: "gate", id: item.id, script: item.script, args: [...item.args] });
54
+ }
55
+ else if (item.type === "master" && exactly(item, ["event", "type"])) {
56
+ if (!plain(item.event) || !/^[A-Za-z]{1,64}$/.test(item.event))
57
+ return undefined;
58
+ commands.push({ type: "master", event: item.event });
59
+ }
60
+ else if (item.type === "script" && exactly(item, ["script", "type"])) {
61
+ if (!script(item.script))
62
+ return undefined;
63
+ commands.push({ type: "script", script: item.script });
64
+ }
65
+ else {
66
+ return undefined;
67
+ }
68
+ }
69
+ return { kind: "codex-settings", event: "PostToolUse", commands };
70
+ }
71
+ /** The environment the released Codex adapter gave its settings hooks, over the daemon's own. */
72
+ export function codexSettingsEnv(base, root, session, id) {
73
+ return {
74
+ ...base,
75
+ BASH_ENV: "/dev/null", HQ_ROOT: root, CLAUDE_PROJECT_DIR: root,
76
+ HQ_CHECKPOINT_RUNTIME: CODEX_SETTINGS_RUNTIME, HQ_WORK_MESH_HARNESS: CODEX_SETTINGS_RUNTIME, HQ_HARNESS: CODEX_SETTINGS_RUNTIME,
77
+ HQAD_EVENT_SESSION_ID: session, HQ_HOOK_REQUEST_ID: id,
78
+ };
79
+ }
80
+ /**
81
+ * The PATH the adapter's shell had after its first gated hook: the root's hook-lib and `hook-gate.sh --lib` are
82
+ * sourced as the adapter sourced them, and `hq_augment_path` runs only where the adapter ran it (the profile lister,
83
+ * the shell launcher and the hook all present, and the profile allows the id). `path` undefined: PATH is left as it
84
+ * is. The probe runs under `spawnRequestProgram`'s stop model (own process group, SIGTERM at the limit or when the
85
+ * daemon stops, SIGKILL after the grace time); `ended` true: it was stopped, and no command after it is started.
86
+ */
87
+ function codexAugmentedPath(root, id, env, options) {
88
+ const probe = [
89
+ '. "$HQ_ROOT/core/scripts/hook-lib.sh" >/dev/null 2>&1 || true',
90
+ '. "$1" --lib >/dev/null 2>&1 || exit 3',
91
+ "command -v hq_hook_profile_allows >/dev/null 2>&1 && command -v hq_launch_shell_path >/dev/null 2>&1 || exit 3",
92
+ 'hq_hook_profile_allows "$2" >/dev/null 2>&1 || exit 3',
93
+ "command -v hq_augment_path >/dev/null 2>&1 || exit 3",
94
+ "hq_augment_path >/dev/null 2>&1",
95
+ 'printf %s "$PATH"',
96
+ ].join("\n");
97
+ const limit = 1024 * 1024;
98
+ return new Promise(resolve => {
99
+ if (options.signal?.aborted) {
100
+ resolve({ path: undefined, ended: true });
101
+ return;
102
+ }
103
+ const { child, settle } = spawnRequestProgram("bash", ["-c", probe, "codex-settings-path", path.join(root, FLEET_LOCAL_HOOK_GATE), id], {
104
+ cwd: root, env, windowsHide: true, stdio: ["ignore", "pipe", "ignore"],
105
+ }, { timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, ...(options.signal ? { signal: options.signal } : {}) });
106
+ let out = "";
107
+ let over = false;
108
+ child.stdout?.setEncoding("utf8");
109
+ child.stdout?.on("data", (text) => { if (out.length + text.length > limit)
110
+ over = true;
111
+ else
112
+ out += text; });
113
+ child.stdout?.on("error", () => undefined);
114
+ let settled = false;
115
+ const finish = (code) => {
116
+ if (settled)
117
+ return;
118
+ settled = true;
119
+ const ended = settle();
120
+ const good = !ended && !over && code === 0 && out !== "" && !out.includes("\0");
121
+ resolve({ path: good ? out : undefined, ended });
122
+ };
123
+ child.once("error", () => finish(null));
124
+ child.once("close", code => finish(code));
125
+ });
126
+ }
127
+ function runOne(program, args, options) {
128
+ return new Promise(resolve => {
129
+ if (options.signal?.aborted) {
130
+ resolve({ ended: true });
131
+ return;
132
+ }
133
+ const { child, settle } = spawnRequestProgram(program, args, {
134
+ cwd: options.cwd, env: options.env, windowsHide: true, stdio: ["pipe", "ignore", "ignore"],
135
+ }, { timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, ...(options.signal ? { signal: options.signal } : {}) });
136
+ child.stdin?.on("error", () => undefined);
137
+ child.stdin?.end(options.input);
138
+ let settled = false;
139
+ const finish = () => { if (settled)
140
+ return; settled = true; resolve({ ended: settle() }); };
141
+ child.once("error", finish);
142
+ child.once("close", finish);
143
+ });
144
+ }
145
+ /**
146
+ * Run the commands of a `codex-settings` note in order. Before any starts, the root's settings file is read again: a
147
+ * command runs only if it is still listed there for the note's event and every file it starts resolves to a real path
148
+ * under the HQ root. A refused command is not started, is logged, and does not stop the rest. A command still running
149
+ * at the limit is ended with its process group and the commands after it are skipped.
150
+ */
151
+ export async function runCodexSettings(request, operation, options) {
152
+ if (!request.body)
153
+ return { code: 1 };
154
+ const listed = fleetLocalSettingsListed(request.root, operation.event);
155
+ let augmented = false;
156
+ const env = codexSettingsEnv({ ...(options.env ?? process.env) }, request.root, request.session, request.id);
157
+ for (const command of operation.commands) {
158
+ const refusal = fleetLocalSettingsRefusal(request.root, command, listed);
159
+ if (refusal !== undefined) {
160
+ options.log?.(`hook request ${request.stem}: refused the ${command.type} settings command: ${refusal}`);
161
+ continue;
162
+ }
163
+ const started = fleetLocalSettingsProgram(request.root, command);
164
+ if (!started)
165
+ continue;
166
+ if (command.type === "gate" && !augmented) {
167
+ augmented = true;
168
+ const searched = await codexAugmentedPath(request.root, command.id, env, {
169
+ timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, ...(options.signal ? { signal: options.signal } : {}),
170
+ });
171
+ if (searched.ended)
172
+ break;
173
+ if (searched.path !== undefined)
174
+ env.PATH = searched.path;
175
+ }
176
+ const ran = await runOne(started.program, started.args, {
177
+ cwd: request.root, env, input: request.body, timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs,
178
+ ...(options.signal ? { signal: options.signal } : {}),
179
+ });
180
+ if (ran.ended)
181
+ break;
182
+ }
183
+ return { code: 0 };
184
+ }
185
+ //# sourceMappingURL=hook-requests-codex-settings.js.map
@@ -3,6 +3,7 @@ export type ConductLinkKind = "conduct-lanes-link-deliver" | "conduct-link-inher
3
3
  export type ConductLinkOperation = {
4
4
  kind: ConductLinkKind;
5
5
  sessionId: string;
6
+ queuedAtOrBefore?: string;
6
7
  };
7
8
  /** The root's hook script each kind runs, with the event the adapter gave it. */
8
9
  export declare const CONDUCT_LINK_SCRIPTS: Readonly<Record<ConductLinkKind, string>>;
@@ -17,7 +17,12 @@
17
17
  * link once the session's companies are bound, and sweeps stale claims.
18
18
  *
19
19
  * Each reads only `session_id` from a root payload, so that is all the note
20
- * carries (`args.session_id`, also the note's session). The daemon runs the
20
+ * carries (`args.session_id`, also the note's session). A deliver note may
21
+ * also carry `args.at`, the event's time (UTC, `...Z`): the daemon passes it to
22
+ * the script as HQ_LINK_DELIVER_QUEUED_AT_OR_BEFORE, which the script's
23
+ * `hq lanes link _deliver` inherits, so the run takes only the messages queued
24
+ * at or before the event; later ones stay queued for the root's next
25
+ * PostToolUse or Stop, where the adapter would have delivered them. The daemon runs the
21
26
  * root's own hook script, `bash <root>/.claude/hooks/<script> PostToolUse`,
22
27
  * with `{"session_id": <sid>}` on stdin:
23
28
  *
@@ -51,19 +56,27 @@ export const CONDUCT_LINK_EVENT = "PostToolUse";
51
56
  * scripts' own `^[A-Za-z0-9._-]+$`, not `.` or `..`, at most 512 characters.
52
57
  */
53
58
  const CONDUCT_SESSION = /^[A-Za-z0-9._-]{1,512}$/;
59
+ /** A deliver note's event time: the form `_deliver` reads (HQ_LINK_DELIVER_QUEUED_AT_OR_BEFORE). */
60
+ const EVENT_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/;
54
61
  export function isConductLinkKind(kind) {
55
62
  return kind === "conduct-lanes-link-deliver" || kind === "conduct-link-inherit";
56
63
  }
57
64
  /** The operation in a conduct note's `args`, or undefined for anything the hook does not write. */
58
65
  export function parseConductLink(kind, args, session) {
59
- const keys = Object.keys(args);
60
- if (keys.length !== 1 || keys[0] !== "session_id")
66
+ const keys = Object.keys(args).sort();
67
+ const timed = kind === "conduct-lanes-link-deliver" && keys.length === 2 && keys[0] === "at" && keys[1] === "session_id";
68
+ if (!timed && (keys.length !== 1 || keys[0] !== "session_id"))
61
69
  return undefined;
62
70
  const sessionId = args.session_id;
63
71
  if (typeof sessionId !== "string" || !CONDUCT_SESSION.test(sessionId) || sessionId === "." || sessionId === ".."
64
72
  || sessionId !== session)
65
73
  return undefined;
66
- return { kind, sessionId };
74
+ if (!timed)
75
+ return { kind, sessionId };
76
+ const at = args.at;
77
+ if (typeof at !== "string" || !EVENT_TIME.test(at) || !Number.isFinite(Date.parse(at)))
78
+ return undefined;
79
+ return { kind, sessionId, queuedAtOrBefore: at };
67
80
  }
68
81
  /** Run the root's hook script for one conduct note (see the file comment). */
69
82
  export async function runConductLink(request, operation, base, options) {
@@ -77,6 +90,10 @@ export async function runConductLink(request, operation, base, options) {
77
90
  }
78
91
  const env = { ...base };
79
92
  delete env.HQ_HOOK_AGENT_ID;
93
+ // Only a note's own event time limits the drain, never one the daemon inherited.
94
+ delete env.HQ_LINK_DELIVER_QUEUED_AT_OR_BEFORE;
95
+ if (operation.queuedAtOrBefore !== undefined)
96
+ env.HQ_LINK_DELIVER_QUEUED_AT_OR_BEFORE = operation.queuedAtOrBefore;
80
97
  Object.assign(env, { HQ_ROOT: request.root, CLAUDE_PROJECT_DIR: request.root, HQ_HOOK_REQUEST_ID: request.id });
81
98
  const input = JSON.stringify({ session_id: operation.sessionId });
82
99
  return new Promise(resolve => {
@@ -55,6 +55,7 @@ import { type MachineCheckResult, type RunMachineChecksOptions } from "./machine
55
55
  import { type MeshToolWritesOperation } from "./hook-requests-mesh-tool-writes.js";
56
56
  import { type FleetSessionStartOperation } from "./hook-requests-fleet-session-start.js";
57
57
  import { type ConductLinkOperation } from "./hook-requests-conduct-link.js";
58
+ import { type CodexSettingsOperation } from "./hook-requests-codex-settings.js";
58
59
  /** What the daemon is asked to do. A closed list, the same as `Kind` in daemon_req.rs. */
59
60
  export type HookOperation = {
60
61
  kind: "reindex";
@@ -88,7 +89,7 @@ export type HookOperation = {
88
89
  * adapter's payload is the note's `.body` file (`host::fleet_settings`). */
89
90
  | {
90
91
  kind: "fleet-local-settings";
91
- event: "PostToolUse";
92
+ event: "PostToolUse" | "SessionEnd";
92
93
  commands: FleetLocalSettingsCommand[];
93
94
  }
94
95
  /** The Work Mesh register step of a mid-session company bind (`spawn_work_mesh_register`, owner decision 36). */
@@ -107,7 +108,7 @@ export type HookOperation = {
107
108
  disabled?: MeshSessionBindSwitch;
108
109
  }
109
110
  /** One machine check run by the daemon for a SessionStart where the hooks own the checks (the machine-check notes at the end of this file). */
110
- | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | FleetSessionStartOperation
111
+ | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | CodexSettingsOperation | FleetSessionStartOperation
111
112
  /** The Codex adapter's SubagentStop runs of the root's conduct-link hooks (hook-requests-conduct-link.ts). */
112
113
  | ConductLinkOperation;
113
114
  /**
@@ -60,6 +60,7 @@ import { MACHINE_CHECKS, machineCheckCollectOnlySupported, runMachineChecks } fr
60
60
  import { parseMeshToolWrites, runMeshToolWrites } from "./hook-requests-mesh-tool-writes.js";
61
61
  import { parseFleetSessionStart, runFleetSessionStart } from "./hook-requests-fleet-session-start.js";
62
62
  import { isConductLinkKind, parseConductLink, runConductLink } from "./hook-requests-conduct-link.js";
63
+ import { parseCodexSettings, runCodexSettings } from "./hook-requests-codex-settings.js";
63
64
  /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
64
65
  export const HOOK_REQUEST_MAX_BYTES = 4096;
65
66
  /** The longest `.body` file the Rust writer leaves (`BODY_MAX_BYTES`). */
@@ -307,6 +308,12 @@ export function parseHookRequest(text, stem) {
307
308
  return undefined;
308
309
  operation = conduct;
309
310
  }
311
+ else if (value.kind === "codex-settings") {
312
+ const codex = parseCodexSettings(value.kind, args);
313
+ if (!codex)
314
+ return undefined;
315
+ operation = codex;
316
+ }
310
317
  else if (isMachineCheckRequestKind(value.kind)) {
311
318
  const check = parseMachineCheckOperation(value.kind, args);
312
319
  if (!check)
@@ -321,10 +328,11 @@ export function parseHookRequest(text, stem) {
321
328
  }
322
329
  return { stem, id: value.id, at, root: value.hqRoot, session: value.session, operation };
323
330
  }
324
- /** The args of a `fleet-local-settings` note: exactly `event` (PostToolUse) and 1 to 64 typed commands. */
331
+ /** The args of a `fleet-local-settings` note: exactly `event` (PostToolUse or SessionEnd) and 1 to 64 typed commands. */
325
332
  function parseFleetLocalSettings(args) {
326
333
  const keys = Object.keys(args).sort();
327
- if (keys.length !== 2 || keys[0] !== "commands" || keys[1] !== "event" || args.event !== "PostToolUse")
334
+ const event = args.event;
335
+ if (keys.length !== 2 || keys[0] !== "commands" || keys[1] !== "event" || (event !== "PostToolUse" && event !== "SessionEnd"))
328
336
  return undefined;
329
337
  const list = args.commands;
330
338
  if (!Array.isArray(list) || list.length === 0 || list.length > FLEET_LOCAL_SETTINGS_MAX_COMMANDS)
@@ -362,7 +370,7 @@ function parseFleetLocalSettings(args) {
362
370
  return undefined;
363
371
  }
364
372
  }
365
- return { kind: "fleet-local-settings", event: "PostToolUse", commands };
373
+ return { kind: "fleet-local-settings", event, commands };
366
374
  }
367
375
  /** A project as the plan-sync writer leaves it: a path under the HQ root, relative, with no `..` part. */
368
376
  function hookRequestProject(project) {
@@ -374,6 +382,7 @@ export function hookRequestHasBody(operation) {
374
382
  return operation.kind === "plan-sync"
375
383
  || operation.kind === "startwork-prefetch"
376
384
  || operation.kind === "fleet-local-settings"
385
+ || operation.kind === "codex-settings"
377
386
  || operation.kind === "fleet-session-start";
378
387
  }
379
388
  /** The helper a plan-sync request runs, inside the HQ root. */
@@ -407,6 +416,8 @@ export function hookRequestArguments(request) {
407
416
  case "acl-suggest":
408
417
  case "session-close": return undefined;
409
418
  // Run by hook-requests-fleet-session-start.ts with the pinned engine.
419
+ // Not a CLI request: the Codex settings commands are started one by one (hook-requests-codex-settings.ts).
420
+ case "codex-settings": return [];
410
421
  case "fleet-session-start": return [];
411
422
  // Not a CLI request: the root's own conduct-link hook script is run (`runConductLink`).
412
423
  case "conduct-lanes-link-deliver":
@@ -1592,6 +1603,8 @@ export function executeHookRequest(request, options) {
1592
1603
  return runMeshToolWrites(operation, { ...options, root: request.root });
1593
1604
  if (operation.kind === "fleet-session-start")
1594
1605
  return runFleetSessionStart(request, operation, options);
1606
+ if (operation.kind === "codex-settings")
1607
+ return runCodexSettings(request, operation, { ...options, timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, killGraceMs: options.killGraceMs ?? HOOK_REQUEST_KILL_GRACE_MS }).catch(() => ({ code: 1 }));
1595
1608
  const cliArgs = hookRequestArguments(request);
1596
1609
  if (!cliArgs)
1597
1610
  return Promise.resolve({ code: 1 });
@@ -12,6 +12,7 @@ import { spawnSync } from "node:child_process";
12
12
  import * as fs from "node:fs";
13
13
  import * as path from "node:path";
14
14
  import { readPidLock } from "../mesh/live/daemon/pid-lock.js";
15
+ import { createLockFile, lockIsStale, releaseLockFile } from "../../utils/exclusive-lock.js";
15
16
  import { ensurePrivateDir } from "./paths.js";
16
17
  export const TAKEOVER_TTL_MS = 30_000;
17
18
  /**
@@ -109,46 +110,45 @@ export function verifyDaemonForKill(owner, run) {
109
110
  }
110
111
  return { verdict: "daemon" };
111
112
  }
113
+ /** Stale policy of the takeover claim: age only, reclaimed once older than TAKEOVER_TTL_MS (by mtime). */
114
+ const TAKEOVER_CLAIM_STALE = { kind: "age", maxAgeMs: TAKEOVER_TTL_MS };
112
115
  function claimTakeover(claim, pid, now) {
113
116
  for (let attempt = 0; attempt < 2; attempt++) {
114
- try {
115
- fs.writeFileSync(claim, `pid=${pid}\n`, { flag: "wx", mode: 0o600 });
117
+ if (createLockFile(claim, `pid=${pid}\n`))
116
118
  return true;
119
+ let age;
120
+ try {
121
+ age = now() - fs.statSync(claim).mtimeMs;
117
122
  }
118
- catch (err) {
119
- if (err.code !== "EEXIST")
120
- throw err;
121
- let age;
122
- try {
123
- age = now() - fs.statSync(claim).mtimeMs;
124
- }
125
- catch (statErr) {
126
- if (statErr.code === "ENOENT")
127
- continue;
128
- throw statErr;
129
- }
130
- if (age <= TAKEOVER_TTL_MS)
131
- return false;
132
- fs.rmSync(claim, { force: true });
123
+ catch (statErr) {
124
+ if (statErr.code === "ENOENT")
125
+ continue;
126
+ throw statErr;
133
127
  }
128
+ if (!lockIsStale(TAKEOVER_CLAIM_STALE, { ageMs: age }))
129
+ return false;
130
+ fs.rmSync(claim, { force: true });
134
131
  }
135
132
  return false;
136
133
  }
134
+ /**
135
+ * Stale policy of the daemon lock: pid only. The lock is reclaimed when its
136
+ * owner is unreadable, is this starter's own pid, or is not a live daemon;
137
+ * a live daemon keeps it at any age.
138
+ */
139
+ function daemonLockStale(pid, alive) {
140
+ return { kind: "pid", alive, self: pid };
141
+ }
137
142
  export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonProcess, now = Date.now) {
138
143
  ensurePrivateDir(path.dirname(lockPath));
139
144
  const body = `pid=${pid}\nts=${Math.floor(now() / 1000)}\n`;
140
145
  const claim = `${lockPath}.takeover`;
146
+ const stale = daemonLockStale(pid, alive);
141
147
  for (let attempt = 0; attempt < 3; attempt++) {
142
- try {
143
- fs.writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
148
+ if (createLockFile(lockPath, body))
144
149
  return { ok: true };
145
- }
146
- catch (err) {
147
- if (err.code !== "EEXIST")
148
- throw err;
149
- }
150
150
  const owner = readPidLock(lockPath);
151
- if (owner && owner.pid !== pid && alive(owner.pid))
151
+ if (owner && !lockIsStale(stale, { owner }))
152
152
  return { ok: false, owner };
153
153
  // Another starter is replacing the same stale lock; let it.
154
154
  if (!claimTakeover(claim, pid, now))
@@ -156,17 +156,11 @@ export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonP
156
156
  try {
157
157
  // Re-check under the claim: the lock may have been replaced since the read above.
158
158
  const current = readPidLock(lockPath);
159
- if (current && current.pid !== pid && alive(current.pid))
159
+ if (current && !lockIsStale(stale, { owner: current }))
160
160
  return { ok: false, owner: current };
161
161
  fs.rmSync(lockPath, { force: true });
162
- try {
163
- fs.writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
162
+ if (createLockFile(lockPath, body))
164
163
  return { ok: true };
165
- }
166
- catch (err) {
167
- if (err.code !== "EEXIST")
168
- throw err;
169
- }
170
164
  }
171
165
  finally {
172
166
  fs.rmSync(claim, { force: true });
@@ -175,14 +169,16 @@ export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonP
175
169
  throw new Error(`could not take the daemon lock at ${lockPath}`);
176
170
  }
177
171
  export function releaseDaemonLock(lockPath, pid = process.pid) {
178
- const owner = readPidLock(lockPath);
179
- if (owner?.pid === pid)
180
- fs.rmSync(lockPath, { force: true });
172
+ releaseLockFile(lockPath, {
173
+ read: (p) => readPidLock(p),
174
+ owns: (owner) => owner.pid === pid,
175
+ remove: (p) => fs.rmSync(p, { force: true }),
176
+ });
181
177
  }
182
178
  /** The live supervisor's lock record (pid and start time), or null when none is running. */
183
179
  export function liveDaemonLock(lockPath, alive = isDaemonProcess) {
184
180
  const owner = readPidLock(lockPath);
185
- return owner && alive(owner.pid) ? owner : null;
181
+ return owner && !lockIsStale({ kind: "pid", alive }, { owner }) ? owner : null;
186
182
  }
187
183
  /** The live supervisor's pid, or null when none is running. */
188
184
  export function runningDaemonPid(lockPath, alive = isDaemonProcess) {
@@ -0,0 +1,99 @@
1
+ /**
2
+ * skill.command op (hq-core-rust US-049, 40-skill-command-script, ANSWERS-1645 option (c)).
3
+ *
4
+ * hq-hook starts no program on UserPromptSubmit, so when the native
5
+ * classifier (`crates/hq-hook/src/skill_command_script.rs`) finds that the
6
+ * released hook would run a skill's `command.sh`, the hook asks hqd to do it
7
+ * over the socket and waits a bounded time for the answer.
8
+ *
9
+ * For exact parity hqd runs the released hook itself, byte-checked against
10
+ * the pinned copy (hq-core-staging v16.0.48-beta.124, b1e484afe): the hook
11
+ * and the `hook-lib.sh` it sources must hash to the pinned sha256 values,
12
+ * and so must `session-scope-capability.sh` and `perl-child-locale.sh`
13
+ * when present (the hook sources them only then), or the op refuses. The hook gets the caller's payload on stdin and the
14
+ * caller's cwd. Its stdout (one `{"systemMessage":...}` line, or nothing) is
15
+ * returned as is.
16
+ *
17
+ * hqd builds the hook's environment itself (`childEnv`; Reviewer O2,
18
+ * ANSWERS-1736): only the hook's own settings and a few plain locale and
19
+ * user variables are taken from the request, PATH is hqd's own, HQ_ROOT is
20
+ * the root hqd verified, and BASH_ENV, ENV, BASH_FUNC_*, SHELLOPTS, BASHOPTS
21
+ * and CDPATH are never set. A request that carries any of these, or a
22
+ * hostile PATH or HQ_ROOT, has them ignored, so a caller cannot make the
23
+ * pinned hook source or run anything else.
24
+ *
25
+ * The op refuses (never answers "nothing") when it cannot run the hook as
26
+ * released: a root that is not hqd's own, a hook or library that differs
27
+ * from the pinned bytes, bash missing, or the hook still running at the
28
+ * request deadline (it is killed then).
29
+ */
30
+ /** The hook, relative to the HQ root. */
31
+ export declare const SKILL_COMMAND_HOOK = "core/hooks/UserPromptSubmit/40-skill-command-script.sh";
32
+ /** The library the hook sources, relative to the HQ root. */
33
+ export declare const SKILL_COMMAND_LIB = "core/scripts/hook-lib.sh";
34
+ /** sha256 of the pinned hook (same value as `skill_command_script::HOOK_SHA256`). */
35
+ export declare const SKILL_COMMAND_HOOK_SHA256 = "e6ddbaf1fe8f996fa0ade56cc89c3634782db49ab90becff3380bcb0ef6c5c3c";
36
+ /** sha256 of the pinned `hook-lib.sh` (same value as `skill_command_script::LIB_SHA256`). */
37
+ export declare const SKILL_COMMAND_LIB_SHA256 = "9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f";
38
+ /**
39
+ * The libraries the hook sources only when they are present (ANSWERS-1817
40
+ * Q-SCS8 (b)): absent is the released behaviour; present, they must be the
41
+ * pinned bytes (same values as `skill_command_script::SCOPE_LIB_SHA256` and
42
+ * `PERL_LOCALE_LIB_SHA256`).
43
+ */
44
+ export declare const SKILL_COMMAND_OPTIONAL_LIBS: readonly {
45
+ readonly rel: string;
46
+ readonly sha256: string;
47
+ }[];
48
+ export declare class SkillCommandOpError extends Error {
49
+ readonly code: string;
50
+ constructor(code: string, message: string);
51
+ }
52
+ export interface SkillCommandRequest {
53
+ /** The caller's HQ root; must be hqd's own. */
54
+ hqRoot: string;
55
+ /** The UserPromptSubmit payload, as the hook read it on stdin. */
56
+ input: string;
57
+ /** The caller's environment; only `CHILD_ENV_FROM_REQUEST` is used. */
58
+ env: Record<string, string>;
59
+ /** The caller's working directory. */
60
+ cwd: string;
61
+ }
62
+ export interface SkillCommandResult {
63
+ /** The hook's stdout: one `{"systemMessage":...}` line, or empty. */
64
+ stdout: string;
65
+ }
66
+ export interface SkillCommandDeps {
67
+ /** hqd's configured HQ root. */
68
+ daemonRoot: string;
69
+ /** When the request must be answered by. */
70
+ deadlineMs: number;
71
+ now?: () => number;
72
+ bash?: string;
73
+ }
74
+ /**
75
+ * The only variables taken from the request: the released hook's own
76
+ * settings (its header's Env list and the master-hook exports it reads), and
77
+ * plain user and locale variables a skill's command.sh may print with.
78
+ * Nothing here names a program, a file to source or a search path.
79
+ */
80
+ export declare const CHILD_ENV_FROM_REQUEST: readonly string[];
81
+ /** Never set in the hook's environment, whatever the request holds. */
82
+ export declare const CHILD_ENV_NEVER: readonly string[];
83
+ /**
84
+ * The hook's environment, built by hqd: `CHILD_ENV_FROM_REQUEST` from the
85
+ * request, PATH from hqd's own environment, HQ_ROOT the verified root.
86
+ */
87
+ export declare function childEnv(requested: Record<string, string>, verifiedRoot: string, ownPath: string | undefined): Record<string, string>;
88
+ /**
89
+ * Kill the hook and everything it started. The released hook runs
90
+ * `command.sh` under coreutils `timeout`, which moves itself into its own
91
+ * process group, so killing the hook's group alone would leave the script
92
+ * running: every descendant is found from the process table and killed.
93
+ */
94
+ export declare function killTree(pid: number | undefined): void;
95
+ /** Parse and check the op's arguments. Never trusts a path but the root, which must be hqd's own. */
96
+ export declare function parseSkillCommandArgs(args: Record<string, unknown>): SkillCommandRequest;
97
+ /** Run the pinned hook for one prompt. */
98
+ export declare function runSkillCommand(req: SkillCommandRequest, deps: SkillCommandDeps): Promise<SkillCommandResult>;
99
+ //# sourceMappingURL=skill-command.d.ts.map