@indigoai-us/hq-cloud 6.11.15 → 6.11.16

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 (43) 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/context.d.ts +8 -2
  21. package/dist/context.d.ts.map +1 -1
  22. package/dist/context.js +16 -6
  23. package/dist/context.js.map +1 -1
  24. package/dist/skill-telemetry.d.ts +15 -0
  25. package/dist/skill-telemetry.d.ts.map +1 -1
  26. package/dist/skill-telemetry.js +34 -3
  27. package/dist/skill-telemetry.js.map +1 -1
  28. package/dist/skill-telemetry.test.js +75 -1
  29. package/dist/skill-telemetry.test.js.map +1 -1
  30. package/dist/vault-client.d.ts +16 -0
  31. package/dist/vault-client.d.ts.map +1 -1
  32. package/dist/vault-client.js +21 -0
  33. package/dist/vault-client.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/agent-codex-instructions.test.ts +332 -0
  36. package/src/agent-codex-instructions.ts +309 -0
  37. package/src/bin/sync-runner-planning.ts +34 -2
  38. package/src/bin/sync-runner.test.ts +413 -0
  39. package/src/bin/sync-runner.ts +53 -0
  40. package/src/context.ts +17 -6
  41. package/src/skill-telemetry.test.ts +94 -0
  42. package/src/skill-telemetry.ts +51 -3
  43. package/src/vault-client.ts +24 -0
@@ -0,0 +1,332 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
2
+ import * as fs from "fs";
3
+ import * as os from "os";
4
+ import * as path from "path";
5
+ import {
6
+ composeCodexAgentsMd,
7
+ orderCapabilityFiles,
8
+ gatherCodexAgentSections,
9
+ materializeCodexAgents,
10
+ codexHomeDir,
11
+ CODEX_AGENTS_MARKER,
12
+ AGENT_CONTRACT_FILE,
13
+ AGENTS_PROFILE_REL,
14
+ AGENT_CAPABILITIES_REL,
15
+ type CodexSection,
16
+ } from "./agent-codex-instructions.js";
17
+
18
+ describe("composeCodexAgentsMd (pure)", () => {
19
+ it("returns empty string for no sections", () => {
20
+ expect(composeCodexAgentsMd([])).toBe("");
21
+ });
22
+
23
+ it("returns empty string when every section is whitespace-only", () => {
24
+ const sections: CodexSection[] = [
25
+ { name: "a", content: " \n\t " },
26
+ { name: "b", content: "" },
27
+ ];
28
+ expect(composeCodexAgentsMd(sections)).toBe("");
29
+ });
30
+
31
+ it("emits the generated marker header then the joined body", () => {
32
+ const out = composeCodexAgentsMd([
33
+ { name: "profile", content: "I am the agent." },
34
+ { name: "contract", content: "Build your own tools." },
35
+ ]);
36
+ expect(out.startsWith(CODEX_AGENTS_MARKER)).toBe(true);
37
+ expect(out).toContain("I am the agent.");
38
+ expect(out).toContain("Build your own tools.");
39
+ // body sections separated by a blank line, trailing newline
40
+ expect(out).toContain("I am the agent.\n\nBuild your own tools.");
41
+ expect(out.endsWith("\n")).toBe(true);
42
+ });
43
+
44
+ it("trims sections and drops the empty ones", () => {
45
+ const out = composeCodexAgentsMd([
46
+ { name: "a", content: "\n\n kept \n\n" },
47
+ { name: "b", content: " " },
48
+ { name: "c", content: "also" },
49
+ ]);
50
+ expect(out).toContain("kept\n\nalso");
51
+ expect(out).not.toMatch(/ {2}kept/);
52
+ });
53
+
54
+ it("is deterministic / carries no timestamp (idempotent bytes)", () => {
55
+ const sections = [{ name: "x", content: "stable" }];
56
+ expect(composeCodexAgentsMd(sections)).toBe(composeCodexAgentsMd(sections));
57
+ });
58
+ });
59
+
60
+ describe("orderCapabilityFiles (pure)", () => {
61
+ it("orders the contract first, then the rest alphabetically", () => {
62
+ expect(
63
+ orderCapabilityFiles(["slack.md", "zeta.md", AGENT_CONTRACT_FILE, "alpha.md"]),
64
+ ).toEqual([AGENT_CONTRACT_FILE, "alpha.md", "slack.md", "zeta.md"]);
65
+ });
66
+
67
+ it("drops non-markdown entries", () => {
68
+ expect(
69
+ orderCapabilityFiles([AGENT_CONTRACT_FILE, "_seed-allowlist.yaml", "notes.txt", "x.md"]),
70
+ ).toEqual([AGENT_CONTRACT_FILE, "x.md"]);
71
+ });
72
+
73
+ it("handles a missing contract gracefully", () => {
74
+ expect(orderCapabilityFiles(["b.md", "a.md"])).toEqual(["a.md", "b.md"]);
75
+ });
76
+ });
77
+
78
+ describe("gatherCodexAgentSections + materializeCodexAgents (IO)", () => {
79
+ let hqRoot: string;
80
+ let codexHome: string;
81
+ const capDir = () => path.join(hqRoot, AGENT_CAPABILITIES_REL);
82
+
83
+ beforeEach(() => {
84
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), "hq-codex-test-"));
85
+ hqRoot = path.join(base, "hq");
86
+ codexHome = path.join(base, ".codex");
87
+ fs.mkdirSync(capDir(), { recursive: true });
88
+ });
89
+
90
+ afterEach(() => {
91
+ try {
92
+ fs.rmSync(path.dirname(hqRoot), { recursive: true, force: true });
93
+ } catch {
94
+ /* best-effort cleanup */
95
+ }
96
+ });
97
+
98
+ const seedProfile = (s: string) =>
99
+ fs.writeFileSync(path.join(hqRoot, AGENTS_PROFILE_REL), s);
100
+ const seedCap = (name: string, s: string) =>
101
+ fs.writeFileSync(path.join(capDir(), name), s);
102
+
103
+ it("gathers profile + contract + others in the right order", () => {
104
+ fs.mkdirSync(path.join(hqRoot, "personal"), { recursive: true });
105
+ seedProfile("PROFILE briefing");
106
+ seedCap("slack.md", "SLACK doc");
107
+ seedCap(AGENT_CONTRACT_FILE, "CONTRACT body");
108
+
109
+ const sections = gatherCodexAgentSections(hqRoot);
110
+ expect(sections.map((s) => s.name)).toEqual([
111
+ AGENTS_PROFILE_REL,
112
+ `${AGENT_CAPABILITIES_REL}/${AGENT_CONTRACT_FILE}`,
113
+ `${AGENT_CAPABILITIES_REL}/slack.md`,
114
+ ]);
115
+ });
116
+
117
+ it("writes ~/.codex/AGENTS.md with contract ahead of other capabilities", () => {
118
+ seedCap(AGENT_CONTRACT_FILE, "CONTRACT body");
119
+ seedCap("slack.md", "SLACK doc");
120
+
121
+ const res = materializeCodexAgents({ hqRoot, codexHome });
122
+ expect(res.written).toBe(true);
123
+ expect(res.sectionCount).toBe(2);
124
+
125
+ const written = fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8");
126
+ expect(written.startsWith(CODEX_AGENTS_MARKER)).toBe(true);
127
+ expect(written.indexOf("CONTRACT body")).toBeLessThan(
128
+ written.indexOf("SLACK doc"),
129
+ );
130
+ });
131
+
132
+ it("SKIPS (no write, no delete) when the overlay is empty — never destructive", () => {
133
+ // Pre-existing materialized file from a prior good sync.
134
+ fs.mkdirSync(codexHome, { recursive: true });
135
+ const existing = `${CODEX_AGENTS_MARKER} prior -->\n\nPRIOR CONTENT\n`;
136
+ fs.writeFileSync(path.join(codexHome, "AGENTS.md"), existing);
137
+
138
+ // Overlay is empty (transient unsynced tree).
139
+ const res = materializeCodexAgents({ hqRoot, codexHome });
140
+ expect(res.written).toBe(false);
141
+ expect(res.skippedReason).toBe("empty-overlay");
142
+ // The previously-materialized file is left intact.
143
+ expect(fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8")).toBe(
144
+ existing,
145
+ );
146
+ });
147
+
148
+ it("creates the codex home dir if missing", () => {
149
+ seedCap(AGENT_CONTRACT_FILE, "CONTRACT body");
150
+ expect(fs.existsSync(codexHome)).toBe(false);
151
+ const res = materializeCodexAgents({ hqRoot, codexHome });
152
+ expect(res.written).toBe(true);
153
+ expect(fs.existsSync(path.join(codexHome, "AGENTS.md"))).toBe(true);
154
+ });
155
+
156
+ it("is idempotent — two runs produce byte-identical output", () => {
157
+ seedCap(AGENT_CONTRACT_FILE, "CONTRACT body");
158
+ seedCap("slack.md", "SLACK doc");
159
+ materializeCodexAgents({ hqRoot, codexHome });
160
+ const first = fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8");
161
+ materializeCodexAgents({ hqRoot, codexHome });
162
+ const second = fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8");
163
+ expect(second).toBe(first);
164
+ });
165
+
166
+ it("never throws on an unreadable hq-root (returns error result)", () => {
167
+ const res = materializeCodexAgents({
168
+ hqRoot: path.join(hqRoot, "does-not-exist"),
169
+ codexHome,
170
+ });
171
+ expect(res.written).toBe(false);
172
+ // No capability dir → empty overlay → skip (not a hard error).
173
+ expect(res.skippedReason).toBe("empty-overlay");
174
+ });
175
+ });
176
+
177
+ describe("materializeCodexAgents — hardening (security + failure modes)", () => {
178
+ let base: string;
179
+ let hqRoot: string;
180
+ let codexHome: string;
181
+ const capDir = () => path.join(hqRoot, AGENT_CAPABILITIES_REL);
182
+
183
+ beforeEach(() => {
184
+ base = fs.mkdtempSync(path.join(os.tmpdir(), "hq-codex-harden-"));
185
+ hqRoot = path.join(base, "hq");
186
+ codexHome = path.join(base, ".codex");
187
+ fs.mkdirSync(capDir(), { recursive: true });
188
+ });
189
+ afterEach(() => {
190
+ vi.restoreAllMocks();
191
+ try {
192
+ fs.rmSync(base, { recursive: true, force: true });
193
+ } catch {
194
+ /* best-effort */
195
+ }
196
+ });
197
+
198
+ it("does NOT follow a symlinked capability file (no out-of-tree exfiltration)", () => {
199
+ // A secret outside the overlay; a symlink inside capDir pointing at it.
200
+ const secret = path.join(base, "secret.txt");
201
+ fs.writeFileSync(secret, "TOP-SECRET-CREDENTIAL");
202
+ fs.writeFileSync(path.join(capDir(), AGENT_CONTRACT_FILE), "CONTRACT body");
203
+ fs.symlinkSync(secret, path.join(capDir(), "escape.md"));
204
+
205
+ const sections = gatherCodexAgentSections(hqRoot);
206
+ // The symlink is skipped; only the real contract file is gathered.
207
+ expect(sections.map((s) => s.name)).toEqual([
208
+ `${AGENT_CAPABILITIES_REL}/${AGENT_CONTRACT_FILE}`,
209
+ ]);
210
+
211
+ const res = materializeCodexAgents({ hqRoot, codexHome });
212
+ const written = fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8");
213
+ expect(written).not.toContain("TOP-SECRET-CREDENTIAL");
214
+ expect(res.sectionCount).toBe(1);
215
+ });
216
+
217
+ it("skips a symlinked capability DIR (no descent through a symlinked capDir)", () => {
218
+ // Replace capDir with a symlink to an external dir containing a real .md.
219
+ const external = path.join(base, "external-caps");
220
+ fs.mkdirSync(external, { recursive: true });
221
+ fs.writeFileSync(path.join(external, AGENT_CONTRACT_FILE), "EXTERNAL body");
222
+ fs.rmSync(capDir(), { recursive: true, force: true });
223
+ fs.symlinkSync(external, capDir());
224
+
225
+ const sections = gatherCodexAgentSections(hqRoot);
226
+ expect(sections).toEqual([]);
227
+ });
228
+
229
+ it("refuses to clobber a SYMLINK target (preserves it; distinct skip reason)", () => {
230
+ fs.writeFileSync(path.join(capDir(), AGENT_CONTRACT_FILE), "CONTRACT body");
231
+ fs.mkdirSync(codexHome, { recursive: true });
232
+ const realTarget = path.join(base, "managed-agents.md");
233
+ fs.writeFileSync(realTarget, "MANAGED BY DOTFILES");
234
+ fs.symlinkSync(realTarget, path.join(codexHome, "AGENTS.md"));
235
+
236
+ const res = materializeCodexAgents({ hqRoot, codexHome });
237
+ expect(res.written).toBe(false);
238
+ expect(res.skippedReason).toBe("target-not-regular-file");
239
+ // The symlink is intact and still points at the managed file.
240
+ expect(fs.lstatSync(path.join(codexHome, "AGENTS.md")).isSymbolicLink()).toBe(
241
+ true,
242
+ );
243
+ expect(fs.readFileSync(realTarget, "utf8")).toBe("MANAGED BY DOTFILES");
244
+ });
245
+
246
+ it("refuses when the target is a DIRECTORY (no EISDIR crash, distinct reason)", () => {
247
+ fs.writeFileSync(path.join(capDir(), AGENT_CONTRACT_FILE), "CONTRACT body");
248
+ fs.mkdirSync(path.join(codexHome, "AGENTS.md"), { recursive: true });
249
+
250
+ const res = materializeCodexAgents({ hqRoot, codexHome });
251
+ expect(res.written).toBe(false);
252
+ expect(res.skippedReason).toBe("target-not-regular-file");
253
+ expect(fs.statSync(path.join(codexHome, "AGENTS.md")).isDirectory()).toBe(true);
254
+ });
255
+
256
+ it("returns an error result and leaves no .hq-tmp orphan when the write fails", () => {
257
+ // Root ignores mode bits, so this deterministic perms-based failure only
258
+ // holds for a non-root user (agent boxes + CI run non-root).
259
+ if (typeof process.getuid === "function" && process.getuid() === 0) return;
260
+ fs.writeFileSync(path.join(capDir(), AGENT_CONTRACT_FILE), "CONTRACT body");
261
+ // Read-only codex home → the temp write inside it fails (EACCES). The
262
+ // write+rename block's catch must unlink any temp before rethrowing, so no
263
+ // `*.hq-tmp` is left behind.
264
+ fs.mkdirSync(codexHome, { recursive: true });
265
+ fs.chmodSync(codexHome, 0o500);
266
+ try {
267
+ const res = materializeCodexAgents({ hqRoot, codexHome });
268
+ expect(res.written).toBe(false);
269
+ expect(res.skippedReason).toBe("error");
270
+ const leftovers = fs
271
+ .readdirSync(codexHome)
272
+ .filter((f) => f.endsWith(".hq-tmp"));
273
+ expect(leftovers).toEqual([]);
274
+ } finally {
275
+ fs.chmodSync(codexHome, 0o700); // restore so afterEach cleanup works
276
+ }
277
+ });
278
+
279
+ it("writes the file with owner-only perms (0o600)", () => {
280
+ fs.writeFileSync(path.join(capDir(), AGENT_CONTRACT_FILE), "CONTRACT body");
281
+ materializeCodexAgents({ hqRoot, codexHome });
282
+ const mode = fs.statSync(path.join(codexHome, "AGENTS.md")).mode & 0o777;
283
+ expect(mode).toBe(0o600);
284
+ });
285
+
286
+ it("emits a distinct event when the overlay is empty but a prior file exists", () => {
287
+ fs.mkdirSync(codexHome, { recursive: true });
288
+ fs.writeFileSync(path.join(codexHome, "AGENTS.md"), "PRIOR\n");
289
+ const events: string[] = [];
290
+ const res = materializeCodexAgents({
291
+ hqRoot, // capDir empty, no profile → empty overlay
292
+ codexHome,
293
+ log: (e) => events.push(e.event),
294
+ });
295
+ expect(res.skippedReason).toBe("empty-overlay");
296
+ expect(events).toContain(
297
+ "runner.agent_codex_instructions.skipped_empty_target_exists",
298
+ );
299
+ // Prior file left intact.
300
+ expect(fs.readFileSync(path.join(codexHome, "AGENTS.md"), "utf8")).toBe(
301
+ "PRIOR\n",
302
+ );
303
+ });
304
+ });
305
+
306
+ describe("codexHomeDir (CODEX_HOME validation)", () => {
307
+ const orig = process.env.CODEX_HOME;
308
+ afterEach(() => {
309
+ if (orig === undefined) delete process.env.CODEX_HOME;
310
+ else process.env.CODEX_HOME = orig;
311
+ });
312
+
313
+ it("defaults to ~/.codex when CODEX_HOME is unset", () => {
314
+ delete process.env.CODEX_HOME;
315
+ expect(codexHomeDir()).toBe(path.join(os.homedir(), ".codex"));
316
+ });
317
+
318
+ it("honors an absolute CODEX_HOME with no traversal", () => {
319
+ process.env.CODEX_HOME = "/var/lib/agent-codex";
320
+ expect(codexHomeDir()).toBe("/var/lib/agent-codex");
321
+ });
322
+
323
+ it("rejects a relative CODEX_HOME (falls back to ~/.codex)", () => {
324
+ process.env.CODEX_HOME = "relative/codex";
325
+ expect(codexHomeDir()).toBe(path.join(os.homedir(), ".codex"));
326
+ });
327
+
328
+ it("rejects a traversing CODEX_HOME (falls back to ~/.codex)", () => {
329
+ process.env.CODEX_HOME = "/tmp/../../etc";
330
+ expect(codexHomeDir()).toBe(path.join(os.homedir(), ".codex"));
331
+ });
332
+ });
@@ -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
+ }