@indigoai-us/hq-cli 5.60.0 → 5.62.0

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 (98) hide show
  1. package/dist/commands/agents.d.ts +109 -0
  2. package/dist/commands/agents.js +385 -0
  3. package/dist/commands/db-migrate.d.ts +6 -0
  4. package/dist/commands/db-migrate.js +42 -0
  5. package/dist/commands/db-provision.d.ts +15 -0
  6. package/dist/commands/db-provision.js +78 -0
  7. package/dist/commands/db-sql.d.ts +9 -0
  8. package/dist/commands/db-sql.js +81 -0
  9. package/dist/commands/db-status.d.ts +7 -0
  10. package/dist/commands/db-status.js +70 -0
  11. package/dist/commands/db.d.ts +9 -0
  12. package/dist/commands/db.js +23 -0
  13. package/dist/commands/integrations.d.ts +78 -0
  14. package/dist/commands/integrations.js +309 -0
  15. package/dist/commands/members.js +4 -4
  16. package/dist/commands/outposts.d.ts +60 -0
  17. package/dist/commands/outposts.js +255 -0
  18. package/dist/commands/pack-install.d.ts +7 -1
  19. package/dist/commands/pack-install.js +86 -15
  20. package/dist/commands/packs.d.ts +2 -1
  21. package/dist/commands/packs.js +13 -8
  22. package/dist/commands/secrets.d.ts +13 -0
  23. package/dist/commands/secrets.js +149 -10
  24. package/dist/commands/skill.d.ts +153 -0
  25. package/dist/commands/skill.js +593 -0
  26. package/dist/commands/workers.d.ts +48 -0
  27. package/dist/commands/workers.js +229 -0
  28. package/dist/index.d.ts +5 -3
  29. package/dist/index.js +14 -240
  30. package/dist/lib/db/control-plane.d.ts +45 -0
  31. package/dist/lib/db/control-plane.js +81 -0
  32. package/dist/lib/db/local.d.ts +49 -0
  33. package/dist/lib/db/local.js +106 -0
  34. package/dist/lib/db/migrate.d.ts +41 -0
  35. package/dist/lib/db/migrate.js +104 -0
  36. package/dist/lib/db/paths.d.ts +56 -0
  37. package/dist/lib/db/paths.js +103 -0
  38. package/dist/lib/db/remote-engine.d.ts +58 -0
  39. package/dist/lib/db/remote-engine.js +90 -0
  40. package/dist/lib/db/remote-sql.d.ts +22 -0
  41. package/dist/lib/db/remote-sql.js +39 -0
  42. package/dist/lib/db/sql.d.ts +49 -0
  43. package/dist/lib/db/sql.js +132 -0
  44. package/dist/main.d.ts +7 -0
  45. package/dist/main.js +272 -0
  46. package/dist/utils/cognito-session.js +3 -3
  47. package/dist/utils/sandbox-runner-client.d.ts +13 -0
  48. package/dist/utils/sandbox-runner-client.js +83 -6
  49. package/dist/utils/version-check.d.ts +6 -0
  50. package/dist/utils/version-check.js +78 -2
  51. package/package.json +9 -1
  52. package/pnpm-workspace.yaml +2 -0
  53. package/src/commands/agents.test.ts +297 -0
  54. package/src/commands/agents.ts +561 -0
  55. package/src/commands/db-migrate.ts +55 -0
  56. package/src/commands/db-provision.ts +102 -0
  57. package/src/commands/db-sql.ts +124 -0
  58. package/src/commands/db-status.ts +100 -0
  59. package/src/commands/db.ts +26 -0
  60. package/src/commands/integrations.test.ts +284 -0
  61. package/src/commands/integrations.ts +438 -0
  62. package/src/commands/members.ts +2 -2
  63. package/src/commands/outposts.test.ts +177 -0
  64. package/src/commands/outposts.ts +338 -0
  65. package/src/commands/pack-install.ts +115 -18
  66. package/src/commands/pack-update-cache.test.ts +149 -0
  67. package/src/commands/packs.ts +28 -7
  68. package/src/commands/secrets.parse-destination.test.ts +38 -0
  69. package/src/commands/secrets.test.ts +342 -0
  70. package/src/commands/secrets.ts +227 -13
  71. package/src/commands/skill.test.ts +770 -0
  72. package/src/commands/skill.ts +796 -0
  73. package/src/commands/workers.test.ts +158 -0
  74. package/src/commands/workers.ts +298 -0
  75. package/src/index.test.ts +32 -0
  76. package/src/index.ts +11 -274
  77. package/src/lib/db/control-plane.test.ts +59 -0
  78. package/src/lib/db/control-plane.ts +113 -0
  79. package/src/lib/db/local.test.ts +81 -0
  80. package/src/lib/db/local.ts +148 -0
  81. package/src/lib/db/migrate.test.ts +133 -0
  82. package/src/lib/db/migrate.ts +137 -0
  83. package/src/lib/db/paths.test.ts +112 -0
  84. package/src/lib/db/paths.ts +128 -0
  85. package/src/lib/db/remote-engine.test.ts +44 -0
  86. package/src/lib/db/remote-engine.ts +148 -0
  87. package/src/lib/db/remote-sql.test.ts +32 -0
  88. package/src/lib/db/remote-sql.ts +62 -0
  89. package/src/lib/db/sql.test.ts +106 -0
  90. package/src/lib/db/sql.ts +192 -0
  91. package/src/main.ts +314 -0
  92. package/src/utils/cognito-session.ts +1 -1
  93. package/src/utils/sandbox-runner-client.test.ts +128 -0
  94. package/src/utils/sandbox-runner-client.ts +100 -4
  95. package/src/utils/version-check.test.ts +30 -0
  96. package/src/utils/version-check.ts +72 -0
  97. package/test/commands/db-tenant-isolation.test.ts +94 -0
  98. package/test/commands/db.test.ts +85 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Migration apply/idempotent/failure tests (vault-databases US-005).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ import { afterEach, describe, expect, it } from "vitest";
10
+
11
+ import { openLocalDb } from "./local.js";
12
+ import { migrateLocalDb, resolveMigrationsDir } from "./migrate.js";
13
+
14
+ const tempRoots: string[] = [];
15
+
16
+ function makeFixture(): { home: string; hqRoot: string } {
17
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "hq-db-migrate-"));
18
+ tempRoots.push(root);
19
+ const home = path.join(root, "home");
20
+ const hqRoot = path.join(root, "hq");
21
+ fs.mkdirSync(home, { recursive: true });
22
+ fs.mkdirSync(hqRoot, { recursive: true });
23
+ return { home, hqRoot };
24
+ }
25
+
26
+ function writeMigration(
27
+ hqRoot: string,
28
+ company: string,
29
+ name: string,
30
+ sql: string,
31
+ ): void {
32
+ const dir = resolveMigrationsDir(hqRoot, company);
33
+ fs.mkdirSync(dir, { recursive: true });
34
+ fs.writeFileSync(path.join(dir, name), sql, "utf8");
35
+ }
36
+
37
+ afterEach(() => {
38
+ while (tempRoots.length > 0) {
39
+ const dir = tempRoots.pop();
40
+ if (dir) fs.rmSync(dir, { recursive: true, force: true });
41
+ }
42
+ });
43
+
44
+ describe("migrateLocalDb", () => {
45
+ it("applies one migration and records ledger", () => {
46
+ const { home, hqRoot } = makeFixture();
47
+ writeMigration(
48
+ hqRoot,
49
+ "indigo",
50
+ "001_create_t.sql",
51
+ "CREATE TABLE t (id INTEGER PRIMARY KEY);",
52
+ );
53
+
54
+ const result = migrateLocalDb({ company: "indigo", home, hqRoot });
55
+ expect(result.applied).toEqual(["001_create_t.sql"]);
56
+ expect(result.head).toBe("001_create_t");
57
+
58
+ const db = openLocalDb("indigo", { home });
59
+ const row = db
60
+ .prepare(
61
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='t'",
62
+ )
63
+ .get() as { name: string };
64
+ expect(row.name).toBe("t");
65
+ db.close();
66
+ });
67
+
68
+ it("applies two migrations in order", () => {
69
+ const { home, hqRoot } = makeFixture();
70
+ writeMigration(
71
+ hqRoot,
72
+ "indigo",
73
+ "001_a.sql",
74
+ "CREATE TABLE a (id INTEGER PRIMARY KEY);",
75
+ );
76
+ writeMigration(
77
+ hqRoot,
78
+ "indigo",
79
+ "002_b.sql",
80
+ "CREATE TABLE b (id INTEGER PRIMARY KEY);",
81
+ );
82
+
83
+ const result = migrateLocalDb({ company: "indigo", home, hqRoot });
84
+ expect(result.applied).toEqual(["001_a.sql", "002_b.sql"]);
85
+ expect(result.head).toBe("002_b");
86
+ });
87
+
88
+ it("re-run is idempotent", () => {
89
+ const { home, hqRoot } = makeFixture();
90
+ writeMigration(
91
+ hqRoot,
92
+ "indigo",
93
+ "001_t.sql",
94
+ "CREATE TABLE t (id INTEGER PRIMARY KEY);",
95
+ );
96
+
97
+ migrateLocalDb({ company: "indigo", home, hqRoot });
98
+ const second = migrateLocalDb({ company: "indigo", home, hqRoot });
99
+ expect(second.applied).toEqual([]);
100
+ expect(second.skipped).toContain("001_t.sql");
101
+ expect(second.head).toBe("001_t");
102
+ });
103
+
104
+ it("failed migration is not marked applied", () => {
105
+ const { home, hqRoot } = makeFixture();
106
+ writeMigration(
107
+ hqRoot,
108
+ "indigo",
109
+ "001_ok.sql",
110
+ "CREATE TABLE ok (id INTEGER PRIMARY KEY);",
111
+ );
112
+ writeMigration(
113
+ hqRoot,
114
+ "indigo",
115
+ "002_bad.sql",
116
+ "CREATE TABLE ok (id INTEGER PRIMARY KEY);", // duplicate → fail
117
+ );
118
+
119
+ expect(() =>
120
+ migrateLocalDb({ company: "indigo", home, hqRoot }),
121
+ ).toThrow(/002_bad\.sql/);
122
+
123
+ const db = openLocalDb("indigo", { home });
124
+ const versions = db
125
+ .prepare("SELECT version FROM hq_schema_migrations ORDER BY version")
126
+ .all() as { version: string }[];
127
+ expect(versions.map((v) => v.version)).toEqual(["001_ok"]);
128
+ expect(
129
+ versions.map((v) => v.version).includes("002_bad"),
130
+ ).toBe(false);
131
+ db.close();
132
+ });
133
+ });
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Vault text migrations for local SQLite (vault-databases US-005).
3
+ *
4
+ * Migrations live as reviewable text under:
5
+ * companies/{company}/db/migrations/*.sql
6
+ * Applied versions are recorded in hq_schema_migrations inside the local DB.
7
+ */
8
+
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ import type { LocalDb } from "./local.js";
13
+ import { openLocalDb, readMigrationHead } from "./local.js";
14
+ import type { LocalDbPathEnv } from "./paths.js";
15
+ import { normalizeCompanySlugForLocalDb } from "./paths.js";
16
+
17
+ export const MIGRATIONS_TABLE = "hq_schema_migrations";
18
+
19
+ export interface MigrateOptions extends LocalDbPathEnv {
20
+ company: string;
21
+ /**
22
+ * Absolute path to HQ root containing companies/{co}/db/migrations.
23
+ * Required for vault-relative migrations.
24
+ */
25
+ hqRoot: string;
26
+ }
27
+
28
+ export interface MigrateResult {
29
+ company: string;
30
+ migrationsDir: string;
31
+ applied: string[];
32
+ skipped: string[];
33
+ head: string | null;
34
+ }
35
+
36
+ export function resolveMigrationsDir(hqRoot: string, companySlug: string): string {
37
+ const slug = normalizeCompanySlugForLocalDb(companySlug);
38
+ return path.join(hqRoot, "companies", slug, "db", "migrations");
39
+ }
40
+
41
+ /**
42
+ * Ensure migrations directory exists (creates empty dir on first migrate).
43
+ */
44
+ export function ensureMigrationsDir(hqRoot: string, companySlug: string): string {
45
+ const dir = resolveMigrationsDir(hqRoot, companySlug);
46
+ fs.mkdirSync(dir, { recursive: true });
47
+ return dir;
48
+ }
49
+
50
+ /**
51
+ * List pending migration files in lexical/version order (filename sort).
52
+ */
53
+ export function listMigrationFiles(migrationsDir: string): string[] {
54
+ if (!fs.existsSync(migrationsDir)) return [];
55
+ return fs
56
+ .readdirSync(migrationsDir)
57
+ .filter((f) => f.endsWith(".sql"))
58
+ .sort((a, b) => a.localeCompare(b, "en"));
59
+ }
60
+
61
+ export function ensureMigrationsLedger(db: LocalDb): void {
62
+ db.exec(`
63
+ CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (
64
+ version TEXT PRIMARY KEY NOT NULL,
65
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
66
+ );
67
+ `);
68
+ }
69
+
70
+ export function listAppliedVersions(db: LocalDb): Set<string> {
71
+ ensureMigrationsLedger(db);
72
+ const rows = db
73
+ .prepare(`SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version`)
74
+ .all() as { version: string }[];
75
+ return new Set(rows.map((r) => r.version));
76
+ }
77
+
78
+ /**
79
+ * Apply pending migrations. On failure, does not mark the failed file applied.
80
+ */
81
+ export function migrateLocalDb(opts: MigrateOptions): MigrateResult {
82
+ const company = normalizeCompanySlugForLocalDb(opts.company);
83
+ if (!opts.hqRoot?.trim()) {
84
+ throw new Error("hqRoot is required for vault migrations");
85
+ }
86
+
87
+ const migrationsDir = ensureMigrationsDir(opts.hqRoot, company);
88
+ const files = listMigrationFiles(migrationsDir);
89
+
90
+ const db = openLocalDb(company, opts);
91
+ const applied: string[] = [];
92
+ const skipped: string[] = [];
93
+
94
+ try {
95
+ ensureMigrationsLedger(db);
96
+ const already = listAppliedVersions(db);
97
+
98
+ for (const file of files) {
99
+ const version = file.replace(/\.sql$/i, "");
100
+ if (already.has(version) || already.has(file)) {
101
+ skipped.push(file);
102
+ continue;
103
+ }
104
+
105
+ const fullPath = path.join(migrationsDir, file);
106
+ const sql = fs.readFileSync(fullPath, "utf8");
107
+
108
+ const run = db.transaction(() => {
109
+ db.exec(sql);
110
+ db.prepare(
111
+ `INSERT INTO ${MIGRATIONS_TABLE} (version) VALUES (?)`,
112
+ ).run(version);
113
+ });
114
+
115
+ try {
116
+ run();
117
+ applied.push(file);
118
+ already.add(version);
119
+ } catch (err) {
120
+ const msg = err instanceof Error ? err.message : String(err);
121
+ throw new Error(
122
+ `migration failed: ${file} — ${msg} (not marked applied)`,
123
+ );
124
+ }
125
+ }
126
+
127
+ return {
128
+ company,
129
+ migrationsDir,
130
+ applied,
131
+ skipped,
132
+ head: readMigrationHead(db),
133
+ };
134
+ } finally {
135
+ db.close();
136
+ }
137
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Unit tests for local vault DB path helpers (vault-databases US-002).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ import { afterEach, describe, expect, it } from "vitest";
10
+
11
+ import {
12
+ LOCAL_DB_IGNORE_PATTERNS,
13
+ LOCAL_VAULT_DB_FILENAME,
14
+ describeLocalDbIgnoreRules,
15
+ ensureLocalDbDir,
16
+ normalizeCompanySlugForLocalDb,
17
+ resolveLocalDbDir,
18
+ resolveLocalDbPath,
19
+ resolveLocalDbRoot,
20
+ } from "./paths.js";
21
+
22
+ const tempHomes: string[] = [];
23
+
24
+ function makeTempHome(): string {
25
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-db-paths-"));
26
+ tempHomes.push(dir);
27
+ return dir;
28
+ }
29
+
30
+ afterEach(() => {
31
+ while (tempHomes.length > 0) {
32
+ const dir = tempHomes.pop();
33
+ if (dir) {
34
+ fs.rmSync(dir, { recursive: true, force: true });
35
+ }
36
+ }
37
+ });
38
+
39
+ describe("resolveLocalDbPath", () => {
40
+ it("resolves indigo under documented root ending with vault.db", () => {
41
+ const home = makeTempHome();
42
+ const p = resolveLocalDbPath("indigo", { home });
43
+ expect(p).toBe(path.join(home, ".hq", "db", "indigo", LOCAL_VAULT_DB_FILENAME));
44
+ expect(p.endsWith(path.join("indigo", "vault.db"))).toBe(true);
45
+ expect(p.startsWith(resolveLocalDbRoot({ home }))).toBe(true);
46
+ });
47
+
48
+ it("resolves a second company slug (acme) distinctly", () => {
49
+ const home = makeTempHome();
50
+ const indigo = resolveLocalDbPath("indigo", { home });
51
+ const acme = resolveLocalDbPath("acme", { home });
52
+ expect(acme).toBe(path.join(home, ".hq", "db", "acme", "vault.db"));
53
+ expect(indigo).not.toBe(acme);
54
+ expect(path.dirname(indigo)).not.toBe(path.dirname(acme));
55
+ });
56
+
57
+ it("normalizes slug casing to lowercase", () => {
58
+ const home = makeTempHome();
59
+ expect(resolveLocalDbPath("Indigo", { home })).toBe(
60
+ resolveLocalDbPath("indigo", { home }),
61
+ );
62
+ });
63
+ });
64
+
65
+ describe("normalizeCompanySlugForLocalDb", () => {
66
+ it("rejects empty and path-traversal slugs", () => {
67
+ expect(() => normalizeCompanySlugForLocalDb("")).toThrow(/required/i);
68
+ expect(() => normalizeCompanySlugForLocalDb("../etc")).toThrow(/invalid/i);
69
+ expect(() => normalizeCompanySlugForLocalDb("a/b")).toThrow(/invalid/i);
70
+ });
71
+ });
72
+
73
+ describe("ensureLocalDbDir", () => {
74
+ it("creates parent directories for a new company slug and is writable", () => {
75
+ const home = makeTempHome();
76
+ const dir = ensureLocalDbDir("newco", { home });
77
+ expect(fs.existsSync(dir)).toBe(true);
78
+ expect(fs.statSync(dir).isDirectory()).toBe(true);
79
+ // Writable: can create a probe file then remove it (no secrets left).
80
+ const probe = path.join(dir, ".write-probe");
81
+ fs.writeFileSync(probe, "ok", { mode: 0o600 });
82
+ expect(fs.readFileSync(probe, "utf8")).toBe("ok");
83
+ fs.unlinkSync(probe);
84
+ // Does not create the .db file itself.
85
+ expect(fs.existsSync(resolveLocalDbPath("newco", { home }))).toBe(false);
86
+ });
87
+
88
+ it("is idempotent when the directory already exists", () => {
89
+ const home = makeTempHome();
90
+ const first = ensureLocalDbDir("acme", { home });
91
+ const second = ensureLocalDbDir("acme", { home });
92
+ expect(first).toBe(second);
93
+ expect(fs.existsSync(first)).toBe(true);
94
+ });
95
+ });
96
+
97
+ describe("resolveLocalDbDir / ignore docs", () => {
98
+ it("dir is parent of vault.db path", () => {
99
+ const home = makeTempHome();
100
+ expect(resolveLocalDbDir("indigo", { home })).toBe(
101
+ path.dirname(resolveLocalDbPath("indigo", { home })),
102
+ );
103
+ });
104
+
105
+ it("documents *.db and .data ignore patterns", () => {
106
+ expect(LOCAL_DB_IGNORE_PATTERNS.some((p) => p.includes("*.db"))).toBe(true);
107
+ expect(LOCAL_DB_IGNORE_PATTERNS.some((p) => p.includes(".data"))).toBe(true);
108
+ const docs = describeLocalDbIgnoreRules();
109
+ expect(docs).toMatch(/\.hq\/db/);
110
+ expect(docs).toMatch(/\*\.db/);
111
+ });
112
+ });
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Vault database path conventions (C1 local tier).
3
+ *
4
+ * Canonical layout (locked by vault-databases PRD):
5
+ * ~/.hq/db/{companySlug}/vault.db
6
+ *
7
+ * Binary DB files are machine-local. They must never live under companies/
8
+ * so hq-sync / git cannot treat them as vault text. Migrations remain vault
9
+ * text at companies/{co}/db/migrations/*.sql (handled by migrate stories).
10
+ */
11
+
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ /** Default filename for the per-company local vault SQLite file. */
17
+ export const LOCAL_VAULT_DB_FILENAME = "vault.db";
18
+
19
+ /**
20
+ * Glob-style ignore patterns for binary / local DB artifacts.
21
+ * Apply in gitignore and hq-sync ignore configuration for any tree that
22
+ * might accidentally host these files. Primary storage is under ~/.hq/db/
23
+ * (outside the vault), but skills must still ignore stray `*.db` / `.data/`.
24
+ */
25
+ export const LOCAL_DB_IGNORE_PATTERNS: readonly string[] = [
26
+ "**/*.db",
27
+ "**/*.db-wal",
28
+ "**/*.db-shm",
29
+ "**/*.db-journal",
30
+ "**/.data/**",
31
+ // Explicit machine-local root (if a tool ever materializes a relative copy)
32
+ "**/.hq/db/**",
33
+ ];
34
+
35
+ export interface LocalDbPathEnv {
36
+ /** Override home directory (tests inject temp dirs). Defaults to os.homedir(). */
37
+ home?: string;
38
+ }
39
+
40
+ /**
41
+ * Resolve the machine-local root that holds all company vault DBs:
42
+ * `{home}/.hq/db`.
43
+ */
44
+ export function resolveLocalDbRoot(env?: LocalDbPathEnv): string {
45
+ const home = (env?.home ?? os.homedir()).trim();
46
+ if (!home) {
47
+ throw new Error(
48
+ "cannot resolve local DB root: home directory is empty (set home or os.homedir())",
49
+ );
50
+ }
51
+ return path.join(home, ".hq", "db");
52
+ }
53
+
54
+ /**
55
+ * Normalize and validate a company slug used in the local path.
56
+ * Tenant isolation still requires HQ identity/membership at the command layer;
57
+ * this only rejects empty / path-traversal slugs so we never open arbitrary paths.
58
+ */
59
+ export function normalizeCompanySlugForLocalDb(companySlug: string): string {
60
+ const slug = companySlug.trim().toLowerCase();
61
+ if (!slug) {
62
+ throw new Error("company slug is required for local DB path resolution");
63
+ }
64
+ if (
65
+ slug.includes("/") ||
66
+ slug.includes("\\") ||
67
+ slug.includes("..") ||
68
+ slug === "." ||
69
+ slug.includes("\0")
70
+ ) {
71
+ throw new Error(
72
+ `invalid company slug for local DB path: ${JSON.stringify(companySlug)}`,
73
+ );
74
+ }
75
+ return slug;
76
+ }
77
+
78
+ /**
79
+ * Canonical path for a company's local vault SQLite file:
80
+ * `~/.hq/db/{companySlug}/vault.db`.
81
+ */
82
+ export function resolveLocalDbPath(
83
+ companySlug: string,
84
+ env?: LocalDbPathEnv,
85
+ ): string {
86
+ const slug = normalizeCompanySlugForLocalDb(companySlug);
87
+ return path.join(resolveLocalDbRoot(env), slug, LOCAL_VAULT_DB_FILENAME);
88
+ }
89
+
90
+ /**
91
+ * Directory that contains the company's vault.db (and WAL side files).
92
+ */
93
+ export function resolveLocalDbDir(
94
+ companySlug: string,
95
+ env?: LocalDbPathEnv,
96
+ ): string {
97
+ return path.dirname(resolveLocalDbPath(companySlug, env));
98
+ }
99
+
100
+ /**
101
+ * Ensure the company local DB directory exists and is writable.
102
+ * Creates parent directories recursively. Does not create the .db file
103
+ * and does not write secrets into the tree.
104
+ *
105
+ * @returns absolute path of the directory
106
+ */
107
+ export function ensureLocalDbDir(
108
+ companySlug: string,
109
+ env?: LocalDbPathEnv,
110
+ ): string {
111
+ const dir = resolveLocalDbDir(companySlug, env);
112
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
113
+ // Verify writable without leaving secrets or DB content behind.
114
+ fs.accessSync(dir, fs.constants.W_OK);
115
+ return dir;
116
+ }
117
+
118
+ /**
119
+ * Human-readable documentation of ignore rules for operators and agents.
120
+ */
121
+ export function describeLocalDbIgnoreRules(): string {
122
+ return [
123
+ "Local vault databases live at ~/.hq/db/{company}/vault.db (outside the vault tree).",
124
+ "Never place *.db under companies/ — binary DB state is not vault-synced.",
125
+ "Ignore patterns:",
126
+ ...LOCAL_DB_IGNORE_PATTERNS.map((p) => ` - ${p}`),
127
+ ].join("\n");
128
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Remote engine registry + mock (vault-databases US-007).
3
+ */
4
+
5
+ import { beforeEach, describe, expect, it } from "vitest";
6
+
7
+ import {
8
+ _resetRemoteEngineRegistryForTests,
9
+ createMockRemoteEngine,
10
+ getRemoteEngine,
11
+ registerRemoteEngine,
12
+ } from "./remote-engine.js";
13
+
14
+ beforeEach(() => {
15
+ _resetRemoteEngineRegistryForTests();
16
+ });
17
+
18
+ describe("RemoteDbEngine mock", () => {
19
+ it("provision and healthCheck work without AWS", async () => {
20
+ const mock = createMockRemoteEngine("mock");
21
+ registerRemoteEngine(mock);
22
+
23
+ const engine = getRemoteEngine("mock");
24
+ const first = await engine.provision({
25
+ companyUid: "cmp_x",
26
+ companySlug: "x",
27
+ });
28
+ expect(first.status).toBe("ready");
29
+ expect(first.resourceArn).toContain("cmp_x");
30
+
31
+ const second = await engine.provision({
32
+ companyUid: "cmp_x",
33
+ companySlug: "x",
34
+ });
35
+ expect(second.status).toBe("existing");
36
+ expect(second.resourceArn).toBe(first.resourceArn);
37
+
38
+ const health = await engine.healthCheck(first.resourceArn);
39
+ expect(health.healthy).toBe(true);
40
+
41
+ // Secret payload must not be a printable postgres URL in mock either
42
+ expect(JSON.stringify(first.connectionSecret)).not.toMatch(/postgres:\/\//i);
43
+ });
44
+ });
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Pluggable remote vault DB engine interface (vault-databases US-007).
3
+ *
4
+ * Default shipped adapter id: aurora-dsql.
5
+ * This module is interface + registry only — no production AWS provision here.
6
+ */
7
+
8
+ /** Connection material written only to secrets stores — never CLI stdout. */
9
+ export interface RemoteConnectionSecretPayload {
10
+ /** Opaque secret body (e.g. JSON with host/user/password or IAM token recipe). */
11
+ payload: Record<string, unknown>;
12
+ /** Suggested vault/Secrets Manager key suffix (namespaced by company elsewhere). */
13
+ secretNameHint: string;
14
+ }
15
+
16
+ export interface RemoteProvisionRequest {
17
+ companyUid: string;
18
+ companySlug: string;
19
+ region?: string;
20
+ /** Engine-specific options (cluster params, etc.). */
21
+ options?: Record<string, unknown>;
22
+ }
23
+
24
+ export interface RemoteProvisionResult {
25
+ engineId: string;
26
+ resourceArn: string;
27
+ region: string;
28
+ status: "ready" | "provisioning" | "failed" | "existing";
29
+ /** Secret payload to store — callers must not print. */
30
+ connectionSecret: RemoteConnectionSecretPayload;
31
+ }
32
+
33
+ export interface RemoteHealth {
34
+ engineId: string;
35
+ resourceArn: string;
36
+ healthy: boolean;
37
+ status: string;
38
+ checkedAt: string;
39
+ }
40
+
41
+ /**
42
+ * Remote Postgres-class engine adapter.
43
+ * Implementations live in control plane (hq-pro) for real AWS; CLI may mock.
44
+ */
45
+ export interface RemoteDbEngine {
46
+ readonly id: string;
47
+ provision(req: RemoteProvisionRequest): Promise<RemoteProvisionResult>;
48
+ deprovision(companyUid: string, resourceArn: string): Promise<void>;
49
+ connectionSecretPayload(
50
+ companyUid: string,
51
+ resourceArn: string,
52
+ ): Promise<RemoteConnectionSecretPayload>;
53
+ healthCheck(resourceArn: string): Promise<RemoteHealth>;
54
+ }
55
+
56
+ /** Default engine selection (PRD decision). */
57
+ export const DEFAULT_REMOTE_ENGINE_ID = "aurora-dsql";
58
+
59
+ const registry = new Map<string, RemoteDbEngine>();
60
+
61
+ export function registerRemoteEngine(engine: RemoteDbEngine): void {
62
+ registry.set(engine.id, engine);
63
+ }
64
+
65
+ export function getRemoteEngine(id: string = DEFAULT_REMOTE_ENGINE_ID): RemoteDbEngine {
66
+ const engine = registry.get(id);
67
+ if (!engine) {
68
+ throw new Error(
69
+ `remote DB engine not registered: ${id} (available: ${[...registry.keys()].join(", ") || "none"})`,
70
+ );
71
+ }
72
+ return engine;
73
+ }
74
+
75
+ export function listRemoteEngineIds(): string[] {
76
+ return [...registry.keys()];
77
+ }
78
+
79
+ /** Clear registry (tests only). */
80
+ export function _resetRemoteEngineRegistryForTests(): void {
81
+ registry.clear();
82
+ }
83
+
84
+ /**
85
+ * In-memory mock engine for unit tests — no AWS.
86
+ */
87
+ export function createMockRemoteEngine(
88
+ id = "mock",
89
+ ): RemoteDbEngine {
90
+ const resources = new Map<string, { companyUid: string; region: string }>();
91
+
92
+ return {
93
+ id,
94
+ async provision(req) {
95
+ const existing = [...resources.entries()].find(
96
+ ([, v]) => v.companyUid === req.companyUid,
97
+ );
98
+ if (existing) {
99
+ const [arn, meta] = existing;
100
+ return {
101
+ engineId: id,
102
+ resourceArn: arn,
103
+ region: meta.region,
104
+ status: "existing",
105
+ connectionSecret: {
106
+ payload: { mock: true, companyUid: req.companyUid },
107
+ secretNameHint: `db/remote/${req.companySlug}`,
108
+ },
109
+ };
110
+ }
111
+ const arn = `arn:mock:db:${req.companyUid}`;
112
+ const region = req.region ?? "us-east-1";
113
+ resources.set(arn, { companyUid: req.companyUid, region });
114
+ return {
115
+ engineId: id,
116
+ resourceArn: arn,
117
+ region,
118
+ status: "ready",
119
+ connectionSecret: {
120
+ payload: { mock: true, companyUid: req.companyUid },
121
+ secretNameHint: `db/remote/${req.companySlug}`,
122
+ },
123
+ };
124
+ },
125
+ async deprovision(companyUid, resourceArn) {
126
+ const meta = resources.get(resourceArn);
127
+ if (meta && meta.companyUid === companyUid) {
128
+ resources.delete(resourceArn);
129
+ }
130
+ },
131
+ async connectionSecretPayload(companyUid, resourceArn) {
132
+ return {
133
+ payload: { mock: true, companyUid, resourceArn },
134
+ secretNameHint: `db/remote/${companyUid}`,
135
+ };
136
+ },
137
+ async healthCheck(resourceArn) {
138
+ const ok = resources.has(resourceArn);
139
+ return {
140
+ engineId: id,
141
+ resourceArn,
142
+ healthy: ok,
143
+ status: ok ? "ready" : "missing",
144
+ checkedAt: new Date().toISOString(),
145
+ };
146
+ },
147
+ };
148
+ }