@indigoai-us/hq-cli 5.9.0 → 5.10.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/CHANGELOG.md +14 -0
- package/dist/commands/cloud-demote.d.ts +90 -0
- package/dist/commands/cloud-demote.js +193 -0
- package/dist/index.js +4 -2
- package/package.json +1 -1
- package/src/commands/cloud-demote.test.ts +401 -0
- package/src/commands/cloud-demote.ts +277 -0
- package/src/index.ts +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [5.10.0] — 2026-05-04
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **`hq cloud demote company <slug>` subcommand** — inverse of
|
|
8
|
+
`hq cloud provision company`. Converts a cloud-backed company back to local-only
|
|
9
|
+
after its entity has been soft-tombstoned in hq-console (Settings → Delete company).
|
|
10
|
+
Removes `companies/<slug>/.hq/config.json`, flips `cloud: true → false` in
|
|
11
|
+
`companies/<slug>/company.yaml`, and strips `cloud_uid` + `bucket_name` from
|
|
12
|
+
`companies/manifest.yaml`. Default safety check verifies the cloud entity is
|
|
13
|
+
`deleted=true`; `--force` skips the check (used by AppBar HQ Sync's Path A after
|
|
14
|
+
it has already verified). All side-effects atomic + idempotent. Exit codes mirror
|
|
15
|
+
`cloud provision` (0 ok, 1 vault HTTP, 2 validation).
|
|
16
|
+
|
|
3
17
|
## [5.9.0] — 2026-05-04
|
|
4
18
|
|
|
5
19
|
### Added
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq cloud demote company <slug>` — convert a cloud-backed company back to
|
|
3
|
+
* local-only after hq-pro has soft-tombstoned its entity (Settings → Delete
|
|
4
|
+
* company in hq-console).
|
|
5
|
+
*
|
|
6
|
+
* Inverse of `hq cloud provision company <slug>`. Both commands live here in
|
|
7
|
+
* hq-cli so the file-touching contract (manifest patch + per-folder config
|
|
8
|
+
* write + company.yaml mutation) is single-sourced. AppBar HQ Sync's Path A
|
|
9
|
+
* shells out to this command on the `deleted=true` branch instead of
|
|
10
|
+
* re-implementing the file mutations in Rust.
|
|
11
|
+
*
|
|
12
|
+
* Side-effects (all atomic + idempotent):
|
|
13
|
+
* 1. Remove `companies/<slug>/.hq/config.json`.
|
|
14
|
+
* 2. Flip `cloud: true → false` in `companies/<slug>/company.yaml`. Without
|
|
15
|
+
* this flip the next `provisionCompany` would re-mint a fresh cloud
|
|
16
|
+
* company — exactly what the user just deleted.
|
|
17
|
+
* 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
|
|
18
|
+
* `companies.<slug>` entry. The slug entry + other fields stay.
|
|
19
|
+
*
|
|
20
|
+
* Safety check (default on): `findCompanyBySlug` MUST return an entity with
|
|
21
|
+
* `deleted: true`. A live entity, or no entity at all, refuses with code 2.
|
|
22
|
+
* `--force` skips the network call (AppBar passes it because Path A just
|
|
23
|
+
* checked).
|
|
24
|
+
*
|
|
25
|
+
* Exit codes (mirrors cloud-provision):
|
|
26
|
+
* 0 — success or idempotent no-op.
|
|
27
|
+
* 1 — vault HTTP failure during the safety check.
|
|
28
|
+
* 2 — validation (bad slug, missing dir/manifest, cloud not deleted).
|
|
29
|
+
*/
|
|
30
|
+
import { Command } from "commander";
|
|
31
|
+
import { type VaultClient } from "./cloud-provision.js";
|
|
32
|
+
/** Final stdout JSON shape. AppBar parses this. */
|
|
33
|
+
export interface DemoteResult {
|
|
34
|
+
ok: boolean;
|
|
35
|
+
company_slug: string;
|
|
36
|
+
/** True if `.hq/config.json` was actually deleted (false if absent). */
|
|
37
|
+
config_removed: boolean;
|
|
38
|
+
/** True if `company.yaml`'s `cloud` was changed (true→false or absent→false). */
|
|
39
|
+
yaml_flipped: boolean;
|
|
40
|
+
/** True if manifest had `cloud_uid` / `bucket_name` to strip. */
|
|
41
|
+
manifest_stripped: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* `true` when the cloud entity verified as `deleted=true`. `null` when
|
|
44
|
+
* `--force` was used and the verify was skipped. (`false` is unreachable —
|
|
45
|
+
* a non-deleted entity throws code 2 before reaching the result.)
|
|
46
|
+
*/
|
|
47
|
+
cloud_was_deleted: boolean | null;
|
|
48
|
+
}
|
|
49
|
+
export interface DemoteCompanyOptions {
|
|
50
|
+
slug: string;
|
|
51
|
+
hqRoot: string;
|
|
52
|
+
vaultApiUrl: string;
|
|
53
|
+
/** Skip the `findCompanyBySlug` safety check. AppBar uses this. */
|
|
54
|
+
force?: boolean;
|
|
55
|
+
/** Injected vault HTTP client (override for tests). */
|
|
56
|
+
vaultClient?: VaultClient;
|
|
57
|
+
/** Injected access-token resolver (override for tests). */
|
|
58
|
+
resolveAccessToken?: () => Promise<string>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Flip `cloud: true → false` in `companies/<slug>/company.yaml`. All other
|
|
62
|
+
* keys + ordering preserved (js-yaml round-trip). Atomic (tmp + rename).
|
|
63
|
+
*
|
|
64
|
+
* Returns true if the file was changed, false if no-op (file missing, or
|
|
65
|
+
* `cloud` was already `false`).
|
|
66
|
+
*
|
|
67
|
+
* NOTE: js-yaml doesn't preserve comments, but this matches what
|
|
68
|
+
* `patchManifest` already does — accepted trade-off.
|
|
69
|
+
*/
|
|
70
|
+
export declare function flipCompanyYamlCloudOff(hqRoot: string, slug: string): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Remove `cloud_uid` + `bucket_name` from `companies.<slug>` in
|
|
73
|
+
* `companies/manifest.yaml`. The slug entry is preserved (other fields like
|
|
74
|
+
* `name`/`status`/`path` stay). Atomic (tmp + rename).
|
|
75
|
+
*
|
|
76
|
+
* Returns true if the file was changed, false if no-op (manifest missing,
|
|
77
|
+
* slug missing, or both fields already absent).
|
|
78
|
+
*/
|
|
79
|
+
export declare function stripManifestCloudForSlug(hqRoot: string, slug: string): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Run the full demote flow. Returns a `DemoteResult` on success; throws
|
|
82
|
+
* `ProvisionError` (codes 1 or 2) on any failure.
|
|
83
|
+
*/
|
|
84
|
+
export declare function demoteCompany(options: DemoteCompanyOptions): Promise<DemoteResult>;
|
|
85
|
+
/**
|
|
86
|
+
* Register `demote company <slug>` under the `cloud` command group. Wired in
|
|
87
|
+
* `src/index.ts` alongside `registerCloudProvisionCommands(cloudCmd)`.
|
|
88
|
+
*/
|
|
89
|
+
export declare function registerCloudDemoteCommands(program: Command): void;
|
|
90
|
+
//# sourceMappingURL=cloud-demote.d.ts.map
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq cloud demote company <slug>` — convert a cloud-backed company back to
|
|
3
|
+
* local-only after hq-pro has soft-tombstoned its entity (Settings → Delete
|
|
4
|
+
* company in hq-console).
|
|
5
|
+
*
|
|
6
|
+
* Inverse of `hq cloud provision company <slug>`. Both commands live here in
|
|
7
|
+
* hq-cli so the file-touching contract (manifest patch + per-folder config
|
|
8
|
+
* write + company.yaml mutation) is single-sourced. AppBar HQ Sync's Path A
|
|
9
|
+
* shells out to this command on the `deleted=true` branch instead of
|
|
10
|
+
* re-implementing the file mutations in Rust.
|
|
11
|
+
*
|
|
12
|
+
* Side-effects (all atomic + idempotent):
|
|
13
|
+
* 1. Remove `companies/<slug>/.hq/config.json`.
|
|
14
|
+
* 2. Flip `cloud: true → false` in `companies/<slug>/company.yaml`. Without
|
|
15
|
+
* this flip the next `provisionCompany` would re-mint a fresh cloud
|
|
16
|
+
* company — exactly what the user just deleted.
|
|
17
|
+
* 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
|
|
18
|
+
* `companies.<slug>` entry. The slug entry + other fields stay.
|
|
19
|
+
*
|
|
20
|
+
* Safety check (default on): `findCompanyBySlug` MUST return an entity with
|
|
21
|
+
* `deleted: true`. A live entity, or no entity at all, refuses with code 2.
|
|
22
|
+
* `--force` skips the network call (AppBar passes it because Path A just
|
|
23
|
+
* checked).
|
|
24
|
+
*
|
|
25
|
+
* Exit codes (mirrors cloud-provision):
|
|
26
|
+
* 0 — success or idempotent no-op.
|
|
27
|
+
* 1 — vault HTTP failure during the safety check.
|
|
28
|
+
* 2 — validation (bad slug, missing dir/manifest, cloud not deleted).
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
!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]="6b5cd717-bba0-5dd4-a743-a070e8a62a6b")}catch(e){}}();
|
|
32
|
+
import * as fs from "node:fs";
|
|
33
|
+
import * as path from "node:path";
|
|
34
|
+
import * as yaml from "js-yaml";
|
|
35
|
+
import chalk from "chalk";
|
|
36
|
+
import { ProvisionError, companyConfigPath, companyDirPath, createDefaultVaultClient, manifestPath, validateManifestAndDir, validateSlug, } from "./cloud-provision.js";
|
|
37
|
+
import { DEFAULT_HQ_ROOT, DEFAULT_VAULT_API_URL, ensureCognitoToken, } from "../utils/cognito-session.js";
|
|
38
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
39
|
+
/**
|
|
40
|
+
* Flip `cloud: true → false` in `companies/<slug>/company.yaml`. All other
|
|
41
|
+
* keys + ordering preserved (js-yaml round-trip). Atomic (tmp + rename).
|
|
42
|
+
*
|
|
43
|
+
* Returns true if the file was changed, false if no-op (file missing, or
|
|
44
|
+
* `cloud` was already `false`).
|
|
45
|
+
*
|
|
46
|
+
* NOTE: js-yaml doesn't preserve comments, but this matches what
|
|
47
|
+
* `patchManifest` already does — accepted trade-off.
|
|
48
|
+
*/
|
|
49
|
+
export function flipCompanyYamlCloudOff(hqRoot, slug) {
|
|
50
|
+
const yPath = path.join(companyDirPath(hqRoot, slug), "company.yaml");
|
|
51
|
+
if (!fs.existsSync(yPath))
|
|
52
|
+
return false;
|
|
53
|
+
const raw = fs.readFileSync(yPath, "utf-8");
|
|
54
|
+
const parsed = yaml.load(raw) ?? {};
|
|
55
|
+
if (parsed.cloud === false)
|
|
56
|
+
return false;
|
|
57
|
+
parsed.cloud = false;
|
|
58
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
59
|
+
const tmp = `${yPath}.tmp.${process.pid}`;
|
|
60
|
+
fs.writeFileSync(tmp, dump);
|
|
61
|
+
fs.renameSync(tmp, yPath);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Remove `cloud_uid` + `bucket_name` from `companies.<slug>` in
|
|
66
|
+
* `companies/manifest.yaml`. The slug entry is preserved (other fields like
|
|
67
|
+
* `name`/`status`/`path` stay). Atomic (tmp + rename).
|
|
68
|
+
*
|
|
69
|
+
* Returns true if the file was changed, false if no-op (manifest missing,
|
|
70
|
+
* slug missing, or both fields already absent).
|
|
71
|
+
*/
|
|
72
|
+
export function stripManifestCloudForSlug(hqRoot, slug) {
|
|
73
|
+
const mPath = manifestPath(hqRoot);
|
|
74
|
+
if (!fs.existsSync(mPath))
|
|
75
|
+
return false;
|
|
76
|
+
const raw = fs.readFileSync(mPath, "utf-8");
|
|
77
|
+
const parsed = yaml.load(raw) ?? {};
|
|
78
|
+
const companies = parsed.companies;
|
|
79
|
+
if (!companies || !(slug in companies))
|
|
80
|
+
return false;
|
|
81
|
+
const entry = companies[slug];
|
|
82
|
+
if (!entry || typeof entry !== "object")
|
|
83
|
+
return false;
|
|
84
|
+
const obj = entry;
|
|
85
|
+
const hadCloudUid = "cloud_uid" in obj;
|
|
86
|
+
const hadBucketName = "bucket_name" in obj;
|
|
87
|
+
if (!hadCloudUid && !hadBucketName)
|
|
88
|
+
return false;
|
|
89
|
+
delete obj.cloud_uid;
|
|
90
|
+
delete obj.bucket_name;
|
|
91
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
92
|
+
const tmp = `${mPath}.tmp.${process.pid}`;
|
|
93
|
+
fs.writeFileSync(tmp, dump);
|
|
94
|
+
fs.renameSync(tmp, mPath);
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
// ── Orchestrator ─────────────────────────────────────────────────────────────
|
|
98
|
+
/**
|
|
99
|
+
* Run the full demote flow. Returns a `DemoteResult` on success; throws
|
|
100
|
+
* `ProvisionError` (codes 1 or 2) on any failure.
|
|
101
|
+
*/
|
|
102
|
+
export async function demoteCompany(options) {
|
|
103
|
+
validateSlug(options.slug);
|
|
104
|
+
// Fails with code 2 if the manifest is missing/malformed, the slug is not
|
|
105
|
+
// present under `.companies`, or `companies/<slug>/` doesn't exist on disk.
|
|
106
|
+
// Without this, a `--force` demote against a missing or renamed slug would
|
|
107
|
+
// be a silent no-op (all helpers return false but we'd still report ok=true).
|
|
108
|
+
validateManifestAndDir(options.hqRoot, options.slug);
|
|
109
|
+
let cloudWasDeleted = null;
|
|
110
|
+
if (!options.force) {
|
|
111
|
+
const accessToken = options.resolveAccessToken
|
|
112
|
+
? await options.resolveAccessToken()
|
|
113
|
+
: await ensureCognitoToken();
|
|
114
|
+
const client = options.vaultClient ??
|
|
115
|
+
createDefaultVaultClient(options.vaultApiUrl, accessToken);
|
|
116
|
+
let entity;
|
|
117
|
+
try {
|
|
118
|
+
entity = await client.findCompanyBySlug(options.slug);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
if (err instanceof ProvisionError)
|
|
122
|
+
throw err;
|
|
123
|
+
throw new ProvisionError(1, `Vault GET by-slug failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
124
|
+
}
|
|
125
|
+
if (!entity) {
|
|
126
|
+
throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found. Pass --force to demote anyway.`);
|
|
127
|
+
}
|
|
128
|
+
// `deleted` is added by hq-pro and isn't in the static VaultEntity type.
|
|
129
|
+
const deleted = entity.deleted === true;
|
|
130
|
+
if (!deleted) {
|
|
131
|
+
throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
|
|
132
|
+
}
|
|
133
|
+
cloudWasDeleted = true;
|
|
134
|
+
}
|
|
135
|
+
const cPath = companyConfigPath(options.hqRoot, options.slug);
|
|
136
|
+
let configRemoved = false;
|
|
137
|
+
if (fs.existsSync(cPath)) {
|
|
138
|
+
fs.rmSync(cPath);
|
|
139
|
+
configRemoved = true;
|
|
140
|
+
}
|
|
141
|
+
const yamlFlipped = flipCompanyYamlCloudOff(options.hqRoot, options.slug);
|
|
142
|
+
const manifestStripped = stripManifestCloudForSlug(options.hqRoot, options.slug);
|
|
143
|
+
return {
|
|
144
|
+
ok: true,
|
|
145
|
+
company_slug: options.slug,
|
|
146
|
+
config_removed: configRemoved,
|
|
147
|
+
yaml_flipped: yamlFlipped,
|
|
148
|
+
manifest_stripped: manifestStripped,
|
|
149
|
+
cloud_was_deleted: cloudWasDeleted,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
// ── Commander wiring ─────────────────────────────────────────────────────────
|
|
153
|
+
/**
|
|
154
|
+
* Register `demote company <slug>` under the `cloud` command group. Wired in
|
|
155
|
+
* `src/index.ts` alongside `registerCloudProvisionCommands(cloudCmd)`.
|
|
156
|
+
*/
|
|
157
|
+
export function registerCloudDemoteCommands(program) {
|
|
158
|
+
const demoteCmd = program
|
|
159
|
+
.command("demote")
|
|
160
|
+
.description("Demote a cloud-backed entity back to local-only");
|
|
161
|
+
demoteCmd
|
|
162
|
+
.command("company")
|
|
163
|
+
.description("Demote a cloud-backed company to local-only after the cloud entity " +
|
|
164
|
+
"has been soft-tombstoned in hq-console. Removes .hq/config.json, " +
|
|
165
|
+
"flips company.yaml `cloud: false`, and strips the manifest cloud refs.")
|
|
166
|
+
.argument("<slug>", "Company slug")
|
|
167
|
+
.option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
|
|
168
|
+
.option("--vault-api-url <url>", `Vault API URL (default: ${DEFAULT_VAULT_API_URL})`, DEFAULT_VAULT_API_URL)
|
|
169
|
+
.option("--force", "Skip the safety check that the cloud entity is actually deleted=true. " +
|
|
170
|
+
"AppBar HQ Sync passes this because its Path A just verified.")
|
|
171
|
+
.action(async (slug, options) => {
|
|
172
|
+
try {
|
|
173
|
+
const result = await demoteCompany({
|
|
174
|
+
slug,
|
|
175
|
+
hqRoot: options.hqRoot,
|
|
176
|
+
vaultApiUrl: options.vaultApiUrl,
|
|
177
|
+
force: options.force,
|
|
178
|
+
});
|
|
179
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
180
|
+
process.exit(0);
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
if (err instanceof ProvisionError) {
|
|
184
|
+
process.stderr.write(chalk.red(`[hq cloud demote] ${err.message}\n`));
|
|
185
|
+
process.exit(err.code);
|
|
186
|
+
}
|
|
187
|
+
process.stderr.write(chalk.red(`[hq cloud demote] Unexpected error: ${err instanceof Error ? err.message : String(err)}\n`));
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=cloud-demote.js.map
|
|
193
|
+
//# debugId=6b5cd717-bba0-5dd4-a743-a070e8a62a6b
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* HQ CLI - Module management, package management, and cloud sync for HQ
|
|
4
4
|
*/
|
|
5
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]="
|
|
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]="ebc3116c-f836-550a-b5bb-4a74bce24abc")}catch(e){}}();
|
|
7
7
|
import { Command } from "commander";
|
|
8
8
|
import { initSentry, Sentry } from "./sentry.js";
|
|
9
9
|
import { registerAddCommand } from "./commands/add.js";
|
|
@@ -12,6 +12,7 @@ import { registerListCommand } from "./commands/list.js";
|
|
|
12
12
|
import { registerUpdateCommand } from "./commands/update.js";
|
|
13
13
|
import { registerCloudCommands } from "./commands/cloud.js";
|
|
14
14
|
import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
|
|
15
|
+
import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
|
|
15
16
|
import { registerLoginCommand } from "./commands/login.js";
|
|
16
17
|
import { registerLogoutCommand } from "./commands/logout.js";
|
|
17
18
|
import { registerWhoamiCommand } from "./commands/whoami.js";
|
|
@@ -64,6 +65,7 @@ const cloudCmd = program
|
|
|
64
65
|
.command("cloud")
|
|
65
66
|
.description("Cloud commands — provision entities and manage cloud-backed companies");
|
|
66
67
|
registerCloudProvisionCommands(cloudCmd);
|
|
68
|
+
registerCloudDemoteCommands(cloudCmd);
|
|
67
69
|
// Team commands (top-level)
|
|
68
70
|
registerTeamSyncCommand(program);
|
|
69
71
|
// Auth commands (top-level — Cognito OAuth)
|
|
@@ -94,4 +96,4 @@ registerOnboardCommand(program);
|
|
|
94
96
|
}
|
|
95
97
|
})();
|
|
96
98
|
//# sourceMappingURL=index.js.map
|
|
97
|
-
//# debugId=
|
|
99
|
+
//# debugId=ebc3116c-f836-550a-b5bb-4a74bce24abc
|
package/package.json
CHANGED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for `hq cloud demote company <slug>` (cloud-demote.ts).
|
|
3
|
+
*
|
|
4
|
+
* Mirrors the cloud-provision test layout: tmp HQ root per test, helpers
|
|
5
|
+
* seed manifests + company yaml + .hq/config.json, then the orchestrator
|
|
6
|
+
* runs with an injected `findCompanyBySlug`.
|
|
7
|
+
*
|
|
8
|
+
* Coverage:
|
|
9
|
+
* - flipCompanyYamlCloudOff — atomic mutation, preserves other keys
|
|
10
|
+
* - stripManifestCloudForSlug — removes cloud_uid + bucket_name only
|
|
11
|
+
* - demoteCompany — full orchestrator (verify + side-effects + JSON shape)
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
15
|
+
import * as fs from "node:fs";
|
|
16
|
+
import * as os from "node:os";
|
|
17
|
+
import * as path from "node:path";
|
|
18
|
+
import * as yaml from "js-yaml";
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
ProvisionError,
|
|
22
|
+
manifestPath,
|
|
23
|
+
companyDirPath,
|
|
24
|
+
companyConfigPath,
|
|
25
|
+
type VaultEntity,
|
|
26
|
+
} from "./cloud-provision.js";
|
|
27
|
+
import {
|
|
28
|
+
demoteCompany,
|
|
29
|
+
flipCompanyYamlCloudOff,
|
|
30
|
+
stripManifestCloudForSlug,
|
|
31
|
+
type DemoteResult,
|
|
32
|
+
} from "./cloud-demote.js";
|
|
33
|
+
|
|
34
|
+
// ── Test fixtures ────────────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
let tmpRoot: string;
|
|
37
|
+
|
|
38
|
+
function seedManifest(
|
|
39
|
+
root: string,
|
|
40
|
+
companies: Record<string, Record<string, unknown> | null> = {
|
|
41
|
+
acme: {
|
|
42
|
+
name: "Acme",
|
|
43
|
+
cloud_uid: "cmp_old",
|
|
44
|
+
bucket_name: "hq-vault-cmp-old",
|
|
45
|
+
status: "active",
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
): void {
|
|
49
|
+
const mPath = manifestPath(root);
|
|
50
|
+
fs.mkdirSync(path.dirname(mPath), { recursive: true });
|
|
51
|
+
fs.writeFileSync(mPath, yaml.dump({ companies }));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function seedCompanyDir(root: string, slug: string, yamlBody?: string): void {
|
|
55
|
+
const dir = companyDirPath(root, slug);
|
|
56
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
57
|
+
if (yamlBody !== undefined) {
|
|
58
|
+
fs.writeFileSync(path.join(dir, "company.yaml"), yamlBody);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function seedCompanyConfig(root: string, slug: string): void {
|
|
63
|
+
const cPath = companyConfigPath(root, slug);
|
|
64
|
+
fs.mkdirSync(path.dirname(cPath), { recursive: true });
|
|
65
|
+
fs.writeFileSync(
|
|
66
|
+
cPath,
|
|
67
|
+
JSON.stringify(
|
|
68
|
+
{
|
|
69
|
+
companyUid: "cmp_old",
|
|
70
|
+
companySlug: slug,
|
|
71
|
+
bucketName: "hq-vault-cmp-old",
|
|
72
|
+
vaultApiUrl: "https://v",
|
|
73
|
+
},
|
|
74
|
+
null,
|
|
75
|
+
2,
|
|
76
|
+
),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function readManifest(root: string): { companies?: Record<string, unknown> } {
|
|
81
|
+
return yaml.load(fs.readFileSync(manifestPath(root), "utf-8")) as {
|
|
82
|
+
companies?: Record<string, unknown>;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function readCompanyYaml(root: string, slug: string): Record<string, unknown> {
|
|
87
|
+
return yaml.load(
|
|
88
|
+
fs.readFileSync(path.join(companyDirPath(root, slug), "company.yaml"), "utf-8"),
|
|
89
|
+
) as Record<string, unknown>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
beforeEach(() => {
|
|
93
|
+
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-demote-test-"));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
afterEach(() => {
|
|
97
|
+
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
98
|
+
vi.restoreAllMocks();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// ── flipCompanyYamlCloudOff ──────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
describe("flipCompanyYamlCloudOff", () => {
|
|
104
|
+
it("flips cloud: true → false and preserves other keys", () => {
|
|
105
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\nname: Acme\nfoo: bar\n");
|
|
106
|
+
const changed = flipCompanyYamlCloudOff(tmpRoot, "acme");
|
|
107
|
+
expect(changed).toBe(true);
|
|
108
|
+
const after = readCompanyYaml(tmpRoot, "acme");
|
|
109
|
+
expect(after.cloud).toBe(false);
|
|
110
|
+
expect(after.name).toBe("Acme");
|
|
111
|
+
expect(after.foo).toBe("bar");
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("is idempotent when cloud is already false", () => {
|
|
115
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: false\nname: Acme\n");
|
|
116
|
+
const changed = flipCompanyYamlCloudOff(tmpRoot, "acme");
|
|
117
|
+
expect(changed).toBe(false);
|
|
118
|
+
expect(readCompanyYaml(tmpRoot, "acme").cloud).toBe(false);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("inserts cloud: false when the field is missing", () => {
|
|
122
|
+
seedCompanyDir(tmpRoot, "acme", "name: Acme\n");
|
|
123
|
+
const changed = flipCompanyYamlCloudOff(tmpRoot, "acme");
|
|
124
|
+
expect(changed).toBe(true);
|
|
125
|
+
expect(readCompanyYaml(tmpRoot, "acme").cloud).toBe(false);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("returns false when company.yaml does not exist", () => {
|
|
129
|
+
seedCompanyDir(tmpRoot, "acme"); // no yaml
|
|
130
|
+
const changed = flipCompanyYamlCloudOff(tmpRoot, "acme");
|
|
131
|
+
expect(changed).toBe(false);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("does not leave a .tmp file behind on success", () => {
|
|
135
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\n");
|
|
136
|
+
flipCompanyYamlCloudOff(tmpRoot, "acme");
|
|
137
|
+
const dir = companyDirPath(tmpRoot, "acme");
|
|
138
|
+
const tmps = fs.readdirSync(dir).filter((f) => f.includes(".tmp."));
|
|
139
|
+
expect(tmps).toEqual([]);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// ── stripManifestCloudForSlug ────────────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
describe("stripManifestCloudForSlug", () => {
|
|
146
|
+
it("removes cloud_uid + bucket_name from the slug entry", () => {
|
|
147
|
+
seedManifest(tmpRoot);
|
|
148
|
+
const changed = stripManifestCloudForSlug(tmpRoot, "acme");
|
|
149
|
+
expect(changed).toBe(true);
|
|
150
|
+
const m = readManifest(tmpRoot);
|
|
151
|
+
const entry = m.companies?.acme as Record<string, unknown>;
|
|
152
|
+
expect(entry.cloud_uid).toBeUndefined();
|
|
153
|
+
expect(entry.bucket_name).toBeUndefined();
|
|
154
|
+
// Other fields preserved.
|
|
155
|
+
expect(entry.name).toBe("Acme");
|
|
156
|
+
expect(entry.status).toBe("active");
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("preserves other companies untouched", () => {
|
|
160
|
+
seedManifest(tmpRoot, {
|
|
161
|
+
acme: { cloud_uid: "cmp_a", bucket_name: "b-a" },
|
|
162
|
+
voyage: { cloud_uid: "cmp_v", bucket_name: "b-v" },
|
|
163
|
+
});
|
|
164
|
+
stripManifestCloudForSlug(tmpRoot, "acme");
|
|
165
|
+
const m = readManifest(tmpRoot);
|
|
166
|
+
const voyage = m.companies?.voyage as Record<string, unknown>;
|
|
167
|
+
expect(voyage.cloud_uid).toBe("cmp_v");
|
|
168
|
+
expect(voyage.bucket_name).toBe("b-v");
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("is idempotent — second call reports no change", () => {
|
|
172
|
+
seedManifest(tmpRoot, { acme: { name: "Acme" } });
|
|
173
|
+
expect(stripManifestCloudForSlug(tmpRoot, "acme")).toBe(false);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("returns false when the manifest does not exist", () => {
|
|
177
|
+
// No seed.
|
|
178
|
+
expect(stripManifestCloudForSlug(tmpRoot, "acme")).toBe(false);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("returns false when the slug is missing from the manifest", () => {
|
|
182
|
+
seedManifest(tmpRoot, { other: { cloud_uid: "x" } });
|
|
183
|
+
expect(stripManifestCloudForSlug(tmpRoot, "acme")).toBe(false);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// ── demoteCompany orchestrator ───────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
function tombstonedEntity(slug: string): VaultEntity {
|
|
190
|
+
return {
|
|
191
|
+
uid: "cmp_old",
|
|
192
|
+
type: "company",
|
|
193
|
+
slug,
|
|
194
|
+
name: slug,
|
|
195
|
+
bucketName: "hq-vault-cmp-old",
|
|
196
|
+
status: "active",
|
|
197
|
+
// @ts-expect-error — `deleted` is added on hq-pro side; VaultEntity
|
|
198
|
+
// doesn't declare it, but the verify path reads it dynamically.
|
|
199
|
+
deleted: true,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function liveEntity(slug: string): VaultEntity {
|
|
204
|
+
return {
|
|
205
|
+
uid: "cmp_old",
|
|
206
|
+
type: "company",
|
|
207
|
+
slug,
|
|
208
|
+
name: slug,
|
|
209
|
+
bucketName: "hq-vault-cmp-old",
|
|
210
|
+
status: "active",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
describe("demoteCompany — happy path", () => {
|
|
215
|
+
it("removes config, flips yaml, strips manifest, returns full result", async () => {
|
|
216
|
+
seedManifest(tmpRoot);
|
|
217
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\nname: Acme\n");
|
|
218
|
+
seedCompanyConfig(tmpRoot, "acme");
|
|
219
|
+
|
|
220
|
+
const result: DemoteResult = await demoteCompany({
|
|
221
|
+
slug: "acme",
|
|
222
|
+
hqRoot: tmpRoot,
|
|
223
|
+
vaultApiUrl: "https://v",
|
|
224
|
+
vaultClient: {
|
|
225
|
+
findCompanyBySlug: async () => tombstonedEntity("acme"),
|
|
226
|
+
// unused on the demote path, but the type requires it
|
|
227
|
+
createCompanyEntity: async () => {
|
|
228
|
+
throw new Error("must not call createCompanyEntity from demote");
|
|
229
|
+
},
|
|
230
|
+
},
|
|
231
|
+
resolveAccessToken: async () => "tok",
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
expect(result).toEqual<DemoteResult>({
|
|
235
|
+
ok: true,
|
|
236
|
+
company_slug: "acme",
|
|
237
|
+
config_removed: true,
|
|
238
|
+
yaml_flipped: true,
|
|
239
|
+
manifest_stripped: true,
|
|
240
|
+
cloud_was_deleted: true,
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// Side-effects landed.
|
|
244
|
+
expect(fs.existsSync(companyConfigPath(tmpRoot, "acme"))).toBe(false);
|
|
245
|
+
expect(readCompanyYaml(tmpRoot, "acme").cloud).toBe(false);
|
|
246
|
+
const entry = readManifest(tmpRoot).companies?.acme as Record<string, unknown>;
|
|
247
|
+
expect(entry.cloud_uid).toBeUndefined();
|
|
248
|
+
expect(entry.bucket_name).toBeUndefined();
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it("is idempotent — re-running on an already-demoted company is a no-op", async () => {
|
|
252
|
+
// Already in post-demote state.
|
|
253
|
+
seedManifest(tmpRoot, { acme: { name: "Acme" } });
|
|
254
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: false\nname: Acme\n");
|
|
255
|
+
|
|
256
|
+
const result = await demoteCompany({
|
|
257
|
+
slug: "acme",
|
|
258
|
+
hqRoot: tmpRoot,
|
|
259
|
+
vaultApiUrl: "https://v",
|
|
260
|
+
vaultClient: {
|
|
261
|
+
findCompanyBySlug: async () => tombstonedEntity("acme"),
|
|
262
|
+
createCompanyEntity: async () => {
|
|
263
|
+
throw new Error("unused");
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
resolveAccessToken: async () => "tok",
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
expect(result.ok).toBe(true);
|
|
270
|
+
expect(result.config_removed).toBe(false);
|
|
271
|
+
expect(result.yaml_flipped).toBe(false);
|
|
272
|
+
expect(result.manifest_stripped).toBe(false);
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
describe("demoteCompany — safety check", () => {
|
|
277
|
+
it("refuses to demote when the cloud entity is NOT deleted (no --force)", async () => {
|
|
278
|
+
seedManifest(tmpRoot);
|
|
279
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\nname: Acme\n");
|
|
280
|
+
seedCompanyConfig(tmpRoot, "acme");
|
|
281
|
+
|
|
282
|
+
await expect(
|
|
283
|
+
demoteCompany({
|
|
284
|
+
slug: "acme",
|
|
285
|
+
hqRoot: tmpRoot,
|
|
286
|
+
vaultApiUrl: "https://v",
|
|
287
|
+
vaultClient: {
|
|
288
|
+
findCompanyBySlug: async () => liveEntity("acme"),
|
|
289
|
+
createCompanyEntity: async () => {
|
|
290
|
+
throw new Error("unused");
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
resolveAccessToken: async () => "tok",
|
|
294
|
+
}),
|
|
295
|
+
).rejects.toMatchObject({
|
|
296
|
+
code: 2,
|
|
297
|
+
message: expect.stringMatching(/not.*deleted/i),
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// No side-effects.
|
|
301
|
+
expect(fs.existsSync(companyConfigPath(tmpRoot, "acme"))).toBe(true);
|
|
302
|
+
expect(readCompanyYaml(tmpRoot, "acme").cloud).toBe(true);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("refuses to demote when the cloud entity does not exist (no --force)", async () => {
|
|
306
|
+
seedManifest(tmpRoot);
|
|
307
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\nname: Acme\n");
|
|
308
|
+
seedCompanyConfig(tmpRoot, "acme");
|
|
309
|
+
|
|
310
|
+
await expect(
|
|
311
|
+
demoteCompany({
|
|
312
|
+
slug: "acme",
|
|
313
|
+
hqRoot: tmpRoot,
|
|
314
|
+
vaultApiUrl: "https://v",
|
|
315
|
+
vaultClient: {
|
|
316
|
+
findCompanyBySlug: async () => null,
|
|
317
|
+
createCompanyEntity: async () => {
|
|
318
|
+
throw new Error("unused");
|
|
319
|
+
},
|
|
320
|
+
},
|
|
321
|
+
resolveAccessToken: async () => "tok",
|
|
322
|
+
}),
|
|
323
|
+
).rejects.toMatchObject({ code: 2 });
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it("--force skips the verify and demotes anyway, recording cloud_was_deleted=null", async () => {
|
|
327
|
+
seedManifest(tmpRoot);
|
|
328
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\nname: Acme\n");
|
|
329
|
+
seedCompanyConfig(tmpRoot, "acme");
|
|
330
|
+
|
|
331
|
+
const find = vi.fn(async () => liveEntity("acme"));
|
|
332
|
+
const result = await demoteCompany({
|
|
333
|
+
slug: "acme",
|
|
334
|
+
hqRoot: tmpRoot,
|
|
335
|
+
vaultApiUrl: "https://v",
|
|
336
|
+
force: true,
|
|
337
|
+
vaultClient: {
|
|
338
|
+
findCompanyBySlug: find,
|
|
339
|
+
createCompanyEntity: async () => {
|
|
340
|
+
throw new Error("unused");
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
resolveAccessToken: async () => "tok",
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
expect(result.ok).toBe(true);
|
|
347
|
+
expect(result.cloud_was_deleted).toBeNull();
|
|
348
|
+
// --force MUST skip the network call entirely.
|
|
349
|
+
expect(find).not.toHaveBeenCalled();
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it("validateSlug rejects bad slugs with code 2", async () => {
|
|
353
|
+
await expect(
|
|
354
|
+
demoteCompany({
|
|
355
|
+
slug: "personal", // reserved
|
|
356
|
+
hqRoot: tmpRoot,
|
|
357
|
+
vaultApiUrl: "https://v",
|
|
358
|
+
force: true,
|
|
359
|
+
vaultClient: {
|
|
360
|
+
findCompanyBySlug: async () => null,
|
|
361
|
+
createCompanyEntity: async () => {
|
|
362
|
+
throw new Error("unused");
|
|
363
|
+
},
|
|
364
|
+
},
|
|
365
|
+
resolveAccessToken: async () => "tok",
|
|
366
|
+
}),
|
|
367
|
+
).rejects.toBeInstanceOf(ProvisionError);
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
it("--force on a slug missing from the manifest throws code 2 (no silent no-op)", async () => {
|
|
371
|
+
seedManifest(tmpRoot, { other: { name: "Other" } });
|
|
372
|
+
seedCompanyDir(tmpRoot, "acme", "cloud: true\n");
|
|
373
|
+
await expect(
|
|
374
|
+
demoteCompany({
|
|
375
|
+
slug: "acme",
|
|
376
|
+
hqRoot: tmpRoot,
|
|
377
|
+
vaultApiUrl: "https://v",
|
|
378
|
+
force: true,
|
|
379
|
+
}),
|
|
380
|
+
).rejects.toMatchObject({
|
|
381
|
+
code: 2,
|
|
382
|
+
message: expect.stringMatching(/not found.*manifest/i),
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
it("--force when company directory is missing throws code 2 (no silent no-op)", async () => {
|
|
387
|
+
seedManifest(tmpRoot); // seeds acme entry
|
|
388
|
+
// No seedCompanyDir — directory is missing.
|
|
389
|
+
await expect(
|
|
390
|
+
demoteCompany({
|
|
391
|
+
slug: "acme",
|
|
392
|
+
hqRoot: tmpRoot,
|
|
393
|
+
vaultApiUrl: "https://v",
|
|
394
|
+
force: true,
|
|
395
|
+
}),
|
|
396
|
+
).rejects.toMatchObject({
|
|
397
|
+
code: 2,
|
|
398
|
+
message: expect.stringMatching(/does not exist/i),
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
});
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq cloud demote company <slug>` — convert a cloud-backed company back to
|
|
3
|
+
* local-only after hq-pro has soft-tombstoned its entity (Settings → Delete
|
|
4
|
+
* company in hq-console).
|
|
5
|
+
*
|
|
6
|
+
* Inverse of `hq cloud provision company <slug>`. Both commands live here in
|
|
7
|
+
* hq-cli so the file-touching contract (manifest patch + per-folder config
|
|
8
|
+
* write + company.yaml mutation) is single-sourced. AppBar HQ Sync's Path A
|
|
9
|
+
* shells out to this command on the `deleted=true` branch instead of
|
|
10
|
+
* re-implementing the file mutations in Rust.
|
|
11
|
+
*
|
|
12
|
+
* Side-effects (all atomic + idempotent):
|
|
13
|
+
* 1. Remove `companies/<slug>/.hq/config.json`.
|
|
14
|
+
* 2. Flip `cloud: true → false` in `companies/<slug>/company.yaml`. Without
|
|
15
|
+
* this flip the next `provisionCompany` would re-mint a fresh cloud
|
|
16
|
+
* company — exactly what the user just deleted.
|
|
17
|
+
* 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
|
|
18
|
+
* `companies.<slug>` entry. The slug entry + other fields stay.
|
|
19
|
+
*
|
|
20
|
+
* Safety check (default on): `findCompanyBySlug` MUST return an entity with
|
|
21
|
+
* `deleted: true`. A live entity, or no entity at all, refuses with code 2.
|
|
22
|
+
* `--force` skips the network call (AppBar passes it because Path A just
|
|
23
|
+
* checked).
|
|
24
|
+
*
|
|
25
|
+
* Exit codes (mirrors cloud-provision):
|
|
26
|
+
* 0 — success or idempotent no-op.
|
|
27
|
+
* 1 — vault HTTP failure during the safety check.
|
|
28
|
+
* 2 — validation (bad slug, missing dir/manifest, cloud not deleted).
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import * as fs from "node:fs";
|
|
32
|
+
import * as path from "node:path";
|
|
33
|
+
import * as yaml from "js-yaml";
|
|
34
|
+
import { Command } from "commander";
|
|
35
|
+
import chalk from "chalk";
|
|
36
|
+
|
|
37
|
+
import {
|
|
38
|
+
ProvisionError,
|
|
39
|
+
companyConfigPath,
|
|
40
|
+
companyDirPath,
|
|
41
|
+
createDefaultVaultClient,
|
|
42
|
+
manifestPath,
|
|
43
|
+
validateManifestAndDir,
|
|
44
|
+
validateSlug,
|
|
45
|
+
type VaultClient,
|
|
46
|
+
} from "./cloud-provision.js";
|
|
47
|
+
import {
|
|
48
|
+
DEFAULT_HQ_ROOT,
|
|
49
|
+
DEFAULT_VAULT_API_URL,
|
|
50
|
+
ensureCognitoToken,
|
|
51
|
+
} from "../utils/cognito-session.js";
|
|
52
|
+
|
|
53
|
+
// ── Types ────────────────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
/** Final stdout JSON shape. AppBar parses this. */
|
|
56
|
+
export interface DemoteResult {
|
|
57
|
+
ok: boolean;
|
|
58
|
+
company_slug: string;
|
|
59
|
+
/** True if `.hq/config.json` was actually deleted (false if absent). */
|
|
60
|
+
config_removed: boolean;
|
|
61
|
+
/** True if `company.yaml`'s `cloud` was changed (true→false or absent→false). */
|
|
62
|
+
yaml_flipped: boolean;
|
|
63
|
+
/** True if manifest had `cloud_uid` / `bucket_name` to strip. */
|
|
64
|
+
manifest_stripped: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* `true` when the cloud entity verified as `deleted=true`. `null` when
|
|
67
|
+
* `--force` was used and the verify was skipped. (`false` is unreachable —
|
|
68
|
+
* a non-deleted entity throws code 2 before reaching the result.)
|
|
69
|
+
*/
|
|
70
|
+
cloud_was_deleted: boolean | null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface DemoteCompanyOptions {
|
|
74
|
+
slug: string;
|
|
75
|
+
hqRoot: string;
|
|
76
|
+
vaultApiUrl: string;
|
|
77
|
+
/** Skip the `findCompanyBySlug` safety check. AppBar uses this. */
|
|
78
|
+
force?: boolean;
|
|
79
|
+
/** Injected vault HTTP client (override for tests). */
|
|
80
|
+
vaultClient?: VaultClient;
|
|
81
|
+
/** Injected access-token resolver (override for tests). */
|
|
82
|
+
resolveAccessToken?: () => Promise<string>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Flip `cloud: true → false` in `companies/<slug>/company.yaml`. All other
|
|
89
|
+
* keys + ordering preserved (js-yaml round-trip). Atomic (tmp + rename).
|
|
90
|
+
*
|
|
91
|
+
* Returns true if the file was changed, false if no-op (file missing, or
|
|
92
|
+
* `cloud` was already `false`).
|
|
93
|
+
*
|
|
94
|
+
* NOTE: js-yaml doesn't preserve comments, but this matches what
|
|
95
|
+
* `patchManifest` already does — accepted trade-off.
|
|
96
|
+
*/
|
|
97
|
+
export function flipCompanyYamlCloudOff(hqRoot: string, slug: string): boolean {
|
|
98
|
+
const yPath = path.join(companyDirPath(hqRoot, slug), "company.yaml");
|
|
99
|
+
if (!fs.existsSync(yPath)) return false;
|
|
100
|
+
const raw = fs.readFileSync(yPath, "utf-8");
|
|
101
|
+
const parsed = (yaml.load(raw) as Record<string, unknown> | null) ?? {};
|
|
102
|
+
if (parsed.cloud === false) return false;
|
|
103
|
+
parsed.cloud = false;
|
|
104
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
105
|
+
const tmp = `${yPath}.tmp.${process.pid}`;
|
|
106
|
+
fs.writeFileSync(tmp, dump);
|
|
107
|
+
fs.renameSync(tmp, yPath);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Remove `cloud_uid` + `bucket_name` from `companies.<slug>` in
|
|
113
|
+
* `companies/manifest.yaml`. The slug entry is preserved (other fields like
|
|
114
|
+
* `name`/`status`/`path` stay). Atomic (tmp + rename).
|
|
115
|
+
*
|
|
116
|
+
* Returns true if the file was changed, false if no-op (manifest missing,
|
|
117
|
+
* slug missing, or both fields already absent).
|
|
118
|
+
*/
|
|
119
|
+
export function stripManifestCloudForSlug(hqRoot: string, slug: string): boolean {
|
|
120
|
+
const mPath = manifestPath(hqRoot);
|
|
121
|
+
if (!fs.existsSync(mPath)) return false;
|
|
122
|
+
const raw = fs.readFileSync(mPath, "utf-8");
|
|
123
|
+
const parsed = (yaml.load(raw) as { companies?: Record<string, unknown> } | null) ?? {};
|
|
124
|
+
const companies = parsed.companies;
|
|
125
|
+
if (!companies || !(slug in companies)) return false;
|
|
126
|
+
const entry = companies[slug];
|
|
127
|
+
if (!entry || typeof entry !== "object") return false;
|
|
128
|
+
const obj = entry as Record<string, unknown>;
|
|
129
|
+
const hadCloudUid = "cloud_uid" in obj;
|
|
130
|
+
const hadBucketName = "bucket_name" in obj;
|
|
131
|
+
if (!hadCloudUid && !hadBucketName) return false;
|
|
132
|
+
delete obj.cloud_uid;
|
|
133
|
+
delete obj.bucket_name;
|
|
134
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
135
|
+
const tmp = `${mPath}.tmp.${process.pid}`;
|
|
136
|
+
fs.writeFileSync(tmp, dump);
|
|
137
|
+
fs.renameSync(tmp, mPath);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── Orchestrator ─────────────────────────────────────────────────────────────
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Run the full demote flow. Returns a `DemoteResult` on success; throws
|
|
145
|
+
* `ProvisionError` (codes 1 or 2) on any failure.
|
|
146
|
+
*/
|
|
147
|
+
export async function demoteCompany(
|
|
148
|
+
options: DemoteCompanyOptions,
|
|
149
|
+
): Promise<DemoteResult> {
|
|
150
|
+
validateSlug(options.slug);
|
|
151
|
+
// Fails with code 2 if the manifest is missing/malformed, the slug is not
|
|
152
|
+
// present under `.companies`, or `companies/<slug>/` doesn't exist on disk.
|
|
153
|
+
// Without this, a `--force` demote against a missing or renamed slug would
|
|
154
|
+
// be a silent no-op (all helpers return false but we'd still report ok=true).
|
|
155
|
+
validateManifestAndDir(options.hqRoot, options.slug);
|
|
156
|
+
|
|
157
|
+
let cloudWasDeleted: boolean | null = null;
|
|
158
|
+
|
|
159
|
+
if (!options.force) {
|
|
160
|
+
const accessToken = options.resolveAccessToken
|
|
161
|
+
? await options.resolveAccessToken()
|
|
162
|
+
: await ensureCognitoToken();
|
|
163
|
+
const client =
|
|
164
|
+
options.vaultClient ??
|
|
165
|
+
createDefaultVaultClient(options.vaultApiUrl, accessToken);
|
|
166
|
+
let entity;
|
|
167
|
+
try {
|
|
168
|
+
entity = await client.findCompanyBySlug(options.slug);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
if (err instanceof ProvisionError) throw err;
|
|
171
|
+
throw new ProvisionError(
|
|
172
|
+
1,
|
|
173
|
+
`Vault GET by-slug failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
if (!entity) {
|
|
177
|
+
throw new ProvisionError(
|
|
178
|
+
2,
|
|
179
|
+
`Refusing to demote '${options.slug}': no cloud entity found. Pass --force to demote anyway.`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
// `deleted` is added by hq-pro and isn't in the static VaultEntity type.
|
|
183
|
+
const deleted = (entity as unknown as { deleted?: boolean }).deleted === true;
|
|
184
|
+
if (!deleted) {
|
|
185
|
+
throw new ProvisionError(
|
|
186
|
+
2,
|
|
187
|
+
`Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
cloudWasDeleted = true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const cPath = companyConfigPath(options.hqRoot, options.slug);
|
|
194
|
+
let configRemoved = false;
|
|
195
|
+
if (fs.existsSync(cPath)) {
|
|
196
|
+
fs.rmSync(cPath);
|
|
197
|
+
configRemoved = true;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const yamlFlipped = flipCompanyYamlCloudOff(options.hqRoot, options.slug);
|
|
201
|
+
const manifestStripped = stripManifestCloudForSlug(options.hqRoot, options.slug);
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
ok: true,
|
|
205
|
+
company_slug: options.slug,
|
|
206
|
+
config_removed: configRemoved,
|
|
207
|
+
yaml_flipped: yamlFlipped,
|
|
208
|
+
manifest_stripped: manifestStripped,
|
|
209
|
+
cloud_was_deleted: cloudWasDeleted,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── Commander wiring ─────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Register `demote company <slug>` under the `cloud` command group. Wired in
|
|
217
|
+
* `src/index.ts` alongside `registerCloudProvisionCommands(cloudCmd)`.
|
|
218
|
+
*/
|
|
219
|
+
export function registerCloudDemoteCommands(program: Command): void {
|
|
220
|
+
const demoteCmd = program
|
|
221
|
+
.command("demote")
|
|
222
|
+
.description("Demote a cloud-backed entity back to local-only");
|
|
223
|
+
|
|
224
|
+
demoteCmd
|
|
225
|
+
.command("company")
|
|
226
|
+
.description(
|
|
227
|
+
"Demote a cloud-backed company to local-only after the cloud entity " +
|
|
228
|
+
"has been soft-tombstoned in hq-console. Removes .hq/config.json, " +
|
|
229
|
+
"flips company.yaml `cloud: false`, and strips the manifest cloud refs.",
|
|
230
|
+
)
|
|
231
|
+
.argument("<slug>", "Company slug")
|
|
232
|
+
.option(
|
|
233
|
+
"--hq-root <path>",
|
|
234
|
+
`Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
|
|
235
|
+
DEFAULT_HQ_ROOT,
|
|
236
|
+
)
|
|
237
|
+
.option(
|
|
238
|
+
"--vault-api-url <url>",
|
|
239
|
+
`Vault API URL (default: ${DEFAULT_VAULT_API_URL})`,
|
|
240
|
+
DEFAULT_VAULT_API_URL,
|
|
241
|
+
)
|
|
242
|
+
.option(
|
|
243
|
+
"--force",
|
|
244
|
+
"Skip the safety check that the cloud entity is actually deleted=true. " +
|
|
245
|
+
"AppBar HQ Sync passes this because its Path A just verified.",
|
|
246
|
+
)
|
|
247
|
+
.action(
|
|
248
|
+
async (
|
|
249
|
+
slug: string,
|
|
250
|
+
options: { hqRoot: string; vaultApiUrl: string; force?: boolean },
|
|
251
|
+
) => {
|
|
252
|
+
try {
|
|
253
|
+
const result = await demoteCompany({
|
|
254
|
+
slug,
|
|
255
|
+
hqRoot: options.hqRoot,
|
|
256
|
+
vaultApiUrl: options.vaultApiUrl,
|
|
257
|
+
force: options.force,
|
|
258
|
+
});
|
|
259
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
260
|
+
process.exit(0);
|
|
261
|
+
} catch (err) {
|
|
262
|
+
if (err instanceof ProvisionError) {
|
|
263
|
+
process.stderr.write(
|
|
264
|
+
chalk.red(`[hq cloud demote] ${err.message}\n`),
|
|
265
|
+
);
|
|
266
|
+
process.exit(err.code);
|
|
267
|
+
}
|
|
268
|
+
process.stderr.write(
|
|
269
|
+
chalk.red(
|
|
270
|
+
`[hq cloud demote] Unexpected error: ${err instanceof Error ? err.message : String(err)}\n`,
|
|
271
|
+
),
|
|
272
|
+
);
|
|
273
|
+
process.exit(1);
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
);
|
|
277
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { registerListCommand } from "./commands/list.js";
|
|
|
12
12
|
import { registerUpdateCommand } from "./commands/update.js";
|
|
13
13
|
import { registerCloudCommands } from "./commands/cloud.js";
|
|
14
14
|
import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
|
|
15
|
+
import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
|
|
15
16
|
import { registerLoginCommand } from "./commands/login.js";
|
|
16
17
|
import { registerLogoutCommand } from "./commands/logout.js";
|
|
17
18
|
import { registerWhoamiCommand } from "./commands/whoami.js";
|
|
@@ -78,6 +79,7 @@ const cloudCmd = program
|
|
|
78
79
|
);
|
|
79
80
|
|
|
80
81
|
registerCloudProvisionCommands(cloudCmd);
|
|
82
|
+
registerCloudDemoteCommands(cloudCmd);
|
|
81
83
|
|
|
82
84
|
// Team commands (top-level)
|
|
83
85
|
registerTeamSyncCommand(program);
|