@indigoai-us/hq-cli 5.345.251 → 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 (160) hide show
  1. package/CHANGELOG.md +112 -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 +121 -1
  5. package/dist/command-catalog.generated.js +148 -1
  6. package/dist/commands/bot.js +7 -2
  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/logout.js +4 -0
  19. package/dist/commands/ontology-graph.d.ts +2 -0
  20. package/dist/commands/ontology-graph.js +33 -0
  21. package/dist/commands/report.js +35 -2
  22. package/dist/commands/storage-gate.js +1 -1
  23. package/dist/commands/vault-retention-flag.js +2 -1
  24. package/dist/commands/whoami.js +1 -1
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/index.js +3 -1
  28. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  29. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  30. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  31. package/dist/lib/bot/fleet-cron.d.ts +35 -0
  32. package/dist/lib/bot/fleet-cron.js +54 -12
  33. package/dist/lib/bot/fleet-local.d.ts +18 -0
  34. package/dist/lib/bot/fleet-local.js +51 -5
  35. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  36. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  37. package/dist/lib/bot/signals-engine-flag.js +1 -1
  38. package/dist/lib/cli-invite-nudge.js +1 -1
  39. package/dist/lib/client-version.d.ts +2 -0
  40. package/dist/lib/client-version.js +24 -0
  41. package/dist/lib/company-flag-gate.d.ts +30 -0
  42. package/dist/lib/company-flag-gate.js +104 -0
  43. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  44. package/dist/lib/daemon/flag.js +2 -1
  45. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  46. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  47. package/dist/lib/doctor/checks/host-core.js +22 -4
  48. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  49. package/dist/lib/doctor/checks/jq.js +46 -8
  50. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  51. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  52. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  53. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  54. package/dist/lib/flag-client-gate-headers.js +62 -0
  55. package/dist/lib/flag-client-headers.d.ts +15 -0
  56. package/dist/lib/flag-client-headers.js +25 -0
  57. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  58. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  59. package/dist/lib/flag-registry-worker.js +35 -0
  60. package/dist/lib/flag-registry.d.ts +1 -20
  61. package/dist/lib/flag-registry.js +5 -81
  62. package/dist/lib/hook-engine/adapter-core-pin.d.ts +29 -0
  63. package/dist/lib/hook-engine/adapter-core-pin.js +29 -0
  64. package/dist/lib/hook-engine/coverage.d.ts +50 -1
  65. package/dist/lib/hook-engine/coverage.js +111 -7
  66. package/dist/lib/hook-engine/reconcile.js +3 -2
  67. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  68. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  69. package/dist/lib/hot-channels/signal-changes.js +683 -0
  70. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  71. package/dist/lib/hot-channels/signals-pass.js +232 -12
  72. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  73. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  74. package/dist/lib/lanes/registry-flag.js +2 -1
  75. package/dist/lib/lanes/spawn.js +11 -1
  76. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  77. package/dist/lib/mesh/live/binding-intent.js +201 -0
  78. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  79. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  80. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  81. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  82. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  83. package/dist/lib/mesh/live/daemon/install.js +2 -1
  84. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  85. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  86. package/dist/lib/mesh/live/daemon/run.js +33 -1
  87. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  88. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  89. package/dist/lib/ontology-graph/model/index.d.ts +54 -0
  90. package/dist/lib/ontology-graph/model/index.js +112 -0
  91. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
  92. package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
  93. package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
  94. package/dist/lib/ontology-graph/model/pass.js +9 -2
  95. package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
  96. package/dist/lib/ontology-graph/model/pending-items.js +24 -1
  97. package/dist/lib/ontology-graph/model/step.d.ts +1 -1
  98. package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
  99. package/dist/lib/ontology-graph/model/tasks.js +20 -7
  100. package/dist/lib/ontology-graph/read/brief.js +41 -6
  101. package/dist/lib/ontology-graph/read/index.d.ts +4 -0
  102. package/dist/lib/ontology-graph/read/index.js +173 -29
  103. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  104. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  105. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  106. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  107. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  108. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  109. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  110. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  111. package/dist/lib/ontology-graph/replay/index.js +9 -3
  112. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  113. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  114. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  115. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  116. package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
  117. package/dist/lib/ontology-graph/schema/index.js +1 -0
  118. package/dist/lib/ontology-graph/setup/index.js +13 -3
  119. package/dist/lib/search-index/index.d.ts +33 -1
  120. package/dist/lib/search-index/index.js +180 -25
  121. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  122. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  123. package/dist/lib/signals/adapters-catalog.js +1 -1
  124. package/dist/lib/sync-core/engine-holds.d.ts +1 -0
  125. package/dist/lib/sync-core/engine-holds.js +26 -0
  126. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  127. package/dist/lib/sync-core/engine-home.js +41 -1
  128. package/dist/lib/sync-core/flag.js +2 -1
  129. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  130. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  131. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  132. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  133. package/dist/lib/sync-core/reconcile.js +30 -5
  134. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  135. package/dist/lib/windows/install-followup.d.ts +41 -0
  136. package/dist/lib/windows/install-followup.js +87 -0
  137. package/dist/lib/windows/jq.d.ts +59 -0
  138. package/dist/lib/windows/jq.js +154 -3
  139. package/dist/lib/windows/user-path.d.ts +5 -0
  140. package/dist/lib/windows/user-path.js +1 -1
  141. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  142. package/dist/lib/work-context/auto-bind.js +49 -3
  143. package/dist/lib/work-context/organize.d.ts +4 -2
  144. package/dist/lib/work-context/organize.js +18 -8
  145. package/dist/lib/work-context/reconcile.js +16 -1
  146. package/dist/main.js +12 -1
  147. package/dist/utils/client-health-contract.d.ts +30 -0
  148. package/dist/utils/client-health-contract.js +111 -0
  149. package/dist/utils/client-health.d.ts +5 -2
  150. package/dist/utils/client-health.js +74 -5
  151. package/dist/utils/exclusive-lock.d.ts +5 -1
  152. package/dist/utils/exclusive-lock.js +9 -2
  153. package/dist/utils/host-registration.d.ts +7 -0
  154. package/dist/utils/host-registration.js +10 -1
  155. package/dist/utils/pid.d.ts +31 -0
  156. package/dist/utils/pid.js +65 -0
  157. package/dist/utils/resident-package-preload.js +12 -4
  158. package/dist/utils/sentry-fingerprint.js +3 -0
  159. package/package.json +8 -8
  160. package/scripts/install-hook-engine.mjs +5 -3
@@ -0,0 +1,140 @@
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 { type BindingAction, type BindingLine, type BindingPaths } from "../lib/mesh/live/binding-receipt.js";
74
+ import type { HqSessionTarget } from "./core-hq-session-native.js";
75
+ export interface RecordSessionBindingDeps extends BindingPaths {
76
+ /**
77
+ * The session the command changed and how it was found. Null, or found
78
+ * through `.current`: no receipt.
79
+ */
80
+ target: HqSessionTarget | null;
81
+ /** Writes the member line. Defaults to stdout. */
82
+ write?: (text: string) => void;
83
+ /** The company's cloud uid, for its reporting flag. Defaults to {@link companyCloudUid}. */
84
+ companyUid?: (hqRoot: string, slug: string) => string | null;
85
+ /** Runs the action while holding the session's company lock. */
86
+ withCompanyLock?: <T>(sessionId: string, action: () => T) => T;
87
+ }
88
+ type ReceiptAction = Exclude<BindingAction, "source">;
89
+ /** The company change a `hq-session` command line asks for, or null. */
90
+ export declare function bindingActionOf(argv: readonly string[]): {
91
+ globalArgs: string[];
92
+ action: ReceiptAction;
93
+ slug: string;
94
+ } | null;
95
+ /**
96
+ * The value of the last `--session-id` in the leading global arguments, as
97
+ * hq-session.sh and the native command read it (a later flag wins). Undefined
98
+ * when there is none.
99
+ */
100
+ export declare function lastSessionFlag(globalArgs: readonly string[]): string | undefined;
101
+ /**
102
+ * Every distinct session id the environment's session variables name,
103
+ * lower-cased: session folders and receipt files live on case-insensitive
104
+ * file systems, so ids that differ only in case are the same session.
105
+ */
106
+ export declare function environmentSessionIds(env: NodeJS.ProcessEnv): string[];
107
+ /**
108
+ * The id came from the environment: hq-session.sh said so, or it equals an
109
+ * id a session variable here names (an older script that sets no marker
110
+ * forwards such an id as --session-id, and an inherited id looks the same).
111
+ */
112
+ export declare function sessionIdFromEnvironment(sessionId: string, env: NodeJS.ProcessEnv): boolean;
113
+ /**
114
+ * The company's cloud uid: `companies/<slug>/.company-uid` first, then
115
+ * `companies.<slug>.cloud_uid` in companies/manifest.yaml, the same order as
116
+ * the daemon's recordedUid (src/lib/daemon/hook-requests-mesh.ts). Null when
117
+ * neither holds a valid uid.
118
+ */
119
+ export declare function companyCloudUid(hqRoot: string, slug: string): string | null;
120
+ /** The company's cloud uid from `companies/manifest.yaml` (`companies.<slug>.cloud_uid`), or null. */
121
+ export declare function manifestCompanyUid(hqRoot: string, slug: string): string | null;
122
+ /**
123
+ * The session the bundled hq-session.sh changed, from the two sources it
124
+ * reads before `.current`: the last `--session-id`, then a session id in the
125
+ * environment (same keys and order as core/scripts/lib/session-id.sh). Null
126
+ * when neither names one; the script then fell back to `.current`.
127
+ */
128
+ export declare function scriptSessionTarget(argv: readonly string[], env?: NodeJS.ProcessEnv): HqSessionTarget | null;
129
+ /**
130
+ * The source of this change. `previous` is the receipt's last line: the bind
131
+ * the session already had.
132
+ */
133
+ /** The source of an unconfirmed line that only closes: never on the allowlist. */
134
+ export declare const UNCONFIRMED_SOURCE = "unconfirmed";
135
+ export declare function recordSessionBinding(argv: readonly string[], context: {
136
+ cwd: string;
137
+ hqRoot?: string;
138
+ }, deps: RecordSessionBindingDeps): BindingLine | null;
139
+ export {};
140
+ //# sourceMappingURL=core-hq-session-binding.d.ts.map
@@ -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