@indigoai-us/hq-cloud 6.11.14 → 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 (64) hide show
  1. package/.github/workflows/ci.yml +1 -0
  2. package/.github/workflows/publish.yml +20 -64
  3. package/dist/agent-codex-instructions.d.ts +84 -0
  4. package/dist/agent-codex-instructions.d.ts.map +1 -0
  5. package/dist/agent-codex-instructions.js +275 -0
  6. package/dist/agent-codex-instructions.js.map +1 -0
  7. package/dist/agent-codex-instructions.test.d.ts +2 -0
  8. package/dist/agent-codex-instructions.test.d.ts.map +1 -0
  9. package/dist/agent-codex-instructions.test.js +271 -0
  10. package/dist/agent-codex-instructions.test.js.map +1 -0
  11. package/dist/bin/sync-runner-planning.d.ts +11 -0
  12. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  13. package/dist/bin/sync-runner-planning.js +19 -2
  14. package/dist/bin/sync-runner-planning.js.map +1 -1
  15. package/dist/bin/sync-runner-telemetry.d.ts +1 -0
  16. package/dist/bin/sync-runner-telemetry.d.ts.map +1 -1
  17. package/dist/bin/sync-runner-telemetry.js +8 -1
  18. package/dist/bin/sync-runner-telemetry.js.map +1 -1
  19. package/dist/bin/sync-runner.d.ts +20 -1
  20. package/dist/bin/sync-runner.d.ts.map +1 -1
  21. package/dist/bin/sync-runner.js +154 -9
  22. package/dist/bin/sync-runner.js.map +1 -1
  23. package/dist/bin/sync-runner.test.js +328 -0
  24. package/dist/bin/sync-runner.test.js.map +1 -1
  25. package/dist/cli/share.js +13 -9
  26. package/dist/cli/share.js.map +1 -1
  27. package/dist/cli/sync.d.ts.map +1 -1
  28. package/dist/cli/sync.js +24 -12
  29. package/dist/cli/sync.js.map +1 -1
  30. package/dist/cli/sync.test.js +16 -0
  31. package/dist/cli/sync.test.js.map +1 -1
  32. package/dist/context.d.ts +8 -2
  33. package/dist/context.d.ts.map +1 -1
  34. package/dist/context.js +16 -6
  35. package/dist/context.js.map +1 -1
  36. package/dist/qmd-reindex.d.ts +7 -0
  37. package/dist/qmd-reindex.d.ts.map +1 -1
  38. package/dist/qmd-reindex.js +12 -1
  39. package/dist/qmd-reindex.js.map +1 -1
  40. package/dist/skill-telemetry.d.ts +15 -0
  41. package/dist/skill-telemetry.d.ts.map +1 -1
  42. package/dist/skill-telemetry.js +34 -3
  43. package/dist/skill-telemetry.js.map +1 -1
  44. package/dist/skill-telemetry.test.js +75 -1
  45. package/dist/skill-telemetry.test.js.map +1 -1
  46. package/dist/vault-client.d.ts +16 -0
  47. package/dist/vault-client.d.ts.map +1 -1
  48. package/dist/vault-client.js +21 -0
  49. package/dist/vault-client.js.map +1 -1
  50. package/package.json +3 -1
  51. package/src/agent-codex-instructions.test.ts +332 -0
  52. package/src/agent-codex-instructions.ts +309 -0
  53. package/src/bin/sync-runner-planning.ts +34 -2
  54. package/src/bin/sync-runner-telemetry.ts +8 -1
  55. package/src/bin/sync-runner.test.ts +413 -0
  56. package/src/bin/sync-runner.ts +184 -7
  57. package/src/cli/share.ts +15 -9
  58. package/src/cli/sync.test.ts +17 -0
  59. package/src/cli/sync.ts +33 -12
  60. package/src/context.ts +17 -6
  61. package/src/qmd-reindex.ts +18 -1
  62. package/src/skill-telemetry.test.ts +94 -0
  63. package/src/skill-telemetry.ts +51 -3
  64. package/src/vault-client.ts +24 -0
@@ -18,6 +18,7 @@ jobs:
18
18
  node-version: "22"
19
19
  run-build: true
20
20
  run-lint: false
21
+ run-coverage: true
21
22
  secrets: inherit
22
23
 
23
24
  # ─────────────────────────────────────────────────────────────────────────
@@ -2,77 +2,33 @@ name: Publish to npm
2
2
  on:
3
3
  push:
4
4
  tags: ["v*"]
5
- # Manual trigger as a fallback when a tag push doesn't fire the workflow
6
- # (e.g. tag created via API, or `gh pr merge` attribution edge cases that
7
- # bypass Actions trigger). Pick the existing tag to publish — the
8
- # checkout step's `ref:` honors this input.
5
+ # Manual trigger: republish an existing tag (set `tag`, dry_run=false), or run
6
+ # a dry-run validation of the current branch (leave `tag` empty, dry_run=true).
9
7
  workflow_dispatch:
10
8
  inputs:
11
9
  tag:
12
- description: 'Tag to publish (e.g. v5.39.0). Must already exist.'
13
- required: true
10
+ description: "Tag to publish (e.g. v6.11.16). Must already exist. Empty = current ref."
11
+ required: false
14
12
  type: string
13
+ dry_run:
14
+ description: "Dry-run (validate build/pack without publishing)"
15
+ type: boolean
16
+ default: true
15
17
 
16
18
  jobs:
17
19
  publish:
18
- runs-on: ubuntu-latest
19
20
  permissions:
20
21
  contents: read
21
22
  id-token: write
22
- steps:
23
- - uses: actions/checkout@v4
24
- with:
25
- # On workflow_dispatch, checkout the input tag rather than the
26
- # branch the dispatch was launched from. On push events, this is
27
- # empty/unset → falls back to the tag that triggered the push.
28
- ref: ${{ inputs.tag || github.ref }}
29
- - uses: actions/setup-node@v4
30
- with:
31
- # Node 24 ships npm 11.x, required for npm's trusted-publisher OIDC
32
- # token-exchange flow. Node 22 ships npm 10.9.x, which signs sigstore
33
- # provenance via OIDC but cannot swap the OIDC token for a short-lived
34
- # publish token — the PUT then goes out unauthenticated and npm returns
35
- # a masked 404. Self-upgrading npm on top of npm 10 trips a known
36
- # promise-retry MODULE_NOT_FOUND bug during self-replacement; upgrading
37
- # the Node base avoids the whole class of failure.
38
- node-version: 24
39
- registry-url: https://registry.npmjs.org
40
-
41
- # pnpm via corepack (bundled with Node 24) instead of pnpm/action-setup —
42
- # the third-party action's codeload fetch is the first thing to break
43
- # when GitHub has partial-storage outages, and the OIDC publish flow
44
- # uses the npm CLI anyway. Corepack is a one-shell-line, zero-network
45
- # path off the pre-installed Node binary.
46
- - run: |
47
- corepack enable
48
- corepack prepare pnpm@10.33.2 --activate
49
- node --version && npm --version && pnpm --version
50
- # Install with pnpm (honors supply-chain min-release-age policy), but
51
- # publish with npm CLI (required for trusted-publisher OIDC flow).
52
- - run: pnpm install --frozen-lockfile --config.minimumReleaseAge=1440
53
- - run: pnpm run build
54
-
55
- # Publish via npm trusted publishing (OIDC). No NODE_AUTH_TOKEN — auth is
56
- # short-lived, minted from the GitHub OIDC identity token at runtime, and
57
- # scoped to this workflow by @indigoai-us/hq-cloud's trusted-publisher
58
- # config on npmjs.com.
59
- #
60
- # `--provenance` is intentionally omitted: npm's sigstore provenance
61
- # verifier refuses to attach provenance bundles produced from PRIVATE
62
- # GitHub repositories (HTTP 422 "Unsupported GitHub Actions source
63
- # repository visibility: 'private'") after npm tightened that check on
64
- # 2026-05-10. Trusted-publisher OIDC auth still works without provenance.
65
- #
66
- # Skip-if-published gate prevents the job from failing when the tag is
67
- # ahead of the package.json version (or when the version was already
68
- # shipped from somewhere else, e.g. the legacy hq monorepo before this
69
- # repo was extracted).
70
- - name: Publish to npm
71
- run: |
72
- NAME=$(jq -r .name package.json)
73
- VER=$(jq -r .version package.json)
74
- if npm view "$NAME@$VER" version >/dev/null 2>&1; then
75
- echo "$NAME@$VER already on npm — skipping"
76
- else
77
- npm publish --access public
78
- fi
23
+ uses: indigoai-us/.github/.github/workflows/_npm-publish.yml@main
24
+ with:
25
+ package-manager: pnpm
26
+ # Corepack (Node-bundled) pnpm no third-party action fetch, resilient to
27
+ # GitHub partial-storage outages. The npm CLI still drives the OIDC publish.
28
+ pnpm-setup: corepack
29
+ pnpm-version: "10.33.2"
30
+ node-version: "24"
31
+ build-command: "pnpm run build"
32
+ # On workflow_dispatch, honor the input tag; on tag push it is empty.
33
+ checkout-ref: ${{ inputs.tag || github.ref }}
34
+ dry-run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
@@ -0,0 +1,84 @@
1
+ /** hq-root-relative location of the (locally-written) agent identity briefing. */
2
+ export declare const AGENTS_PROFILE_REL = "personal/agents-profile.md";
3
+ /** hq-root-relative dir holding the synced agent-capability overlay docs. */
4
+ export declare const AGENT_CAPABILITIES_REL = "personal/knowledge/public/agent-capabilities";
5
+ /** The capability doc carrying the operating contract — ordered first. */
6
+ export declare const AGENT_CONTRACT_FILE = "hq-agent-contract.md";
7
+ /** Leading marker so the file is self-describing and recognizable as generated. */
8
+ export declare const CODEX_AGENTS_MARKER = "<!-- hq-agent: generated by hq-sync-runner";
9
+ export interface CodexSection {
10
+ /** hq-root-relative source path (for diagnostics; not written to the file). */
11
+ name: string;
12
+ content: string;
13
+ }
14
+ /**
15
+ * Pure: compose the codex global `AGENTS.md` body from ordered sections.
16
+ * Trims and drops empty/whitespace-only sections. Returns "" when nothing
17
+ * substantive remains, so the caller can SKIP the write (never emit an
18
+ * empty/marker-only file, never wipe a previously-materialized one).
19
+ *
20
+ * Deliberately carries NO timestamp: the output is a deterministic projection
21
+ * of its inputs, so a no-change sync rewrites byte-identical content (no churn;
22
+ * the write/skip/error events are timestamped in the diagnostic log instead).
23
+ */
24
+ export declare function composeCodexAgentsMd(sections: CodexSection[]): string;
25
+ /**
26
+ * Pure: order capability filenames — the operating contract first, then the
27
+ * remaining `*.md` alphabetically. Non-markdown entries are dropped.
28
+ */
29
+ export declare function orderCapabilityFiles(files: string[]): string[];
30
+ /**
31
+ * IO: gather the agent overlay sections present under `hqRoot`. Order:
32
+ * 1. identity briefing (`personal/agents-profile.md`)
33
+ * 2. the operating contract (`agent-capabilities/hq-agent-contract.md`)
34
+ * 3. any other `agent-capabilities/*.md`, alphabetically
35
+ * Each is included only when it is a regular file and non-whitespace-only.
36
+ * Symlinks and directories are skipped (containment / no symlink-escape).
37
+ */
38
+ export declare function gatherCodexAgentSections(hqRoot: string): CodexSection[];
39
+ export interface MaterializeLog {
40
+ (e: {
41
+ event: string;
42
+ message: string;
43
+ err?: unknown;
44
+ context?: Record<string, unknown>;
45
+ }): void;
46
+ }
47
+ export interface MaterializeResult {
48
+ written: boolean;
49
+ path: string;
50
+ sectionCount: number;
51
+ skippedReason?: "empty-overlay" | "target-not-regular-file" | "error";
52
+ }
53
+ /**
54
+ * Resolve the codex home dir. Honors `CODEX_HOME` only when it is an ABSOLUTE
55
+ * path with no `..` traversal; otherwise falls back to `~/.codex` (an injected
56
+ * relative/traversing value must not redirect the write off-target).
57
+ */
58
+ export declare function codexHomeDir(): string;
59
+ /**
60
+ * Best-effort: project the synced agent overlay into `~/.codex/AGENTS.md`.
61
+ * Idempotent atomic rewrite (write entropy-named temp + rename). NEVER throws —
62
+ * logs and returns a result.
63
+ *
64
+ * Non-destructive guarantees:
65
+ * - SKIPS (no write, no delete) when the overlay yields no content, so a
66
+ * transient empty/unsynced tree can never wipe a previously-materialized
67
+ * file. (Emits a distinct event when a prior file exists — a possible
68
+ * provisioning regression worth an operator's eye.)
69
+ * - SKIPS when the target already exists but is NOT a regular file (a symlink
70
+ * or directory), rather than silently clobbering an external config
71
+ * relationship (or failing opaquely with EISDIR).
72
+ * - On any write/rename failure, the entropy-named temp file is cleaned up so
73
+ * repeated failures can't accumulate `*.hq-tmp` orphans.
74
+ *
75
+ * First boot: before the first `--personal` sync lands, the overlay is absent
76
+ * and this skips — the agent operates on the project `AGENTS.md` (charter)
77
+ * alone until the first sync materializes the contract (~one cycle).
78
+ */
79
+ export declare function materializeCodexAgents(opts: {
80
+ hqRoot: string;
81
+ codexHome?: string;
82
+ log?: MaterializeLog;
83
+ }): MaterializeResult;
84
+ //# sourceMappingURL=agent-codex-instructions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-codex-instructions.d.ts","sourceRoot":"","sources":["../src/agent-codex-instructions.ts"],"names":[],"mappings":"AA6CA,kFAAkF;AAClF,eAAO,MAAM,kBAAkB,+BAA+B,CAAC;AAE/D,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB,iDACa,CAAC;AAEjD,0EAA0E;AAC1E,eAAO,MAAM,mBAAmB,yBAAyB,CAAC;AAE1D,mFAAmF;AACnF,eAAO,MAAM,mBAAmB,+CACc,CAAC;AAE/C,MAAM,WAAW,YAAY;IAC3B,+EAA+E;IAC/E,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,MAAM,CAWrE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAK9D;AA0BD;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,EAAE,CA6BvE;AAED,MAAM,WAAW,cAAc;IAC7B,CAAC,CAAC,EAAE;QACF,KAAK,EAAE,MAAM,CAAC;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,GAAG,CAAC,EAAE,OAAO,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACnC,GAAG,IAAI,CAAC;CACV;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,eAAe,GAAG,yBAAyB,GAAG,OAAO,CAAC;CACvE;AAED;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAMrC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,cAAc,CAAC;CACtB,GAAG,iBAAiB,CA6FpB"}
@@ -0,0 +1,275 @@
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
+ /** hq-root-relative location of the (locally-written) agent identity briefing. */
46
+ export const AGENTS_PROFILE_REL = "personal/agents-profile.md";
47
+ /** hq-root-relative dir holding the synced agent-capability overlay docs. */
48
+ export const AGENT_CAPABILITIES_REL = "personal/knowledge/public/agent-capabilities";
49
+ /** The capability doc carrying the operating contract — ordered first. */
50
+ export const AGENT_CONTRACT_FILE = "hq-agent-contract.md";
51
+ /** Leading marker so the file is self-describing and recognizable as generated. */
52
+ export const CODEX_AGENTS_MARKER = "<!-- hq-agent: generated by hq-sync-runner";
53
+ /**
54
+ * Pure: compose the codex global `AGENTS.md` body from ordered sections.
55
+ * Trims and drops empty/whitespace-only sections. Returns "" when nothing
56
+ * substantive remains, so the caller can SKIP the write (never emit an
57
+ * empty/marker-only file, never wipe a previously-materialized one).
58
+ *
59
+ * Deliberately carries NO timestamp: the output is a deterministic projection
60
+ * of its inputs, so a no-change sync rewrites byte-identical content (no churn;
61
+ * the write/skip/error events are timestamped in the diagnostic log instead).
62
+ */
63
+ export function composeCodexAgentsMd(sections) {
64
+ const body = sections
65
+ .map((s) => s.content.trim())
66
+ .filter((c) => c.length > 0)
67
+ .join("\n\n");
68
+ if (body.length === 0)
69
+ return "";
70
+ const header = `${CODEX_AGENTS_MARKER} from the synced HQ agent overlay. ` +
71
+ `Do not edit by hand — regenerated on every agent sync. ` +
72
+ `Source: ${AGENTS_PROFILE_REL} + ${AGENT_CAPABILITIES_REL}/*.md -->`;
73
+ return `${header}\n\n${body}\n`;
74
+ }
75
+ /**
76
+ * Pure: order capability filenames — the operating contract first, then the
77
+ * remaining `*.md` alphabetically. Non-markdown entries are dropped.
78
+ */
79
+ export function orderCapabilityFiles(files) {
80
+ const md = files.filter((f) => f.endsWith(".md")).sort();
81
+ const contractFirst = md.filter((f) => f === AGENT_CONTRACT_FILE);
82
+ const rest = md.filter((f) => f !== AGENT_CONTRACT_FILE);
83
+ return [...contractFirst, ...rest];
84
+ }
85
+ /** True iff `p` exists and is a REGULAR file (symlinks/dirs/etc. → false). */
86
+ function isRegularFile(p) {
87
+ try {
88
+ return fs.lstatSync(p).isFile();
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ /**
95
+ * Read `p` only when it is a regular file (best-effort, never throws). lstat
96
+ * gates the read so a symlink is never followed — a planted symlink in the
97
+ * overlay cannot exfiltrate an out-of-tree file into the materialized output.
98
+ */
99
+ function readRegularFileIfPresent(p) {
100
+ if (!isRegularFile(p))
101
+ return null;
102
+ try {
103
+ const s = fs.readFileSync(p, "utf8");
104
+ return s.trim().length > 0 ? s : null;
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /**
111
+ * IO: gather the agent overlay sections present under `hqRoot`. Order:
112
+ * 1. identity briefing (`personal/agents-profile.md`)
113
+ * 2. the operating contract (`agent-capabilities/hq-agent-contract.md`)
114
+ * 3. any other `agent-capabilities/*.md`, alphabetically
115
+ * Each is included only when it is a regular file and non-whitespace-only.
116
+ * Symlinks and directories are skipped (containment / no symlink-escape).
117
+ */
118
+ export function gatherCodexAgentSections(hqRoot) {
119
+ const sections = [];
120
+ const profile = readRegularFileIfPresent(path.join(hqRoot, AGENTS_PROFILE_REL));
121
+ if (profile)
122
+ sections.push({ name: AGENTS_PROFILE_REL, content: profile });
123
+ const capDir = path.join(hqRoot, AGENT_CAPABILITIES_REL);
124
+ // Reject a symlinked capability DIR (only descend into a real directory).
125
+ let capDirIsRealDir = false;
126
+ try {
127
+ capDirIsRealDir = fs.lstatSync(capDir).isDirectory();
128
+ }
129
+ catch {
130
+ capDirIsRealDir = false;
131
+ }
132
+ if (capDirIsRealDir) {
133
+ let entries = [];
134
+ try {
135
+ entries = fs.readdirSync(capDir);
136
+ }
137
+ catch {
138
+ entries = [];
139
+ }
140
+ for (const f of orderCapabilityFiles(entries)) {
141
+ const content = readRegularFileIfPresent(path.join(capDir, f));
142
+ if (content) {
143
+ sections.push({ name: `${AGENT_CAPABILITIES_REL}/${f}`, content });
144
+ }
145
+ }
146
+ }
147
+ return sections;
148
+ }
149
+ /**
150
+ * Resolve the codex home dir. Honors `CODEX_HOME` only when it is an ABSOLUTE
151
+ * path with no `..` traversal; otherwise falls back to `~/.codex` (an injected
152
+ * relative/traversing value must not redirect the write off-target).
153
+ */
154
+ export function codexHomeDir() {
155
+ const env = process.env.CODEX_HOME?.trim();
156
+ if (env && path.isAbsolute(env) && !env.split(path.sep).includes("..")) {
157
+ return env;
158
+ }
159
+ return path.join(os.homedir(), ".codex");
160
+ }
161
+ /**
162
+ * Best-effort: project the synced agent overlay into `~/.codex/AGENTS.md`.
163
+ * Idempotent atomic rewrite (write entropy-named temp + rename). NEVER throws —
164
+ * logs and returns a result.
165
+ *
166
+ * Non-destructive guarantees:
167
+ * - SKIPS (no write, no delete) when the overlay yields no content, so a
168
+ * transient empty/unsynced tree can never wipe a previously-materialized
169
+ * file. (Emits a distinct event when a prior file exists — a possible
170
+ * provisioning regression worth an operator's eye.)
171
+ * - SKIPS when the target already exists but is NOT a regular file (a symlink
172
+ * or directory), rather than silently clobbering an external config
173
+ * relationship (or failing opaquely with EISDIR).
174
+ * - On any write/rename failure, the entropy-named temp file is cleaned up so
175
+ * repeated failures can't accumulate `*.hq-tmp` orphans.
176
+ *
177
+ * First boot: before the first `--personal` sync lands, the overlay is absent
178
+ * and this skips — the agent operates on the project `AGENTS.md` (charter)
179
+ * alone until the first sync materializes the contract (~one cycle).
180
+ */
181
+ export function materializeCodexAgents(opts) {
182
+ const codexHome = opts.codexHome ?? codexHomeDir();
183
+ const target = path.join(codexHome, "AGENTS.md");
184
+ const log = opts.log ?? (() => { });
185
+ try {
186
+ const sections = gatherCodexAgentSections(opts.hqRoot);
187
+ const body = composeCodexAgentsMd(sections);
188
+ if (body.length === 0) {
189
+ const targetExists = (() => {
190
+ try {
191
+ fs.lstatSync(target);
192
+ return true;
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ })();
198
+ log({
199
+ // A pre-existing target + now-empty overlay is a likely regression
200
+ // (broken provisioning / seed), distinct from a clean first-boot skip.
201
+ event: targetExists
202
+ ? "runner.agent_codex_instructions.skipped_empty_target_exists"
203
+ : "runner.agent_codex_instructions.skipped",
204
+ message: "no agent overlay content found; leaving ~/.codex/AGENTS.md untouched",
205
+ context: { target, targetExists },
206
+ });
207
+ return {
208
+ written: false,
209
+ path: target,
210
+ sectionCount: 0,
211
+ skippedReason: "empty-overlay",
212
+ };
213
+ }
214
+ // Refuse to clobber a non-regular target (symlink / directory): preserve an
215
+ // external config relationship + surface EISDIR-class problems distinctly.
216
+ let targetStat = null;
217
+ try {
218
+ targetStat = fs.lstatSync(target);
219
+ }
220
+ catch {
221
+ targetStat = null; // absent — fine, we create it
222
+ }
223
+ if (targetStat && !targetStat.isFile()) {
224
+ log({
225
+ event: "runner.agent_codex_instructions.config_error",
226
+ message: "~/.codex/AGENTS.md exists but is not a regular file (symlink or directory); refusing to overwrite",
227
+ context: {
228
+ target,
229
+ isSymbolicLink: targetStat.isSymbolicLink(),
230
+ isDirectory: targetStat.isDirectory(),
231
+ },
232
+ });
233
+ return {
234
+ written: false,
235
+ path: target,
236
+ sectionCount: sections.length,
237
+ skippedReason: "target-not-regular-file",
238
+ };
239
+ }
240
+ fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
241
+ const tmp = `${target}.${process.pid}.${crypto
242
+ .randomBytes(6)
243
+ .toString("hex")}.hq-tmp`;
244
+ try {
245
+ fs.writeFileSync(tmp, body, { mode: 0o600 });
246
+ fs.renameSync(tmp, target);
247
+ }
248
+ catch (writeErr) {
249
+ // Clean up the orphaned temp so repeated failures don't accumulate.
250
+ try {
251
+ fs.unlinkSync(tmp);
252
+ }
253
+ catch {
254
+ /* best-effort */
255
+ }
256
+ throw writeErr;
257
+ }
258
+ log({
259
+ event: "runner.agent_codex_instructions.written",
260
+ message: `materialized codex global AGENTS.md from ${sections.length} overlay section(s)`,
261
+ context: { target, sectionCount: sections.length },
262
+ });
263
+ return { written: true, path: target, sectionCount: sections.length };
264
+ }
265
+ catch (err) {
266
+ log({
267
+ event: "runner.agent_codex_instructions.error",
268
+ message: "failed to materialize codex global AGENTS.md",
269
+ err,
270
+ context: { target },
271
+ });
272
+ return { written: false, path: target, sectionCount: 0, skippedReason: "error" };
273
+ }
274
+ }
275
+ //# sourceMappingURL=agent-codex-instructions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-codex-instructions.js","sourceRoot":"","sources":["../src/agent-codex-instructions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,kFAAkF;AAClF,MAAM,CAAC,MAAM,kBAAkB,GAAG,4BAA4B,CAAC;AAE/D,6EAA6E;AAC7E,MAAM,CAAC,MAAM,sBAAsB,GACjC,8CAA8C,CAAC;AAEjD,0EAA0E;AAC1E,MAAM,CAAC,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AAE1D,mFAAmF;AACnF,MAAM,CAAC,MAAM,mBAAmB,GAC9B,4CAA4C,CAAC;AAQ/C;;;;;;;;;GASG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAwB;IAC3D,MAAM,IAAI,GAAG,QAAQ;SAClB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;SAC3B,IAAI,CAAC,MAAM,CAAC,CAAC;IAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,MAAM,MAAM,GACV,GAAG,mBAAmB,qCAAqC;QAC3D,yDAAyD;QACzD,WAAW,kBAAkB,MAAM,sBAAsB,WAAW,CAAC;IACvE,OAAO,GAAG,MAAM,OAAO,IAAI,IAAI,CAAC;AAClC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OAAO,QAAQ,EAAE,CAAC;YAClB,oEAAoE;YACpE,IAAI,CAAC;gBACH,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YACrB,CAAC;YAAC,MAAM,CAAC;gBACP,iBAAiB;YACnB,CAAC;YACD,MAAM,QAAQ,CAAC;QACjB,CAAC;QACD,GAAG,CAAC;YACF,KAAK,EAAE,yCAAyC;YAChD,OAAO,EAAE,4CAA4C,QAAQ,CAAC,MAAM,qBAAqB;YACzF,OAAO,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,QAAQ,CAAC,MAAM,EAAE;SACnD,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACxE,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,GAAG,CAAC;YACF,KAAK,EAAE,uCAAuC;YAC9C,OAAO,EAAE,8CAA8C;YACvD,GAAG;YACH,OAAO,EAAE,EAAE,MAAM,EAAE;SACpB,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;IACnF,CAAC;AACH,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=agent-codex-instructions.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-codex-instructions.test.d.ts","sourceRoot":"","sources":["../src/agent-codex-instructions.test.ts"],"names":[],"mappings":""}