@indigoai-us/hq-cli 5.345.250 → 5.345.252

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 (186) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +316 -2
  5. package/dist/command-catalog.generated.js +389 -2
  6. package/dist/commands/bot.js +12 -3
  7. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  8. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  9. package/dist/commands/core-hq-session-binding.js +363 -0
  10. package/dist/commands/core-hq-session-native.d.ts +23 -0
  11. package/dist/commands/core-hq-session-native.js +59 -9
  12. package/dist/commands/core-stop-autosave.js +1 -1
  13. package/dist/commands/core.js +10 -0
  14. package/dist/commands/doctor.d.ts +5 -1
  15. package/dist/commands/doctor.js +42 -5
  16. package/dist/commands/files.js +1 -1
  17. package/dist/commands/install-global.js +4 -2
  18. package/dist/commands/lanes.d.ts +2 -0
  19. package/dist/commands/lanes.js +9 -4
  20. package/dist/commands/logout.js +4 -0
  21. package/dist/commands/ontology-graph.d.ts +11 -2
  22. package/dist/commands/ontology-graph.js +130 -4
  23. package/dist/commands/report.js +35 -2
  24. package/dist/commands/sources.js +26 -8
  25. package/dist/commands/storage-gate.js +1 -1
  26. package/dist/commands/vault-retention-flag.js +2 -1
  27. package/dist/commands/whoami.js +1 -1
  28. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  29. package/dist/hq-cloud-sync-runner/package.json +1 -1
  30. package/dist/index.js +3 -1
  31. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  32. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  33. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  34. package/dist/lib/bot/fleet-cron.d.ts +37 -0
  35. package/dist/lib/bot/fleet-cron.js +59 -12
  36. package/dist/lib/bot/fleet-local.d.ts +18 -0
  37. package/dist/lib/bot/fleet-local.js +51 -5
  38. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  39. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  40. package/dist/lib/bot/signals-engine-flag.js +1 -1
  41. package/dist/lib/cli-invite-nudge.js +1 -1
  42. package/dist/lib/client-version.d.ts +2 -0
  43. package/dist/lib/client-version.js +24 -0
  44. package/dist/lib/company-flag-gate.d.ts +30 -0
  45. package/dist/lib/company-flag-gate.js +104 -0
  46. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  47. package/dist/lib/daemon/flag.js +2 -1
  48. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  49. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  50. package/dist/lib/doctor/checks/host-core.js +22 -4
  51. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  52. package/dist/lib/doctor/checks/jq.js +46 -8
  53. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  54. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  55. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  56. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  57. package/dist/lib/flag-client-gate-headers.js +62 -0
  58. package/dist/lib/flag-client-headers.d.ts +15 -0
  59. package/dist/lib/flag-client-headers.js +25 -0
  60. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  61. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  62. package/dist/lib/flag-registry-worker.js +35 -0
  63. package/dist/lib/flag-registry.d.ts +1 -20
  64. package/dist/lib/flag-registry.js +5 -81
  65. package/dist/lib/hook-engine/adapter-core-pin.d.ts +29 -0
  66. package/dist/lib/hook-engine/adapter-core-pin.js +29 -0
  67. package/dist/lib/hook-engine/coverage.d.ts +68 -8
  68. package/dist/lib/hook-engine/coverage.js +167 -25
  69. package/dist/lib/hook-engine/native-stop-compatibility.json +9 -4
  70. package/dist/lib/hook-engine/reconcile.js +3 -2
  71. package/dist/lib/hot-channels/graph-context.d.ts +26 -1
  72. package/dist/lib/hot-channels/graph-context.js +76 -9
  73. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  74. package/dist/lib/hot-channels/run.d.ts +1 -0
  75. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  76. package/dist/lib/hot-channels/signal-changes.js +683 -0
  77. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  78. package/dist/lib/hot-channels/signals-pass.js +240 -15
  79. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  80. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  81. package/dist/lib/lanes/registry-flag.js +2 -1
  82. package/dist/lib/lanes/spawn.js +11 -1
  83. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  84. package/dist/lib/mesh/live/binding-intent.js +201 -0
  85. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  86. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  87. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  88. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  89. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  90. package/dist/lib/mesh/live/daemon/install.js +2 -1
  91. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  92. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  93. package/dist/lib/mesh/live/daemon/run.js +33 -1
  94. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  95. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  96. package/dist/lib/ontology-graph/model/files.d.ts +4 -0
  97. package/dist/lib/ontology-graph/model/files.js +23 -0
  98. package/dist/lib/ontology-graph/model/index.d.ts +65 -1
  99. package/dist/lib/ontology-graph/model/index.js +154 -18
  100. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +84 -1
  101. package/dist/lib/ontology-graph/model/pass-tasks.js +173 -4
  102. package/dist/lib/ontology-graph/model/pass.d.ts +11 -0
  103. package/dist/lib/ontology-graph/model/pass.js +17 -10
  104. package/dist/lib/ontology-graph/model/pending-items.d.ts +39 -0
  105. package/dist/lib/ontology-graph/model/pending-items.js +136 -0
  106. package/dist/lib/ontology-graph/model/step.d.ts +47 -2
  107. package/dist/lib/ontology-graph/model/step.js +202 -36
  108. package/dist/lib/ontology-graph/model/tasks.d.ts +28 -4
  109. package/dist/lib/ontology-graph/model/tasks.js +48 -15
  110. package/dist/lib/ontology-graph/pages/render.d.ts +1 -1
  111. package/dist/lib/ontology-graph/pages/render.js +4 -3
  112. package/dist/lib/ontology-graph/read/brief.d.ts +13 -3
  113. package/dist/lib/ontology-graph/read/brief.js +349 -67
  114. package/dist/lib/ontology-graph/read/index.d.ts +5 -1
  115. package/dist/lib/ontology-graph/read/index.js +174 -30
  116. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  117. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  118. package/dist/lib/ontology-graph/read/reader-setting.d.ts +2 -0
  119. package/dist/lib/ontology-graph/read/reader-setting.js +4 -1
  120. package/dist/lib/ontology-graph/remodel/index.d.ts +174 -0
  121. package/dist/lib/ontology-graph/remodel/index.js +450 -0
  122. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  123. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  124. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  125. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  126. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  127. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  128. package/dist/lib/ontology-graph/replay/index.js +120 -8
  129. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  130. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  131. package/dist/lib/ontology-graph/schema/authority.d.ts +14 -5
  132. package/dist/lib/ontology-graph/schema/authority.js +13 -3
  133. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  134. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  135. package/dist/lib/ontology-graph/schema/index.d.ts +2 -1
  136. package/dist/lib/ontology-graph/schema/index.js +2 -1
  137. package/dist/lib/ontology-graph/setup/index.d.ts +88 -0
  138. package/dist/lib/ontology-graph/setup/index.js +499 -0
  139. package/dist/lib/ontology-graph/types.d.ts +21 -0
  140. package/dist/lib/ontology-graph/types.js +5 -0
  141. package/dist/lib/search-index/index.d.ts +33 -1
  142. package/dist/lib/search-index/index.js +180 -25
  143. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  144. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  145. package/dist/lib/signals/adapters-catalog.js +1 -1
  146. package/dist/lib/signals/failure-alert.js +4 -5
  147. package/dist/lib/signals/steps/adapters.js +3 -0
  148. package/dist/lib/sync-core/engine-holds.d.ts +1 -0
  149. package/dist/lib/sync-core/engine-holds.js +26 -0
  150. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  151. package/dist/lib/sync-core/engine-home.js +41 -1
  152. package/dist/lib/sync-core/flag.js +2 -1
  153. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  154. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  155. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  156. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  157. package/dist/lib/sync-core/reconcile.js +30 -5
  158. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  159. package/dist/lib/windows/install-followup.d.ts +41 -0
  160. package/dist/lib/windows/install-followup.js +87 -0
  161. package/dist/lib/windows/jq.d.ts +59 -0
  162. package/dist/lib/windows/jq.js +154 -3
  163. package/dist/lib/windows/user-path.d.ts +5 -0
  164. package/dist/lib/windows/user-path.js +1 -1
  165. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  166. package/dist/lib/work-context/auto-bind.js +49 -3
  167. package/dist/lib/work-context/organize.d.ts +4 -2
  168. package/dist/lib/work-context/organize.js +18 -8
  169. package/dist/lib/work-context/reconcile.js +16 -1
  170. package/dist/main.js +12 -1
  171. package/dist/utils/client-health-contract.d.ts +30 -0
  172. package/dist/utils/client-health-contract.js +111 -0
  173. package/dist/utils/client-health.d.ts +5 -2
  174. package/dist/utils/client-health.js +74 -5
  175. package/dist/utils/exclusive-lock.d.ts +5 -1
  176. package/dist/utils/exclusive-lock.js +9 -2
  177. package/dist/utils/host-registration.d.ts +7 -0
  178. package/dist/utils/host-registration.js +10 -1
  179. package/dist/utils/pid.d.ts +31 -0
  180. package/dist/utils/pid.js +65 -0
  181. package/dist/utils/resident-package-preload.js +12 -4
  182. package/dist/utils/sentry-fingerprint.js +3 -0
  183. package/dist/utils/sync-person.d.ts +15 -0
  184. package/dist/utils/sync-person.js +74 -0
  185. package/package.json +8 -8
  186. package/scripts/install-hook-engine.mjs +5 -3
@@ -0,0 +1,363 @@
1
+ /**
2
+ * After a successful `hq core hq-session` company change, write the session's
3
+ * binding receipt (src/lib/mesh/live/binding-receipt.ts).
4
+ *
5
+ * A receipt is written only for a change that reached `hq` from a person, an
6
+ * agent or a launcher:
7
+ *
8
+ * - not when `HQ_HQ_SESSION_NO_CLI=1` is set (a hook wrote meta.yaml itself
9
+ * and told the script not to come here);
10
+ * - not from inside a hook run. master-hook (`export HQ_HOOK_EVENT`) and the
11
+ * native hook host (crates/hq-hook/src/dispatch) set `HQ_HOOK_EVENT` for
12
+ * every child they start, so a bind a hook makes on its own, such as the
13
+ * SessionStart folder-registry bind, carries it. A command the agent runs
14
+ * is started by the host, not by a hook, and does not;
15
+ * - not, as a second guard for hook runtimes that set no such variable,
16
+ * when meta.yaml carries `foreign_cwd` (the registry bind's own line) and
17
+ * the session has not had a turn yet (no Work Mesh sequence file);
18
+ * - not for a session the command found through the global, last-writer-wins
19
+ * `workspace/sessions/.current`. Another session can rewrite that file
20
+ * between the change and this write.
21
+ * - not for a session found through the environment. A child process
22
+ * inherits its parent's session variables: a Codex child has the
23
+ * parent's CLAUDE_CODE_SESSION_ID next to its own CODEX_THREAD_ID, and a
24
+ * Cursor or Antigravity shell started from Claude Code has only the
25
+ * parent's. Only a `--session-id` the caller typed counts, and only when
26
+ * it names a session that no session variable in this environment names:
27
+ * hq-session.sh forwards an id it took from the environment as
28
+ * `--session-id` (and, from the release that has it, says so with
29
+ * `HQ_SESSION_ID_SOURCE=env`), so an id equal to one in the environment
30
+ * cannot be told from an inherited one by the CLI alone. That holds
31
+ * for scripts that do not set the marker too. Such a change gets a
32
+ * receipt only when the hook host confirmed it: the native scope guard
33
+ * leaves a single-use intent for the real session of the tool call that
34
+ * ran it (src/lib/mesh/live/binding-intent.ts), and this command consumes
35
+ * a matching one. Until the hook writes intents, there is none, and the
36
+ * change gets no counting receipt, as before. One rule keeps the
37
+ * receipt from disagreeing with the lock set: when such an unconfirmed
38
+ * change leaves a lock set different from the session's last line in
39
+ * this tree (an unbind, a remove, a switch, or an add that turns one
40
+ * company into two), a line is still written with the new lock set and
41
+ * the source `unconfirmed`, which never counts. Only an exact repeat of
42
+ * the last line's set writes nothing;
43
+ * - not when meta.yaml of that session does not show the change (another
44
+ * writer won).
45
+ *
46
+ * The receipt's source is the source of the bind action itself, never the
47
+ * label meta.yaml happens to carry: a `set company_slug` that got here is an
48
+ * explicit act (`explicit`), unless the caller names its own source in
49
+ * `HQ_SESSION_COMPANY_SOURCE` (a value that is not a plain lowercase word is
50
+ * recorded as no source, which never counts), or the run is unattended
51
+ * (`HQ_SYNC_UNATTENDED`,
52
+ * which `hq core job run` and Outpost units export): that is
53
+ * `scheduled_task`. `set company_source` writes no receipt, so the label
54
+ * cannot turn a default into a choice afterwards.
55
+ *
56
+ * Each line names the HQ tree it was made in, so a reader of another tree
57
+ * never counts it. When `--session-id` names a session other than the
58
+ * caller's own (the session id in the environment), the caller is recorded
59
+ * as `actor`.
60
+ *
61
+ * meta.yaml is read and the line appended under the session's company lock,
62
+ * so the line holds the lock set as the last writer left it.
63
+ *
64
+ * After a receipt line that leaves the session bound to exactly one company,
65
+ * when that bind counts and the company's `work-mesh-company-reporting-required`
66
+ * flag is fresh and on, the command prints "Activity in session <short id>
67
+ * (this session | not this session) is reported to <company>. Required by
68
+ * the company." Nothing records that the line was shown: whether a person
69
+ * saw it is decided by slice 6's person-only channel, not by this command.
70
+ *
71
+ * Nothing here can fail the command: any error means no receipt and no line.
72
+ */
73
+ import * as fs from "node:fs";
74
+ import * as os from "node:os";
75
+ import * as path from "node:path";
76
+ import { appendBindingReceipt, bindingSourceCounts, sessionReportingRequiredNotice, treeKeyOf, readBindingReceipt, readSessionMeta, unattendedRun, } from "../lib/mesh/live/binding-receipt.js";
77
+ import { workMeshRoot } from "../lib/mesh/live/paths.js";
78
+ import { consumeBindIntent, pruneBindIntents } from "../lib/mesh/live/binding-intent.js";
79
+ import { SESSION_ID_ENV_KEYS, sessionIdFromEnv, validSessionId } from "../lib/core-utils/session-id.js";
80
+ // Not reporting-privacy.js: its import closure reaches network code, and this
81
+ // module is on the hq-session fast path (src/node-network-compat-closure.test.ts).
82
+ import { readFlagSnapshotFile } from "../lib/flag-snapshot-file.js";
83
+ import { WORK_MESH_COMPANY_REPORTING_REQUIRED } from "../lib/mesh/live/company-reporting-gaps.js";
84
+ import { load as loadYaml, JSON_SCHEMA } from "js-yaml";
85
+ /** The company change a `hq-session` command line asks for, or null. */
86
+ export function bindingActionOf(argv) {
87
+ let index = 0;
88
+ const globalArgs = [];
89
+ while (index < argv.length) {
90
+ const value = argv[index];
91
+ if (value === "--session-id") {
92
+ globalArgs.push(value, argv[index + 1] ?? "");
93
+ index += 2;
94
+ }
95
+ else if (value.startsWith("--session-id=")) {
96
+ globalArgs.push(value);
97
+ index += 1;
98
+ }
99
+ else {
100
+ break;
101
+ }
102
+ }
103
+ const [sub, key, value = ""] = argv.slice(index);
104
+ if (sub === "set" && key === "company_slug") {
105
+ return { globalArgs, action: !value || value.toLowerCase() === "personal" ? "unbind" : "bind", slug: value };
106
+ }
107
+ if (sub === "add" && key === "company" && value)
108
+ return { globalArgs, action: "add", slug: value };
109
+ if (sub === "remove" && key === "company" && value)
110
+ return { globalArgs, action: "remove", slug: value };
111
+ return null;
112
+ }
113
+ /**
114
+ * The value of the last `--session-id` in the leading global arguments, as
115
+ * hq-session.sh and the native command read it (a later flag wins). Undefined
116
+ * when there is none.
117
+ */
118
+ export function lastSessionFlag(globalArgs) {
119
+ let value;
120
+ for (let index = 0; index < globalArgs.length; index += 1) {
121
+ const arg = globalArgs[index];
122
+ if (arg === "--session-id") {
123
+ value = globalArgs[index + 1] ?? "";
124
+ index += 1;
125
+ }
126
+ else if (arg.startsWith("--session-id=")) {
127
+ value = arg.slice("--session-id=".length);
128
+ }
129
+ }
130
+ return value;
131
+ }
132
+ /**
133
+ * Variables that name a session or a host conversation without being a
134
+ * session id hq-session resolves. An id equal to one of them is refused for a
135
+ * receipt too: CURSOR_TRACE_ID is shared by every chat in a Cursor window.
136
+ */
137
+ const ENVIRONMENT_ID_EXTRA_KEYS = ["CURSOR_TRACE_ID"];
138
+ /**
139
+ * Every distinct session id the environment's session variables name,
140
+ * lower-cased: session folders and receipt files live on case-insensitive
141
+ * file systems, so ids that differ only in case are the same session.
142
+ */
143
+ export function environmentSessionIds(env) {
144
+ const ids = [];
145
+ for (const key of [...SESSION_ID_ENV_KEYS, ...ENVIRONMENT_ID_EXTRA_KEYS]) {
146
+ const value = (env[key] ?? "").replace(/[\t\n\v\f\r ]/g, "").toLowerCase();
147
+ if (validSessionId(value) && !ids.includes(value))
148
+ ids.push(value);
149
+ }
150
+ return ids;
151
+ }
152
+ /**
153
+ * The id came from the environment: hq-session.sh said so, or it equals an
154
+ * id a session variable here names (an older script that sets no marker
155
+ * forwards such an id as --session-id, and an inherited id looks the same).
156
+ */
157
+ export function sessionIdFromEnvironment(sessionId, env) {
158
+ if ((env.HQ_SESSION_ID_SOURCE ?? "").trim() === "env")
159
+ return true;
160
+ return environmentSessionIds(env).includes(sessionId.toLowerCase());
161
+ }
162
+ /** Do two lock sets hold the same companies (compared without case or order)? */
163
+ function sameCompanySet(a, b) {
164
+ const key = (set) => [...new Set(set.map((slug) => slug.toLowerCase()))].sort().join("\n");
165
+ return key(a) === key(b);
166
+ }
167
+ /** Are two session ids the same session (compared without case)? */
168
+ function sameSession(a, b) {
169
+ return a.toLowerCase() === b.toLowerCase();
170
+ }
171
+ const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
172
+ /**
173
+ * The company's cloud uid: `companies/<slug>/.company-uid` first, then
174
+ * `companies.<slug>.cloud_uid` in companies/manifest.yaml, the same order as
175
+ * the daemon's recordedUid (src/lib/daemon/hook-requests-mesh.ts). Null when
176
+ * neither holds a valid uid.
177
+ */
178
+ export function companyCloudUid(hqRoot, slug) {
179
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(slug))
180
+ return null;
181
+ try {
182
+ const file = path.join(hqRoot, "companies", slug, ".company-uid");
183
+ const stat = fs.lstatSync(file);
184
+ if (stat.isFile() && stat.size <= 256) {
185
+ const uid = fs.readFileSync(file, "utf8").replace(/[ \t\n\v\f\r]/g, "");
186
+ return COMPANY_UID_RE.test(uid) ? uid : null;
187
+ }
188
+ }
189
+ catch {
190
+ // No uid file: the manifest.
191
+ }
192
+ return manifestCompanyUid(hqRoot, slug);
193
+ }
194
+ /** The company's cloud uid from `companies/manifest.yaml` (`companies.<slug>.cloud_uid`), or null. */
195
+ export function manifestCompanyUid(hqRoot, slug) {
196
+ try {
197
+ const file = path.join(hqRoot, "companies", "manifest.yaml");
198
+ const stat = fs.lstatSync(file);
199
+ if (!stat.isFile() || stat.size > 1024 * 1024)
200
+ return null;
201
+ const doc = loadYaml(fs.readFileSync(file, "utf8"), { schema: JSON_SCHEMA });
202
+ const companies = doc && typeof doc === "object" ? doc.companies : undefined;
203
+ if (!companies || typeof companies !== "object" || !Object.hasOwn(companies, slug))
204
+ return null;
205
+ const uid = companies[slug]?.cloud_uid;
206
+ return typeof uid === "string" && COMPANY_UID_RE.test(uid) ? uid : null;
207
+ }
208
+ catch {
209
+ return null;
210
+ }
211
+ }
212
+ /**
213
+ * The session the bundled hq-session.sh changed, from the two sources it
214
+ * reads before `.current`: the last `--session-id`, then a session id in the
215
+ * environment (same keys and order as core/scripts/lib/session-id.sh). Null
216
+ * when neither names one; the script then fell back to `.current`.
217
+ */
218
+ export function scriptSessionTarget(argv, env = process.env) {
219
+ const parsed = bindingActionOf(argv);
220
+ if (!parsed)
221
+ return null;
222
+ const flag = lastSessionFlag(parsed.globalArgs);
223
+ if (flag !== undefined)
224
+ return validSessionId(flag) ? { sessionId: flag, via: "flag" } : null;
225
+ const fromEnv = sessionIdFromEnv(env);
226
+ return fromEnv ? { sessionId: fromEnv, via: "env" } : null;
227
+ }
228
+ /** Does meta.yaml now show the change the command asked for? */
229
+ function metaShowsChange(action, slug, meta) {
230
+ const holds = meta.companies.some((company) => company.toLowerCase() === slug.toLowerCase());
231
+ switch (action) {
232
+ case "bind": return meta.companies.length === 1 && holds;
233
+ case "unbind": return meta.companies.length === 0;
234
+ case "add": return holds;
235
+ case "remove": return !holds;
236
+ }
237
+ }
238
+ /**
239
+ * The source of this change. `previous` is the receipt's last line: the bind
240
+ * the session already had.
241
+ */
242
+ /** The source of an unconfirmed line that only closes: never on the allowlist. */
243
+ export const UNCONFIRMED_SOURCE = "unconfirmed";
244
+ function sourceOf(action, env, previous, companies, added) {
245
+ if (action === "unbind")
246
+ return "";
247
+ // What the act itself is: named by the caller, a scheduled run, or a choice.
248
+ const named = env.HQ_SESSION_COMPANY_SOURCE?.trim() ?? "";
249
+ const act = unattendedRun(env)
250
+ ? "scheduled_task"
251
+ : named ? (/^[a-z][a-z_]*$/.test(named) ? named : "") : "explicit";
252
+ if (action === "bind")
253
+ return act;
254
+ const bound = previous && previous.companies.length > 0 ? previous : null;
255
+ // Removing a company does not change how the remaining ones were bound.
256
+ if (action === "remove")
257
+ return bound ? bound.source : "";
258
+ // Adding a company: a weak act weakens the set; a chosen one keeps what the
259
+ // set already was. A company the session holds with no receipt (a default)
260
+ // is not made a choice by adding another next to it.
261
+ if (act !== "explicit")
262
+ return act;
263
+ if (bound)
264
+ return bound.source;
265
+ return companies.length === 1 && companies[0].toLowerCase() === added.toLowerCase() ? act : "";
266
+ }
267
+ export function recordSessionBinding(argv, context, deps) {
268
+ try {
269
+ const env = deps.env ?? process.env;
270
+ if (env.HQ_HQ_SESSION_NO_CLI === "1")
271
+ return null;
272
+ if (env.HQ_HOOK_EVENT?.trim())
273
+ return null;
274
+ const parsed = bindingActionOf(argv);
275
+ if (!parsed)
276
+ return null;
277
+ const target = deps.target;
278
+ // Only a typed --session-id, never .current or the environment.
279
+ if (!target || target.via !== "flag")
280
+ return null;
281
+ const sessionId = target.sessionId.trim();
282
+ if (!validSessionId(sessionId))
283
+ return null;
284
+ // An id the environment names needs the hook's confirmation (or is a narrowing change).
285
+ const fromEnvironment = sessionIdFromEnvironment(sessionId, env);
286
+ const hqRoot = context.hqRoot || context.cwd;
287
+ const home = deps.home ?? (env.HOME?.trim() || os.homedir());
288
+ const meshRoot = deps.workMeshRoot ?? workMeshRoot(home, env);
289
+ const paths = { env, home, workMeshRoot: meshRoot, now: deps.now, hqRoot };
290
+ const written = (deps.withCompanyLock ?? ((_sessionId, action) => action()))(sessionId, () => {
291
+ const meta = readSessionMeta(hqRoot, sessionId);
292
+ if (!meta || !metaShowsChange(parsed.action, parsed.slug, meta))
293
+ return null;
294
+ if (meta.foreignCwd && !fs.existsSync(path.join(meshRoot, "seq", sessionId)))
295
+ return null;
296
+ // The bind the session already had in this tree.
297
+ const tree = treeKeyOf(hqRoot);
298
+ const previous = readBindingReceipt(sessionId, paths)?.filter((line) => line.root === tree).at(-1) ?? null;
299
+ let confirmedCall;
300
+ let unconfirmed = false;
301
+ if (fromEnvironment) {
302
+ pruneBindIntents(paths);
303
+ const intent = consumeBindIntent({
304
+ sessionId, action: parsed.action, company: parsed.action === "unbind" ? "" : parsed.slug, at: (deps.now?.() ?? new Date()),
305
+ }, paths);
306
+ if (intent) {
307
+ confirmedCall = intent.call;
308
+ }
309
+ else {
310
+ // No open bind left behind: an unconfirmed change whose lock set
311
+ // differs from the last line's closes that line, with a source that
312
+ // never counts. An add counts here too: one company counts, two
313
+ // count for nobody. Only an exact repeat writes nothing.
314
+ if (!previous || sameCompanySet(previous.companies, meta.companies))
315
+ return null;
316
+ unconfirmed = true;
317
+ }
318
+ }
319
+ // An unconfirmed line never keeps the previous counting source.
320
+ const source = unconfirmed ? UNCONFIRMED_SOURCE : sourceOf(parsed.action, env, previous, meta.companies, parsed.slug);
321
+ const parent = source === "parent" ? env.HQ_PARENT_SESSION_ID?.trim() : undefined;
322
+ // The caller's own session, when it named another one.
323
+ const own = target.via === "flag" ? sessionIdFromEnv(env) : "";
324
+ const actor = own && !sameSession(own, sessionId) ? own : undefined;
325
+ return appendBindingReceipt(sessionId, {
326
+ action: parsed.action, companies: meta.companies, source, parent, hqRoot, actor, confirmedCall,
327
+ }, paths);
328
+ });
329
+ if (written)
330
+ showMemberLine(sessionId, written, hqRoot, env, paths, deps);
331
+ return written;
332
+ }
333
+ catch {
334
+ return null;
335
+ }
336
+ }
337
+ /**
338
+ * Print the member line for a bind that counts, to a company whose reporting
339
+ * flag is on. It names the session it applies to, and says whether that is
340
+ * the caller's own session (the session id in the environment).
341
+ */
342
+ function showMemberLine(sessionId, line, hqRoot, env, paths, deps) {
343
+ try {
344
+ if (line.companies.length !== 1)
345
+ return;
346
+ const company = line.companies[0];
347
+ const at = new Date(line.at);
348
+ if (!bindingSourceCounts(sessionId, company, at, paths))
349
+ return;
350
+ const uid = (deps.companyUid ?? companyCloudUid)(hqRoot, company);
351
+ // The same reading as reporting-privacy.ts workMeshCompanyReportingRequired:
352
+ // a fresh snapshot that says on. Missing, stale or unreadable is off.
353
+ if (!uid || readFlagSnapshotFile(uid, { env })?.flags[WORK_MESH_COMPANY_REPORTING_REQUIRED] !== true)
354
+ return;
355
+ const own = sessionIdFromEnv(env);
356
+ const relation = !own ? "unknown" : sameSession(own, sessionId) ? "own" : "other";
357
+ (deps.write ?? ((text) => { process.stdout.write(text); }))(`${sessionReportingRequiredNotice(company, sessionId, relation)}\n`);
358
+ }
359
+ catch {
360
+ // No line.
361
+ }
362
+ }
363
+ //# sourceMappingURL=core-hq-session-binding.js.map
@@ -1,10 +1,24 @@
1
1
  export declare const HQ_SESSION_ASSET = "core/scripts/hq-session.sh";
2
2
  export declare const HQ_SESSION_HELP: string;
3
+ /**
4
+ * How a command found the session it changed: `--session-id`, a session id in
5
+ * the environment, or the global, last-writer-wins `workspace/sessions/.current`.
6
+ */
7
+ export type HqSessionVia = "flag" | "env" | "current";
8
+ /** The session a successful company change wrote, and how it was found. */
9
+ export interface HqSessionTarget {
10
+ sessionId: string;
11
+ via: HqSessionVia;
12
+ }
3
13
  export type HqSessionResult = {
4
14
  code: number;
5
15
  stdout: string;
6
16
  stderr: string;
7
17
  };
18
+ /** A result plus, for a successful company change, the session it wrote. */
19
+ export type HqSessionTargetedResult = HqSessionResult & {
20
+ target?: HqSessionTarget;
21
+ };
8
22
  export type HqSessionDependencies = {
9
23
  env: NodeJS.ProcessEnv;
10
24
  now: () => Date;
@@ -31,11 +45,20 @@ export type HqSessionDependencies = {
31
45
  multiCompanyLockEnabled: boolean;
32
46
  };
33
47
  export { validSessionId } from "../lib/core-utils/session-id.js";
48
+ export declare function withCompanyLock<T>(root: string, sessionId: string, action: () => T): T;
34
49
  /** In-process command body, with injectable file access for parity tests. */
35
50
  export declare function executeHqSession(argv: readonly string[], context: {
36
51
  cwd: string;
37
52
  hqRoot?: string;
38
53
  }, overrides?: Partial<HqSessionDependencies>): HqSessionResult;
54
+ /**
55
+ * {@link executeHqSession}, plus the session a successful company change
56
+ * wrote and how it was found, for the binding receipt.
57
+ */
58
+ export declare function executeHqSessionTargeted(argv: readonly string[], context: {
59
+ cwd: string;
60
+ hqRoot?: string;
61
+ }, overrides?: Partial<HqSessionDependencies>): HqSessionTargetedResult;
39
62
  /** Signature consumed by the lightweight fast-core dispatcher. */
40
63
  export declare function runHqSessionFast(argv: readonly string[], _stdin: string, cwd: string, hqRoot: string | undefined): Promise<number>;
41
64
  //# sourceMappingURL=core-hq-session-native.d.ts.map
@@ -6,7 +6,7 @@ import { createRequire } from "node:module";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { awkCannotOpenFileDiagnostic } from "../lib/core-utils/awk-diagnostics.js";
8
8
  import { shellDisplayPath } from "../lib/core-utils/shell-display-path.js";
9
- import { SESSION_ID_ENV_KEYS, validSessionId, resolveSessionId as resolveSharedSessionId } from "../lib/core-utils/session-id.js";
9
+ import { SESSION_ID_ENV_KEYS, sessionIdFromEnv, validSessionId, resolveSessionId as resolveSharedSessionId } from "../lib/core-utils/session-id.js";
10
10
  export const HQ_SESSION_ASSET = "core/scripts/hq-session.sh";
11
11
  const requireSessionDependency = createRequire(import.meta.url);
12
12
  export const HQ_SESSION_HELP = [
@@ -28,6 +28,12 @@ export const HQ_SESSION_HELP = [
28
28
  "Global option (before the subcommand):",
29
29
  " --session-id <id> operate on this session instead of the resolved one",
30
30
  ].join("\n") + "\n";
31
+ /** How `sessionOverride || resolveSessionId(...)` found its id. */
32
+ function sessionVia(sessionOverride, env) {
33
+ if (sessionOverride)
34
+ return "flag";
35
+ return sessionIdFromEnv(env) ? "env" : "current";
36
+ }
31
37
  const defaultDependencies = () => ({
32
38
  env: process.env,
33
39
  now: () => new Date(),
@@ -136,7 +142,7 @@ function isRegisteredCompany(root, slug, deps) {
136
142
  return false;
137
143
  }
138
144
  }
139
- function withCompanyLock(root, sessionId, action) {
145
+ export function withCompanyLock(root, sessionId, action) {
140
146
  const lock = path.join(root, "workspace", "sessions", sessionId, ".company-lock-set.lock");
141
147
  const deadline = Date.now() + 30_000;
142
148
  while (true) {
@@ -566,6 +572,15 @@ function mintScopeCapability(root, sessionId, companies, deps, includeSet = fals
566
572
  }
567
573
  /** In-process command body, with injectable file access for parity tests. */
568
574
  export function executeHqSession(argv, context, overrides = {}) {
575
+ // The result keeps the shell's shape (code, stdout, stderr) for parity.
576
+ const { code, stdout, stderr } = executeHqSessionTargeted(argv, context, overrides);
577
+ return { code, stdout, stderr };
578
+ }
579
+ /**
580
+ * {@link executeHqSession}, plus the session a successful company change
581
+ * wrote and how it was found, for the binding receipt.
582
+ */
583
+ export function executeHqSessionTargeted(argv, context, overrides = {}) {
569
584
  const deps = { ...defaultDependencies(), ...overrides };
570
585
  const root = context.hqRoot || context.cwd;
571
586
  let sessionOverride = "";
@@ -687,7 +702,10 @@ export function executeHqSession(argv, context, overrides = {}) {
687
702
  const workMeshOutput = primaryChanged
688
703
  ? registerWorkMeshCompany(root, sessionId, next[0], updatedText, context.cwd, deps)
689
704
  : { stdout: "", stderr: "" };
690
- return { code: 0, stdout: stdout + workMeshOutput.stdout, stderr: workMeshOutput.stderr };
705
+ return {
706
+ code: 0, stdout: stdout + workMeshOutput.stdout, stderr: workMeshOutput.stderr,
707
+ target: { sessionId, via: sessionVia(sessionOverride, deps.env) },
708
+ };
691
709
  }
692
710
  catch (error) {
693
711
  const message = error instanceof Error ? error.message : String(error);
@@ -696,7 +714,9 @@ export function executeHqSession(argv, context, overrides = {}) {
696
714
  });
697
715
  }
698
716
  const key = args[0] ?? "";
699
- const value = args[1] ?? "";
717
+ // `personal` in any letter case is the no-company scope, as hq-session.sh
718
+ // folds it and the CLI's session readers read it: never a company named PERSONAL.
719
+ const value = key === "company_slug" && /^personal$/i.test(args[1] ?? "") ? "personal" : (args[1] ?? "");
700
720
  if (!key || args.length < 2)
701
721
  return { code: 1, stdout: "", stderr: "usage: hq-session.sh set <key> <value>\n" };
702
722
  if (key === "company_slugs")
@@ -772,7 +792,10 @@ export function executeHqSession(argv, context, overrides = {}) {
772
792
  cwd: deps.env.PWD || context.cwd,
773
793
  metadata: updatedText,
774
794
  }, deps);
775
- return { code: 0, stdout: stdout + workMeshOutput.stdout, stderr: workMeshOutput.stderr };
795
+ return {
796
+ code: 0, stdout: stdout + workMeshOutput.stdout, stderr: workMeshOutput.stderr,
797
+ target: { sessionId, via: sessionVia(sessionOverride, deps.env) },
798
+ };
776
799
  }
777
800
  catch (error) {
778
801
  const message = error instanceof Error ? error.message : String(error);
@@ -781,9 +804,18 @@ export function executeHqSession(argv, context, overrides = {}) {
781
804
  }
782
805
  /** Signature consumed by the lightweight fast-core dispatcher. */
783
806
  export async function runHqSessionFast(argv, _stdin, cwd, hqRoot) {
784
- const commandArgs = argv[0] === "--session-id"
785
- ? argv.slice(2)
786
- : argv[0]?.startsWith("--session-id=") ? argv.slice(1) : argv;
807
+ // Every leading --session-id, as executeHqSessionTargeted reads them (the
808
+ // last one wins): a doubled flag must not hide the subcommand.
809
+ let first = 0;
810
+ while (first < argv.length) {
811
+ if (argv[first] === "--session-id")
812
+ first += 2;
813
+ else if (argv[first]?.startsWith("--session-id="))
814
+ first += 1;
815
+ else
816
+ break;
817
+ }
818
+ const commandArgs = argv.slice(first);
787
819
  const needsMultiCompanyFlag = commandArgs[0] === "add"
788
820
  || (commandArgs[0] === "get" && commandArgs[1] === "company_slugs");
789
821
  let enabled = false;
@@ -794,11 +826,29 @@ export async function runHqSessionFast(argv, _stdin, cwd, hqRoot) {
794
826
  ]);
795
827
  enabled = await fastFlagEnabledDefaultOn(MULTI_COMPANY_SESSION_LOCK_FLAG);
796
828
  }
797
- const result = executeHqSession(argv, { cwd, hqRoot }, { multiCompanyLockEnabled: enabled });
829
+ const result = executeHqSessionTargeted(argv, { cwd, hqRoot }, { multiCompanyLockEnabled: enabled });
798
830
  if (result.stdout)
799
831
  process.stdout.write(result.stdout);
800
832
  if (result.stderr)
801
833
  process.stderr.write(result.stderr);
834
+ // A company change that succeeded leaves a dated binding receipt. Loaded
835
+ // only for those commands, so other calls keep the fast path's cost.
836
+ if (result.code === 0 && ["set", "add", "remove"].includes(commandArgs[0] ?? "") &&
837
+ ["company_slug", "company"].includes(commandArgs[1] ?? "")) {
838
+ try {
839
+ const { recordSessionBinding } = await import("./core-hq-session-binding.js");
840
+ // The session this command wrote, never a second lookup of .current,
841
+ // and only when --session-id named it: an inherited environment can
842
+ // name a parent session (hq-session.sh always forwards --session-id).
843
+ recordSessionBinding(argv, { cwd, hqRoot }, {
844
+ target: result.target ?? null,
845
+ withCompanyLock: (sessionId, action) => withCompanyLock(hqRoot || cwd, sessionId, action),
846
+ });
847
+ }
848
+ catch {
849
+ // No receipt. The command itself succeeded.
850
+ }
851
+ }
802
852
  return result.code;
803
853
  }
804
854
  //# sourceMappingURL=core-hq-session-native.js.map
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
- import { createFlagClient } from "@indigoai-us/hq-flags-client";
5
+ import { createHqFlagClient as createFlagClient } from "../lib/flag-client-headers.js";
6
6
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
7
7
  import { resolveFlagRegistryEndpoint } from "../lib/flag-registry-endpoint.js";
8
8
  import { executeHqSession } from "./core-hq-session-native.js";
@@ -30,6 +30,8 @@
30
30
  */
31
31
  import { Option } from "commander";
32
32
  import { registerCoreHookRegistrationPlan } from "./core-hook-registration-plan.js";
33
+ import { recordSessionBinding, scriptSessionTarget } from "./core-hq-session-binding.js";
34
+ import { withCompanyLock } from "./core-hq-session-native.js";
33
35
  import { registerCoreCheckpointCommand } from "./core-checkpoint.js";
34
36
  import { registerCoreStopAutosave } from "./core-stop-autosave.js";
35
37
  import { runHookEnginePath } from '../hook-engine-path.js';
@@ -428,6 +430,14 @@ function runEntry(entry, scope, args) {
428
430
  // caller's contract.
429
431
  if (code !== 0)
430
432
  process.exit(code);
433
+ if (entry.asset === "core/scripts/hq-session.sh") {
434
+ // A company change that succeeded leaves a dated binding receipt, for the
435
+ // session the script was named (--session-id or the environment) only.
436
+ recordSessionBinding(args, { cwd, hqRoot }, {
437
+ target: scriptSessionTarget(args),
438
+ withCompanyLock: (sessionId, action) => withCompanyLock(hqRoot || cwd, sessionId, action),
439
+ });
440
+ }
431
441
  }
432
442
  function expectedUserError(message) {
433
443
  return Object.assign(new Error(message), { expected: true });
@@ -25,6 +25,8 @@ import { Command } from "commander";
25
25
  import { type DoctorRegistry } from "../lib/doctor/registry.js";
26
26
  import type { FamilyRun } from "../lib/doctor/types.js";
27
27
  import { type DoctorPlatform } from "../lib/doctor/report.js";
28
+ import type { CheckResult } from "../lib/doctor/types.js";
29
+ import { type EnsureJqResult } from "../lib/windows/jq.js";
28
30
  import { type TempHomeSweepResult } from "../lib/doctor/temp-home-sweeper.js";
29
31
  /**
30
32
  * Marker directories that identify an HQ tree root. A directory is an HQ root
@@ -133,7 +135,9 @@ export interface DoctorCommandDeps {
133
135
  sweepTempHomes?: (options: {
134
136
  dryRun: boolean;
135
137
  }) => TempHomeSweepResult;
136
- installWindowsJq?: () => Promise<string | undefined>;
138
+ ensureWindowsJq?: () => Promise<EnsureJqResult | undefined>;
139
+ /** The closing check of --fix-jq: jq.on-path against the stored Windows PATH. */
140
+ verifyJq?: () => CheckResult[];
137
141
  }
138
142
  /** Text report for `hq doctor --sweep-temp-homes`. */
139
143
  export declare function renderTempHomeSweepText(result: TempHomeSweepResult): string;