@indigoai-us/hq-cli 5.61.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.
- package/dist/commands/agents.d.ts +109 -0
- package/dist/commands/agents.js +385 -0
- package/dist/commands/db-migrate.d.ts +6 -0
- package/dist/commands/db-migrate.js +42 -0
- package/dist/commands/db-provision.d.ts +15 -0
- package/dist/commands/db-provision.js +78 -0
- package/dist/commands/db-sql.d.ts +9 -0
- package/dist/commands/db-sql.js +81 -0
- package/dist/commands/db-status.d.ts +7 -0
- package/dist/commands/db-status.js +70 -0
- package/dist/commands/db.d.ts +9 -0
- package/dist/commands/db.js +23 -0
- package/dist/commands/integrations.d.ts +78 -0
- package/dist/commands/integrations.js +309 -0
- package/dist/commands/members.js +4 -4
- package/dist/commands/outposts.d.ts +60 -0
- package/dist/commands/outposts.js +255 -0
- package/dist/commands/secrets.d.ts +8 -0
- package/dist/commands/secrets.js +23 -8
- package/dist/commands/skill.d.ts +153 -0
- package/dist/commands/skill.js +593 -0
- package/dist/commands/workers.d.ts +48 -0
- package/dist/commands/workers.js +229 -0
- package/dist/lib/db/control-plane.d.ts +45 -0
- package/dist/lib/db/control-plane.js +81 -0
- package/dist/lib/db/local.d.ts +49 -0
- package/dist/lib/db/local.js +106 -0
- package/dist/lib/db/migrate.d.ts +41 -0
- package/dist/lib/db/migrate.js +104 -0
- package/dist/lib/db/paths.d.ts +56 -0
- package/dist/lib/db/paths.js +103 -0
- package/dist/lib/db/remote-engine.d.ts +58 -0
- package/dist/lib/db/remote-engine.js +90 -0
- package/dist/lib/db/remote-sql.d.ts +22 -0
- package/dist/lib/db/remote-sql.js +39 -0
- package/dist/lib/db/sql.d.ts +49 -0
- package/dist/lib/db/sql.js +132 -0
- package/dist/main.js +27 -2
- package/dist/utils/cognito-session.js +3 -3
- package/dist/utils/sandbox-runner-client.js +3 -3
- package/package.json +9 -1
- package/pnpm-workspace.yaml +2 -0
- package/src/commands/agents.test.ts +297 -0
- package/src/commands/agents.ts +561 -0
- package/src/commands/db-migrate.ts +55 -0
- package/src/commands/db-provision.ts +102 -0
- package/src/commands/db-sql.ts +124 -0
- package/src/commands/db-status.ts +100 -0
- package/src/commands/db.ts +26 -0
- package/src/commands/integrations.test.ts +284 -0
- package/src/commands/integrations.ts +438 -0
- package/src/commands/members.ts +2 -2
- package/src/commands/outposts.test.ts +177 -0
- package/src/commands/outposts.ts +338 -0
- package/src/commands/secrets.parse-destination.test.ts +38 -0
- package/src/commands/secrets.test.ts +24 -0
- package/src/commands/secrets.ts +30 -10
- package/src/commands/skill.test.ts +770 -0
- package/src/commands/skill.ts +796 -0
- package/src/commands/workers.test.ts +158 -0
- package/src/commands/workers.ts +298 -0
- package/src/lib/db/control-plane.test.ts +59 -0
- package/src/lib/db/control-plane.ts +113 -0
- package/src/lib/db/local.test.ts +81 -0
- package/src/lib/db/local.ts +148 -0
- package/src/lib/db/migrate.test.ts +133 -0
- package/src/lib/db/migrate.ts +137 -0
- package/src/lib/db/paths.test.ts +112 -0
- package/src/lib/db/paths.ts +128 -0
- package/src/lib/db/remote-engine.test.ts +44 -0
- package/src/lib/db/remote-engine.ts +148 -0
- package/src/lib/db/remote-sql.test.ts +32 -0
- package/src/lib/db/remote-sql.ts +62 -0
- package/src/lib/db/sql.test.ts +106 -0
- package/src/lib/db/sql.ts +192 -0
- package/src/main.ts +31 -0
- package/src/utils/cognito-session.ts +1 -1
- package/src/utils/sandbox-runner-client.ts +1 -1
- package/test/commands/db-tenant-isolation.test.ts +94 -0
- package/test/commands/db.test.ts +85 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a4a2bf8b-0a33-57ba-a565-412a14132c99")}catch(e){}}();
|
|
3
|
+
import chalk from "chalk";
|
|
4
|
+
import * as fs from "fs";
|
|
5
|
+
import * as path from "path";
|
|
6
|
+
import * as yaml from "js-yaml";
|
|
7
|
+
import { ensureCognitoToken } from "../utils/cognito-session.js";
|
|
8
|
+
import { vaultApiFetch, getCompanyUid } from "./secrets.js";
|
|
9
|
+
import { GROUP_ID_PATTERN, EMAIL_PATTERN, normalizeFilePrefix } from "./_patterns.js";
|
|
10
|
+
import { findHqRoot } from "../utils/manifest.js";
|
|
11
|
+
/** Read + parse the worker registry. Empty array if it does not exist. */
|
|
12
|
+
export function readWorkerRegistry(hqRoot) {
|
|
13
|
+
const p = path.join(hqRoot, "core/workers/registry.yaml");
|
|
14
|
+
if (!fs.existsSync(p))
|
|
15
|
+
return [];
|
|
16
|
+
const doc = yaml.load(fs.readFileSync(p, "utf8"));
|
|
17
|
+
return doc?.workers ?? [];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Best-effort active company: workspace/sessions/.current -> meta.yaml
|
|
21
|
+
* company_slug. Undefined when no session context is set. Pure/read-only.
|
|
22
|
+
*/
|
|
23
|
+
export function resolveActiveCompany(hqRoot) {
|
|
24
|
+
try {
|
|
25
|
+
const currentFile = path.join(hqRoot, "workspace/sessions/.current");
|
|
26
|
+
const current = fs.readFileSync(currentFile, "utf8").trim();
|
|
27
|
+
if (!current)
|
|
28
|
+
return undefined;
|
|
29
|
+
const metaPath = path.join(hqRoot, "workspace/sessions", current, "meta.yaml");
|
|
30
|
+
if (!fs.existsSync(metaPath))
|
|
31
|
+
return undefined;
|
|
32
|
+
const meta = yaml.load(fs.readFileSync(metaPath, "utf8"));
|
|
33
|
+
const co = meta?.company_slug;
|
|
34
|
+
return typeof co === "string" && co ? co : undefined;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Membership-aware access filter for worker discovery: public workers always;
|
|
42
|
+
* company workers only for the active company. Mirrors the /run skill and the
|
|
43
|
+
* inject-worker-suggestion hook so all three surfaces agree.
|
|
44
|
+
*/
|
|
45
|
+
export function filterAccessibleWorkers(workers, activeCompany) {
|
|
46
|
+
return workers.filter((w) => {
|
|
47
|
+
if (w.visibility === "public")
|
|
48
|
+
return true;
|
|
49
|
+
if (!w.company)
|
|
50
|
+
return false;
|
|
51
|
+
return activeCompany !== undefined && w.company === activeCompany;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The company-relative vault prefix for a worker, e.g.
|
|
56
|
+
* companies/indigo/workers/deal-brain/ -> workers/deal-brain/. Returns null for
|
|
57
|
+
* a worker with no company (public/shared — not shareable via ACL).
|
|
58
|
+
*/
|
|
59
|
+
export function workerVaultPrefix(w) {
|
|
60
|
+
if (!w.company)
|
|
61
|
+
return null;
|
|
62
|
+
const companyRoot = `companies/${w.company}/`;
|
|
63
|
+
const rel = w.path.startsWith(companyRoot)
|
|
64
|
+
? w.path.slice(companyRoot.length)
|
|
65
|
+
: w.path;
|
|
66
|
+
return normalizeFilePrefix(rel);
|
|
67
|
+
}
|
|
68
|
+
/** Classify a share principal (@all | email | grp_*) — null when invalid. */
|
|
69
|
+
export function classifyPrincipal(principal) {
|
|
70
|
+
if (principal === "@all") {
|
|
71
|
+
return { granteeType: "company-wide", granteeId: "", label: "everyone in the company" };
|
|
72
|
+
}
|
|
73
|
+
if (EMAIL_PATTERN.test(principal)) {
|
|
74
|
+
const id = principal.trim().toLowerCase();
|
|
75
|
+
return { granteeType: "email", granteeId: id, label: id };
|
|
76
|
+
}
|
|
77
|
+
if (GROUP_ID_PATTERN.test(principal)) {
|
|
78
|
+
return { granteeType: "group", granteeId: principal, label: principal };
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Record a grant locally in the worker's tool-owned .grants.yaml sidecar. Kept
|
|
84
|
+
* out of worker.yaml so we never rewrite a hand-authored file; the registry
|
|
85
|
+
* generator unions this sidecar into the registry `grants:` field. Idempotent.
|
|
86
|
+
*/
|
|
87
|
+
export function writeGrantSidecar(hqRoot, workerPath, principalLabel) {
|
|
88
|
+
const dir = path.join(hqRoot, workerPath);
|
|
89
|
+
const sidecar = path.join(dir, ".grants.yaml");
|
|
90
|
+
let grants = [];
|
|
91
|
+
if (fs.existsSync(sidecar)) {
|
|
92
|
+
const doc = yaml.load(fs.readFileSync(sidecar, "utf8"));
|
|
93
|
+
if (Array.isArray(doc?.grants))
|
|
94
|
+
grants = doc.grants.filter((g) => typeof g === "string");
|
|
95
|
+
}
|
|
96
|
+
if (!grants.includes(principalLabel))
|
|
97
|
+
grants.push(principalLabel);
|
|
98
|
+
const header = "# Worker access grants — tool-owned, written by `hq workers share`.\n" +
|
|
99
|
+
"# Unioned into core/workers/registry.yaml `grants:` by the registry generator.\n";
|
|
100
|
+
fs.writeFileSync(sidecar, header + yaml.dump({ grants }), "utf8");
|
|
101
|
+
}
|
|
102
|
+
async function runWorkersShare(workerId, opts) {
|
|
103
|
+
const hqRoot = findHqRoot();
|
|
104
|
+
const worker = readWorkerRegistry(hqRoot).find((w) => w.id === workerId);
|
|
105
|
+
if (!worker) {
|
|
106
|
+
console.error(chalk.red(`Worker '${workerId}' not found in registry.`), "\nRun 'hq workers list' to see accessible workers.");
|
|
107
|
+
process.exit(1);
|
|
108
|
+
}
|
|
109
|
+
const prefix = workerVaultPrefix(worker);
|
|
110
|
+
if (!prefix) {
|
|
111
|
+
console.error(chalk.red(`'${workerId}' is a shared/public worker (visibility ${worker.visibility}).`), "\nPublic workers already ship to every HQ install — only company-scoped workers are shared with `hq workers share`.");
|
|
112
|
+
process.exit(1);
|
|
113
|
+
}
|
|
114
|
+
const permission = opts.permission ?? "read";
|
|
115
|
+
if (!["read", "write"].includes(permission)) {
|
|
116
|
+
console.error(chalk.red(`Invalid permission '${permission}': must be read or write`));
|
|
117
|
+
process.exit(1);
|
|
118
|
+
}
|
|
119
|
+
const classified = classifyPrincipal(opts.with);
|
|
120
|
+
if (!classified) {
|
|
121
|
+
console.error(chalk.red(`Invalid principal '${opts.with}': must be '@all', an email address, or a group id matching grp_<alphanumeric>`));
|
|
122
|
+
process.exit(1);
|
|
123
|
+
}
|
|
124
|
+
const companySlug = opts.company ?? worker.company;
|
|
125
|
+
const token = await ensureCognitoToken();
|
|
126
|
+
const companyUid = await getCompanyUid(token, companySlug);
|
|
127
|
+
const body = {
|
|
128
|
+
prefix,
|
|
129
|
+
granteeType: classified.granteeType,
|
|
130
|
+
granteeId: classified.granteeId,
|
|
131
|
+
permission,
|
|
132
|
+
};
|
|
133
|
+
let res = await vaultApiFetch({
|
|
134
|
+
token,
|
|
135
|
+
path: `/files/${encodeURIComponent(companyUid)}/acl/grant`,
|
|
136
|
+
method: "POST",
|
|
137
|
+
body,
|
|
138
|
+
});
|
|
139
|
+
// No ACL row for this prefix yet — auto-create one with this grant.
|
|
140
|
+
if (res.status === 404) {
|
|
141
|
+
res = await vaultApiFetch({
|
|
142
|
+
token,
|
|
143
|
+
path: `/files/${encodeURIComponent(companyUid)}/acl`,
|
|
144
|
+
method: "POST",
|
|
145
|
+
body: {
|
|
146
|
+
prefix,
|
|
147
|
+
entries: [
|
|
148
|
+
{
|
|
149
|
+
granteeType: classified.granteeType,
|
|
150
|
+
granteeId: classified.granteeId,
|
|
151
|
+
permission,
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
if (!res.ok) {
|
|
158
|
+
const text = await res.text().catch(() => "");
|
|
159
|
+
console.error(chalk.red(`Failed to share worker (HTTP ${res.status}). ${text}`));
|
|
160
|
+
process.exit(1);
|
|
161
|
+
}
|
|
162
|
+
writeGrantSidecar(hqRoot, worker.path, classified.label);
|
|
163
|
+
console.log(chalk.green("✓"), `Shared worker '${workerId}' with ${classified.label} (${permission}).`);
|
|
164
|
+
console.log(chalk.dim(` Vault prefix ${prefix} granted in company '${companySlug}'. It will sync to granted members and appear in their /run list.`));
|
|
165
|
+
}
|
|
166
|
+
function runWorkersList(opts) {
|
|
167
|
+
const hqRoot = findHqRoot();
|
|
168
|
+
const activeCompany = opts.company ?? resolveActiveCompany(hqRoot);
|
|
169
|
+
let workers = filterAccessibleWorkers(readWorkerRegistry(hqRoot), activeCompany);
|
|
170
|
+
if (opts.shared)
|
|
171
|
+
workers = workers.filter((w) => Boolean(w.grants && w.grants.trim()));
|
|
172
|
+
if (opts.mine)
|
|
173
|
+
workers = workers.filter((w) => Boolean(w.company) && w.company === activeCompany);
|
|
174
|
+
if (workers.length === 0) {
|
|
175
|
+
console.log("No accessible workers.");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const publicWorkers = workers.filter((w) => w.visibility === "public");
|
|
179
|
+
const companyWorkers = workers.filter((w) => w.visibility !== "public");
|
|
180
|
+
console.log(chalk.bold("Available Workers:"));
|
|
181
|
+
const printGroup = (title, list) => {
|
|
182
|
+
if (list.length === 0)
|
|
183
|
+
return;
|
|
184
|
+
console.log(`\n ${chalk.cyan(title)}:`);
|
|
185
|
+
for (const w of list.sort((a, b) => a.id.localeCompare(b.id))) {
|
|
186
|
+
const desc = (w.description ?? "").slice(0, 72);
|
|
187
|
+
const shared = w.grants && w.grants.trim() ? chalk.dim(` [shared: ${w.grants}]`) : "";
|
|
188
|
+
console.log(` ${w.id.padEnd(24)} ${desc}${shared}`);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
printGroup("Public", publicWorkers);
|
|
192
|
+
if (activeCompany)
|
|
193
|
+
printGroup(activeCompany, companyWorkers);
|
|
194
|
+
console.log(chalk.dim("\nUsage: hq run {worker-id} [skill] [args]"));
|
|
195
|
+
console.log(chalk.dim("Share a company worker: hq workers share {worker-id} --with {grp_<name>|@all} --permission read"));
|
|
196
|
+
}
|
|
197
|
+
export function registerWorkersCommand(program) {
|
|
198
|
+
const workers = program
|
|
199
|
+
.command("workers")
|
|
200
|
+
.description("Discover and share HQ workers")
|
|
201
|
+
.option("--company <slug>", "Company slug (resolves to companyUid)");
|
|
202
|
+
workers
|
|
203
|
+
.command("list")
|
|
204
|
+
.description("List workers you can access (public + your active company's)")
|
|
205
|
+
.option("--mine", "Only this company's workers")
|
|
206
|
+
.option("--shared", "Only workers that have been shared with someone")
|
|
207
|
+
.action((opts) => {
|
|
208
|
+
runWorkersList({ ...opts, company: workers.opts().company });
|
|
209
|
+
});
|
|
210
|
+
workers
|
|
211
|
+
.command("share <workerId>")
|
|
212
|
+
.description("Grant a teammate, group, or @all access to a company worker")
|
|
213
|
+
.requiredOption("--with <principal>", "Email address, group id (grp_<name>), or '@all' to share with every active company member")
|
|
214
|
+
.option("--permission <level>", "Permission level: read | write (default: read)")
|
|
215
|
+
.action(async (workerId, opts) => {
|
|
216
|
+
try {
|
|
217
|
+
await runWorkersShare(workerId, {
|
|
218
|
+
...opts,
|
|
219
|
+
company: workers.opts().company,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
console.error(chalk.red("Error:"), err instanceof Error ? err.message : String(err));
|
|
224
|
+
process.exit(1);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
//# sourceMappingURL=workers.js.map
|
|
229
|
+
//# debugId=a4a2bf8b-0a33-57ba-a565-412a14132c99
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control-plane client for remote vault DB (US-009).
|
|
3
|
+
* Injectable fetch for tests — never logs response bodies that might hold secrets.
|
|
4
|
+
*/
|
|
5
|
+
export interface RemoteProvisionResponse {
|
|
6
|
+
ok: boolean;
|
|
7
|
+
companyUid: string;
|
|
8
|
+
companySlug: string;
|
|
9
|
+
engineId: string;
|
|
10
|
+
resourceArn: string;
|
|
11
|
+
region: string;
|
|
12
|
+
status: string;
|
|
13
|
+
secretRef: string;
|
|
14
|
+
idempotent: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface RemoteStatusResponse {
|
|
17
|
+
companyUid: string;
|
|
18
|
+
companySlug?: string;
|
|
19
|
+
remote: {
|
|
20
|
+
engineId: string;
|
|
21
|
+
resourceArn: string;
|
|
22
|
+
region: string;
|
|
23
|
+
status: string;
|
|
24
|
+
secretRef: string;
|
|
25
|
+
} | null;
|
|
26
|
+
}
|
|
27
|
+
export interface ControlPlaneClientOptions {
|
|
28
|
+
baseUrl: string;
|
|
29
|
+
/** Bearer access token */
|
|
30
|
+
getAccessToken: () => Promise<string>;
|
|
31
|
+
fetchImpl?: typeof fetch;
|
|
32
|
+
}
|
|
33
|
+
export declare class ControlPlaneDbClient {
|
|
34
|
+
private readonly baseUrl;
|
|
35
|
+
private readonly getAccessToken;
|
|
36
|
+
private readonly fetchImpl;
|
|
37
|
+
constructor(opts: ControlPlaneClientOptions);
|
|
38
|
+
provision(input: {
|
|
39
|
+
companyUid: string;
|
|
40
|
+
companySlug: string;
|
|
41
|
+
region?: string;
|
|
42
|
+
}): Promise<RemoteProvisionResponse>;
|
|
43
|
+
status(companyUid: string): Promise<RemoteStatusResponse>;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=control-plane.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control-plane client for remote vault DB (US-009).
|
|
3
|
+
* Injectable fetch for tests — never logs response bodies that might hold secrets.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b2bf60fc-6b3a-5534-af8e-3b92b9518e29")}catch(e){}}();
|
|
7
|
+
function assertNoPostgresUrl(label, text) {
|
|
8
|
+
if (/postgres:\/\//i.test(text) || /postgresql:\/\//i.test(text)) {
|
|
9
|
+
throw new Error(`${label}: control plane returned a connection string (refusing to surface)`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class ControlPlaneDbClient {
|
|
13
|
+
baseUrl;
|
|
14
|
+
getAccessToken;
|
|
15
|
+
fetchImpl;
|
|
16
|
+
constructor(opts) {
|
|
17
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
18
|
+
this.getAccessToken = opts.getAccessToken;
|
|
19
|
+
this.fetchImpl = opts.fetchImpl ?? fetch;
|
|
20
|
+
}
|
|
21
|
+
async provision(input) {
|
|
22
|
+
const token = await this.getAccessToken();
|
|
23
|
+
const res = await this.fetchImpl(`${this.baseUrl}/v1/db/provision`, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: {
|
|
26
|
+
Authorization: `Bearer ${token}`,
|
|
27
|
+
"Content-Type": "application/json",
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify(input),
|
|
30
|
+
});
|
|
31
|
+
const text = await res.text();
|
|
32
|
+
assertNoPostgresUrl("provision", text);
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
let msg = `provision failed (${res.status})`;
|
|
35
|
+
let code;
|
|
36
|
+
try {
|
|
37
|
+
const j = JSON.parse(text);
|
|
38
|
+
if (j.error)
|
|
39
|
+
msg = j.error;
|
|
40
|
+
if (j.code)
|
|
41
|
+
code = j.code;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
/* keep */
|
|
45
|
+
}
|
|
46
|
+
const err = new Error(msg);
|
|
47
|
+
err.status = res.status;
|
|
48
|
+
if (code)
|
|
49
|
+
err.code = code;
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
return JSON.parse(text);
|
|
53
|
+
}
|
|
54
|
+
async status(companyUid) {
|
|
55
|
+
const token = await this.getAccessToken();
|
|
56
|
+
const url = `${this.baseUrl}/v1/db/status?companyUid=${encodeURIComponent(companyUid)}`;
|
|
57
|
+
const res = await this.fetchImpl(url, {
|
|
58
|
+
method: "GET",
|
|
59
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
60
|
+
});
|
|
61
|
+
const text = await res.text();
|
|
62
|
+
assertNoPostgresUrl("status", text);
|
|
63
|
+
if (!res.ok) {
|
|
64
|
+
let msg = `status failed (${res.status})`;
|
|
65
|
+
try {
|
|
66
|
+
const j = JSON.parse(text);
|
|
67
|
+
if (j.error)
|
|
68
|
+
msg = j.error;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
/* keep */
|
|
72
|
+
}
|
|
73
|
+
const err = new Error(msg);
|
|
74
|
+
err.status = res.status;
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
return JSON.parse(text);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=control-plane.js.map
|
|
81
|
+
//# debugId=b2bf60fc-6b3a-5534-af8e-3b92b9518e29
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local vault SQLite open/create (C1).
|
|
3
|
+
*
|
|
4
|
+
* File lives at ~/.hq/db/{company}/vault.db with WAL journal mode.
|
|
5
|
+
* Never returns or logs remote connection strings.
|
|
6
|
+
*/
|
|
7
|
+
import Database from "better-sqlite3";
|
|
8
|
+
import { type LocalDbPathEnv } from "./paths.js";
|
|
9
|
+
export type LocalDb = Database.Database;
|
|
10
|
+
export interface OpenLocalDbOptions extends LocalDbPathEnv {
|
|
11
|
+
/** When true, do not create the file if missing (throws). Default false. */
|
|
12
|
+
readonly?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface LocalDbStatus {
|
|
15
|
+
company: string;
|
|
16
|
+
tier: "local";
|
|
17
|
+
path: string;
|
|
18
|
+
exists: boolean;
|
|
19
|
+
healthy: boolean;
|
|
20
|
+
journalMode: string | null;
|
|
21
|
+
/** Migration ledger head when present; null if ledger not initialized. */
|
|
22
|
+
schemaVersion: string | null;
|
|
23
|
+
/** Fingerprint of path for logs that prefer not to echo full home paths. */
|
|
24
|
+
pathFingerprint: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Short non-reversible fingerprint of a path (for status display).
|
|
28
|
+
* Not a secret — just avoids dumping full home paths when preferred.
|
|
29
|
+
*/
|
|
30
|
+
export declare function fingerprintPath(filePath: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* Open (and create if missing) the company local vault DB with WAL mode.
|
|
33
|
+
* Idempotent: reopening an existing file does not recreate or wipe it.
|
|
34
|
+
*/
|
|
35
|
+
export declare function openLocalDb(companySlug: string, opts?: OpenLocalDbOptions): LocalDb;
|
|
36
|
+
/**
|
|
37
|
+
* Read migration head from platform ledger if the table exists.
|
|
38
|
+
*/
|
|
39
|
+
export declare function readMigrationHead(db: LocalDb): string | null;
|
|
40
|
+
/**
|
|
41
|
+
* Ensure local DB exists (create if needed), report status, close handle.
|
|
42
|
+
* Safe for CLI status: never includes connection strings.
|
|
43
|
+
*/
|
|
44
|
+
export declare function ensureAndStatusLocalDb(companySlug: string, opts?: LocalDbPathEnv): LocalDbStatus;
|
|
45
|
+
/**
|
|
46
|
+
* Format status for CLI stdout (no secrets).
|
|
47
|
+
*/
|
|
48
|
+
export declare function formatLocalDbStatus(status: LocalDbStatus): string;
|
|
49
|
+
//# sourceMappingURL=local.d.ts.map
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local vault SQLite open/create (C1).
|
|
3
|
+
*
|
|
4
|
+
* File lives at ~/.hq/db/{company}/vault.db with WAL journal mode.
|
|
5
|
+
* Never returns or logs remote connection strings.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3cf7d852-6ced-5521-a8de-8da889a5b97c")}catch(e){}}();
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import Database from "better-sqlite3";
|
|
11
|
+
import { ensureLocalDbDir, resolveLocalDbPath, } from "./paths.js";
|
|
12
|
+
const MIGRATIONS_TABLE = "hq_schema_migrations";
|
|
13
|
+
/**
|
|
14
|
+
* Short non-reversible fingerprint of a path (for status display).
|
|
15
|
+
* Not a secret — just avoids dumping full home paths when preferred.
|
|
16
|
+
*/
|
|
17
|
+
export function fingerprintPath(filePath) {
|
|
18
|
+
let h = 2166136261;
|
|
19
|
+
for (let i = 0; i < filePath.length; i++) {
|
|
20
|
+
h ^= filePath.charCodeAt(i);
|
|
21
|
+
h = Math.imul(h, 16777619);
|
|
22
|
+
}
|
|
23
|
+
return `fp_${(h >>> 0).toString(16).padStart(8, "0")}`;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Open (and create if missing) the company local vault DB with WAL mode.
|
|
27
|
+
* Idempotent: reopening an existing file does not recreate or wipe it.
|
|
28
|
+
*/
|
|
29
|
+
export function openLocalDb(companySlug, opts) {
|
|
30
|
+
const dbPath = resolveLocalDbPath(companySlug, opts);
|
|
31
|
+
const exists = fs.existsSync(dbPath);
|
|
32
|
+
if (!exists) {
|
|
33
|
+
if (opts?.readonly) {
|
|
34
|
+
throw new Error(`local vault DB not found for company ${JSON.stringify(companySlug)} at ${dbPath}`);
|
|
35
|
+
}
|
|
36
|
+
ensureLocalDbDir(companySlug, opts);
|
|
37
|
+
}
|
|
38
|
+
const db = new Database(dbPath);
|
|
39
|
+
// WAL for concurrent readers; safe for agent/CLI workloads.
|
|
40
|
+
db.pragma("journal_mode = WAL");
|
|
41
|
+
db.pragma("foreign_keys = ON");
|
|
42
|
+
return db;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Read migration head from platform ledger if the table exists.
|
|
46
|
+
*/
|
|
47
|
+
export function readMigrationHead(db) {
|
|
48
|
+
try {
|
|
49
|
+
const row = db
|
|
50
|
+
.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`)
|
|
51
|
+
.get(MIGRATIONS_TABLE);
|
|
52
|
+
if (!row?.name)
|
|
53
|
+
return null;
|
|
54
|
+
const head = db
|
|
55
|
+
.prepare(`SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version DESC LIMIT 1`)
|
|
56
|
+
.get();
|
|
57
|
+
return head?.version ?? null;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Ensure local DB exists (create if needed), report status, close handle.
|
|
65
|
+
* Safe for CLI status: never includes connection strings.
|
|
66
|
+
*/
|
|
67
|
+
export function ensureAndStatusLocalDb(companySlug, opts) {
|
|
68
|
+
const dbPath = resolveLocalDbPath(companySlug, opts);
|
|
69
|
+
const db = openLocalDb(companySlug, opts);
|
|
70
|
+
try {
|
|
71
|
+
const journalMode = String(db.pragma("journal_mode", { simple: true }));
|
|
72
|
+
const schemaVersion = readMigrationHead(db);
|
|
73
|
+
// Touch a trivial query to prove the handle is healthy.
|
|
74
|
+
db.prepare("SELECT 1 AS ok").get();
|
|
75
|
+
return {
|
|
76
|
+
company: companySlug.trim().toLowerCase(),
|
|
77
|
+
tier: "local",
|
|
78
|
+
path: dbPath,
|
|
79
|
+
exists: true,
|
|
80
|
+
healthy: true,
|
|
81
|
+
journalMode,
|
|
82
|
+
schemaVersion,
|
|
83
|
+
pathFingerprint: fingerprintPath(dbPath),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
db.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Format status for CLI stdout (no secrets).
|
|
92
|
+
*/
|
|
93
|
+
export function formatLocalDbStatus(status) {
|
|
94
|
+
const lines = [
|
|
95
|
+
`company: ${status.company}`,
|
|
96
|
+
`tier: ${status.tier}`,
|
|
97
|
+
`healthy: ${status.healthy ? "yes" : "no"}`,
|
|
98
|
+
`path: ${status.path}`,
|
|
99
|
+
`pathFingerprint: ${status.pathFingerprint}`,
|
|
100
|
+
`journalMode: ${status.journalMode ?? "unknown"}`,
|
|
101
|
+
`schemaVersion: ${status.schemaVersion ?? "(none)"}`,
|
|
102
|
+
];
|
|
103
|
+
return lines.join("\n");
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=local.js.map
|
|
106
|
+
//# debugId=3cf7d852-6ced-5521-a8de-8da889a5b97c
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
import type { LocalDb } from "./local.js";
|
|
9
|
+
import type { LocalDbPathEnv } from "./paths.js";
|
|
10
|
+
export declare const MIGRATIONS_TABLE = "hq_schema_migrations";
|
|
11
|
+
export interface MigrateOptions extends LocalDbPathEnv {
|
|
12
|
+
company: string;
|
|
13
|
+
/**
|
|
14
|
+
* Absolute path to HQ root containing companies/{co}/db/migrations.
|
|
15
|
+
* Required for vault-relative migrations.
|
|
16
|
+
*/
|
|
17
|
+
hqRoot: string;
|
|
18
|
+
}
|
|
19
|
+
export interface MigrateResult {
|
|
20
|
+
company: string;
|
|
21
|
+
migrationsDir: string;
|
|
22
|
+
applied: string[];
|
|
23
|
+
skipped: string[];
|
|
24
|
+
head: string | null;
|
|
25
|
+
}
|
|
26
|
+
export declare function resolveMigrationsDir(hqRoot: string, companySlug: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Ensure migrations directory exists (creates empty dir on first migrate).
|
|
29
|
+
*/
|
|
30
|
+
export declare function ensureMigrationsDir(hqRoot: string, companySlug: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* List pending migration files in lexical/version order (filename sort).
|
|
33
|
+
*/
|
|
34
|
+
export declare function listMigrationFiles(migrationsDir: string): string[];
|
|
35
|
+
export declare function ensureMigrationsLedger(db: LocalDb): void;
|
|
36
|
+
export declare function listAppliedVersions(db: LocalDb): Set<string>;
|
|
37
|
+
/**
|
|
38
|
+
* Apply pending migrations. On failure, does not mark the failed file applied.
|
|
39
|
+
*/
|
|
40
|
+
export declare function migrateLocalDb(opts: MigrateOptions): MigrateResult;
|
|
41
|
+
//# sourceMappingURL=migrate.d.ts.map
|
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d8abc231-bc36-5aad-a942-acbb0b86ea96")}catch(e){}}();
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { openLocalDb, readMigrationHead } from "./local.js";
|
|
13
|
+
import { normalizeCompanySlugForLocalDb } from "./paths.js";
|
|
14
|
+
export const MIGRATIONS_TABLE = "hq_schema_migrations";
|
|
15
|
+
export function resolveMigrationsDir(hqRoot, companySlug) {
|
|
16
|
+
const slug = normalizeCompanySlugForLocalDb(companySlug);
|
|
17
|
+
return path.join(hqRoot, "companies", slug, "db", "migrations");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Ensure migrations directory exists (creates empty dir on first migrate).
|
|
21
|
+
*/
|
|
22
|
+
export function ensureMigrationsDir(hqRoot, companySlug) {
|
|
23
|
+
const dir = resolveMigrationsDir(hqRoot, companySlug);
|
|
24
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* List pending migration files in lexical/version order (filename sort).
|
|
29
|
+
*/
|
|
30
|
+
export function listMigrationFiles(migrationsDir) {
|
|
31
|
+
if (!fs.existsSync(migrationsDir))
|
|
32
|
+
return [];
|
|
33
|
+
return fs
|
|
34
|
+
.readdirSync(migrationsDir)
|
|
35
|
+
.filter((f) => f.endsWith(".sql"))
|
|
36
|
+
.sort((a, b) => a.localeCompare(b, "en"));
|
|
37
|
+
}
|
|
38
|
+
export function ensureMigrationsLedger(db) {
|
|
39
|
+
db.exec(`
|
|
40
|
+
CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (
|
|
41
|
+
version TEXT PRIMARY KEY NOT NULL,
|
|
42
|
+
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
43
|
+
);
|
|
44
|
+
`);
|
|
45
|
+
}
|
|
46
|
+
export function listAppliedVersions(db) {
|
|
47
|
+
ensureMigrationsLedger(db);
|
|
48
|
+
const rows = db
|
|
49
|
+
.prepare(`SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version`)
|
|
50
|
+
.all();
|
|
51
|
+
return new Set(rows.map((r) => r.version));
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Apply pending migrations. On failure, does not mark the failed file applied.
|
|
55
|
+
*/
|
|
56
|
+
export function migrateLocalDb(opts) {
|
|
57
|
+
const company = normalizeCompanySlugForLocalDb(opts.company);
|
|
58
|
+
if (!opts.hqRoot?.trim()) {
|
|
59
|
+
throw new Error("hqRoot is required for vault migrations");
|
|
60
|
+
}
|
|
61
|
+
const migrationsDir = ensureMigrationsDir(opts.hqRoot, company);
|
|
62
|
+
const files = listMigrationFiles(migrationsDir);
|
|
63
|
+
const db = openLocalDb(company, opts);
|
|
64
|
+
const applied = [];
|
|
65
|
+
const skipped = [];
|
|
66
|
+
try {
|
|
67
|
+
ensureMigrationsLedger(db);
|
|
68
|
+
const already = listAppliedVersions(db);
|
|
69
|
+
for (const file of files) {
|
|
70
|
+
const version = file.replace(/\.sql$/i, "");
|
|
71
|
+
if (already.has(version) || already.has(file)) {
|
|
72
|
+
skipped.push(file);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const fullPath = path.join(migrationsDir, file);
|
|
76
|
+
const sql = fs.readFileSync(fullPath, "utf8");
|
|
77
|
+
const run = db.transaction(() => {
|
|
78
|
+
db.exec(sql);
|
|
79
|
+
db.prepare(`INSERT INTO ${MIGRATIONS_TABLE} (version) VALUES (?)`).run(version);
|
|
80
|
+
});
|
|
81
|
+
try {
|
|
82
|
+
run();
|
|
83
|
+
applied.push(file);
|
|
84
|
+
already.add(version);
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
88
|
+
throw new Error(`migration failed: ${file} — ${msg} (not marked applied)`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
company,
|
|
93
|
+
migrationsDir,
|
|
94
|
+
applied,
|
|
95
|
+
skipped,
|
|
96
|
+
head: readMigrationHead(db),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
db.close();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=migrate.js.map
|
|
104
|
+
//# debugId=d8abc231-bc36-5aad-a942-acbb0b86ea96
|