@indigoai-us/hq-cli 5.345.258 → 5.345.261

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 (47) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/assets/scaffold/core/scripts/handoff-knowledge-commit.sh +163 -5
  3. package/assets/scaffold/core/scripts/handoff-post.sh +30 -0
  4. package/assets/scaffold/core/scripts/handoff-sync-prefetch.sh +39 -0
  5. package/assets/scaffold/core/scripts/handoff-sync-publish.sh +51 -3
  6. package/contracts/host-canary-release.json +7 -7
  7. package/dist/commands/cloud.d.ts +2 -7
  8. package/dist/commands/cloud.js +2 -29
  9. package/dist/commands/core-bucket-c-handoff-knowledge-native.d.ts +24 -2
  10. package/dist/commands/core-bucket-c-handoff-knowledge-native.js +170 -19
  11. package/dist/commands/core-bucket-c-handoff-sync-native.d.ts +4 -2
  12. package/dist/commands/core-bucket-c-handoff-sync-native.js +153 -34
  13. package/dist/commands/core-bucket-c-handoff-sync-worker.cjs +201 -0
  14. package/dist/commands/core-delegate-w1b.js +17 -16
  15. package/dist/commands/core-delegate.js +5 -4
  16. package/dist/commands/core-handoff.d.ts +10 -0
  17. package/dist/commands/core-handoff.js +138 -16
  18. package/dist/commands/reindex.d.ts +3 -0
  19. package/dist/commands/reindex.js +11 -5
  20. package/dist/commands/rescue.js +7 -2
  21. package/dist/commands/sync-core.js +24 -7
  22. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +3227 -2138
  23. package/dist/hq-cloud-sync-runner/package.json +1 -1
  24. package/dist/lib/canonical-person.d.ts +19 -0
  25. package/dist/lib/canonical-person.js +30 -0
  26. package/dist/lib/company-sessions-cli.d.ts +12 -0
  27. package/dist/lib/company-sessions-cli.js +54 -0
  28. package/dist/lib/company-sessions.d.ts +31 -0
  29. package/dist/lib/company-sessions.js +304 -0
  30. package/dist/lib/doctor/fix/process-identity.d.ts +13 -0
  31. package/dist/lib/doctor/fix/process-identity.js +63 -7
  32. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  33. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  34. package/dist/lib/hook-engine/coverage.d.ts +44 -1
  35. package/dist/lib/hook-engine/coverage.js +129 -1
  36. package/dist/lib/onboarding/orchestrator.js +4 -2
  37. package/dist/lib/sync-core/engine-home.d.ts +5 -1
  38. package/dist/lib/sync-core/engine-home.js +6 -2
  39. package/dist/lib/sync-core/reconcile.d.ts +5 -0
  40. package/dist/lib/sync-core/reconcile.js +21 -1
  41. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  42. package/dist/lib/sync-core/vault-uid.js +4 -0
  43. package/dist/utils/delegate-lock.d.ts +18 -0
  44. package/dist/utils/delegate-lock.js +149 -37
  45. package/dist/utils/sync-operation-lock.d.ts +2 -1
  46. package/dist/utils/sync-operation-lock.js +13 -2
  47. package/package.json +8 -8
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.124","bundleSha256":"98bb542b595ecef200dd72eb1d25a8b741d7df41a0d7afd06241e553d6eefe12","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.127","bundleSha256":"3b601653b18d56f3abd11998d2a778de384322f1bd217a416679bc07a1542b95","formatVersion":1}
@@ -0,0 +1,19 @@
1
+ export declare function pickCanonicalPerson<E extends {
2
+ uid: string;
3
+ type: string;
4
+ createdAt: string;
5
+ }>(persons: E[]): E | null;
6
+ /**
7
+ * Resolve the canonical person entity UID for the logged-in user. Used by
8
+ * `hq sync {push,pull,now} --personal` to target the personal vault without
9
+ * the caller needing to know the UID. Throws a clean error if the user has
10
+ * no person entity (typically means they haven't run `hq onboard`).
11
+ */
12
+ export declare function resolveCanonicalPersonUid<C extends {
13
+ listPersonEntities(): Promise<Array<{
14
+ uid: string;
15
+ type: string;
16
+ createdAt: string;
17
+ }>>;
18
+ }>(vaultClient: C): Promise<string>;
19
+ //# sourceMappingURL=canonical-person.d.ts.map
@@ -0,0 +1,30 @@
1
+ // Oldest-first by createdAt, ties broken by uid lexicographic — matches
2
+ // `pickCanonicalPersonEntity` in @indigoai-us/hq-cloud so the CLI lands on
3
+ // the same person bucket that `hq-sync-runner` picks.
4
+ export function pickCanonicalPerson(persons) {
5
+ const onlyPersons = persons.filter((e) => e.type === "person");
6
+ if (onlyPersons.length === 0)
7
+ return null;
8
+ return [...onlyPersons].sort((a, b) => {
9
+ if (a.createdAt !== b.createdAt)
10
+ return a.createdAt < b.createdAt ? -1 : 1;
11
+ return a.uid < b.uid ? -1 : 1;
12
+ })[0];
13
+ }
14
+ /**
15
+ * Resolve the canonical person entity UID for the logged-in user. Used by
16
+ * `hq sync {push,pull,now} --personal` to target the personal vault without
17
+ * the caller needing to know the UID. Throws a clean error if the user has
18
+ * no person entity (typically means they haven't run `hq onboard`).
19
+ */
20
+ export async function resolveCanonicalPersonUid(vaultClient) {
21
+ const persons = await vaultClient.listPersonEntities();
22
+ const pick = pickCanonicalPerson(persons);
23
+ if (!pick) {
24
+ throw new Error("No personal vault found for the logged-in user. Run `hq onboard` " +
25
+ "first, or check `hq whoami` to confirm you're signed in to the " +
26
+ "right account.");
27
+ }
28
+ return pick.uid;
29
+ }
30
+ //# sourceMappingURL=canonical-person.js.map
@@ -0,0 +1,12 @@
1
+ import { type CompanySessionRetentionOptions } from "./company-sessions.js";
2
+ export declare const COMPANY_SESSIONS_HOME_ENV = "HQ_COMPANY_SESSIONS_HOME";
3
+ export declare function runsAsAgent(home: string, env: NodeJS.ProcessEnv): boolean;
4
+ export interface CommandCompanySessionDeps {
5
+ home?: string;
6
+ env?: NodeJS.ProcessEnv;
7
+ fetchPersonUid?: () => Promise<string | null>;
8
+ isAgent?: () => boolean | Promise<boolean>;
9
+ log?: (line: string) => void;
10
+ }
11
+ export declare function companySessionsForCommand(hqRoot: string, allowLookup: boolean, deps?: CommandCompanySessionDeps): Promise<CompanySessionRetentionOptions | undefined>;
12
+ //# sourceMappingURL=company-sessions-cli.d.ts.map
@@ -0,0 +1,54 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { personTokenCacheFile, readTokenFile } from "../utils/person-token-cache.js";
5
+ import { resolveCanonicalPersonUid } from "./canonical-person.js";
6
+ import { resolveCompanySessionOptions, signedInPersonPrincipal, } from "./company-sessions.js";
7
+ const PERSON_UID_LOOKUP_TIMEOUT_MS = 10_000;
8
+ export const COMPANY_SESSIONS_HOME_ENV = "HQ_COMPANY_SESSIONS_HOME";
9
+ async function lookUpPersonUid() {
10
+ const [{ VaultClient }, { buildVaultConfig, ensureCognitoIdToken, wantsMachineCognitoTokens }] = await Promise.all([
11
+ import("@indigoai-us/hq-cloud"),
12
+ import("../utils/cognito-session.js"),
13
+ ]);
14
+ if (wantsMachineCognitoTokens({}))
15
+ return null;
16
+ const token = await ensureCognitoIdToken({ interactive: false });
17
+ const client = new VaultClient(buildVaultConfig(token));
18
+ return resolveCanonicalPersonUid({ listPersonEntities: () => client.entity.listByType("person") });
19
+ }
20
+ export function runsAsAgent(home, env) {
21
+ if (env.HQ_MACHINE_CREDS_FILE?.trim())
22
+ return true;
23
+ if (readTokenFile(personTokenCacheFile(home, env)))
24
+ return false;
25
+ try {
26
+ return fs.lstatSync(path.join(home, ".hq-agent", "machine-creds.json")).isFile();
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ function withTimeout(work, ms) {
33
+ let timer;
34
+ const timeout = new Promise((_, reject) => {
35
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms / 1000}s`)), ms);
36
+ timer.unref?.();
37
+ });
38
+ return Promise.race([work(), timeout]).finally(() => clearTimeout(timer));
39
+ }
40
+ export async function companySessionsForCommand(hqRoot, allowLookup, deps = {}) {
41
+ const env = deps.env ?? process.env;
42
+ const home = deps.home ?? (env[COMPANY_SESSIONS_HOME_ENV]?.trim() || os.homedir());
43
+ const fetchPersonUid = deps.fetchPersonUid ?? lookUpPersonUid;
44
+ const agent = await (deps.isAgent ?? (() => runsAsAgent(home, env)))();
45
+ return resolveCompanySessionOptions({
46
+ home,
47
+ hqRoot,
48
+ agent,
49
+ principal: signedInPersonPrincipal(home, env),
50
+ log: deps.log ?? ((line) => console.warn(line)),
51
+ ...(allowLookup ? { fetchPersonUid: () => withTimeout(fetchPersonUid, PERSON_UID_LOOKUP_TIMEOUT_MS) } : {}),
52
+ });
53
+ }
54
+ //# sourceMappingURL=company-sessions-cli.js.map
@@ -0,0 +1,31 @@
1
+ import { type CompanySessionCaptureOptions, type CompanySessionRetentionOptions, type CompanySessionUploadEvidence, type CompanySessionUploadRecord } from "@indigoai-us/hq-cloud";
2
+ import { isPersonUid } from "./sync-core/vault-uid.js";
3
+ export { isPersonUid };
4
+ export declare const CONFIRMED_UPLOAD_LEDGER_MAX_BYTES: number;
5
+ export type { CompanySessionCaptureOptions, CompanySessionRetentionOptions, CompanySessionUploadEvidence, CompanySessionUploadRecord, };
6
+ export declare const AGENT_COMPANY_SESSIONS: CompanySessionRetentionOptions;
7
+ export declare function personUidCachePath(home: string): string;
8
+ export declare function personUidUnknownMarkerPath(home: string): string;
9
+ export declare function principalFromIdToken(idToken: string | undefined): string | null;
10
+ export declare function signedInPersonPrincipal(home: string, env: NodeJS.ProcessEnv): string | null;
11
+ export declare function readCachedPersonUid(home: string, principal: string): string | null;
12
+ export declare function rememberPersonUid(home: string, principal: string, personUid: string): void;
13
+ export interface ResolveSessionPersonUidDeps {
14
+ home: string;
15
+ principal: string | null;
16
+ fetchPersonUid?: () => Promise<string | null>;
17
+ log: (line: string) => void;
18
+ }
19
+ export declare function resolveSessionPersonUid(deps: ResolveSessionPersonUidDeps): Promise<string | null>;
20
+ export declare function cloudBackedCompanySlugs(hqRoot: string, home?: string): string[];
21
+ export declare function confirmedUploadLedgerPath(home: string, vaultUid: string): string;
22
+ export declare function readConfirmedUploads(home: string, vaultUid: string): Map<string, CompanySessionUploadRecord>;
23
+ export declare function engineUploadEvidence(home: string): CompanySessionUploadEvidence;
24
+ export interface CompanySessionOptionsDeps extends ResolveSessionPersonUidDeps {
25
+ hqRoot: string;
26
+ agent?: boolean;
27
+ }
28
+ export declare function isAgentPrincipal(principal: string | null): boolean;
29
+ export declare function resolveCompanySessionOptions(deps: CompanySessionOptionsDeps): Promise<CompanySessionRetentionOptions | undefined>;
30
+ export declare function withCompanySessions<T extends object>(options: T, companySessions: CompanySessionRetentionOptions | undefined): T;
31
+ //# sourceMappingURL=company-sessions.d.ts.map
@@ -0,0 +1,304 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { isCompanyInPersonalVaultScope, } from "@indigoai-us/hq-cloud";
4
+ import { readCompaniesManifestMap } from "./work-context/repo-remote.js";
5
+ import { readSyncCoreRolloutState } from "./sync-core/rollout-state.js";
6
+ import { syncCoreEngineHome } from "./sync-core/engine-home.js";
7
+ import { isPersonUid } from "./sync-core/vault-uid.js";
8
+ import { NON_CLOUD_COMPANY_SLUG } from "./work-context/company-rebind.js";
9
+ import { decodeJwtPayload, personTokenCacheFile, readTokenFile } from "../utils/person-token-cache.js";
10
+ export { isPersonUid };
11
+ const COMPANY_SLUG_PATTERN = /^[A-Za-z0-9_-]+$/;
12
+ const AGENT_UID_PREFIX = "agt_";
13
+ const COMPANY_UID_PATTERN = /^cmp_[A-Za-z0-9][A-Za-z0-9_-]*$/;
14
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
15
+ const SESSIONS_PREFIX = "sessions/";
16
+ export const CONFIRMED_UPLOAD_LEDGER_MAX_BYTES = 16 * 1024 * 1024;
17
+ const PERSON_UID_CACHE_MAX_BYTES = 64 * 1024;
18
+ export const AGENT_COMPANY_SESSIONS = { identity: "agent" };
19
+ function companySessionsStateDir(home) {
20
+ return path.join(home, ".hq", "company-sessions");
21
+ }
22
+ export function personUidCachePath(home) {
23
+ return path.join(companySessionsStateDir(home), "person-uid.json");
24
+ }
25
+ export function personUidUnknownMarkerPath(home) {
26
+ return path.join(companySessionsStateDir(home), "person-uid-unknown.json");
27
+ }
28
+ function readSmallRegularFile(file, maxBytes) {
29
+ let fd;
30
+ try {
31
+ const before = fs.lstatSync(file);
32
+ if (!before.isFile() || before.size > maxBytes)
33
+ return null;
34
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
35
+ const stat = fs.fstatSync(fd);
36
+ if (!stat.isFile() || stat.size > maxBytes || stat.ino !== before.ino || stat.dev !== before.dev)
37
+ return null;
38
+ const buffer = Buffer.alloc(stat.size);
39
+ let read = 0;
40
+ while (read < stat.size) {
41
+ const n = fs.readSync(fd, buffer, read, stat.size - read, read);
42
+ if (n === 0)
43
+ break;
44
+ read += n;
45
+ }
46
+ return read === stat.size ? buffer : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ finally {
52
+ if (fd !== undefined)
53
+ closeQuietly(fd);
54
+ }
55
+ }
56
+ function closeQuietly(fd) {
57
+ try {
58
+ fs.closeSync(fd);
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ }
64
+ function readJsonRecord(file, maxBytes) {
65
+ const bytes = readSmallRegularFile(file, maxBytes);
66
+ if (!bytes)
67
+ return null;
68
+ try {
69
+ const parsed = JSON.parse(bytes.toString("utf8"));
70
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ function writeJsonAtomic(file, value) {
77
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
78
+ const tmp = `${file}.${process.pid}.tmp`;
79
+ fs.writeFileSync(tmp, `${JSON.stringify(value)}\n`, { mode: 0o600 });
80
+ fs.renameSync(tmp, file);
81
+ }
82
+ export function principalFromIdToken(idToken) {
83
+ const claims = decodeJwtPayload(idToken);
84
+ const entityUid = claims?.["custom:entityUid"];
85
+ if (typeof entityUid === "string" && entityUid.length > 0)
86
+ return entityUid;
87
+ return typeof claims?.sub === "string" && claims.sub.length > 0 ? claims.sub : null;
88
+ }
89
+ export function signedInPersonPrincipal(home, env) {
90
+ return principalFromIdToken(readTokenFile(personTokenCacheFile(home, env))?.idToken);
91
+ }
92
+ export function readCachedPersonUid(home, principal) {
93
+ const cached = readJsonRecord(personUidCachePath(home), PERSON_UID_CACHE_MAX_BYTES);
94
+ if (!cached || cached.principal !== principal || !isPersonUid(cached.personUid))
95
+ return null;
96
+ return cached.personUid;
97
+ }
98
+ export function rememberPersonUid(home, principal, personUid) {
99
+ if (!principal || !isPersonUid(personUid))
100
+ return;
101
+ try {
102
+ if (readCachedPersonUid(home, principal) !== personUid) {
103
+ writeJsonAtomic(personUidCachePath(home), { version: 1, principal, personUid });
104
+ }
105
+ fs.rmSync(personUidUnknownMarkerPath(home), { force: true });
106
+ }
107
+ catch {
108
+ return;
109
+ }
110
+ }
111
+ function noteUnknownOnce(home, reason, log) {
112
+ const marker = personUidUnknownMarkerPath(home);
113
+ if (readJsonRecord(marker, PERSON_UID_CACHE_MAX_BYTES)?.reason === reason)
114
+ return;
115
+ log(`reindex: transcripts of company-bound sessions are held on this computer until this account's person uid is known: ${reason}`);
116
+ try {
117
+ writeJsonAtomic(marker, { version: 1, reason });
118
+ }
119
+ catch {
120
+ return;
121
+ }
122
+ }
123
+ export async function resolveSessionPersonUid(deps) {
124
+ if (!deps.principal || isAgentPrincipal(deps.principal))
125
+ return null;
126
+ const cached = readCachedPersonUid(deps.home, deps.principal);
127
+ if (cached)
128
+ return cached;
129
+ if (!deps.fetchPersonUid) {
130
+ noteUnknownOnce(deps.home, "this account's person uid is not known yet (run `hq reindex` or `hq sync-core reconcile` once)", deps.log);
131
+ return null;
132
+ }
133
+ try {
134
+ const uid = await deps.fetchPersonUid();
135
+ if (isPersonUid(uid)) {
136
+ rememberPersonUid(deps.home, deps.principal, uid);
137
+ return uid;
138
+ }
139
+ noteUnknownOnce(deps.home, "this account has no person uid", deps.log);
140
+ }
141
+ catch (error) {
142
+ noteUnknownOnce(deps.home, `could not look up this account's person uid (${error instanceof Error ? error.message : String(error)})`, deps.log);
143
+ }
144
+ return null;
145
+ }
146
+ function companyYamlMarksCloud(hqRoot, slug) {
147
+ try {
148
+ return /^cloud:\s*true\b/m.test(fs.readFileSync(path.join(hqRoot, "companies", slug, "company.yaml"), "utf8"));
149
+ }
150
+ catch (error) {
151
+ return error.code !== "ENOENT";
152
+ }
153
+ }
154
+ function companyFolders(hqRoot) {
155
+ try {
156
+ return fs.readdirSync(path.join(hqRoot, "companies"), { withFileTypes: true })
157
+ .filter((entry) => entry.isDirectory())
158
+ .map((entry) => entry.name);
159
+ }
160
+ catch {
161
+ return [];
162
+ }
163
+ }
164
+ function rolloutCompanySlugs(home) {
165
+ try {
166
+ const state = readSyncCoreRolloutState(home);
167
+ return [...(state?.vaults ?? []), ...(state?.handingBack ?? [])]
168
+ .filter((vault) => vault.kind === "company" && vault.slug !== undefined)
169
+ .map((vault) => vault.slug);
170
+ }
171
+ catch {
172
+ return [];
173
+ }
174
+ }
175
+ export function cloudBackedCompanySlugs(hqRoot, home) {
176
+ const slugs = new Set();
177
+ for (const [slug, entry] of Object.entries(readCompaniesManifestMap(hqRoot) ?? {})) {
178
+ const uid = entry?.cloud_uid;
179
+ if (typeof uid === "string" && COMPANY_UID_PATTERN.test(uid))
180
+ slugs.add(slug);
181
+ }
182
+ if (home !== undefined)
183
+ for (const slug of rolloutCompanySlugs(home))
184
+ slugs.add(slug);
185
+ for (const slug of companyFolders(hqRoot)) {
186
+ if (!slugs.has(slug) && COMPANY_SLUG_PATTERN.test(slug) && companyYamlMarksCloud(hqRoot, slug))
187
+ slugs.add(slug);
188
+ }
189
+ const candidates = [...slugs].filter((slug) => COMPANY_SLUG_PATTERN.test(slug) && slug !== NON_CLOUD_COMPANY_SLUG);
190
+ const inPersonalVault = personalVaultScopeCheck(hqRoot, new Set(candidates));
191
+ return candidates.filter((slug) => !inPersonalVault(slug)).sort();
192
+ }
193
+ function personalVaultScopeCheck(hqRoot, teamSynced) {
194
+ return (slug) => {
195
+ try {
196
+ return isCompanyInPersonalVaultScope(hqRoot, slug, teamSynced);
197
+ }
198
+ catch {
199
+ return false;
200
+ }
201
+ };
202
+ }
203
+ export function confirmedUploadLedgerPath(home, vaultUid) {
204
+ return path.join(syncCoreEngineHome(home, vaultUid), ".hq", "sync-core", "state", "push-only-confirmed", `${vaultUid}.json`);
205
+ }
206
+ function realDirectoryChain(base, parts) {
207
+ let current = base;
208
+ for (const part of ["", ...parts]) {
209
+ current = part ? path.join(current, part) : current;
210
+ try {
211
+ const stat = fs.lstatSync(current);
212
+ if (stat.isSymbolicLink() || !stat.isDirectory())
213
+ return false;
214
+ }
215
+ catch {
216
+ return false;
217
+ }
218
+ }
219
+ return true;
220
+ }
221
+ function uploadRecord(value) {
222
+ if (!value || typeof value !== "object" || Array.isArray(value))
223
+ return null;
224
+ const entry = value;
225
+ const { sha256, size, confirmedAtMs } = entry;
226
+ if (typeof sha256 !== "string" || !SHA256_PATTERN.test(sha256))
227
+ return null;
228
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)
229
+ return null;
230
+ if (typeof confirmedAtMs !== "number" || !Number.isSafeInteger(confirmedAtMs) || confirmedAtMs <= 0)
231
+ return null;
232
+ return { sha256, size, confirmedAtMs };
233
+ }
234
+ export function readConfirmedUploads(home, vaultUid) {
235
+ const records = new Map();
236
+ if (!COMPANY_UID_PATTERN.test(vaultUid))
237
+ return records;
238
+ const engineHome = syncCoreEngineHome(home, vaultUid);
239
+ if (!realDirectoryChain(engineHome, [".hq", "sync-core", "state", "push-only-confirmed"]))
240
+ return records;
241
+ const ledger = readJsonRecord(confirmedUploadLedgerPath(home, vaultUid), CONFIRMED_UPLOAD_LEDGER_MAX_BYTES);
242
+ if (!ledger)
243
+ return records;
244
+ for (const [key, value] of Object.entries(ledger)) {
245
+ if (!key.startsWith(SESSIONS_PREFIX) || key.split("/").some((part) => part === "" || part === "." || part === ".."))
246
+ continue;
247
+ const record = uploadRecord(value);
248
+ if (record)
249
+ records.set(key, record);
250
+ }
251
+ return records;
252
+ }
253
+ export function engineUploadEvidence(home) {
254
+ const vaultBySlug = new Map();
255
+ try {
256
+ for (const vault of readSyncCoreRolloutState(home)?.vaults ?? []) {
257
+ if (vault.kind === "company" && vault.phase === "full" && vault.slug)
258
+ vaultBySlug.set(vault.slug, vault.uid);
259
+ }
260
+ }
261
+ catch {
262
+ vaultBySlug.clear();
263
+ }
264
+ const ledgers = new Map();
265
+ return (companySlug, vaultKey) => {
266
+ const uid = vaultBySlug.get(companySlug);
267
+ if (!uid)
268
+ return undefined;
269
+ let ledger = ledgers.get(uid);
270
+ if (!ledger) {
271
+ ledger = readConfirmedUploads(home, uid);
272
+ ledgers.set(uid, ledger);
273
+ }
274
+ return ledger.get(vaultKey) ?? ledger.get(vaultKey.normalize("NFC")) ?? null;
275
+ };
276
+ }
277
+ export function isAgentPrincipal(principal) {
278
+ return principal?.startsWith(AGENT_UID_PREFIX) === true;
279
+ }
280
+ export async function resolveCompanySessionOptions(deps) {
281
+ if (deps.agent === true || isAgentPrincipal(deps.principal))
282
+ return AGENT_COMPANY_SESSIONS;
283
+ try {
284
+ const personUid = await resolveSessionPersonUid(deps);
285
+ if (!personUid)
286
+ return undefined;
287
+ return {
288
+ personUid,
289
+ cloudCompanySlugs: cloudBackedCompanySlugs(deps.hqRoot, deps.home),
290
+ uploadEvidence: engineUploadEvidence(deps.home),
291
+ };
292
+ }
293
+ catch (error) {
294
+ deps.log(`reindex: could not route company session transcripts (${error instanceof Error ? error.message : String(error)})`);
295
+ return undefined;
296
+ }
297
+ }
298
+ export function withCompanySessions(options, companySessions) {
299
+ if (!companySessions)
300
+ return options;
301
+ const routed = { ...options, companySessions };
302
+ return routed;
303
+ }
304
+ //# sourceMappingURL=company-sessions.js.map
@@ -2,13 +2,26 @@
2
2
  * Process start times, used to tell the owner of a pid from a later process
3
3
  * that reused it (feedback cd56a501).
4
4
  */
5
+ import { spawnSync } from "node:child_process";
5
6
  import type { RefreshOwnerIdentity } from "./refresh-sync-handoff.js";
6
7
  /** Inputs for locating the system process tool; tests inject them. */
7
8
  export interface ProcessToolProbe {
8
9
  platform?: NodeJS.Platform;
9
10
  env?: NodeJS.ProcessEnv;
10
11
  isExecutable?: (file: string) => boolean;
12
+ spawn?: typeof spawnSync;
11
13
  }
14
+ export type ProcessStartFailureReason = "invalid-pid" | "tool-missing" | "timeout" | "failed";
15
+ export interface ProcessStartFailure {
16
+ pid: number;
17
+ reason: ProcessStartFailureReason;
18
+ tool?: string;
19
+ detail?: string;
20
+ }
21
+ /** Details of the most recent failed {@link processStartTime} call, or null if the last call succeeded. */
22
+ export declare function lastProcessStartFailure(): ProcessStartFailure | null;
23
+ /** Test seam: clear cached self start time and last failure state. */
24
+ export declare function resetProcessStartTimeCache(): void;
12
25
  /** The fixed POSIX locations of `ps`, tried in order. */
13
26
  export declare const POSIX_PS_PATHS: readonly string[];
14
27
  /**
@@ -5,6 +5,17 @@
5
5
  import { spawnSync } from "node:child_process";
6
6
  import * as fs from "node:fs";
7
7
  import * as path from "node:path";
8
+ let cachedSelfStart = null;
9
+ let lastFailure = null;
10
+ /** Details of the most recent failed {@link processStartTime} call, or null if the last call succeeded. */
11
+ export function lastProcessStartFailure() {
12
+ return lastFailure;
13
+ }
14
+ /** Test seam: clear cached self start time and last failure state. */
15
+ export function resetProcessStartTimeCache() {
16
+ cachedSelfStart = null;
17
+ lastFailure = null;
18
+ }
8
19
  /** The fixed POSIX locations of `ps`, tried in order. */
9
20
  export const POSIX_PS_PATHS = ["/bin/ps", "/usr/bin/ps"];
10
21
  function defaultIsExecutable(platform) {
@@ -47,25 +58,70 @@ export function processStartTool(probe = {}) {
47
58
  * null, which lock callers treat as busy.
48
59
  */
49
60
  export function processStartTime(pid, probe = {}) {
50
- if (!Number.isInteger(pid) || pid <= 0)
61
+ lastFailure = null;
62
+ const useCache = pid === process.pid &&
63
+ probe.platform === undefined &&
64
+ probe.env === undefined &&
65
+ probe.isExecutable === undefined &&
66
+ probe.spawn === undefined;
67
+ if (useCache && cachedSelfStart && cachedSelfStart.pid === process.pid) {
68
+ return cachedSelfStart.start;
69
+ }
70
+ if (!Number.isInteger(pid) || pid <= 0) {
71
+ lastFailure = { pid, reason: "invalid-pid", detail: "invalid process id" };
51
72
  return null;
73
+ }
74
+ const platform = probe.platform ?? process.platform;
52
75
  const tool = processStartTool(probe);
53
- if (!tool)
76
+ if (!tool) {
77
+ lastFailure = {
78
+ pid,
79
+ reason: "tool-missing",
80
+ detail: platform === "win32" ? "powershell.exe not found" : "ps not found",
81
+ };
54
82
  return null;
55
- const platform = probe.platform ?? process.platform;
83
+ }
84
+ const runSpawn = probe.spawn ?? spawnSync;
56
85
  try {
57
86
  const result = platform === "win32"
58
- ? spawnSync(tool, [
87
+ ? runSpawn(tool, [
59
88
  "-NoProfile",
60
89
  "-NonInteractive",
61
90
  "-Command",
62
91
  `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
63
92
  ], { encoding: "utf8", timeout: 10_000, windowsHide: true })
64
- : spawnSync(tool, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
93
+ : runSpawn(tool, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
65
94
  const text = (result.stdout ?? "").trim();
66
- return result.status === 0 && text ? text : null;
95
+ if (result.status === 0 && text) {
96
+ if (useCache)
97
+ cachedSelfStart = { pid: process.pid, start: text };
98
+ return text;
99
+ }
100
+ const errCode = result.error?.code;
101
+ if (errCode === "ETIMEDOUT") {
102
+ lastFailure = { pid, reason: "timeout", tool, detail: `${path.basename(tool)} timed out` };
103
+ }
104
+ else if (result.error) {
105
+ lastFailure = { pid, reason: "failed", tool, detail: errCode || result.error.message };
106
+ }
107
+ else {
108
+ lastFailure = {
109
+ pid,
110
+ reason: "failed",
111
+ tool,
112
+ detail: result.signal ? `signal ${result.signal}` : `exit ${result.status ?? "unknown"}`,
113
+ };
114
+ }
115
+ return null;
67
116
  }
68
- catch {
117
+ catch (error) {
118
+ const errCode = error?.code;
119
+ lastFailure = {
120
+ pid,
121
+ reason: "failed",
122
+ tool,
123
+ detail: errCode || (error instanceof Error ? error.message : String(error)),
124
+ };
69
125
  return null;
70
126
  }
71
127
  }