@indigoai-us/hq-cli 5.5.1 → 5.5.2-sentry-rc.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 (127) hide show
  1. package/dist/bin/hq-auth-refresh.js +22 -12
  2. package/dist/bin/hq-auth-refresh.js.map +1 -1
  3. package/dist/commands/_patterns.d.ts +3 -0
  4. package/dist/commands/_patterns.d.ts.map +1 -0
  5. package/dist/commands/_patterns.js +3 -0
  6. package/dist/commands/_patterns.js.map +1 -0
  7. package/dist/commands/add.d.ts.map +1 -1
  8. package/dist/commands/add.js +2 -1
  9. package/dist/commands/add.js.map +1 -1
  10. package/dist/commands/auth.d.ts +0 -3
  11. package/dist/commands/auth.d.ts.map +1 -1
  12. package/dist/commands/auth.js +0 -3
  13. package/dist/commands/auth.js.map +1 -1
  14. package/dist/commands/groups.d.ts +3 -0
  15. package/dist/commands/groups.d.ts.map +1 -0
  16. package/dist/commands/groups.js +341 -0
  17. package/dist/commands/groups.js.map +1 -0
  18. package/dist/commands/list.d.ts.map +1 -1
  19. package/dist/commands/list.js +18 -1
  20. package/dist/commands/list.js.map +1 -1
  21. package/dist/commands/login.d.ts +1 -1
  22. package/dist/commands/login.d.ts.map +1 -1
  23. package/dist/commands/login.js +28 -9
  24. package/dist/commands/login.js.map +1 -1
  25. package/dist/commands/logout.d.ts +1 -1
  26. package/dist/commands/logout.d.ts.map +1 -1
  27. package/dist/commands/logout.js +8 -3
  28. package/dist/commands/logout.js.map +1 -1
  29. package/dist/commands/pack-install.d.ts +44 -0
  30. package/dist/commands/pack-install.d.ts.map +1 -0
  31. package/dist/commands/pack-install.js +513 -0
  32. package/dist/commands/pack-install.js.map +1 -0
  33. package/dist/commands/pkg-install.d.ts.map +1 -1
  34. package/dist/commands/pkg-install.js +20 -8
  35. package/dist/commands/pkg-install.js.map +1 -1
  36. package/dist/commands/pkg-list.js +4 -4
  37. package/dist/commands/pkg-list.js.map +1 -1
  38. package/dist/commands/pkg-update.js +3 -3
  39. package/dist/commands/pkg-update.js.map +1 -1
  40. package/dist/commands/secrets.d.ts +12 -0
  41. package/dist/commands/secrets.d.ts.map +1 -0
  42. package/dist/commands/secrets.js +756 -0
  43. package/dist/commands/secrets.js.map +1 -0
  44. package/dist/commands/sync.d.ts.map +1 -1
  45. package/dist/commands/sync.js +10 -2
  46. package/dist/commands/sync.js.map +1 -1
  47. package/dist/commands/team-sync.d.ts.map +1 -1
  48. package/dist/commands/team-sync.js +6 -6
  49. package/dist/commands/team-sync.js.map +1 -1
  50. package/dist/commands/whoami.d.ts +1 -1
  51. package/dist/commands/whoami.d.ts.map +1 -1
  52. package/dist/commands/whoami.js +23 -7
  53. package/dist/commands/whoami.js.map +1 -1
  54. package/dist/index.js +21 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/sentry-before-send.d.ts +3 -0
  57. package/dist/sentry-before-send.d.ts.map +1 -0
  58. package/dist/sentry-before-send.js +216 -0
  59. package/dist/sentry-before-send.js.map +1 -0
  60. package/dist/sentry-dsn.generated.d.ts +2 -0
  61. package/dist/sentry-dsn.generated.d.ts.map +1 -0
  62. package/dist/sentry-dsn.generated.js.map +1 -0
  63. package/dist/sentry.d.ts +4 -0
  64. package/dist/sentry.d.ts.map +1 -0
  65. package/dist/sentry.js +19 -0
  66. package/dist/sentry.js.map +1 -0
  67. package/dist/strategies/link.d.ts +2 -2
  68. package/dist/strategies/link.d.ts.map +1 -1
  69. package/dist/strategies/link.js.map +1 -1
  70. package/dist/strategies/merge.d.ts +2 -2
  71. package/dist/strategies/merge.d.ts.map +1 -1
  72. package/dist/strategies/merge.js.map +1 -1
  73. package/dist/types.d.ts +37 -3
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js +6 -0
  76. package/dist/types.js.map +1 -1
  77. package/dist/utils/cognito-session.js +3 -3
  78. package/dist/utils/cognito-session.js.map +1 -1
  79. package/dist/utils/manifest.d.ts +13 -0
  80. package/dist/utils/manifest.d.ts.map +1 -1
  81. package/dist/utils/manifest.js +24 -1
  82. package/dist/utils/manifest.js.map +1 -1
  83. package/dist/utils/secrets-cache.d.ts +7 -0
  84. package/dist/utils/secrets-cache.d.ts.map +1 -0
  85. package/dist/utils/secrets-cache.js +135 -0
  86. package/dist/utils/secrets-cache.js.map +1 -0
  87. package/package.json +9 -5
  88. package/scripts/generate-dsn.mjs +26 -0
  89. package/src/bin/hq-auth-refresh.ts +23 -16
  90. package/src/commands/_patterns.ts +2 -0
  91. package/src/commands/add.ts +7 -6
  92. package/src/commands/auth.ts +0 -3
  93. package/src/commands/groups.ts +357 -0
  94. package/src/commands/list.ts +20 -1
  95. package/src/commands/login.ts +28 -9
  96. package/src/commands/logout.ts +8 -3
  97. package/src/commands/pack-install.ts +667 -0
  98. package/src/commands/pkg-install.ts +34 -16
  99. package/src/commands/pkg-list.ts +4 -4
  100. package/src/commands/pkg-update.ts +3 -3
  101. package/src/commands/secrets.ts +950 -0
  102. package/src/commands/sync.ts +20 -4
  103. package/src/commands/team-sync.ts +7 -8
  104. package/src/commands/whoami.ts +22 -7
  105. package/src/index.ts +22 -2
  106. package/src/sentry-before-send.test.ts +359 -0
  107. package/src/sentry-before-send.ts +221 -0
  108. package/src/sentry.test.ts +24 -0
  109. package/src/sentry.ts +19 -0
  110. package/src/strategies/link.ts +2 -2
  111. package/src/strategies/merge.ts +2 -2
  112. package/src/types.ts +54 -4
  113. package/src/utils/cognito-session.ts +3 -3
  114. package/src/utils/manifest.test.ts +148 -0
  115. package/src/utils/manifest.ts +22 -1
  116. package/src/utils/secrets-cache.ts +130 -0
  117. package/tsconfig.json +2 -1
  118. package/dist/utils/auth.d.ts +0 -27
  119. package/dist/utils/auth.d.ts.map +0 -1
  120. package/dist/utils/auth.js +0 -155
  121. package/dist/utils/auth.js.map +0 -1
  122. package/dist/utils/token-store.d.ts +0 -28
  123. package/dist/utils/token-store.d.ts.map +0 -1
  124. package/dist/utils/token-store.js +0 -68
  125. package/dist/utils/token-store.js.map +0 -1
  126. package/src/utils/auth.ts +0 -193
  127. package/src/utils/token-store.ts +0 -83
@@ -0,0 +1,221 @@
1
+ // src/sentry-before-send.ts — canonical fleet scrubber
2
+ // Line 1 is per-repo — see "Per-repo `import type` line" table in Step 3.
3
+ // hq-console uses @sentry/nextjs. Consumer steps override to their own SDK.
4
+ import type { ErrorEvent, EventHint } from "@sentry/node";
5
+
6
+ const SENSITIVE_FIELD_NAMES = new Set([
7
+ "password", "secret", "apikey", "api_key", "token",
8
+ // Cognito token-response fields captured as error context.
9
+ "idtoken", "accesstoken", "refreshtoken",
10
+ ]);
11
+
12
+ // Stored lowercased; membership tested against `name.toLowerCase()`.
13
+ // MUST cover BOTH Auth.js v5 (current in hq-console, pinned to
14
+ // next-auth@5.0.0-beta.25 which resolves @auth/core@0.37.2) AND legacy
15
+ // NextAuth v4 name spaces — covering both is cheap and survives accidental
16
+ // downgrades or mixed-version repos. Grounded against @auth/core@0.37.2's
17
+ // src/lib/utils/cookie.ts (re-ground via `grep -nE
18
+ // '(sessionToken|callbackUrl|csrfToken|pkceCodeVerifier|state|nonce|webauthnChallenge): \{'
19
+ // node_modules/.pnpm/@auth+core@0.37.2/node_modules/@auth/core/src/lib/utils/cookie.ts`
20
+ // — seven matches, one per cookie family): two distinct prefixing patterns
21
+ // coexist there, and the entries below mirror BOTH exactly:
22
+ // • session-token / callback-url / pkce.code_verifier / state / nonce /
23
+ // challenge each pair the bare form (HTTP dev, cookiePrefix="") with
24
+ // the __Secure- form (HTTPS prod, cookiePrefix="__Secure-").
25
+ // • csrf-token is special: the source explicitly uses __Host- (NOT
26
+ // __Secure-) under HTTPS for stricter cookie scoping (the csrfToken
27
+ // entry in @auth/core's cookie.ts is the only one whose name template
28
+ // uses `__Host-` instead of `${cookiePrefix}`; the comment above it
29
+ // reads "Default to __Host- for CSRF token for additional protection
30
+ // if using useSecureCookies"). The set therefore pairs the bare form
31
+ // with __Host-, and does NOT include __Secure-authjs.csrf-token
32
+ // because @auth/core never emits that name. The legacy v4 entry mirrors
33
+ // the same pattern (bare next-auth.csrf-token + __Host-next-auth.csrf-token,
34
+ // no __Secure- variant).
35
+ // Missing any of the four OAuth-state families (pkce.code_verifier, state,
36
+ // nonce, challenge) ships a cookie-leak in the same class as the v4-only
37
+ // defect Round-4 called out. This set is the single authoritative spec;
38
+ // all of Steps 3/8/9a/12/13 reproduce it identically.
39
+ //
40
+ // MAINTAINER NOTE: Do NOT extend this set by mechanically pairing every
41
+ // cookie with bare + __Secure- + __Host-. The pairing follows the source:
42
+ // session-style cookies use __Secure-; csrf-style cookies use __Host-.
43
+ // New entries added in the future must be grounded against the actual
44
+ // emitter (Auth.js source for v5/v4, vendor docs for Clerk, etc.) rather
45
+ // than copied from the existing pattern.
46
+ const SENSITIVE_COOKIE_NAMES = new Set([
47
+ // ==== Auth.js v5 (next-auth@5 / @auth/core) ====
48
+ // Session JWT — bare + __Secure-
49
+ "authjs.session-token",
50
+ "__secure-authjs.session-token",
51
+ // CSRF double-submit token — bare + __Host- ONLY (@auth/core's cookie.ts
52
+ // csrfToken entry uses __Host-, never __Secure-)
53
+ "authjs.csrf-token",
54
+ "__host-authjs.csrf-token",
55
+ // Post-auth redirect URL — bare + __Secure-
56
+ "authjs.callback-url",
57
+ "__secure-authjs.callback-url",
58
+ // OAuth PKCE verifier — leaking this enables interception of an in-flight
59
+ // OAuth code exchange.
60
+ "authjs.pkce.code_verifier",
61
+ "__secure-authjs.pkce.code_verifier",
62
+ // OAuth CSRF/replay protection
63
+ "authjs.state",
64
+ "__secure-authjs.state",
65
+ // OpenID Connect nonce — replay protection
66
+ "authjs.nonce",
67
+ "__secure-authjs.nonce",
68
+ // OAuth WebAuthn challenge
69
+ "authjs.challenge",
70
+ "__secure-authjs.challenge",
71
+ // ==== NextAuth v4 legacy names (kept so accidental downgrades /
72
+ // mixed-version monorepos don't silently leak). Same prefix
73
+ // discipline as v5: csrf-token uses __Host-, others use __Secure-. ====
74
+ "next-auth.session-token",
75
+ "__secure-next-auth.session-token",
76
+ "next-auth.csrf-token",
77
+ "__host-next-auth.csrf-token",
78
+ "next-auth.callback-url",
79
+ "__secure-next-auth.callback-url",
80
+ "next-auth.pkce.code_verifier",
81
+ "__secure-next-auth.pkce.code_verifier",
82
+ "next-auth.state",
83
+ "__secure-next-auth.state",
84
+ // ==== Clerk (documented for future; no-op today) ====
85
+ "__clerk_db_jwt", "__session",
86
+ ]);
87
+
88
+ const REDACTED = "[Filtered]";
89
+
90
+ const SENSITIVE_HEADER_NAMES = new Set([
91
+ "authorization", "proxy-authorization",
92
+ "cookie", "set-cookie",
93
+ "x-api-key", "x-auth-token", "x-access-token", "x-session-token",
94
+ ]);
95
+
96
+ function scrubHeaders(h?: Record<string, unknown>): Record<string, unknown> | undefined {
97
+ if (!h) return h;
98
+ const out: Record<string, unknown> = {};
99
+ for (const [k, v] of Object.entries(h)) {
100
+ out[k] = SENSITIVE_HEADER_NAMES.has(k.toLowerCase()) ? REDACTED : v;
101
+ }
102
+ return out;
103
+ }
104
+
105
+ type CookieField = Record<string, unknown> | string | undefined;
106
+
107
+ function scrubCookies(c: CookieField): CookieField {
108
+ if (!c) return c;
109
+ if (typeof c === "string") return REDACTED; // raw Cookie header — wholesale redact
110
+ const out: Record<string, unknown> = {};
111
+ for (const [k, v] of Object.entries(c)) {
112
+ out[k] = SENSITIVE_COOKIE_NAMES.has(k.toLowerCase()) ? REDACTED : v;
113
+ }
114
+ return out;
115
+ }
116
+
117
+ const SENSITIVE_STRING_PATTERNS: RegExp[] = [
118
+ // kv pairs; `(?:id|access|refresh)[_-]?token` catches Cognito-style free-text
119
+ // `accessToken=...`, `refreshToken: ...`, `id_token=...` which bare `\btoken` misses.
120
+ /\b(password|secret|api[_-]?key|(?:id|access|refresh)[_-]?token|token)\s*[:=]\s*[^\s&"'<>]+/gi,
121
+ /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi,
122
+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
123
+ ];
124
+
125
+ function scrubString(s: string): string {
126
+ let out = s;
127
+ for (const re of SENSITIVE_STRING_PATTERNS) {
128
+ out = out.replace(re, (m) => {
129
+ const sep = m.search(/[:=\s]/);
130
+ return sep > 0 ? `${m.slice(0, sep + 1)}${REDACTED}` : REDACTED;
131
+ });
132
+ }
133
+ return out;
134
+ }
135
+
136
+ function scrubQueryString(qs: string): string {
137
+ try {
138
+ const params = new URLSearchParams(qs.startsWith("?") ? qs.slice(1) : qs);
139
+ const out: string[] = [];
140
+ for (const [k, v] of params) {
141
+ out.push(`${k}=${SENSITIVE_FIELD_NAMES.has(k.toLowerCase()) ? REDACTED : v}`);
142
+ }
143
+ const joined = out.join("&");
144
+ return qs.startsWith("?") ? `?${joined}` : joined;
145
+ } catch {
146
+ return scrubString(qs);
147
+ }
148
+ }
149
+
150
+ function scrubFields<T>(value: T, memo: Map<object, unknown> = new Map()): T {
151
+ if (value === null || typeof value !== "object") return value;
152
+ const obj = value as unknown as object;
153
+ // On cycle revisit, return the SAME scrubbed copy built on first visit —
154
+ // NOT the original. Returning the original would leak fields reachable
155
+ // only through the cycle (e.g., a.self.token).
156
+ if (memo.has(obj)) return memo.get(obj) as T;
157
+
158
+ if (Array.isArray(value)) {
159
+ const arr: unknown[] = [];
160
+ memo.set(obj, arr);
161
+ for (const v of value) arr.push(scrubFields(v, memo));
162
+ return arr as unknown as T;
163
+ }
164
+
165
+ const out: Record<string, unknown> = {};
166
+ memo.set(obj, out);
167
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
168
+ if (SENSITIVE_FIELD_NAMES.has(k.toLowerCase())) {
169
+ out[k] = REDACTED;
170
+ } else if (v !== null && typeof v === "object") {
171
+ out[k] = scrubFields(v, memo);
172
+ } else if (typeof v === "string") {
173
+ // SCALAR-STRING DEFENSE-IN-DEPTH. A stringified log line stashed via
174
+ // setExtra / setContext / setUser can embed `password=...` or a Bearer
175
+ // token even when the outer key (`note`, `bio`, `log_line`, …) isn't
176
+ // in SENSITIVE_FIELD_NAMES. Route scalar strings through scrubString so
177
+ // these don't bypass the scrubber on their way into Sentry.
178
+ out[k] = scrubString(v);
179
+ } else {
180
+ out[k] = v;
181
+ }
182
+ }
183
+ return out as unknown as T;
184
+ }
185
+
186
+ export function beforeSend(event: ErrorEvent, _hint: EventHint): ErrorEvent | null {
187
+ if (event.request) {
188
+ const req = event.request as { headers?: unknown; cookies?: unknown; data?: unknown; query_string?: unknown };
189
+ event.request = {
190
+ ...event.request,
191
+ headers: scrubHeaders(req.headers as Record<string, unknown> | undefined) as typeof event.request.headers,
192
+ cookies: scrubCookies(req.cookies as CookieField) as typeof event.request.cookies,
193
+ data: scrubFields(req.data),
194
+ query_string:
195
+ typeof req.query_string === "string"
196
+ ? scrubQueryString(req.query_string)
197
+ : (req.query_string as typeof event.request.query_string),
198
+ };
199
+ }
200
+ if (typeof event.message === "string") event.message = scrubString(event.message);
201
+ if (event.exception?.values) {
202
+ event.exception = {
203
+ ...event.exception,
204
+ values: event.exception.values.map((v) => ({
205
+ ...v,
206
+ value: typeof v.value === "string" ? scrubString(v.value) : v.value,
207
+ })),
208
+ };
209
+ }
210
+ if (event.user) event.user = scrubFields(event.user as Record<string, unknown>) as typeof event.user;
211
+ if (event.breadcrumbs) {
212
+ event.breadcrumbs = event.breadcrumbs.map((b) => ({
213
+ ...b,
214
+ message: typeof b.message === "string" ? scrubString(b.message) : b.message,
215
+ data: b.data ? scrubFields(b.data) : b.data,
216
+ }));
217
+ }
218
+ if (event.extra) event.extra = scrubFields(event.extra);
219
+ if (event.contexts) event.contexts = scrubFields(event.contexts);
220
+ return event;
221
+ }
@@ -0,0 +1,24 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import * as Sentry from "@sentry/node";
3
+ import { initSentry } from "./sentry.js";
4
+
5
+ vi.mock("./sentry-dsn.generated.js", () => ({ BUNDLED_DSN: "" }));
6
+
7
+ describe("initSentry — empty BUNDLED_DSN no-op", () => {
8
+ afterEach(() => {
9
+ vi.unstubAllEnvs();
10
+ });
11
+
12
+ it("fakeTransport.send is never called after captureException + flush(2000) when no DSN configured", async () => {
13
+ vi.stubEnv("SENTRY_DSN", "");
14
+
15
+ const fakeTransport = { send: vi.fn().mockResolvedValue(undefined) };
16
+
17
+ initSentry();
18
+
19
+ Sentry.captureException(new Error("no-dsn-should-not-send"));
20
+ await Sentry.flush(2000);
21
+
22
+ expect(fakeTransport.send).not.toHaveBeenCalled();
23
+ });
24
+ });
package/src/sentry.ts ADDED
@@ -0,0 +1,19 @@
1
+ import * as Sentry from "@sentry/node";
2
+ import { BUNDLED_DSN } from "./sentry-dsn.generated.js";
3
+ import { beforeSend } from "./sentry-before-send.js";
4
+
5
+ export function initSentry(): void {
6
+ const dsn = BUNDLED_DSN || process.env.SENTRY_DSN;
7
+ if (!dsn) return;
8
+ Sentry.init({
9
+ dsn,
10
+ release: `hq-cli@${process.env.npm_package_version ?? "0.0.0"}`,
11
+ environment: process.env.HQ_CLI_ENV ?? "production",
12
+ initialScope: {
13
+ tags: { repo: "hq-cli" },
14
+ },
15
+ beforeSend,
16
+ });
17
+ }
18
+
19
+ export { Sentry };
@@ -5,10 +5,10 @@
5
5
 
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
8
- import type { ModuleDefinition, SyncResult } from '../types.js';
8
+ import type { LegacyModuleDefinition, SyncResult } from '../types.js';
9
9
 
10
10
  export async function linkSync(
11
- module: ModuleDefinition,
11
+ module: LegacyModuleDefinition,
12
12
  moduleDir: string,
13
13
  hqRoot: string
14
14
  ): Promise<SyncResult> {
@@ -6,7 +6,7 @@
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
8
8
  import * as crypto from 'crypto';
9
- import type { ModuleDefinition, SyncResult, SyncState } from '../types.js';
9
+ import type { LegacyModuleDefinition, SyncResult, SyncState } from '../types.js';
10
10
  import { readState, writeState } from '../utils/manifest.js';
11
11
 
12
12
  function hashFile(filePath: string): string {
@@ -69,7 +69,7 @@ function copyRecursive(
69
69
  }
70
70
 
71
71
  export async function mergeSync(
72
- module: ModuleDefinition,
72
+ module: LegacyModuleDefinition,
73
73
  moduleDir: string,
74
74
  hqRoot: string
75
75
  ): Promise<SyncResult> {
package/src/types.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  /**
2
2
  * HQ Module Manifest Types (US-001)
3
+ *
4
+ * `modules.yaml` hosts two kinds of entries, discriminated by `strategy`:
5
+ * - link | merge | copy → git-repo-based module sync (existing flow)
6
+ * - package → hq-pack content pack installed via `hq install`
7
+ * (new in hq-core v12.0.0; see
8
+ * knowledge/public/hq-core/package-yaml-spec.md)
3
9
  */
4
10
 
5
- export type SyncStrategy = 'link' | 'merge' | 'copy';
11
+ export type LegacyStrategy = 'link' | 'merge' | 'copy';
12
+ export type SyncStrategy = LegacyStrategy | 'package';
6
13
  export type AccessLevel = 'public' | 'team' | `role:${string}`;
7
14
 
8
15
  export interface PathMapping {
@@ -10,15 +17,28 @@ export interface PathMapping {
10
17
  dest: string; // Path in HQ tree (relative to HQ root)
11
18
  }
12
19
 
13
- export interface ModuleDefinition {
20
+ export interface LegacyModuleDefinition {
14
21
  name: string;
15
22
  repo: string; // Git URL (https or git@)
16
23
  branch?: string; // Default: main
17
- strategy: SyncStrategy; // link | merge | copy
24
+ strategy: LegacyStrategy;
18
25
  paths: PathMapping[]; // What to sync and where
19
- access?: AccessLevel; // For future RBAC
26
+ access?: AccessLevel;
20
27
  }
21
28
 
29
+ export interface PackModuleDefinition {
30
+ name: string; // e.g. 'hq-pack-gstack'
31
+ strategy: 'package';
32
+ source: string; // '@scope/name@ver' | git URL#sha | local path
33
+ version?: string; // semver from the pack's package.yaml
34
+ installed_at?: string; // e.g. 'packages/hq-pack-gstack'
35
+ installed_at_iso?: string; // ISO timestamp
36
+ resolved_sha?: string; // git transport only
37
+ access?: AccessLevel;
38
+ }
39
+
40
+ export type ModuleDefinition = LegacyModuleDefinition | PackModuleDefinition;
41
+
22
42
  export interface ModulesManifest {
23
43
  version: '1';
24
44
  modules: ModuleDefinition[];
@@ -45,3 +65,33 @@ export interface SyncResult {
45
65
  message?: string;
46
66
  filesChanged?: number;
47
67
  }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // hq-pack content-pack manifest (packages/{name}/package.yaml).
71
+ //
72
+ // Distinct from packages/hq-cli/src/schemas/hq-package.schema.json, which
73
+ // covers the entitlement-gated registry flow (`hq packages install <slug>`).
74
+ // ---------------------------------------------------------------------------
75
+
76
+ export type PackContributeKey =
77
+ | 'workers'
78
+ | 'knowledge'
79
+ | 'skills'
80
+ | 'commands'
81
+ | 'hooks'
82
+ | 'policies'
83
+ | 'scripts';
84
+
85
+ export interface PackManifest {
86
+ name: string; // ^hq-pack-[a-z0-9][a-z0-9-]*$
87
+ version: string; // semver
88
+ publisher: string; // @scope
89
+ access: 'public' | 'private';
90
+ requires: { hqCore: string }; // semver range
91
+ contributes: Partial<Record<PackContributeKey, string[]>>;
92
+ description?: string;
93
+ license?: string;
94
+ repository?: string;
95
+ keywords?: string[];
96
+ conditional?: string; // bash predicate; skip install if exits non-zero
97
+ }
@@ -65,13 +65,13 @@ export async function ensureCognitoToken(options: {
65
65
  if (cached) {
66
66
  try {
67
67
  if (interactive) {
68
- console.log(chalk.dim(" Refreshing expiring HQ session..."));
68
+ console.error(chalk.dim(" Refreshing expiring HQ session..."));
69
69
  }
70
70
  const refreshed = await refreshTokens(DEFAULT_COGNITO, cached.refreshToken);
71
71
  return refreshed.accessToken;
72
72
  } catch (err) {
73
73
  if (interactive) {
74
- console.log(
74
+ console.error(
75
75
  chalk.dim(
76
76
  ` Refresh failed (${err instanceof Error ? err.message : err}), falling back to browser login`,
77
77
  ),
@@ -86,7 +86,7 @@ export async function ensureCognitoToken(options: {
86
86
  );
87
87
  }
88
88
 
89
- console.log(chalk.cyan(" No cached HQ session — launching browser sign-in..."));
89
+ console.error(chalk.cyan(" No cached HQ session — launching browser sign-in..."));
90
90
  const tokens = await browserLogin(DEFAULT_COGNITO);
91
91
  return tokens.accessToken;
92
92
  }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Regression tests for manifest path resolution.
3
+ *
4
+ * Bug caught during hq-core-split S3 testing (2026-04-21): prior to this
5
+ * fix, `getManifestPath()` returned a flat path (`{hqRoot}/modules.yaml`),
6
+ * but real HQ installs use the nested layout (`{hqRoot}/modules/modules.yaml`).
7
+ * Running `hq install` against a real HQ would silently create a shadow
8
+ * manifest at the root, orphaning the canonical nested one.
9
+ *
10
+ * These tests lock in:
11
+ * 1. Nested layout is preferred when it exists.
12
+ * 2. Flat layout is honored when (and only when) it already exists.
13
+ * 3. Fresh HQs default to writing the nested form — never shadow-writing
14
+ * a root-level `modules.yaml`.
15
+ * 4. Read/write round-trips correctly against the nested layout.
16
+ */
17
+
18
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
19
+ import * as fs from 'node:fs';
20
+ import * as os from 'node:os';
21
+ import * as path from 'node:path';
22
+ import * as yaml from 'js-yaml';
23
+
24
+ import {
25
+ addModule,
26
+ getManifestPath,
27
+ readManifest,
28
+ writeManifest,
29
+ } from './manifest.js';
30
+ import type { ModulesManifest } from '../types.js';
31
+
32
+ let tmpRoot: string;
33
+
34
+ beforeEach(() => {
35
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'hq-manifest-test-'));
36
+ });
37
+
38
+ afterEach(() => {
39
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
40
+ });
41
+
42
+ const sampleManifest: ModulesManifest = {
43
+ version: '1',
44
+ modules: [
45
+ {
46
+ name: 'knowledge-public-hq-core',
47
+ repo: 'https://github.com/indigoai-us/knowledge-public-hq-core.git',
48
+ strategy: 'link',
49
+ paths: [
50
+ {
51
+ src: '.',
52
+ dest: 'knowledge/public/hq-core',
53
+ },
54
+ ],
55
+ },
56
+ ],
57
+ };
58
+
59
+ describe('getManifestPath', () => {
60
+ it('prefers nested modules/modules.yaml when it exists', () => {
61
+ const nested = path.join(tmpRoot, 'modules', 'modules.yaml');
62
+ fs.mkdirSync(path.dirname(nested), { recursive: true });
63
+ fs.writeFileSync(nested, yaml.dump(sampleManifest));
64
+
65
+ expect(getManifestPath(tmpRoot)).toBe(nested);
66
+ });
67
+
68
+ it('honors legacy flat modules.yaml when only the flat form exists', () => {
69
+ // Legacy fixtures / very old HQ instances may pre-date the nested layout.
70
+ const flat = path.join(tmpRoot, 'modules.yaml');
71
+ fs.writeFileSync(flat, yaml.dump(sampleManifest));
72
+
73
+ expect(getManifestPath(tmpRoot)).toBe(flat);
74
+ });
75
+
76
+ it('defaults to nested path on a fresh HQ (neither file exists)', () => {
77
+ // Regression: previously returned the flat path, which meant writeManifest
78
+ // created a shadow root-level manifest on real HQs.
79
+ expect(getManifestPath(tmpRoot)).toBe(
80
+ path.join(tmpRoot, 'modules', 'modules.yaml'),
81
+ );
82
+ });
83
+ });
84
+
85
+ describe('readManifest / writeManifest round-trip', () => {
86
+ it('round-trips against the nested layout', () => {
87
+ writeManifest(tmpRoot, sampleManifest);
88
+
89
+ const nested = path.join(tmpRoot, 'modules', 'modules.yaml');
90
+ expect(fs.existsSync(nested)).toBe(true);
91
+
92
+ const roundTripped = readManifest(tmpRoot);
93
+ expect(roundTripped).toEqual(sampleManifest);
94
+ });
95
+
96
+ it('writes into the nested modules/ dir on fresh HQs (creates dir)', () => {
97
+ // The nested dir does not exist yet — writeManifest must mkdir-p.
98
+ expect(fs.existsSync(path.join(tmpRoot, 'modules'))).toBe(false);
99
+
100
+ writeManifest(tmpRoot, sampleManifest);
101
+
102
+ expect(fs.existsSync(path.join(tmpRoot, 'modules'))).toBe(true);
103
+ expect(fs.existsSync(path.join(tmpRoot, 'modules', 'modules.yaml'))).toBe(
104
+ true,
105
+ );
106
+ });
107
+
108
+ it('does NOT shadow-write a root-level modules.yaml on fresh HQs', () => {
109
+ // This is the original bug: pre-fix, writeManifest on a fresh HQ created
110
+ // `{hqRoot}/modules.yaml`, which shadowed the canonical nested manifest.
111
+ writeManifest(tmpRoot, sampleManifest);
112
+
113
+ expect(fs.existsSync(path.join(tmpRoot, 'modules.yaml'))).toBe(false);
114
+ });
115
+
116
+ it('rewrites into the flat layout when flat already exists (legacy compat)', () => {
117
+ const flat = path.join(tmpRoot, 'modules.yaml');
118
+ fs.writeFileSync(flat, yaml.dump({ version: '1', modules: [] }));
119
+
120
+ writeManifest(tmpRoot, sampleManifest);
121
+
122
+ // Flat stays flat; no silent migration to nested, no shadow write.
123
+ expect(fs.existsSync(flat)).toBe(true);
124
+ expect(
125
+ fs.existsSync(path.join(tmpRoot, 'modules', 'modules.yaml')),
126
+ ).toBe(false);
127
+
128
+ const reread = readManifest(tmpRoot);
129
+ expect(reread).toEqual(sampleManifest);
130
+ });
131
+ });
132
+
133
+ describe('addModule', () => {
134
+ it('appends to the existing nested manifest without creating a flat shadow', () => {
135
+ writeManifest(tmpRoot, sampleManifest);
136
+
137
+ addModule(tmpRoot, {
138
+ name: 'knowledge-public-testing',
139
+ repo: 'https://github.com/indigoai-us/knowledge-public-testing.git',
140
+ strategy: 'link',
141
+ paths: [{ src: '.', dest: 'knowledge/public/testing' }],
142
+ });
143
+
144
+ const after = readManifest(tmpRoot);
145
+ expect(after?.modules).toHaveLength(2);
146
+ expect(fs.existsSync(path.join(tmpRoot, 'modules.yaml'))).toBe(false);
147
+ });
148
+ });
@@ -18,8 +18,25 @@ export function findHqRoot(): string {
18
18
  return process.cwd();
19
19
  }
20
20
 
21
+ /**
22
+ * Resolve the manifest path for a given HQ root.
23
+ *
24
+ * The canonical layout is nested: `{hqRoot}/modules/modules.yaml` (catalog)
25
+ * alongside `{hqRoot}/modules/<module-name>/` (clone targets).
26
+ *
27
+ * Legacy fixtures and very old HQ instances may have the flat layout
28
+ * (`{hqRoot}/modules.yaml`); we honor that if — and only if — the flat file
29
+ * already exists. On fresh HQs we default to the nested form so we never
30
+ * silently create a second shadow manifest at the root.
31
+ *
32
+ * Exported for tests.
33
+ */
21
34
  export function getManifestPath(hqRoot: string): string {
22
- return path.join(hqRoot, MANIFEST_FILE);
35
+ const nested = path.join(hqRoot, 'modules', MANIFEST_FILE);
36
+ const flat = path.join(hqRoot, MANIFEST_FILE);
37
+ if (fs.existsSync(nested)) return nested;
38
+ if (fs.existsSync(flat)) return flat;
39
+ return nested; // default for fresh HQs — see getModulesDir()
23
40
  }
24
41
 
25
42
  export function getLockPath(hqRoot: string): string {
@@ -45,6 +62,10 @@ export function readManifest(hqRoot: string): ModulesManifest | null {
45
62
 
46
63
  export function writeManifest(hqRoot: string, manifest: ModulesManifest): void {
47
64
  const manifestPath = getManifestPath(hqRoot);
65
+ // Ensure the parent directory exists — on a fresh HQ the nested
66
+ // `modules/` dir may not yet be present, and fs.writeFileSync does not
67
+ // auto-mkdir. Safe no-op when the dir already exists.
68
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
48
69
  const content = yaml.dump(manifest, { lineWidth: -1 });
49
70
  fs.writeFileSync(manifestPath, content);
50
71
  }