@indigoai-us/hq-cli 5.17.0 → 5.18.1

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.
@@ -0,0 +1,249 @@
1
+ /**
2
+ * `hq sync mode <mode>` (US-006) — flip a membership's syncMode for a company.
3
+ *
4
+ * Subcommand of the `hq sync` group. Three call shapes:
5
+ *
6
+ * hq sync mode shared|all|custom [--company <slug>]
7
+ * Resolves the target membership for the given company (or the cwd's
8
+ * active company from `.hq/config.json` if `--company` is omitted) and
9
+ * calls `VaultClient.setMembershipSyncConfig`. Prints membershipId +
10
+ * previous mode → new mode as a chat audit trail.
11
+ *
12
+ * hq sync mode --show
13
+ * No positional. Prints a table of every membership the caller has
14
+ * with its company slug, current sync-mode, and last-updated stamp.
15
+ *
16
+ * hq sync mode custom --paths a/,b/ (planned follow-up)
17
+ * For the `custom` mode the server requires `customPaths`. This command
18
+ * accepts `--paths` as a comma-separated list to forward to the API; if
19
+ * omitted on `custom` the server validation will reject.
20
+ *
21
+ * Auto-detect of `--company` from cwd: best-effort via the active-company
22
+ * slug in `<hq-root>/.hq/config.json`. If absent, the caller must pass
23
+ * `--company` explicitly — there's no cwd-walk to a `companies/<slug>/`
24
+ * folder in this initial implementation (follow-up US could add it).
25
+ *
26
+ * Cross-package note: this command depends on `VaultClient`
27
+ * (`getMembershipSyncConfig` / `setMembershipSyncConfig`) added in
28
+ * hq-cloud US-004 (commit 41e5ee1). While that hq-cloud release is
29
+ * unpublished, hq-cli pins `@indigoai-us/hq-cloud` to `file:../hq-cloud`
30
+ * in package.json — revert that line to `^5.20.0` (or whatever the
31
+ * published cut is) once US-004 ships to npm.
32
+ */
33
+
34
+ !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]="534a51ec-53e8-5cde-98c6-5ffc1741d2c1")}catch(e){}}();
35
+ import chalk from "chalk";
36
+ import * as fs from "node:fs";
37
+ import * as path from "node:path";
38
+ import { VaultClient, } from "@indigoai-us/hq-cloud";
39
+ import { DEFAULT_HQ_ROOT, ensureCognitoToken, buildVaultConfig, } from "../utils/cognito-session.js";
40
+ // ── Constants ───────────────────────────────────────────────────────────────
41
+ export const LEGAL_SYNC_MODES = [
42
+ "shared",
43
+ "all",
44
+ "custom",
45
+ ];
46
+ // ── Pure helpers ────────────────────────────────────────────────────────────
47
+ /** Throws a helpful Error if `mode` is not a legal SyncMode. */
48
+ export function validateMode(mode) {
49
+ if (LEGAL_SYNC_MODES.includes(mode)) {
50
+ return mode;
51
+ }
52
+ throw new Error(`Invalid sync mode '${mode}'. Legal values: ${LEGAL_SYNC_MODES.join(", ")}.`);
53
+ }
54
+ /**
55
+ * Read the active company slug from `<hq-root>/.hq/config.json`. Returns
56
+ * undefined when the file is missing or `activeCompany` isn't set. Never
57
+ * throws — auto-detect is best-effort.
58
+ */
59
+ export function readActiveCompanySlug(hqRoot) {
60
+ const configPath = path.join(hqRoot, ".hq", "config.json");
61
+ if (!fs.existsSync(configPath))
62
+ return undefined;
63
+ try {
64
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
65
+ const slug = cfg.activeCompany;
66
+ return typeof slug === "string" && slug.length > 0 ? slug : undefined;
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /** Parse `--paths a/,b/c/` into trimmed non-empty entries. */
73
+ export function parseCustomPaths(raw) {
74
+ if (!raw)
75
+ return undefined;
76
+ const parts = raw
77
+ .split(",")
78
+ .map((s) => s.trim())
79
+ .filter((s) => s.length > 0);
80
+ return parts.length > 0 ? parts : undefined;
81
+ }
82
+ // ── Orchestrators (pure, injectable — driven by tests) ──────────────────────
83
+ /**
84
+ * Resolve a membership by company slug, then PUT the new sync-mode. Returns
85
+ * the membershipId, the previous mode (read via GET first), and the server's
86
+ * fresh config (which sets `isDefault: false` once a row exists).
87
+ */
88
+ export async function setSyncMode(options) {
89
+ const { mode, companySlug, customPaths, vaultClient } = options;
90
+ // 1. Find the caller's membership for this company.
91
+ const memberships = await vaultClient.listMyMemberships();
92
+ // Resolve slug → uid via entity.get on each membership's companyUid in
93
+ // parallel. Cheaper than a per-membership lookup loop and matches the
94
+ // pattern AppBar uses to render its company picker.
95
+ const enriched = await Promise.all(memberships.map(async (m) => {
96
+ try {
97
+ const ent = await vaultClient.entity.get(m.companyUid);
98
+ return { membership: m, slug: ent.slug, name: ent.name };
99
+ }
100
+ catch {
101
+ return { membership: m, slug: undefined, name: undefined };
102
+ }
103
+ }));
104
+ const match = enriched.find((row) => row.slug === companySlug);
105
+ if (!match) {
106
+ const known = enriched
107
+ .map((r) => r.slug)
108
+ .filter((s) => !!s)
109
+ .join(", ");
110
+ throw new Error(`No membership found for company '${companySlug}'. Memberships visible to you: ${known || "(none)"}.`);
111
+ }
112
+ const membershipId = match.membership.membershipKey;
113
+ // 2. Read the current config (server defaults to `shared`/isDefault:true
114
+ // when no row exists). We surface this in the audit line.
115
+ const before = await vaultClient.getMembershipSyncConfig(membershipId);
116
+ // 3. Write the new mode.
117
+ const after = await vaultClient.setMembershipSyncConfig(membershipId, {
118
+ syncMode: mode,
119
+ customPaths,
120
+ });
121
+ return {
122
+ membershipId,
123
+ companySlug,
124
+ previousMode: before.syncMode,
125
+ previousWasDefault: before.isDefault,
126
+ newMode: after.syncMode,
127
+ newConfig: after,
128
+ };
129
+ }
130
+ /**
131
+ * Fetch every membership the caller has, resolve company slugs, and look up
132
+ * each effective sync-config in parallel. Returns rows sorted by slug for
133
+ * stable table output.
134
+ */
135
+ export async function showSyncModes(options) {
136
+ const { vaultClient } = options;
137
+ const memberships = await vaultClient.listMyMemberships();
138
+ if (memberships.length === 0)
139
+ return [];
140
+ const rows = await Promise.all(memberships.map(async (m) => {
141
+ const [config, entity] = await Promise.all([
142
+ vaultClient.getMembershipSyncConfig(m.membershipKey).catch(() => ({
143
+ membershipId: m.membershipKey,
144
+ syncMode: "shared",
145
+ isDefault: true,
146
+ })),
147
+ vaultClient.entity
148
+ .get(m.companyUid)
149
+ .catch(() => ({ uid: m.companyUid, slug: m.companyUid, name: undefined })),
150
+ ]);
151
+ return {
152
+ companySlug: entity.slug,
153
+ companyName: entity.name,
154
+ membershipId: m.membershipKey,
155
+ syncMode: config.syncMode,
156
+ isDefault: config.isDefault,
157
+ updatedAt: config.updatedAt,
158
+ };
159
+ }));
160
+ rows.sort((a, b) => a.companySlug.localeCompare(b.companySlug));
161
+ return rows;
162
+ }
163
+ // ── Table rendering (used by CLI action, separable for tests) ──────────────
164
+ /**
165
+ * Render the `--show` table as plain text. No external dep — hq-cli doesn't
166
+ * use cli-table3, so we hand-format columns to match the existing chalk +
167
+ * padEnd pattern used by `hq members list`.
168
+ */
169
+ export function formatShowTable(rows) {
170
+ if (rows.length === 0) {
171
+ return "No memberships found. Run `hq onboard` or accept an invite first.";
172
+ }
173
+ const cols = ["COMPANY", "MODE", "UPDATED", "MEMBERSHIP"];
174
+ const data = rows.map((r) => [
175
+ r.companySlug,
176
+ r.isDefault ? `${r.syncMode} (default)` : r.syncMode,
177
+ r.updatedAt ?? "—",
178
+ r.membershipId,
179
+ ]);
180
+ const widths = cols.map((c, i) => Math.max(c.length, ...data.map((row) => row[i].length)));
181
+ const renderRow = (row) => row.map((cell, i) => cell.padEnd(widths[i])).join(" ");
182
+ const lines = [
183
+ chalk.bold(renderRow(cols)),
184
+ chalk.dim(renderRow(widths.map((w) => "─".repeat(w)))),
185
+ ...data.map(renderRow),
186
+ ];
187
+ return lines.join("\n");
188
+ }
189
+ /**
190
+ * Wire `hq sync mode` onto an existing `sync` Commander group. The caller
191
+ * (`src/index.ts`) constructs the `sync` group and calls this after
192
+ * `registerCloudCommands` so push/pull/status/mode all coexist.
193
+ */
194
+ export function registerSyncModeCommand(syncCmd) {
195
+ syncCmd
196
+ .command("mode [mode]")
197
+ .description("Flip a membership's sync-mode (shared|all|custom), or --show every membership's current mode")
198
+ .option("--company <slug>", "Company slug (defaults to the active company in <hq-root>/.hq/config.json)")
199
+ .option("--show", "Print the current sync-mode for every membership the caller has")
200
+ .option("--paths <csv>", "Comma-separated allowed prefixes (required when mode is 'custom')")
201
+ .option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
202
+ .action(async (modeArg, options) => {
203
+ try {
204
+ const accessToken = await ensureCognitoToken();
205
+ const vaultConfig = buildVaultConfig(accessToken);
206
+ const client = new VaultClient(vaultConfig);
207
+ if (options.show) {
208
+ if (modeArg !== undefined) {
209
+ throw new Error("`--show` is incompatible with a positional <mode>. Pass one or the other.");
210
+ }
211
+ const rows = await showSyncModes({ vaultClient: client });
212
+ console.log(formatShowTable(rows));
213
+ return;
214
+ }
215
+ if (!modeArg) {
216
+ throw new Error(`Missing <mode>. Usage: hq sync mode <${LEGAL_SYNC_MODES.join("|")}> [--company <slug>] or hq sync mode --show`);
217
+ }
218
+ const mode = validateMode(modeArg);
219
+ const customPaths = parseCustomPaths(options.paths);
220
+ const companySlug = options.company ?? readActiveCompanySlug(options.hqRoot);
221
+ if (!companySlug) {
222
+ throw new Error("No company specified. Pass --company <slug> or set activeCompany in <hq-root>/.hq/config.json.");
223
+ }
224
+ const result = await setSyncMode({
225
+ mode,
226
+ companySlug,
227
+ customPaths,
228
+ vaultClient: client,
229
+ });
230
+ const prevLabel = result.previousWasDefault
231
+ ? `${result.previousMode} (default)`
232
+ : result.previousMode;
233
+ console.log(chalk.green("✓"), `Set sync-mode for ${chalk.bold(result.companySlug)}: ${chalk.dim(prevLabel)} → ${chalk.bold(result.newMode)}`);
234
+ console.log(chalk.dim(` membershipId: ${result.membershipId}`));
235
+ if (result.newConfig.customPaths && result.newConfig.customPaths.length > 0) {
236
+ console.log(chalk.dim(` customPaths: ${result.newConfig.customPaths.join(", ")}`));
237
+ }
238
+ if (result.newConfig.updatedAt) {
239
+ console.log(chalk.dim(` updatedAt: ${result.newConfig.updatedAt}`));
240
+ }
241
+ }
242
+ catch (err) {
243
+ console.error(chalk.red("✗ sync mode failed:"), err instanceof Error ? err.message : String(err));
244
+ process.exit(1);
245
+ }
246
+ });
247
+ }
248
+ //# sourceMappingURL=sync-mode.js.map
249
+ //# debugId=534a51ec-53e8-5cde-98c6-5ffc1741d2c1
@@ -0,0 +1,154 @@
1
+ /**
2
+ * `hq sync narrow` (US-007) — explicit migration ritual to flip a company's
3
+ * membership from `syncMode: all` to `syncMode: shared`, with a dry-run
4
+ * preview and a dirty-file safety gate.
5
+ *
6
+ * Two call shapes:
7
+ *
8
+ * hq sync narrow --dry-run [--company <slug>]
9
+ * Resolves the membership for <slug> (or the active company), fetches
10
+ * the caller's explicit grants, coalesces them, walks the local
11
+ * `companies/<slug>/` tree, and prints a table:
12
+ *
13
+ * files staying: N
14
+ * clean orphans: N (size)
15
+ * dirty orphans: N (size)
16
+ *
17
+ * Writes nothing — no journal, no local file, no server call beyond
18
+ * the read-only GET on grants + sync-config.
19
+ *
20
+ * hq sync narrow --apply [--yes] [--force] [--company <slug>]
21
+ * Same computation, then:
22
+ * - if `dirty > 0` and `--force` NOT set → abort with conflict report
23
+ * and a recovery message.
24
+ * - else delete clean orphans on disk, tombstone their journal
25
+ * entries, optionally delete dirty orphans too (with `--force`),
26
+ * then PUT sync-config to `shared`. The server's PUT writes the
27
+ * authoritative `MEMBERSHIP_SYNC_CONFIG_CHANGED` audit row; the
28
+ * CLI prints a local audit line as well.
29
+ *
30
+ * Refuses on already-`shared` or `custom` memberships (acceptance 5) —
31
+ * narrowing makes sense only as `all → shared`.
32
+ *
33
+ * Cross-package note: depends on hq-cloud helpers shipped in US-005
34
+ * (`coalescePrefixes`, `readJournal`/`writeJournal`, `tombstoneEntry`) and
35
+ * the VaultClient sync-config endpoints from US-003. While that hq-cloud
36
+ * release is unpublished, hq-cli pins `@indigoai-us/hq-cloud` to
37
+ * `file:../hq-cloud` via `pnpm.overrides`.
38
+ */
39
+ import { Command } from "commander";
40
+ import { type ExplicitGrant, type Membership, type MembershipSyncConfig, type SyncMode, type SyncJournal } from "@indigoai-us/hq-cloud";
41
+ import { type NarrowPlan, type NarrowDirtyFile } from "../lib/local-tree-diff.js";
42
+ /** Subset of VaultClient surface this command exercises (test seam). */
43
+ export interface SyncNarrowVaultClient {
44
+ listMyMemberships(): Promise<Membership[]>;
45
+ getMembershipSyncConfig(membershipId: string): Promise<MembershipSyncConfig>;
46
+ setMembershipSyncConfig(membershipId: string, partial: {
47
+ syncMode: SyncMode;
48
+ customPaths?: string[];
49
+ }): Promise<MembershipSyncConfig>;
50
+ listMyExplicitGrants(companyUid: string): Promise<ExplicitGrant[]>;
51
+ entity: {
52
+ get(uid: string): Promise<{
53
+ uid: string;
54
+ slug: string;
55
+ name?: string;
56
+ }>;
57
+ };
58
+ }
59
+ /** Journal I/O seam — defaults to the real `readJournal`/`writeJournal`. */
60
+ export interface JournalIO {
61
+ read(slug: string): SyncJournal;
62
+ write(slug: string, journal: SyncJournal): void;
63
+ }
64
+ /** Filesystem seam — defaults to real `fs` (only `unlinkSync` is exercised). */
65
+ export interface FsIO {
66
+ unlinkSync(p: string): void;
67
+ }
68
+ /** Confirmation prompt seam — defaults to a `readline` y/N gate. */
69
+ export type ConfirmFn = (message: string) => Promise<boolean>;
70
+ export interface ResolveTargetInput {
71
+ companySlug: string;
72
+ vaultClient: SyncNarrowVaultClient;
73
+ }
74
+ export interface ResolveTargetResult {
75
+ membership: Membership;
76
+ companyUid: string;
77
+ companySlug: string;
78
+ syncConfig: MembershipSyncConfig;
79
+ }
80
+ /**
81
+ * Resolve the caller's membership for `companySlug` and read its current
82
+ * sync-config. Throws if the slug doesn't match any membership or if the
83
+ * current mode isn't eligible for narrowing (`all` → `shared` only).
84
+ */
85
+ export declare function resolveNarrowTarget(input: ResolveTargetInput): Promise<ResolveTargetResult>;
86
+ export interface ComputePlanInput {
87
+ hqRoot: string;
88
+ companySlug: string;
89
+ companyUid: string;
90
+ vaultClient: SyncNarrowVaultClient;
91
+ journalIO?: JournalIO;
92
+ }
93
+ export interface ComputePlanResult {
94
+ plan: NarrowPlan;
95
+ prospectivePrefixSet: string[];
96
+ grants: ExplicitGrant[];
97
+ journal: SyncJournal;
98
+ }
99
+ /**
100
+ * Compute the narrow plan for one company: fetch explicit grants, coalesce,
101
+ * read the per-company journal, walk the local tree, classify.
102
+ *
103
+ * Reads only — never mutates the journal or hits a destructive endpoint.
104
+ * `apply()` consumes this and performs the destructive steps.
105
+ */
106
+ export declare function computeNarrowPlan(input: ComputePlanInput): Promise<ComputePlanResult>;
107
+ export interface ApplyNarrowInput {
108
+ companySlug: string;
109
+ membershipId: string;
110
+ plan: NarrowPlan;
111
+ journal: SyncJournal;
112
+ vaultClient: SyncNarrowVaultClient;
113
+ /** If true, delete dirty orphans too (still tombstoned). */
114
+ force: boolean;
115
+ journalIO?: JournalIO;
116
+ fsIO?: FsIO;
117
+ }
118
+ export interface ApplyNarrowResult {
119
+ cleanDeleted: number;
120
+ cleanBytes: number;
121
+ dirtyDeleted: number;
122
+ dirtyBytes: number;
123
+ tombstoned: number;
124
+ newConfig: MembershipSyncConfig;
125
+ }
126
+ /**
127
+ * Apply the destructive side of a narrow:
128
+ * 1. Delete clean orphans (best-effort — ENOENT is ignored).
129
+ * 2. Tombstone their journal entries.
130
+ * 3. If `force`, also delete + tombstone dirty orphans.
131
+ * 4. Persist the journal.
132
+ * 5. PUT sync-config → `shared` (server writes the audit row).
133
+ *
134
+ * Order is fail-safe: if a delete throws partway, the journal write below
135
+ * won't run, but the in-progress deletions are already on disk — that's the
136
+ * "don't roll back I/O" contract from the spec. The CLI surfaces a
137
+ * recovery message when this throws.
138
+ *
139
+ * Pure-ish: no prompting (the CLI wrapper handles that), no console
140
+ * output. Just disk + network.
141
+ */
142
+ export declare function applyNarrow(input: ApplyNarrowInput): Promise<ApplyNarrowResult>;
143
+ /**
144
+ * Format the dirty-file conflict report shown on `--apply` when dirty files
145
+ * are present and `--force` is NOT set. The CLI prints this and exits
146
+ * non-zero so the operator can resolve before retrying.
147
+ */
148
+ export declare function formatDirtyConflictReport(dirty: NarrowDirtyFile[], companySlug: string): string;
149
+ /**
150
+ * Wire `hq sync narrow` onto the existing `sync` Commander group. Called
151
+ * from `src/index.ts` after `registerSyncModeCommand`.
152
+ */
153
+ export declare function registerSyncNarrowCommand(syncCmd: Command): void;
154
+ //# sourceMappingURL=sync-narrow.d.ts.map