@indigoai-us/hq-cloud 6.11.15 → 6.11.17

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 (49) hide show
  1. package/.github/workflows/publish.yml +20 -64
  2. package/dist/agent-codex-instructions.d.ts +84 -0
  3. package/dist/agent-codex-instructions.d.ts.map +1 -0
  4. package/dist/agent-codex-instructions.js +275 -0
  5. package/dist/agent-codex-instructions.js.map +1 -0
  6. package/dist/agent-codex-instructions.test.d.ts +2 -0
  7. package/dist/agent-codex-instructions.test.d.ts.map +1 -0
  8. package/dist/agent-codex-instructions.test.js +271 -0
  9. package/dist/agent-codex-instructions.test.js.map +1 -0
  10. package/dist/bin/sync-runner-planning.d.ts +11 -0
  11. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  12. package/dist/bin/sync-runner-planning.js +19 -2
  13. package/dist/bin/sync-runner-planning.js.map +1 -1
  14. package/dist/bin/sync-runner.d.ts +11 -0
  15. package/dist/bin/sync-runner.d.ts.map +1 -1
  16. package/dist/bin/sync-runner.js +39 -0
  17. package/dist/bin/sync-runner.js.map +1 -1
  18. package/dist/bin/sync-runner.test.js +328 -0
  19. package/dist/bin/sync-runner.test.js.map +1 -1
  20. package/dist/cli/sync.js +12 -1
  21. package/dist/cli/sync.js.map +1 -1
  22. package/dist/cli/sync.test.js +44 -0
  23. package/dist/cli/sync.test.js.map +1 -1
  24. package/dist/context.d.ts +8 -2
  25. package/dist/context.d.ts.map +1 -1
  26. package/dist/context.js +16 -6
  27. package/dist/context.js.map +1 -1
  28. package/dist/skill-telemetry.d.ts +15 -0
  29. package/dist/skill-telemetry.d.ts.map +1 -1
  30. package/dist/skill-telemetry.js +34 -3
  31. package/dist/skill-telemetry.js.map +1 -1
  32. package/dist/skill-telemetry.test.js +75 -1
  33. package/dist/skill-telemetry.test.js.map +1 -1
  34. package/dist/vault-client.d.ts +16 -0
  35. package/dist/vault-client.d.ts.map +1 -1
  36. package/dist/vault-client.js +21 -0
  37. package/dist/vault-client.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/agent-codex-instructions.test.ts +332 -0
  40. package/src/agent-codex-instructions.ts +309 -0
  41. package/src/bin/sync-runner-planning.ts +34 -2
  42. package/src/bin/sync-runner.test.ts +413 -0
  43. package/src/bin/sync-runner.ts +53 -0
  44. package/src/cli/sync.test.ts +53 -0
  45. package/src/cli/sync.ts +14 -1
  46. package/src/context.ts +17 -6
  47. package/src/skill-telemetry.test.ts +94 -0
  48. package/src/skill-telemetry.ts +51 -3
  49. package/src/vault-client.ts +24 -0
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Agent codex-instructions materialization.
3
+ *
4
+ * Projects the synced HQ agent overlay into `~/.codex/AGENTS.md` — the codex
5
+ * GLOBAL instruction file, which `codex exec` natively merges on every run
6
+ * (alongside the project `AGENTS.md`, which on an HQ box symlinks to the
7
+ * `.claude/CLAUDE.md` charter). This is the codex mirror of how Claude reads
8
+ * `~/.claude/CLAUDE.md`: it carries the agent OPERATING CONTRACT (build your
9
+ * own tools, resolve credentials via group grants, follow team policy, the
10
+ * safety boundary) on top of the generic HQ charter.
11
+ *
12
+ * Why here (the sync runner), and why this file:
13
+ * - DURABLE: `~/.codex/AGENTS.md` lives OUTSIDE the hq-root, so `hq rescue`
14
+ * (`--hq-root`) and core upgrades never touch it. (In-tree `AGENTS.md` is
15
+ * classified regenerable and silently overwritten by rescue.)
16
+ * - SCALABLE: every agent box runs `@indigoai-us/hq-cloud@latest`
17
+ * `hq-sync-runner` each cycle, so shipping the projection here reaches the
18
+ * whole fleet — new and existing agents — with no reprovision or SSM push.
19
+ * - AGENT-ONLY: the caller gates on `custom:entityType === "agent"`, so a
20
+ * human running `hq sync` never materializes this file.
21
+ *
22
+ * Trust + isolation boundary (where it is actually enforced):
23
+ * - Tenant isolation is enforced UPSTREAM at the sync boundary: an agent's
24
+ * `--personal` sync resolves the agent's OWN vault (`pickAgentSelfEntity`,
25
+ * server-authorized by the agent's machine JWT). This function trusts that
26
+ * `hqRoot/personal/` was populated by that agent-scoped sync; it does not
27
+ * re-fetch entity membership (the gate claim is the SAME one the runner
28
+ * already trusts for `--personal` resolution; tampering it requires local
29
+ * compromise of the 0o600 token cache, i.e. the box is already owned).
30
+ * - DEFENCE-IN-DEPTH against a tampered local tree: every read is restricted
31
+ * to REGULAR files (symlinks/dirs are skipped), so a planted symlink in the
32
+ * overlay can't exfiltrate arbitrary files into `~/.codex/AGENTS.md`.
33
+ * - The projection NEVER reads release-shipped `core/` content — the charter
34
+ * reaches codex via the project `AGENTS.md` symlink, not this file.
35
+ *
36
+ * Deployment assumption: ONE agent identity per machine (the EC2 agent box
37
+ * model). `~/.codex/AGENTS.md` is a single, non-namespaced path; multiple agent
38
+ * identities sharing one OS home would last-write-wins. Not a concern in the
39
+ * one-agent-per-box fleet; revisit (per-agent namespacing) if that changes.
40
+ */
41
+ import * as crypto from "crypto";
42
+ import * as fs from "fs";
43
+ import * as os from "os";
44
+ import * as path from "path";
45
+
46
+ /** hq-root-relative location of the (locally-written) agent identity briefing. */
47
+ export const AGENTS_PROFILE_REL = "personal/agents-profile.md";
48
+
49
+ /** hq-root-relative dir holding the synced agent-capability overlay docs. */
50
+ export const AGENT_CAPABILITIES_REL =
51
+ "personal/knowledge/public/agent-capabilities";
52
+
53
+ /** The capability doc carrying the operating contract — ordered first. */
54
+ export const AGENT_CONTRACT_FILE = "hq-agent-contract.md";
55
+
56
+ /** Leading marker so the file is self-describing and recognizable as generated. */
57
+ export const CODEX_AGENTS_MARKER =
58
+ "<!-- hq-agent: generated by hq-sync-runner";
59
+
60
+ export interface CodexSection {
61
+ /** hq-root-relative source path (for diagnostics; not written to the file). */
62
+ name: string;
63
+ content: string;
64
+ }
65
+
66
+ /**
67
+ * Pure: compose the codex global `AGENTS.md` body from ordered sections.
68
+ * Trims and drops empty/whitespace-only sections. Returns "" when nothing
69
+ * substantive remains, so the caller can SKIP the write (never emit an
70
+ * empty/marker-only file, never wipe a previously-materialized one).
71
+ *
72
+ * Deliberately carries NO timestamp: the output is a deterministic projection
73
+ * of its inputs, so a no-change sync rewrites byte-identical content (no churn;
74
+ * the write/skip/error events are timestamped in the diagnostic log instead).
75
+ */
76
+ export function composeCodexAgentsMd(sections: CodexSection[]): string {
77
+ const body = sections
78
+ .map((s) => s.content.trim())
79
+ .filter((c) => c.length > 0)
80
+ .join("\n\n");
81
+ if (body.length === 0) return "";
82
+ const header =
83
+ `${CODEX_AGENTS_MARKER} from the synced HQ agent overlay. ` +
84
+ `Do not edit by hand — regenerated on every agent sync. ` +
85
+ `Source: ${AGENTS_PROFILE_REL} + ${AGENT_CAPABILITIES_REL}/*.md -->`;
86
+ return `${header}\n\n${body}\n`;
87
+ }
88
+
89
+ /**
90
+ * Pure: order capability filenames — the operating contract first, then the
91
+ * remaining `*.md` alphabetically. Non-markdown entries are dropped.
92
+ */
93
+ export function orderCapabilityFiles(files: string[]): string[] {
94
+ const md = files.filter((f) => f.endsWith(".md")).sort();
95
+ const contractFirst = md.filter((f) => f === AGENT_CONTRACT_FILE);
96
+ const rest = md.filter((f) => f !== AGENT_CONTRACT_FILE);
97
+ return [...contractFirst, ...rest];
98
+ }
99
+
100
+ /** True iff `p` exists and is a REGULAR file (symlinks/dirs/etc. → false). */
101
+ function isRegularFile(p: string): boolean {
102
+ try {
103
+ return fs.lstatSync(p).isFile();
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Read `p` only when it is a regular file (best-effort, never throws). lstat
111
+ * gates the read so a symlink is never followed — a planted symlink in the
112
+ * overlay cannot exfiltrate an out-of-tree file into the materialized output.
113
+ */
114
+ function readRegularFileIfPresent(p: string): string | null {
115
+ if (!isRegularFile(p)) return null;
116
+ try {
117
+ const s = fs.readFileSync(p, "utf8");
118
+ return s.trim().length > 0 ? s : null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * IO: gather the agent overlay sections present under `hqRoot`. Order:
126
+ * 1. identity briefing (`personal/agents-profile.md`)
127
+ * 2. the operating contract (`agent-capabilities/hq-agent-contract.md`)
128
+ * 3. any other `agent-capabilities/*.md`, alphabetically
129
+ * Each is included only when it is a regular file and non-whitespace-only.
130
+ * Symlinks and directories are skipped (containment / no symlink-escape).
131
+ */
132
+ export function gatherCodexAgentSections(hqRoot: string): CodexSection[] {
133
+ const sections: CodexSection[] = [];
134
+
135
+ const profile = readRegularFileIfPresent(path.join(hqRoot, AGENTS_PROFILE_REL));
136
+ if (profile) sections.push({ name: AGENTS_PROFILE_REL, content: profile });
137
+
138
+ const capDir = path.join(hqRoot, AGENT_CAPABILITIES_REL);
139
+ // Reject a symlinked capability DIR (only descend into a real directory).
140
+ let capDirIsRealDir = false;
141
+ try {
142
+ capDirIsRealDir = fs.lstatSync(capDir).isDirectory();
143
+ } catch {
144
+ capDirIsRealDir = false;
145
+ }
146
+ if (capDirIsRealDir) {
147
+ let entries: string[] = [];
148
+ try {
149
+ entries = fs.readdirSync(capDir);
150
+ } catch {
151
+ entries = [];
152
+ }
153
+ for (const f of orderCapabilityFiles(entries)) {
154
+ const content = readRegularFileIfPresent(path.join(capDir, f));
155
+ if (content) {
156
+ sections.push({ name: `${AGENT_CAPABILITIES_REL}/${f}`, content });
157
+ }
158
+ }
159
+ }
160
+ return sections;
161
+ }
162
+
163
+ export interface MaterializeLog {
164
+ (e: {
165
+ event: string;
166
+ message: string;
167
+ err?: unknown;
168
+ context?: Record<string, unknown>;
169
+ }): void;
170
+ }
171
+
172
+ export interface MaterializeResult {
173
+ written: boolean;
174
+ path: string;
175
+ sectionCount: number;
176
+ skippedReason?: "empty-overlay" | "target-not-regular-file" | "error";
177
+ }
178
+
179
+ /**
180
+ * Resolve the codex home dir. Honors `CODEX_HOME` only when it is an ABSOLUTE
181
+ * path with no `..` traversal; otherwise falls back to `~/.codex` (an injected
182
+ * relative/traversing value must not redirect the write off-target).
183
+ */
184
+ export function codexHomeDir(): string {
185
+ const env = process.env.CODEX_HOME?.trim();
186
+ if (env && path.isAbsolute(env) && !env.split(path.sep).includes("..")) {
187
+ return env;
188
+ }
189
+ return path.join(os.homedir(), ".codex");
190
+ }
191
+
192
+ /**
193
+ * Best-effort: project the synced agent overlay into `~/.codex/AGENTS.md`.
194
+ * Idempotent atomic rewrite (write entropy-named temp + rename). NEVER throws —
195
+ * logs and returns a result.
196
+ *
197
+ * Non-destructive guarantees:
198
+ * - SKIPS (no write, no delete) when the overlay yields no content, so a
199
+ * transient empty/unsynced tree can never wipe a previously-materialized
200
+ * file. (Emits a distinct event when a prior file exists — a possible
201
+ * provisioning regression worth an operator's eye.)
202
+ * - SKIPS when the target already exists but is NOT a regular file (a symlink
203
+ * or directory), rather than silently clobbering an external config
204
+ * relationship (or failing opaquely with EISDIR).
205
+ * - On any write/rename failure, the entropy-named temp file is cleaned up so
206
+ * repeated failures can't accumulate `*.hq-tmp` orphans.
207
+ *
208
+ * First boot: before the first `--personal` sync lands, the overlay is absent
209
+ * and this skips — the agent operates on the project `AGENTS.md` (charter)
210
+ * alone until the first sync materializes the contract (~one cycle).
211
+ */
212
+ export function materializeCodexAgents(opts: {
213
+ hqRoot: string;
214
+ codexHome?: string;
215
+ log?: MaterializeLog;
216
+ }): MaterializeResult {
217
+ const codexHome = opts.codexHome ?? codexHomeDir();
218
+ const target = path.join(codexHome, "AGENTS.md");
219
+ const log = opts.log ?? (() => {});
220
+ try {
221
+ const sections = gatherCodexAgentSections(opts.hqRoot);
222
+ const body = composeCodexAgentsMd(sections);
223
+
224
+ if (body.length === 0) {
225
+ const targetExists = (() => {
226
+ try {
227
+ fs.lstatSync(target);
228
+ return true;
229
+ } catch {
230
+ return false;
231
+ }
232
+ })();
233
+ log({
234
+ // A pre-existing target + now-empty overlay is a likely regression
235
+ // (broken provisioning / seed), distinct from a clean first-boot skip.
236
+ event: targetExists
237
+ ? "runner.agent_codex_instructions.skipped_empty_target_exists"
238
+ : "runner.agent_codex_instructions.skipped",
239
+ message:
240
+ "no agent overlay content found; leaving ~/.codex/AGENTS.md untouched",
241
+ context: { target, targetExists },
242
+ });
243
+ return {
244
+ written: false,
245
+ path: target,
246
+ sectionCount: 0,
247
+ skippedReason: "empty-overlay",
248
+ };
249
+ }
250
+
251
+ // Refuse to clobber a non-regular target (symlink / directory): preserve an
252
+ // external config relationship + surface EISDIR-class problems distinctly.
253
+ let targetStat: fs.Stats | null = null;
254
+ try {
255
+ targetStat = fs.lstatSync(target);
256
+ } catch {
257
+ targetStat = null; // absent — fine, we create it
258
+ }
259
+ if (targetStat && !targetStat.isFile()) {
260
+ log({
261
+ event: "runner.agent_codex_instructions.config_error",
262
+ message:
263
+ "~/.codex/AGENTS.md exists but is not a regular file (symlink or directory); refusing to overwrite",
264
+ context: {
265
+ target,
266
+ isSymbolicLink: targetStat.isSymbolicLink(),
267
+ isDirectory: targetStat.isDirectory(),
268
+ },
269
+ });
270
+ return {
271
+ written: false,
272
+ path: target,
273
+ sectionCount: sections.length,
274
+ skippedReason: "target-not-regular-file",
275
+ };
276
+ }
277
+
278
+ fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
279
+ const tmp = `${target}.${process.pid}.${crypto
280
+ .randomBytes(6)
281
+ .toString("hex")}.hq-tmp`;
282
+ try {
283
+ fs.writeFileSync(tmp, body, { mode: 0o600 });
284
+ fs.renameSync(tmp, target);
285
+ } catch (writeErr) {
286
+ // Clean up the orphaned temp so repeated failures don't accumulate.
287
+ try {
288
+ fs.unlinkSync(tmp);
289
+ } catch {
290
+ /* best-effort */
291
+ }
292
+ throw writeErr;
293
+ }
294
+ log({
295
+ event: "runner.agent_codex_instructions.written",
296
+ message: `materialized codex global AGENTS.md from ${sections.length} overlay section(s)`,
297
+ context: { target, sectionCount: sections.length },
298
+ });
299
+ return { written: true, path: target, sectionCount: sections.length };
300
+ } catch (err) {
301
+ log({
302
+ event: "runner.agent_codex_instructions.error",
303
+ message: "failed to materialize codex global AGENTS.md",
304
+ err,
305
+ context: { target },
306
+ });
307
+ return { written: false, path: target, sectionCount: 0, skippedReason: "error" };
308
+ }
309
+ }
@@ -1,5 +1,8 @@
1
1
  import type { Membership } from "../index.js";
2
- import { pickCanonicalPersonEntity } from "../vault-client.js";
2
+ import {
3
+ pickCanonicalPersonEntity,
4
+ pickAgentSelfEntity,
5
+ } from "../vault-client.js";
3
6
  import { PERSONAL_VAULT_JOURNAL_SLUG } from "../journal.js";
4
7
  import type { RunnerEvent, VaultClientSurface } from "./sync-runner.js";
5
8
 
@@ -9,6 +12,16 @@ interface IdentityClaims {
9
12
  name?: string;
10
13
  given_name?: string;
11
14
  family_name?: string;
15
+ /**
16
+ * Entity-bound machine-identity claims (US-013, unblocks US-004). A headless
17
+ * agent box authenticates with machine creds; its idToken carries the agent's
18
+ * own entity binding here. The `--personal` target resolver reads these to
19
+ * resolve the agent AS itself: when `custom:entityType === "agent"`, the
20
+ * personal slot resolves to the agent's OWN entity (`custom:entityUid`,
21
+ * `agt_*`) instead of the person-only canonical pick.
22
+ */
23
+ "custom:entityType"?: string;
24
+ "custom:entityUid"?: string;
12
25
  }
13
26
 
14
27
  export interface RunnerTarget {
@@ -72,6 +85,7 @@ export async function buildFanoutPlan(options: {
72
85
  personal: boolean;
73
86
  skipPersonal: boolean;
74
87
  client: VaultClientSurface;
88
+ claims: IdentityClaims | null;
75
89
  resolveSkipPersonal: (flag: boolean) => boolean;
76
90
  }): Promise<
77
91
  | { status: "setup-needed" }
@@ -95,8 +109,26 @@ export async function buildFanoutPlan(options: {
95
109
  (options.companies || options.personal) &&
96
110
  !options.resolveSkipPersonal(options.skipPersonal)
97
111
  ) {
112
+ // Self-entity listing. For a person identity this returns the caller's
113
+ // person entit(ies); for an agent machine identity (idToken
114
+ // `custom:entityType=agent`) the server scopes it to the agent's OWN
115
+ // entity (type: "agent"). `listByType("person")` is the same orphan-safe
116
+ // self-listing call in both cases — the server resolves the caller from
117
+ // the JWT, so an agent box gets back its own agt_ entity here.
98
118
  const persons = await options.client.entity.listByType("person");
99
- const pick = pickCanonicalPersonEntity(persons);
119
+
120
+ // Agent-aware target selection (US-013, unblocks US-004): when the runner
121
+ // is an agent machine identity, the person-only canonical pick drops the
122
+ // agent's own `type: "agent"` entity — so resolve the agent's OWN entity
123
+ // by its claimed self-uid instead. Falls back to the person-only pick for
124
+ // a person identity (or an agent whose self-entity didn't list), so the
125
+ // prs_* `--personal` path is unchanged.
126
+ const isAgentIdentity = options.claims?.["custom:entityType"] === "agent";
127
+ const agentSelfUid = options.claims?.["custom:entityUid"] ?? "";
128
+ const pick = isAgentIdentity
129
+ ? (pickAgentSelfEntity(persons, agentSelfUid) ??
130
+ pickCanonicalPersonEntity(persons))
131
+ : pickCanonicalPersonEntity(persons);
100
132
  if (pick?.bucketName) {
101
133
  plan.push({
102
134
  slug: "personal",