@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.
Files changed (80) 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/secrets.d.ts +8 -0
  19. package/dist/commands/secrets.js +23 -8
  20. package/dist/commands/skill.d.ts +153 -0
  21. package/dist/commands/skill.js +593 -0
  22. package/dist/commands/workers.d.ts +48 -0
  23. package/dist/commands/workers.js +229 -0
  24. package/dist/lib/db/control-plane.d.ts +45 -0
  25. package/dist/lib/db/control-plane.js +81 -0
  26. package/dist/lib/db/local.d.ts +49 -0
  27. package/dist/lib/db/local.js +106 -0
  28. package/dist/lib/db/migrate.d.ts +41 -0
  29. package/dist/lib/db/migrate.js +104 -0
  30. package/dist/lib/db/paths.d.ts +56 -0
  31. package/dist/lib/db/paths.js +103 -0
  32. package/dist/lib/db/remote-engine.d.ts +58 -0
  33. package/dist/lib/db/remote-engine.js +90 -0
  34. package/dist/lib/db/remote-sql.d.ts +22 -0
  35. package/dist/lib/db/remote-sql.js +39 -0
  36. package/dist/lib/db/sql.d.ts +49 -0
  37. package/dist/lib/db/sql.js +132 -0
  38. package/dist/main.js +27 -2
  39. package/dist/utils/cognito-session.js +3 -3
  40. package/dist/utils/sandbox-runner-client.js +3 -3
  41. package/package.json +9 -1
  42. package/pnpm-workspace.yaml +2 -0
  43. package/src/commands/agents.test.ts +297 -0
  44. package/src/commands/agents.ts +561 -0
  45. package/src/commands/db-migrate.ts +55 -0
  46. package/src/commands/db-provision.ts +102 -0
  47. package/src/commands/db-sql.ts +124 -0
  48. package/src/commands/db-status.ts +100 -0
  49. package/src/commands/db.ts +26 -0
  50. package/src/commands/integrations.test.ts +284 -0
  51. package/src/commands/integrations.ts +438 -0
  52. package/src/commands/members.ts +2 -2
  53. package/src/commands/outposts.test.ts +177 -0
  54. package/src/commands/outposts.ts +338 -0
  55. package/src/commands/secrets.parse-destination.test.ts +38 -0
  56. package/src/commands/secrets.test.ts +24 -0
  57. package/src/commands/secrets.ts +30 -10
  58. package/src/commands/skill.test.ts +770 -0
  59. package/src/commands/skill.ts +796 -0
  60. package/src/commands/workers.test.ts +158 -0
  61. package/src/commands/workers.ts +298 -0
  62. package/src/lib/db/control-plane.test.ts +59 -0
  63. package/src/lib/db/control-plane.ts +113 -0
  64. package/src/lib/db/local.test.ts +81 -0
  65. package/src/lib/db/local.ts +148 -0
  66. package/src/lib/db/migrate.test.ts +133 -0
  67. package/src/lib/db/migrate.ts +137 -0
  68. package/src/lib/db/paths.test.ts +112 -0
  69. package/src/lib/db/paths.ts +128 -0
  70. package/src/lib/db/remote-engine.test.ts +44 -0
  71. package/src/lib/db/remote-engine.ts +148 -0
  72. package/src/lib/db/remote-sql.test.ts +32 -0
  73. package/src/lib/db/remote-sql.ts +62 -0
  74. package/src/lib/db/sql.test.ts +106 -0
  75. package/src/lib/db/sql.ts +192 -0
  76. package/src/main.ts +31 -0
  77. package/src/utils/cognito-session.ts +1 -1
  78. package/src/utils/sandbox-runner-client.ts +1 -1
  79. package/test/commands/db-tenant-isolation.test.ts +94 -0
  80. package/test/commands/db.test.ts +85 -0
@@ -0,0 +1,593 @@
1
+ /**
2
+ * `hq skill` subcommand group (US-017).
3
+ *
4
+ * Terminal / scriptable access to the skill collaboration loop:
5
+ *
6
+ * hq skill suggest <uid|path> Propose a change to a skill from working edits.
7
+ * hq skill list-suggestions Show the review inbox (suggestions on skills you own).
8
+ * hq skill review <sgn_…> Accept (merge) or decline a pending suggestion.
9
+ *
10
+ * This is a THIN front-end over the SAME wired hq-pro routes the MCP surface
11
+ * (US-007) and the console merge path (US-009) use — there is NO forked
12
+ * suggestion or merge logic here. The CLI reads the local working SKILL.md,
13
+ * computes the proposed content (+ its base for a diff), and POSTs to:
14
+ *
15
+ * CREATE POST /v1/files/skills/company/{slug}/{skillUid}/suggestions
16
+ * LIST POST /v1/files/skills/company/{slug}/suggestions/list
17
+ * ACCEPT POST /v1/files/skills/company/{slug}/{skillUid}/suggestions/{id}/accept
18
+ * DECLINE POST /v1/files/skills/company/{slug}/{skillUid}/suggestions/{id}/decline
19
+ *
20
+ * The skill routes are keyed on the company SLUG (path param, resolved
21
+ * server-side via findEntityBySlug) — NOT the companyUid the vault/ACL routes
22
+ * use — so this module resolves a slug (from `--company` or the active company)
23
+ * and passes it straight through.
24
+ *
25
+ * Lock semantics (AC3): a suggest against a skill the caller cannot WRITE still
26
+ * SUCCEEDS as a proposal. The CREATE route is MEMBER-gated (never write-gated),
27
+ * so this command performs NO client-side lock/permission pre-check — it always
28
+ * posts and renders whatever the server returns. A locked-out member lands a
29
+ * suggestion, never a hard permission error.
30
+ *
31
+ * Attribution (AC4): the invoking identity (from the Cognito JWT) is the server-
32
+ * derived `authorPersonUid`; the CLI never sends an author. An optional
33
+ * `--note` rides as `authorNote` (the change's rationale / failure context).
34
+ */
35
+
36
+ !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]="5bdf8a18-3088-5615-b596-9be2c9fdb5cc")}catch(e){}}();
37
+ import * as fs from "node:fs";
38
+ import * as path from "node:path";
39
+ import { createHash } from "node:crypto";
40
+ import chalk from "chalk";
41
+ import yaml from "js-yaml";
42
+ import simpleGit from "simple-git";
43
+ import { ensureCognitoToken, DEFAULT_HQ_ROOT } from "../utils/cognito-session.js";
44
+ import { vaultApiFetch } from "../utils/vault-api.js";
45
+ // ---------------------------------------------------------------------------
46
+ // Patterns
47
+ // ---------------------------------------------------------------------------
48
+ /**
49
+ * A `skl_…` argument to `suggest` is a skill UID (resolve the local file from
50
+ * it); anything else is a filesystem path. Lenient on the suffix (the strict
51
+ * `skl_<ulid>` shape is `isSkillUid` on the server) so a hand-typed / fixture
52
+ * uid still routes to the uid branch.
53
+ */
54
+ export const SKILL_UID_PATTERN = /^skl_[A-Za-z0-9]+$/;
55
+ /** A `sgn_…` suggestion id — the `review` target and the LIST row key. */
56
+ export const SUGGESTION_ID_PATTERN = /^sgn_[A-Za-z0-9]+$/;
57
+ const VALID_LIST_STATUSES = ["open", "accepted", "declined", "all"];
58
+ // ---------------------------------------------------------------------------
59
+ // Pure helpers (exported for unit tests)
60
+ // ---------------------------------------------------------------------------
61
+ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
62
+ /**
63
+ * Read the top-level `skill_uid` from a SKILL.md's YAML frontmatter. Mirrors
64
+ * hq-pro's `parseSkillFrontmatter` (block extraction → YAML parse → read the
65
+ * top-level `skill_uid` string). Returns `undefined` when there is no
66
+ * frontmatter, it fails to parse, or `skill_uid` is absent / not a `skl_…`
67
+ * string. Never throws.
68
+ */
69
+ export function parseSkillUid(md) {
70
+ const match = md.match(FRONTMATTER_RE);
71
+ if (!match)
72
+ return undefined;
73
+ let doc;
74
+ try {
75
+ doc = yaml.load(match[1]);
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
81
+ return undefined;
82
+ const uid = doc.skill_uid;
83
+ return typeof uid === "string" && SKILL_UID_PATTERN.test(uid) ? uid : undefined;
84
+ }
85
+ /** sha256 hex of a string — the base-version fingerprint the server records (AC2). */
86
+ export function sha256Hex(content) {
87
+ return createHash("sha256").update(content, "utf8").digest("hex");
88
+ }
89
+ /**
90
+ * Build the CREATE request body from the resolved proposed content and an
91
+ * optional base. Mirrors the server's two payload shapes:
92
+ * - `baseContent` present → the server derives the unified diff + base hash
93
+ * (the diff-by-default path). A no-op (base === proposed) is rejected here
94
+ * rather than round-tripped to an EmptySuggestion 400.
95
+ * - no base → a `full-file` proposal; the server REQUIRES a `baseContentHash`,
96
+ * so we fingerprint the proposed content (a "here is my whole file" proposal
97
+ * with no base to diff against).
98
+ * An empty / whitespace-only note is dropped (kept absent, not blank).
99
+ */
100
+ export function buildSuggestionCreateBody(input) {
101
+ const body = { proposedContent: input.proposedContent };
102
+ if (input.baseContent !== undefined) {
103
+ if (input.baseContent === input.proposedContent) {
104
+ throw new Error("No changes to propose — the working SKILL.md matches its base.");
105
+ }
106
+ body.baseContent = input.baseContent;
107
+ }
108
+ else {
109
+ body.baseContentHash = sha256Hex(input.proposedContent);
110
+ }
111
+ const note = input.note?.trim();
112
+ if (note)
113
+ body.authorNote = note;
114
+ return body;
115
+ }
116
+ /**
117
+ * Map an hq-pro skill route error to a single user-facing line. Pure so the
118
+ * status → copy mapping is unit-tested independently of the network. Prefers the
119
+ * server's own `error` / `message` (they carry the actionable specifics — e.g.
120
+ * "Skill not found", "You need write access to this skill…").
121
+ */
122
+ export function mapSkillError(status, body) {
123
+ const server = (typeof body.error === "string" && body.error) ||
124
+ (typeof body.message === "string" && body.message) ||
125
+ "";
126
+ if (status === 401)
127
+ return "Not authenticated — please run `hq login`";
128
+ if (status === 403)
129
+ return server || "Not authorized";
130
+ if (status === 404)
131
+ return server || "Not found";
132
+ if (status === 409)
133
+ return server || "Conflict — please retry";
134
+ if (status === 422)
135
+ return server || "Company vault not provisioned";
136
+ if (status >= 500)
137
+ return `Server error: ${server || status}`;
138
+ return server || `Request failed (${status})`;
139
+ }
140
+ function shortDate(iso) {
141
+ return typeof iso === "string" ? iso.slice(0, 10) : "";
142
+ }
143
+ /**
144
+ * Render the review inbox as a table (one row per suggestion), optionally
145
+ * printing each suggestion's unified diff (or full proposed file, when the base
146
+ * drifted / the proposal is full-file) beneath its row. Pure → snapshot-testable.
147
+ */
148
+ export function formatSuggestionsList(suggestions, opts = {}) {
149
+ if (suggestions.length === 0) {
150
+ return chalk.gray("No suggestions match — the review inbox is empty.");
151
+ }
152
+ const idW = Math.max(13, ...suggestions.map((s) => s.suggestionId.length));
153
+ const skillW = Math.max(8, ...suggestions.map((s) => s.skillUid.length));
154
+ const authW = Math.max(6, ...suggestions.map((s) => s.authorPersonUid.length));
155
+ const statusW = Math.max(6, ...suggestions.map((s) => s.status.length));
156
+ const lines = [];
157
+ lines.push(chalk.bold([
158
+ "SUGGESTION_ID".padEnd(idW),
159
+ "SKILL".padEnd(skillW),
160
+ "AUTHOR".padEnd(authW),
161
+ "STATUS".padEnd(statusW),
162
+ "BASE",
163
+ "CREATED",
164
+ ].join(" ")));
165
+ for (const s of suggestions) {
166
+ lines.push([
167
+ s.suggestionId.padEnd(idW),
168
+ s.skillUid.padEnd(skillW),
169
+ s.authorPersonUid.padEnd(authW),
170
+ s.status.padEnd(statusW),
171
+ s.baseChanged ? chalk.yellow("changed") : "ok".padEnd(7),
172
+ shortDate(s.createdAt),
173
+ ].join(" "));
174
+ if (s.authorNote) {
175
+ lines.push(chalk.dim(` note: ${s.authorNote}`));
176
+ }
177
+ if (opts.showDiff) {
178
+ const diff = s.presentation === "diff" && s.unifiedDiff
179
+ ? s.unifiedDiff
180
+ : (s.fullContent ?? "");
181
+ const label = s.presentation === "diff" && s.unifiedDiff
182
+ ? "diff"
183
+ : `full file${s.baseChanged ? " (base changed)" : ""}`;
184
+ lines.push(chalk.dim(` ── ${label} ──`));
185
+ for (const dl of diff.split("\n")) {
186
+ lines.push(colorizeDiffLine(` ${dl}`));
187
+ }
188
+ }
189
+ }
190
+ return lines.join("\n");
191
+ }
192
+ /** Colour a unified-diff line (green add / red del / dim header). Pure. */
193
+ function colorizeDiffLine(line) {
194
+ const trimmed = line.trimStart();
195
+ if (trimmed.startsWith("+"))
196
+ return chalk.green(line);
197
+ if (trimmed.startsWith("-"))
198
+ return chalk.red(line);
199
+ if (trimmed.startsWith("@@"))
200
+ return chalk.cyan(line);
201
+ return chalk.dim(line);
202
+ }
203
+ // ---------------------------------------------------------------------------
204
+ // Company slug + local skill resolution
205
+ // ---------------------------------------------------------------------------
206
+ /** Read `.hq/config.json`'s `activeCompany` (mirrors signals/sources). */
207
+ export function readActiveCompanySlug(hqRoot) {
208
+ const configPath = path.join(hqRoot, ".hq", "config.json");
209
+ if (!fs.existsSync(configPath))
210
+ return undefined;
211
+ try {
212
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
213
+ return typeof cfg.activeCompany === "string" && cfg.activeCompany.length > 0
214
+ ? cfg.activeCompany
215
+ : undefined;
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
221
+ /**
222
+ * The skill routes are keyed on the company SLUG. Precedence: explicit
223
+ * `--company` → `.hq/config.json` activeCompany. Throws with actionable copy
224
+ * when neither is available.
225
+ */
226
+ export function resolveCompanySlug(flag, hqRoot = DEFAULT_HQ_ROOT) {
227
+ const slug = flag ?? readActiveCompanySlug(hqRoot);
228
+ if (!slug) {
229
+ throw new Error("No company specified. Pass --company <slug> (or set an active company in .hq/config.json).");
230
+ }
231
+ return slug;
232
+ }
233
+ /**
234
+ * Recursively find a SKILL.md whose frontmatter `skill_uid` equals `uid`,
235
+ * searching each root breadth-first with a bounded depth (skips VCS / build /
236
+ * dependency dirs). Returns the first match's absolute path, or null.
237
+ */
238
+ export function findSkillFileByUid(roots, uid, maxDepth = 6) {
239
+ const SKIP = new Set([
240
+ "node_modules",
241
+ ".git",
242
+ "dist",
243
+ "build",
244
+ ".next",
245
+ "coverage",
246
+ ]);
247
+ const queue = [];
248
+ for (const r of roots) {
249
+ if (fs.existsSync(r))
250
+ queue.push({ dir: r, depth: 0 });
251
+ }
252
+ while (queue.length > 0) {
253
+ const { dir, depth } = queue.shift();
254
+ let entries;
255
+ try {
256
+ entries = fs.readdirSync(dir, { withFileTypes: true });
257
+ }
258
+ catch {
259
+ continue;
260
+ }
261
+ for (const entry of entries) {
262
+ const full = path.join(dir, entry.name);
263
+ if (entry.isDirectory()) {
264
+ if (depth < maxDepth && !SKIP.has(entry.name)) {
265
+ queue.push({ dir: full, depth: depth + 1 });
266
+ }
267
+ }
268
+ else if (entry.isFile() && entry.name === "SKILL.md") {
269
+ let content;
270
+ try {
271
+ content = fs.readFileSync(full, "utf-8");
272
+ }
273
+ catch {
274
+ continue;
275
+ }
276
+ if (parseSkillUid(content) === uid)
277
+ return full;
278
+ }
279
+ }
280
+ }
281
+ return null;
282
+ }
283
+ /**
284
+ * Resolve a `suggest` target (a `skl_…` uid OR a filesystem path) to the local
285
+ * SKILL.md, its uid, and its content. A uid is resolved by scanning the company
286
+ * skills dir and the cwd; a path is read directly (a directory → its SKILL.md),
287
+ * with the uid read from the file's frontmatter.
288
+ */
289
+ export function resolveSkillTarget(target, deps) {
290
+ if (SKILL_UID_PATTERN.test(target)) {
291
+ const roots = Array.from(new Set([
292
+ path.join(deps.hqRoot, "companies", deps.companySlug, "skills"),
293
+ deps.cwd,
294
+ ]));
295
+ const filePath = findSkillFileByUid(roots, target);
296
+ if (!filePath) {
297
+ throw new Error(`Could not find a local SKILL.md with skill_uid '${target}' under ${roots.join(", ")}. ` +
298
+ "Pass the path to the edited SKILL.md instead.");
299
+ }
300
+ return { filePath, skillUid: target, content: fs.readFileSync(filePath, "utf-8") };
301
+ }
302
+ // Filesystem path — accept either a SKILL.md file or a directory containing one.
303
+ let filePath = path.resolve(deps.cwd, target);
304
+ if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
305
+ filePath = path.join(filePath, "SKILL.md");
306
+ }
307
+ if (!fs.existsSync(filePath)) {
308
+ throw new Error(`No SKILL.md found at '${target}'. Pass the path to a SKILL.md (or its directory), or a skl_… uid.`);
309
+ }
310
+ const content = fs.readFileSync(filePath, "utf-8");
311
+ const skillUid = parseSkillUid(content);
312
+ if (!skillUid) {
313
+ throw new Error(`The SKILL.md at '${filePath}' has no skill_uid in its frontmatter — it is not registered yet. ` +
314
+ "Sync / reindex the skill first so it has a stable identity, then suggest against it.");
315
+ }
316
+ return { filePath, skillUid, content };
317
+ }
318
+ /**
319
+ * Read the committed (HEAD) version of a file from its git repo — the diff base
320
+ * for "propose my working changes". Returns null when the file is untracked, not
321
+ * in a repo, or git is unavailable (the caller then falls back to full-file, or
322
+ * errors under `--diff`). Never throws.
323
+ */
324
+ export async function readGitBase(filePath) {
325
+ try {
326
+ const git = simpleGit(path.dirname(filePath));
327
+ const top = (await git.revparse(["--show-toplevel"])).trim();
328
+ const rel = path.relative(top, filePath);
329
+ return await git.show([`HEAD:${rel}`]);
330
+ }
331
+ catch {
332
+ return null;
333
+ }
334
+ }
335
+ // ---------------------------------------------------------------------------
336
+ // Network helpers
337
+ // ---------------------------------------------------------------------------
338
+ async function readJsonBody(res) {
339
+ return (await res.json().catch(() => ({})));
340
+ }
341
+ /** Print the mapped error for a non-2xx response and exit(1). Returns never. */
342
+ async function failFromResponse(res) {
343
+ const body = await readJsonBody(res);
344
+ console.error(chalk.red(mapSkillError(res.status, body)));
345
+ process.exit(1);
346
+ }
347
+ function skillRoutePrefix(slug) {
348
+ return `/v1/files/skills/company/${encodeURIComponent(slug)}`;
349
+ }
350
+ // ---------------------------------------------------------------------------
351
+ // Command registration
352
+ // ---------------------------------------------------------------------------
353
+ export function registerSkillCommand(program, deps = {}) {
354
+ const gitBase = deps.gitBase ?? readGitBase;
355
+ const skill = program
356
+ .command("skill")
357
+ .description("Propose, review, and merge skill changes from the terminal")
358
+ .option("--company <slug>", "Company slug (defaults to the active company)");
359
+ // ── suggest ────────────────────────────────────────────────────────────────
360
+ skill
361
+ .command("suggest <target>")
362
+ .description("Create a suggestion from a local SKILL.md (a skl_… uid or a path). Never blocked by a skill lock — a suggestion is always a proposal.")
363
+ .option("--diff", "Require a diff base (git HEAD, or --base): fail if none is found. Default falls back to a full-file proposal.")
364
+ .option("--base <file>", "Explicit base file to diff the working SKILL.md against")
365
+ .option("--note <text>", "Author note — the rationale / failure context attached to the suggestion")
366
+ .action(async (target, opts) => {
367
+ try {
368
+ const companySlug = resolveCompanySlug(skill.opts().company);
369
+ const resolved = resolveSkillTarget(target, {
370
+ cwd: process.cwd(),
371
+ hqRoot: DEFAULT_HQ_ROOT,
372
+ companySlug,
373
+ });
374
+ // Base resolution: explicit --base wins; otherwise diff against git
375
+ // HEAD when the file is tracked. No base + --diff → hard error; no
376
+ // base without --diff → a full-file proposal.
377
+ let baseContent;
378
+ let baseSource = "";
379
+ if (opts.base !== undefined) {
380
+ const basePath = path.resolve(process.cwd(), opts.base);
381
+ if (!fs.existsSync(basePath)) {
382
+ console.error(chalk.red(`Base file not found: ${opts.base}`));
383
+ process.exit(1);
384
+ }
385
+ baseContent = fs.readFileSync(basePath, "utf-8");
386
+ baseSource = opts.base;
387
+ }
388
+ else {
389
+ const fromGit = await gitBase(resolved.filePath);
390
+ if (fromGit !== null) {
391
+ baseContent = fromGit;
392
+ baseSource = "git HEAD";
393
+ }
394
+ }
395
+ if (baseContent === undefined && opts.diff) {
396
+ console.error(chalk.red(`--diff needs a base, but none was found for ${resolved.filePath}. ` +
397
+ "Pass --base <file>, or commit a base version first."));
398
+ process.exit(1);
399
+ }
400
+ if (baseContent !== undefined && baseContent === resolved.content) {
401
+ console.error(chalk.red(`No changes to propose — the working SKILL.md matches its base (${baseSource}).`));
402
+ process.exit(1);
403
+ }
404
+ const body = buildSuggestionCreateBody({
405
+ proposedContent: resolved.content,
406
+ baseContent,
407
+ note: opts.note,
408
+ });
409
+ const token = await ensureCognitoToken();
410
+ const res = await vaultApiFetch({
411
+ token,
412
+ path: `${skillRoutePrefix(companySlug)}/${encodeURIComponent(resolved.skillUid)}/suggestions`,
413
+ method: "POST",
414
+ body: body,
415
+ });
416
+ if (!res.ok)
417
+ await failFromResponse(res);
418
+ const data = (await res.json());
419
+ console.log(chalk.green(`Suggestion created: ${data.suggestionId}`));
420
+ console.log(` Skill: ${data.skillUid}`);
421
+ console.log(` Status: ${data.status}`);
422
+ // AC4 — attribution is server-derived from the invoking identity.
423
+ console.log(` Author: ${data.authorPersonUid}`);
424
+ console.log(` Change: ${data.payloadFormat === "diff" ? `diff vs ${baseSource || "base"}` : "full file"}`);
425
+ if (data.authorNote)
426
+ console.log(` Note: ${data.authorNote}`);
427
+ console.log(chalk.dim(` The skill owner can review it: hq skill review ${data.suggestionId} --accept|--decline`));
428
+ }
429
+ catch (err) {
430
+ console.error(chalk.red("Error:"), err instanceof Error ? err.message : String(err));
431
+ process.exit(1);
432
+ }
433
+ });
434
+ // ── list-suggestions ─────────────────────────────────────────────────────────
435
+ skill
436
+ .command("list-suggestions")
437
+ .description("List the review inbox — open suggestions on skills you own (or one skill via --skill)")
438
+ .option("--skill <skillUid>", "Scope to one skill (skl_…); requires write access on it")
439
+ .option("--status <status>", "open | accepted | declined | all (default: open)")
440
+ .option("--show-diff", "Print each suggestion's unified diff / proposed file")
441
+ .option("--json", "Emit raw JSON instead of a table")
442
+ .action(async (opts) => {
443
+ try {
444
+ const companySlug = resolveCompanySlug(skill.opts().company);
445
+ const status = (opts.status ?? "open");
446
+ if (!VALID_LIST_STATUSES.includes(status)) {
447
+ console.error(chalk.red(`Invalid --status '${opts.status}': must be one of ${VALID_LIST_STATUSES.join(", ")}`));
448
+ process.exit(1);
449
+ }
450
+ if (opts.skill !== undefined && !SKILL_UID_PATTERN.test(opts.skill)) {
451
+ console.error(chalk.red(`Invalid --skill '${opts.skill}': must be a skl_… uid`));
452
+ process.exit(1);
453
+ }
454
+ const body = { status };
455
+ if (opts.skill !== undefined)
456
+ body.skillUid = opts.skill;
457
+ const token = await ensureCognitoToken();
458
+ const res = await vaultApiFetch({
459
+ token,
460
+ path: `${skillRoutePrefix(companySlug)}/suggestions/list`,
461
+ method: "POST",
462
+ body,
463
+ });
464
+ if (!res.ok)
465
+ await failFromResponse(res);
466
+ const data = (await res.json());
467
+ if (opts.json) {
468
+ console.log(JSON.stringify(data, null, 2));
469
+ return;
470
+ }
471
+ console.log(formatSuggestionsList(data.suggestions, { showDiff: opts.showDiff }));
472
+ }
473
+ catch (err) {
474
+ console.error(chalk.red("Error:"), err instanceof Error ? err.message : String(err));
475
+ process.exit(1);
476
+ }
477
+ });
478
+ // ── review ─────────────────────────────────────────────────────────────────
479
+ skill
480
+ .command("review <suggestionId>")
481
+ .description("Accept (merge) or decline a pending suggestion")
482
+ .option("--accept", "Accept the suggestion — merges the proposed change into the skill")
483
+ .option("--decline", "Decline the suggestion — leaves the skill unchanged")
484
+ .option("--reason <text>", "Reason recorded on a decline")
485
+ .option("--skill <skillUid>", "Scope the lookup to one skill (skl_…)")
486
+ .option("--acknowledge-base-changed", "On accept: overwrite with the full proposed file even if the skill changed since the suggestion")
487
+ .action(async (suggestionId, opts) => {
488
+ try {
489
+ if (!SUGGESTION_ID_PATTERN.test(suggestionId)) {
490
+ console.error(chalk.red(`Invalid suggestion id '${suggestionId}': must be a sgn_… id`));
491
+ process.exit(1);
492
+ }
493
+ const accept = opts.accept === true;
494
+ const decline = opts.decline === true;
495
+ if (accept === decline) {
496
+ console.error(chalk.red("Pass exactly one of --accept or --decline."));
497
+ process.exit(1);
498
+ }
499
+ if (opts.skill !== undefined && !SKILL_UID_PATTERN.test(opts.skill)) {
500
+ console.error(chalk.red(`Invalid --skill '${opts.skill}': must be a skl_… uid`));
501
+ process.exit(1);
502
+ }
503
+ const companySlug = resolveCompanySlug(skill.opts().company);
504
+ const token = await ensureCognitoToken();
505
+ // Resolve the suggestion's skillUid + live path from the SAME LIST route
506
+ // the console uses — accept/decline are path↔uid guarded, so the path
507
+ // must come from the authoritative row, never guessed. `all` so an
508
+ // already-resolved suggestion yields a precise "already <status>" error.
509
+ const listBody = { status: "all" };
510
+ if (opts.skill !== undefined)
511
+ listBody.skillUid = opts.skill;
512
+ const listRes = await vaultApiFetch({
513
+ token,
514
+ path: `${skillRoutePrefix(companySlug)}/suggestions/list`,
515
+ method: "POST",
516
+ body: listBody,
517
+ });
518
+ if (!listRes.ok)
519
+ await failFromResponse(listRes);
520
+ const { suggestions } = (await listRes.json());
521
+ const row = suggestions.find((s) => s.suggestionId === suggestionId);
522
+ if (!row) {
523
+ console.error(chalk.red(`Suggestion ${suggestionId} is not in your review inbox. ` +
524
+ "If it targets a skill you don't own, scope the lookup with --skill <skl_…>."));
525
+ process.exit(1);
526
+ }
527
+ if (row.status !== "open") {
528
+ console.error(chalk.yellow(`Suggestion ${suggestionId} is already ${row.status} — nothing to do.`));
529
+ process.exit(1);
530
+ }
531
+ if (accept) {
532
+ if (!row.path) {
533
+ console.error(chalk.red("Could not resolve the live skill path for this suggestion — the skill may have been removed."));
534
+ process.exit(1);
535
+ }
536
+ const acceptBody = { path: row.path };
537
+ if (opts.acknowledgeBaseChanged)
538
+ acceptBody.acknowledgeBaseChanged = true;
539
+ const res = await vaultApiFetch({
540
+ token,
541
+ path: `${skillRoutePrefix(companySlug)}/${encodeURIComponent(row.skillUid)}/suggestions/${encodeURIComponent(suggestionId)}/accept`,
542
+ method: "POST",
543
+ body: acceptBody,
544
+ });
545
+ if (!res.ok) {
546
+ const errBody = await readJsonBody(res);
547
+ // AC4 (US-009): the base drifted — guide the operator to re-run
548
+ // with acknowledgement rather than silently overwriting.
549
+ if (res.status === 409 &&
550
+ errBody.code === "WRITE_SKILL_SUGGESTION_BASE_CHANGED") {
551
+ console.error(chalk.yellow("The skill changed since this suggestion was written. Re-run with " +
552
+ "--acknowledge-base-changed to overwrite it with the full proposed file."));
553
+ process.exit(1);
554
+ }
555
+ console.error(chalk.red(mapSkillError(res.status, errBody)));
556
+ process.exit(1);
557
+ }
558
+ const data = (await res.json());
559
+ console.log(chalk.green("Suggestion accepted — merged and closed."));
560
+ console.log(` Skill: ${data.skillUid}`);
561
+ console.log(` Suggestion: ${data.suggestionId}`);
562
+ console.log(` Accepted by: ${data.acceptedBy}`);
563
+ return;
564
+ }
565
+ // Decline.
566
+ const declineBody = {};
567
+ if (opts.reason !== undefined)
568
+ declineBody.reason = opts.reason;
569
+ const res = await vaultApiFetch({
570
+ token,
571
+ path: `${skillRoutePrefix(companySlug)}/${encodeURIComponent(row.skillUid)}/suggestions/${encodeURIComponent(suggestionId)}/decline`,
572
+ method: "POST",
573
+ body: declineBody,
574
+ });
575
+ if (!res.ok)
576
+ await failFromResponse(res);
577
+ const data = (await res.json());
578
+ console.log(chalk.green("Suggestion declined — the skill was left unchanged."));
579
+ console.log(` Skill: ${data.skillUid}`);
580
+ console.log(` Suggestion: ${data.suggestionId}`);
581
+ console.log(` Declined by: ${data.declinedBy}`);
582
+ if (data.reason)
583
+ console.log(` Reason: ${data.reason}`);
584
+ }
585
+ catch (err) {
586
+ console.error(chalk.red("Error:"), err instanceof Error ? err.message : String(err));
587
+ process.exit(1);
588
+ }
589
+ });
590
+ return skill;
591
+ }
592
+ //# sourceMappingURL=skill.js.map
593
+ //# debugId=5bdf8a18-3088-5615-b596-9be2c9fdb5cc
@@ -0,0 +1,48 @@
1
+ import { Command } from "commander";
2
+ export interface RegistryWorker {
3
+ id: string;
4
+ path: string;
5
+ type: string;
6
+ visibility: string;
7
+ company?: string;
8
+ team?: string;
9
+ status?: string;
10
+ description?: string;
11
+ triggers?: string;
12
+ grants?: string;
13
+ }
14
+ /** Read + parse the worker registry. Empty array if it does not exist. */
15
+ export declare function readWorkerRegistry(hqRoot: string): RegistryWorker[];
16
+ /**
17
+ * Best-effort active company: workspace/sessions/.current -> meta.yaml
18
+ * company_slug. Undefined when no session context is set. Pure/read-only.
19
+ */
20
+ export declare function resolveActiveCompany(hqRoot: string): string | undefined;
21
+ /**
22
+ * Membership-aware access filter for worker discovery: public workers always;
23
+ * company workers only for the active company. Mirrors the /run skill and the
24
+ * inject-worker-suggestion hook so all three surfaces agree.
25
+ */
26
+ export declare function filterAccessibleWorkers(workers: RegistryWorker[], activeCompany: string | undefined): RegistryWorker[];
27
+ /**
28
+ * The company-relative vault prefix for a worker, e.g.
29
+ * companies/indigo/workers/deal-brain/ -> workers/deal-brain/. Returns null for
30
+ * a worker with no company (public/shared — not shareable via ACL).
31
+ */
32
+ export declare function workerVaultPrefix(w: RegistryWorker): string | null;
33
+ export type GranteeType = "company-wide" | "email" | "group";
34
+ export interface ClassifiedPrincipal {
35
+ granteeType: GranteeType;
36
+ granteeId: string;
37
+ label: string;
38
+ }
39
+ /** Classify a share principal (@all | email | grp_*) — null when invalid. */
40
+ export declare function classifyPrincipal(principal: string): ClassifiedPrincipal | null;
41
+ /**
42
+ * Record a grant locally in the worker's tool-owned .grants.yaml sidecar. Kept
43
+ * out of worker.yaml so we never rewrite a hand-authored file; the registry
44
+ * generator unions this sidecar into the registry `grants:` field. Idempotent.
45
+ */
46
+ export declare function writeGrantSidecar(hqRoot: string, workerPath: string, principalLabel: string): void;
47
+ export declare function registerWorkersCommand(program: Command): void;
48
+ //# sourceMappingURL=workers.d.ts.map