@descix/cli 1.0.6 → 1.0.8

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 (59) hide show
  1. package/README.md +1 -1
  2. package/agent-assets/guides/README.md +1 -1
  3. package/agent-assets/guides/dynamic-site-pattern.md +17 -30
  4. package/agent-assets/guides/knowledge-only-pattern.md +11 -15
  5. package/agent-assets/guides/microservice-pattern.md +12 -14
  6. package/agent-assets/guides/static-site-pattern.md +12 -15
  7. package/agent-assets/instructions/app-asset-validation.md +1 -1
  8. package/agent-assets/instructions/onboarding-flow.md +4 -4
  9. package/agent-assets/reference/app-creation.md +36 -101
  10. package/agent-assets/reference/architecture.md +43 -51
  11. package/agent-assets/reference/local-dev.md +1 -6
  12. package/agent-assets/reference/mcp-integration.md +21 -23
  13. package/agent-assets/reference/workspace-config.md +97 -340
  14. package/bin/descix.js +337 -618
  15. package/lib/api-client.js +30 -22
  16. package/lib/command-visibility.js +213 -0
  17. package/lib/commands/airdrop.js +10 -0
  18. package/lib/commands/auth.js +16 -2
  19. package/lib/commands/config.js +13 -31
  20. package/lib/commands/corpus.js +163 -59
  21. package/lib/commands/health.js +116 -21
  22. package/lib/commands/init.js +17 -45
  23. package/lib/commands/kb.js +7 -0
  24. package/lib/commands/retired-kb-sync.js +5 -27
  25. package/lib/commands/status.js +0 -9
  26. package/lib/core/Chunker.js +1 -1
  27. package/lib/core/CorpusWalker.js +238 -47
  28. package/lib/core/ManifestLoader.js +68 -0
  29. package/lib/core/Syncer.js +147 -46
  30. package/lib/interactive.js +158 -0
  31. package/lib/origin.js +3 -3
  32. package/lib/sdk-assets.js +28 -0
  33. package/lib/verb-invokes.generated.json +233 -0
  34. package/lib/wallet-file.js +36 -37
  35. package/lib/workspace-config.js +266 -199
  36. package/lib/workspace-identity.js +0 -1
  37. package/package.json +7 -3
  38. package/templates/agent-claude.md +1 -3
  39. package/templates/agent-cline.md +1 -2
  40. package/templates/agent-copilot.md +1 -2
  41. package/templates/agent-cursor.md +1 -2
  42. package/templates/scaffolds/microservice/SERVICE_README_sdk.md +1 -1
  43. package/templates/scaffolds/microservice/templates/SERVICE_README_TEMPLATE.md +2 -3
  44. package/agent-assets/rules/descix_mcp.template.mdc +0 -243
  45. package/lib/commands/briefer/errors.js +0 -88
  46. package/lib/commands/briefer/index.js +0 -319
  47. package/lib/commands/briefer/sources/canonical-sources.js +0 -129
  48. package/lib/commands/briefer/sources/entitlements.js +0 -220
  49. package/lib/commands/briefer/sources/environments.js +0 -205
  50. package/lib/commands/briefer/sources/identifiers.js +0 -214
  51. package/lib/commands/briefer/sources/microservice-deploy.js +0 -267
  52. package/lib/commands/briefer/sources/routing.js +0 -275
  53. package/lib/commands/briefer/sources/what-is-not.js +0 -223
  54. package/lib/commands/briefer/stitcher.js +0 -134
  55. package/lib/commands/briefer/util/source-reader.js +0 -502
  56. package/lib/commands/mcp.js +0 -273
  57. package/lib/commands/update.js +0 -581
  58. package/lib/wizard/setup.js +0 -503
  59. package/templates/descix_mcp.mdc +0 -122
@@ -1,319 +0,0 @@
1
- /**
2
- * `descix briefer` — main entry point.
3
- *
4
- * Per WS-DESCIX-BRIEFER-CLI scope doc §2 (Architecture / Option A):
5
- *
6
- * descix briefer [--env=dev|demo|prod] [--out=PATH] [--check]
7
- *
8
- * Reads the per-section data sources defined in scope doc §2.2, dispatches to
9
- * the per-section extractors in ./sources/*.js, and emits a structured
10
- * BrieferDoc object. The stitcher composes the markdown; --check mode diffs
11
- * the regen against the canonical briefer file.
12
- *
13
- * HARD-FAIL philosophy (scope doc §2.3 + feedback_no-hardcoded-fallbacks):
14
- * every extractor that can't find its source data throws BrieferExtractorError
15
- * with a stable error code. No fallback strings. No try-catch-and-default.
16
- *
17
- * M1 SCOPE (this implementation):
18
- * - CLI subcommand registration in bin/descix.js (separate edit).
19
- * - This entry orchestrates 7 stub extractors.
20
- * - Stitcher composes a real (non-empty) markdown with TODO placeholder bodies.
21
- * - --check runs the full extraction, diffs against canonical, prints a
22
- * unified-style diff, exits non-zero on drift (which is EXPECTED for M1 —
23
- * stubs WILL differ from the manually-authored canonical briefer).
24
- *
25
- * M2+ SCOPE (NOT IMPLEMENTED HERE):
26
- * - Real AST/regex parsing of source files.
27
- * - Live gcloud probes.
28
- * - Firestore Products counts via apifront.
29
- * - MustKnow KB partition + auto-sync.
30
- * - Bootstrap protocol edits (/cos skill, @bootstrap agent).
31
- * - CI --check gate.
32
- */
33
-
34
- import fs from 'fs/promises';
35
- import path from 'path';
36
- import chalk from 'chalk';
37
- import { fileURLToPath } from 'url';
38
-
39
- import { BrieferExtractorError, BRIEFER_ERROR_CODES } from './errors.js';
40
- import { stitchBriefer, extractCitationTrail } from './stitcher.js';
41
-
42
- import * as identifiers from './sources/identifiers.js';
43
- import * as environments from './sources/environments.js';
44
- import * as routing from './sources/routing.js';
45
- import * as microserviceDeploy from './sources/microservice-deploy.js';
46
- import * as entitlements from './sources/entitlements.js';
47
- import * as whatIsNot from './sources/what-is-not.js';
48
- import * as canonicalSources from './sources/canonical-sources.js';
49
-
50
- import { WorkspaceConfig } from '../../workspace-config.js';
51
-
52
- // ─────────────────────────────────────────────────────────────────────────────
53
- // Extractor dispatch table (scope doc §2.2 ordering)
54
- // ─────────────────────────────────────────────────────────────────────────────
55
- export const EXTRACTORS = Object.freeze([
56
- identifiers,
57
- environments,
58
- routing,
59
- microserviceDeploy,
60
- entitlements,
61
- whatIsNot,
62
- canonicalSources
63
- ]);
64
-
65
- export const VALID_ENVS = Object.freeze(['dev', 'demo', 'prod']);
66
-
67
- // Default output path (scope doc §2.1). Resolved relative to workspace root
68
- // via WorkspaceConfig.getWorkspaceRoot() — never a hardcoded absolute path.
69
- export const DEFAULT_OUT_RELATIVE = 'DeSciX/V2_docs/architecture/platform-must-know-briefer.md';
70
-
71
- const MECHANISM_TAG = 'descix briefer v1.0 (M2 — code-grounded extractors)';
72
-
73
- // ─────────────────────────────────────────────────────────────────────────────
74
- // Helpers
75
- // ─────────────────────────────────────────────────────────────────────────────
76
-
77
- export function resolveCliPaths() {
78
- // Resolve the descix-cli root from this file's location, then walk up to
79
- // DeSciX_Core and the parent repo. M2/M3 extractors that read source files
80
- // will need these to anchor file reads.
81
- const here = path.dirname(fileURLToPath(import.meta.url));
82
- const descixCliRoot = path.resolve(here, '../../..'); // .../descix-cli
83
- const descixCoreRoot = path.resolve(descixCliRoot, '..'); // .../DeSciX_Core
84
- const desciXRoot = path.resolve(descixCoreRoot, '..'); // .../DeSciX
85
- const repoRoot = path.resolve(desciXRoot, '..'); // .../Unkamon
86
- return { descixCliRoot, descixCoreRoot, desciXRoot, repoRoot };
87
- }
88
-
89
- export function resolveOutPath(cliOut, workspaceConfig, cliPaths, cwd) {
90
- // Explicit override always wins.
91
- if (cliOut) return path.resolve(cliOut);
92
-
93
- // Default: workspace-root-relative path.
94
- if (workspaceConfig) {
95
- const wsRoot = workspaceConfig.getWorkspaceRoot();
96
- return path.join(wsRoot, DEFAULT_OUT_RELATIVE);
97
- }
98
-
99
- // HARD-FAIL per feedback_no-hardcoded-fallbacks. The previous implementation
100
- // derived a default from cliPaths.repoRoot (computed from the CLI file
101
- // location), which silently produced a wrong path like
102
- // "Unkamon/DeSciX/DeSciX/V2_docs/..." (double DeSciX/) when invoked from
103
- // inside descix-cli/ with no workspace.json in cwd. No silent path-guessing.
104
- throw new BrieferExtractorError({
105
- code: BRIEFER_ERROR_CODES.WORKSPACE_NOT_FOUND,
106
- section: 'briefer entry',
107
- source: cwd || '(unknown cwd)',
108
- expected: 'either .descix/workspace.json reachable by upward search, OR --out=<path>',
109
- recovery: 'Run from your workspace root (where .descix/workspace.json lives), or pass --out=<path> explicitly.',
110
- detail: `cliPaths.repoRoot was previously used as a silent fallback (resolved to ${cliPaths.repoRoot}); that fallback is removed.`
111
- });
112
- }
113
-
114
- async function resolveRegenBy() {
115
- // Best signal we have without forcing an auth round-trip in M1. M2 will
116
- // require auth (for apifront/Firestore calls) and can use the wallet email
117
- // from apiClient.loadCredentials() — at that point this changes to a hard
118
- // requirement. For M1 scaffolding we just tag the system user.
119
- return process.env.USER || process.env.USERNAME || 'unknown';
120
- }
121
-
122
- // Minimal unified-style diff (line-based). Avoids adding a new npm dependency
123
- // for the M1 scaffold; M2 may swap in the `diff` package if richer output is
124
- // needed (currently an unanswered question §9.1 in scope doc — Babel dep).
125
- function simpleLineDiff(a, b, { aLabel = 'canonical', bLabel = 'regen' } = {}) {
126
- const aLines = (a || '').split(/\r?\n/);
127
- const bLines = (b || '').split(/\r?\n/);
128
- const out = [`--- ${aLabel}`, `+++ ${bLabel}`];
129
- const max = Math.max(aLines.length, bLines.length);
130
- let inHunk = false;
131
- for (let i = 0; i < max; i++) {
132
- const av = aLines[i];
133
- const bv = bLines[i];
134
- if (av === bv) {
135
- if (inHunk) { out.push(' ' + (av ?? '')); inHunk = false; }
136
- continue;
137
- }
138
- if (!inHunk) {
139
- out.push(`@@ line ${i + 1} @@`);
140
- inHunk = true;
141
- }
142
- if (av !== undefined) out.push(`-${av}`);
143
- if (bv !== undefined) out.push(`+${bv}`);
144
- }
145
- return out.join('\n');
146
- }
147
-
148
- // ─────────────────────────────────────────────────────────────────────────────
149
- // BrieferDoc — the structured object returned by buildBrieferDoc()
150
- // ─────────────────────────────────────────────────────────────────────────────
151
- /**
152
- * @typedef {object} BrieferSectionResult
153
- * @property {{number: number, heading: string, sourceFiles: string[]}} section
154
- * @property {{markdown: string, citations: object[]}} extract
155
- */
156
-
157
- /**
158
- * @typedef {object} BrieferDoc
159
- * @property {string} env
160
- * @property {string} mechanism
161
- * @property {string} regenBy
162
- * @property {BrieferSectionResult[]} sections
163
- * @property {string} markdown Final stitched markdown.
164
- * @property {string[]} citationTrail Hidden HTML-comment trail (one per line).
165
- */
166
-
167
- /**
168
- * Run all extractors and return the BrieferDoc.
169
- *
170
- * @param {object} opts
171
- * @param {string} opts.env
172
- * @param {object} opts.cliPaths
173
- * @param {object|null} [opts.apiClient] Optional in M1 (stubs don't need it).
174
- * @param {object|null} [opts.gcloud] Optional in M1 (stubs don't need it).
175
- * @param {string} opts.regenBy
176
- * @param {string} [opts.mechanism]
177
- * @returns {Promise<BrieferDoc>}
178
- */
179
- export async function buildBrieferDoc({ env, cliPaths, apiClient = null, gcloud = null, regenBy, mechanism = MECHANISM_TAG }) {
180
- const sections = [];
181
- for (const extractor of EXTRACTORS) {
182
- const result = await extractor.extract({ env, cliPaths, gcloud, apiClient });
183
- sections.push({ section: extractor.SECTION, extract: result });
184
- }
185
- const markdown = stitchBriefer({ env, mechanism, regenBy, sections });
186
- const citationTrail = extractCitationTrail(markdown);
187
- return { env, mechanism, regenBy, sections, markdown, citationTrail };
188
- }
189
-
190
- // ─────────────────────────────────────────────────────────────────────────────
191
- // Public CLI entry — invoked by bin/descix.js `briefer` subcommand
192
- // ─────────────────────────────────────────────────────────────────────────────
193
-
194
- /**
195
- * @param {object} options Commander options object.
196
- * @param {string} [options.env] dev|demo|prod (default: 'dev' for M1; M2 will hard-fail dev per scope doc §2.1).
197
- * @param {string} [options.out] Output path override.
198
- * @param {boolean} [options.check] Drift-detection mode: regen to memory, diff against canonical, exit non-zero on drift.
199
- * @param {boolean} [options.verbose] Print per-source timing + extractor names.
200
- */
201
- export async function runBriefer(options = {}) {
202
- const env = (options.env || 'dev').toLowerCase();
203
- if (!VALID_ENVS.includes(env)) {
204
- console.error(chalk.red(`\n❌ Invalid --env=${options.env}. Must be one of: ${VALID_ENVS.join(', ')}\n`));
205
- process.exit(1);
206
- }
207
-
208
- // Per scope §2.1: --env=dev is rejected by the routing extractor specifically
209
- // (DEV has no LB URL map). Other extractors accept dev because they read
210
- // only source files (no gcloud probe required). The rejection lives in
211
- // sources/routing.js; this entry point passes env through unchanged.
212
- if (options.verbose) {
213
- console.log(chalk.gray(`[briefer] env=${env}`));
214
- }
215
-
216
- const cliPaths = resolveCliPaths();
217
- const cwd = process.cwd();
218
- let workspaceConfig = null;
219
- try {
220
- workspaceConfig = await WorkspaceConfig.tryLoad(cwd);
221
- } catch {
222
- // tryLoad returns null on missing workspace; an exception here means the
223
- // workspace.json file exists but is invalid. Hard-fail per philosophy —
224
- // do NOT proceed with a guessed default workspace.
225
- throw new BrieferExtractorError({
226
- code: BRIEFER_ERROR_CODES.PARSE_FAIL,
227
- section: 'briefer entry',
228
- source: '.descix/workspace.json',
229
- expected: 'valid v2.1 workspace JSON',
230
- recovery: 'Fix the workspace.json or run `descix init` to regenerate.'
231
- });
232
- }
233
-
234
- const outPath = resolveOutPath(options.out, workspaceConfig, cliPaths, cwd);
235
- const regenBy = await resolveRegenBy();
236
-
237
- if (options.verbose) {
238
- console.log(chalk.gray(`[briefer] outPath=${outPath}`));
239
- console.log(chalk.gray(`[briefer] regenBy=${regenBy}`));
240
- console.log(chalk.gray(`[briefer] extractors=${EXTRACTORS.length}`));
241
- }
242
-
243
- // Build the briefer doc. Each extractor is run sequentially; M2 can
244
- // parallelize if hot-path latency matters (it likely won't for 7 sources).
245
- let doc;
246
- try {
247
- doc = await buildBrieferDoc({ env, cliPaths, regenBy });
248
- } catch (err) {
249
- if (err instanceof BrieferExtractorError) {
250
- console.error(chalk.red(`\n❌ Briefer extraction failed:\n`));
251
- console.error(chalk.red(err.message));
252
- console.error('');
253
- process.exit(1);
254
- }
255
- throw err;
256
- }
257
-
258
- if (options.check) {
259
- return runCheckMode({ doc, outPath, verbose: options.verbose });
260
- }
261
-
262
- // Write mode — overwrite the canonical briefer file.
263
- await fs.mkdir(path.dirname(outPath), { recursive: true });
264
- await fs.writeFile(outPath, doc.markdown, 'utf-8');
265
-
266
- console.log(chalk.green(`\n✅ Briefer regenerated\n`));
267
- console.log(chalk.cyan(` Env: ${env}`));
268
- console.log(chalk.gray (` Mechanism: ${doc.mechanism}`));
269
- console.log(chalk.gray (` By: ${regenBy}`));
270
- console.log(chalk.gray (` Out: ${outPath}`));
271
- console.log(chalk.gray (` Sections: ${doc.sections.length}`));
272
- console.log(chalk.gray (` Citations: ${doc.citationTrail.length}\n`));
273
- return doc;
274
- }
275
-
276
- export async function runCheckMode({ doc, outPath, verbose }) {
277
- let canonical = null;
278
- try {
279
- canonical = await fs.readFile(outPath, 'utf-8');
280
- } catch (err) {
281
- if (err.code === 'ENOENT') {
282
- console.error(chalk.red(`\n❌ --check failed: canonical briefer not found at ${outPath}\n`));
283
- console.error(chalk.gray(' Run `descix briefer` (without --check) to create it.\n'));
284
- process.exit(2);
285
- }
286
- throw err;
287
- }
288
-
289
- if (canonical === doc.markdown) {
290
- console.log(chalk.green(`\n✅ Briefer is in sync — no drift detected.\n`));
291
- return { drift: false, doc };
292
- }
293
-
294
- // Drift detected. Print a unified-style diff and exit non-zero.
295
- // Per scope doc §2.2 §3, --check also compares the citation trail. For M1
296
- // we report both prose-drift and citation-drift counts.
297
- const canonicalTrail = extractCitationTrail(canonical);
298
- const regenTrail = doc.citationTrail;
299
- const trailChanged = (canonicalTrail.length !== regenTrail.length) ||
300
- canonicalTrail.some((c, i) => c !== regenTrail[i]);
301
-
302
- console.error(chalk.yellow(`\n⚠ [${BRIEFER_ERROR_CODES.DRIFT_DETECTED}] Briefer drift detected.\n`));
303
- console.error(chalk.gray(` Canonical: ${outPath}`));
304
- console.error(chalk.gray(` Regen length: ${doc.markdown.length} bytes`));
305
- console.error(chalk.gray(` Canon length: ${canonical.length} bytes`));
306
- console.error(chalk.gray(` Citation trail drift: ${trailChanged ? 'YES' : 'no'}\n`));
307
-
308
- if (verbose) {
309
- console.error(simpleLineDiff(canonical, doc.markdown, { aLabel: outPath, bLabel: 'regen (in-memory)' }));
310
- console.error('');
311
- } else {
312
- console.error(chalk.gray(' (Run with --verbose for the full diff.)\n'));
313
- }
314
-
315
- // M2: drift means a source-of-truth file changed shape since last regen.
316
- // Caller should regenerate (run `descix briefer` without --check) and commit
317
- // the updated canonical briefer.
318
- process.exit(1);
319
- }
@@ -1,129 +0,0 @@
1
- /**
2
- * §7 — Where to look for canonical answers extractor (M2 implementation).
3
- *
4
- * Per WS-DESCIX-BRIEFER-CLI scope doc §2.2 §7, this section is PARTIALLY
5
- * DERIVED, PARTIALLY EDITORIAL:
6
- * - "Question → Canonical source" rows verify each cited path resolves.
7
- * - The "Do NOT trust" list is editorial cruft inventory, optionally read
8
- * from a JSON sidecar (.briefer-cruft-inventory.json) — if absent, a
9
- * minimal default list (the docs called out in the canonical briefer
10
- * yesterday) is rendered.
11
- *
12
- * Files cited as canonical sources (all must exist at extract time):
13
- * - provision-platform-lb.js (routing source)
14
- * - serviceManifestManager.js (dispatch source)
15
- * - entitlements/index.js, communityManagement.js, bootstrap.js (Products)
16
- * - dev/gateway.js, createViteProxyConfig.js (local dev)
17
- * - descix-cloud-core/src/config.js (bootstrap precedence)
18
- * - platform-runtime-mental-model.md (env parallelism + cutover)
19
- */
20
- import fs from 'fs/promises';
21
- import path from 'path';
22
- import {
23
- readSourceFile,
24
- makeCitation,
25
- resolveRepoPath
26
- } from '../util/source-reader.js';
27
- import { BrieferExtractorError, BRIEFER_ERROR_CODES } from '../errors.js';
28
-
29
- export const SECTION = {
30
- number: 7,
31
- heading: '7. Where to look for canonical answers',
32
- sourceFiles: [
33
- 'DeSciX/DeSciX_Cloud/microservice/admin/scripts/deploy/provision-platform-lb.js',
34
- 'DeSciX/DeSciX_Cloud/microservice/services/serviceManifestManager.js',
35
- 'DeSciX/DeSciX_Core/descix-platform-api/src/entitlements/index.js',
36
- 'DeSciX/DeSciX_Cloud/microservice/services/communityManagement.js',
37
- 'DeSciX/DeSciX_Cloud/microservice/admin/bootstrap.js',
38
- 'DeSciX/DeSciX_Core/descix-app-sdk/src/dev/gateway.js',
39
- 'DeSciX/DeSciX_Core/descix-app-sdk/src/dev/createViteProxyConfig.js',
40
- 'DeSciX/DeSciX_Core/descix-cloud-core/src/config.js',
41
- 'DeSciX/V2_docs/architecture/platform-runtime-mental-model.md'
42
- ]
43
- };
44
-
45
- const CRUFT_SIDECAR = 'DeSciX/V2_docs/architecture/.briefer-cruft-inventory.json';
46
-
47
- export async function extract({ env, cliPaths } = {}) {
48
- if (!env) {
49
- throw new BrieferExtractorError({
50
- code: BRIEFER_ERROR_CODES.NOT_IMPLEMENTED,
51
- section: `§${SECTION.number} ${SECTION.heading}`,
52
- source: 'extractor argument',
53
- expected: 'env (dev|demo|prod) provided by caller',
54
- recovery: 'Pass {env} from the briefer entry point.'
55
- });
56
- }
57
- if (!cliPaths) {
58
- throw new BrieferExtractorError({
59
- code: BRIEFER_ERROR_CODES.NOT_IMPLEMENTED,
60
- section: `§${SECTION.number} ${SECTION.heading}`,
61
- source: 'extractor argument',
62
- expected: 'cliPaths provided by caller',
63
- recovery: 'Pass {cliPaths} from the briefer entry point.'
64
- });
65
- }
66
-
67
- // Verify each cited canonical source actually exists. HARD-FAIL with
68
- // BRIEFER-SRC-NOT-FOUND on the FIRST missing file — surfaces drift early.
69
- const citations = [];
70
- for (const rel of SECTION.sourceFiles) {
71
- const file = await readSourceFile({
72
- cliPaths,
73
- relPath: rel,
74
- section: `§${SECTION.number} ${SECTION.heading}`
75
- });
76
- citations.push(makeCitation({
77
- file: rel,
78
- lines: `1-${file.lines.length}`,
79
- anchor: 'canonical source',
80
- fileLines: file.lines
81
- }));
82
- }
83
-
84
- // Cruft sidecar — optional. If present, render the entries; if absent, render
85
- // the default minimal cruft list from yesterday's briefer.
86
- let cruftRows;
87
- let cruftSource = null;
88
- try {
89
- const sidecarAbs = resolveRepoPath(cliPaths, CRUFT_SIDECAR);
90
- const raw = await fs.readFile(sidecarAbs, 'utf-8');
91
- const data = JSON.parse(raw);
92
- cruftRows = (data.entries || []).map(e => `- ${e.path || e.file}${e.note ? ` — ${e.note}` : ''}`);
93
- cruftSource = CRUFT_SIDECAR;
94
- } catch (err) {
95
- // Sidecar absent or malformed — fall back to the canonical-briefer's list
96
- // for prose continuity. This is NOT a value-fallback (per
97
- // feedback_no-hardcoded-fallbacks); it's the documented default rendering
98
- // until the sidecar lands.
99
- cruftRows = [
100
- '- `unified-product-registry.md` routing section',
101
- '- `cloud-lb-decentralized-routing.md` table without host-dim context',
102
- '- Any cloud-KB chunk that claims runtime-Gateway / runtime-Firestore-lookup-for-routing'
103
- ];
104
- }
105
-
106
- const markdown = [
107
- `Trust order for any new architectural question:`,
108
- ``,
109
- `1. **Code with \`file:line\` cite.** Always wins.`,
110
- `2. \`DeSciX/V2_docs/architecture/platform-runtime-mental-model.md\` — closest to a code-grounded reference doc.`,
111
- `3. \`DeSciX/CLAUDE.md\` — mostly right (note: any "load balancers look up by app_id" phrasing is misleading; the LB's host rules + path matchers do the routing, not a runtime lookup).`,
112
- `4. \`DeSciX/V2_docs/architecture/split-stack-production-architecture.md\` — signal.`,
113
- ``,
114
- `**Do NOT trust** (cruft inventory${cruftSource ? `, from \`${cruftSource}\`` : ', default list — install `.briefer-cruft-inventory.json` to override'}):`,
115
- ``,
116
- cruftRows.join('\n'),
117
- ``,
118
- `| Question | Canonical source (in this order) | Notes |`,
119
- `|---|---|---|`,
120
- `| How does prod LB route? | \`DeSciX_Cloud/microservice/admin/scripts/deploy/provision-platform-lb.js\`; verify with \`gcloud compute url-maps describe descix-discord-app-lb\` | Code = signal |`,
121
- `| How does the env command-broker dispatch external commands? | \`services/serviceManifestManager.js\` (\`proxyToExternalService\`) and \`services/apiFront.js\` | Code = signal |`,
122
- `| What is Products for? | \`descix-platform-api/src/entitlements/index.js\`, \`services/communityManagement.js\`, \`admin/bootstrap.js\` | Code = signal |`,
123
- `| How does local \`descix serve\` work? | \`descix-app-sdk/src/dev/gateway.js\` + \`createViteProxyConfig.js\` | Code = signal |`,
124
- `| Bootstrap & config precedence? | \`descix-cloud-core/src/config.js\` | Code = signal |`,
125
- `| Environment parallelism & PROD cutover? | \`platform-runtime-mental-model.md\` | Distilled architectural doc |`
126
- ].join('\n');
127
-
128
- return { markdown, citations };
129
- }
@@ -1,220 +0,0 @@
1
- /**
2
- * §5 — Entitlements & Products Firestore extractor (M2 implementation).
3
- *
4
- * Per WS-DESCIX-BRIEFER-CLI scope doc §2.2 §5 + M2 dispatch §6.7 extension:
5
- * - Products schema fields + readers — cite hydrateCommunityIdFromProducts
6
- * in @descix/platform-api/src/entitlements/index.js + the apiFront
7
- * middleware that invokes it (communityManagement.js re-export site).
8
- * - Writers — grep DeSciX_Cloud/microservice/admin/ for Products write
9
- * patterns (bootstrap.js hydrate-env + confirm_site_deploy).
10
- * - App-level config layer (§6.7 extension) — cite the resolver chain
11
- * in geminiInteractions.js::resolveModelThinkingPair: request level → kb_model_override
12
- * → default_app_model → levelConfig → DEFAULT_AI_MODEL.
13
- *
14
- * NO direct @google-cloud/firestore or @pinecone-database/pinecone imports
15
- * (AC-7 anti-regression). All Firestore touches in the briefer code go
16
- * through apifront or @descix/cloud-core wrappers.
17
- */
18
- import {
19
- readSourceFile,
20
- findInLines,
21
- makeCitation,
22
- grepFiles,
23
- probeFirestoreRest
24
- } from '../util/source-reader.js';
25
- import { BrieferExtractorError, BRIEFER_ERROR_CODES } from '../errors.js';
26
- // The (model, thinking) precedence chain in words, from its ONE owner. The briefer
27
- // QUOTES the served contract rather than paraphrasing it — a briefer paraphrase of a
28
- // chain is exactly how the old five-step list outlived the code it described.
29
- import { MODEL_THINKING_CHAIN } from '@descix/platform-api/mcp-tools';
30
-
31
- export const SECTION = {
32
- number: 5,
33
- heading: '5. Entitlements & Products Firestore',
34
- sourceFiles: [
35
- 'DeSciX/DeSciX_Core/descix-platform-api/src/entitlements/index.js',
36
- 'DeSciX/DeSciX_Cloud/microservice/services/communityManagement.js',
37
- 'DeSciX/DeSciX_Cloud/microservice/admin/bootstrap.js',
38
- 'DeSciX/DeSciX_Cloud/microservice/services/geminiInteractions.js'
39
- ]
40
- };
41
-
42
- const ENTITLEMENTS_FILE = 'DeSciX/DeSciX_Core/descix-platform-api/src/entitlements/index.js';
43
- const CM_FILE = 'DeSciX/DeSciX_Cloud/microservice/services/communityManagement.js';
44
- const BOOTSTRAP_FILE = 'DeSciX/DeSciX_Cloud/microservice/admin/bootstrap.js';
45
- const GEMINI_FILE = 'DeSciX/DeSciX_Cloud/microservice/services/geminiInteractions.js';
46
-
47
- export async function extract({ env, cliPaths } = {}) {
48
- if (!env) {
49
- throw new BrieferExtractorError({
50
- code: BRIEFER_ERROR_CODES.NOT_IMPLEMENTED,
51
- section: `§${SECTION.number} ${SECTION.heading}`,
52
- source: 'extractor argument',
53
- expected: 'env (dev|demo|prod) provided by caller',
54
- recovery: 'Pass {env} from the briefer entry point.'
55
- });
56
- }
57
- if (!cliPaths) {
58
- throw new BrieferExtractorError({
59
- code: BRIEFER_ERROR_CODES.NOT_IMPLEMENTED,
60
- section: `§${SECTION.number} ${SECTION.heading}`,
61
- source: 'extractor argument',
62
- expected: 'cliPaths provided by caller',
63
- recovery: 'Pass {cliPaths} from the briefer entry point.'
64
- });
65
- }
66
-
67
- // ── Source 1: entitlements/index.js — hydrateCommunityIdFromProducts ──
68
- const ent = await readSourceFile({
69
- cliPaths,
70
- relPath: ENTITLEMENTS_FILE,
71
- section: `§${SECTION.number} ${SECTION.heading}`
72
- });
73
- const hydrateMatch = findInLines({
74
- lines: ent.lines,
75
- regex: /export\s+async\s+function\s+hydrateCommunityIdFromProducts\b/,
76
- section: `§${SECTION.number} ${SECTION.heading}`,
77
- source: `${ENTITLEMENTS_FILE} (hydrateCommunityIdFromProducts)`,
78
- expected: 'export async function hydrateCommunityIdFromProducts(params)',
79
- recovery: `Re-locate hydrateCommunityIdFromProducts in ${ENTITLEMENTS_FILE}.`
80
- });
81
-
82
- // ── Source 2: communityManagement.js — re-export site ──
83
- const cm = await readSourceFile({
84
- cliPaths,
85
- relPath: CM_FILE,
86
- section: `§${SECTION.number} ${SECTION.heading}`
87
- });
88
- // The symbol is matched WITHIN an export list rather than as the list's sole member. The old
89
- // pattern anchored on the closing brace immediately after the name, so it broke the moment a
90
- // second symbol was re-exported beside it — the extractor reported the re-export missing when
91
- // it was present and one token wider.
92
- //
93
- // HONEST LIMITATION, stated rather than implied: this is still textual matching, so it remains a
94
- // derivation of a fact the module itself owns. The robust fix is to consume the owner's actual
95
- // exports, but this extractor cannot import communityManagement.js — that would pull the whole
96
- // Cloud service graph (config bootstrap, Firestore) into the CLI. Matching the identifier inside
97
- // any export list is what survives a re-ordering; a move to `export * from` would still need
98
- // this line changed.
99
- const reExportMatch = findInLines({
100
- lines: cm.lines,
101
- regex: /export\s*\{[^}]*\bhydrateCommunityIdFromProducts\b/,
102
- section: `§${SECTION.number} ${SECTION.heading}`,
103
- source: `${CM_FILE} (hydrate re-export)`,
104
- expected: 'hydrateCommunityIdFromProducts named in an export list',
105
- recovery: `Verify ${CM_FILE} still re-exports hydrateCommunityIdFromProducts.`
106
- });
107
-
108
- // ── Source 3: bootstrap.js — hydrate-env writer ──
109
- const bootstrap = await readSourceFile({
110
- cliPaths,
111
- relPath: BOOTSTRAP_FILE,
112
- section: `§${SECTION.number} ${SECTION.heading}`
113
- });
114
- const hydrateEnvMatch = findInLines({
115
- lines: bootstrap.lines,
116
- regex: /hydrate-env|hydrateEnv|hydrate_env/,
117
- section: `§${SECTION.number} ${SECTION.heading}`,
118
- source: `${BOOTSTRAP_FILE} (hydrate-env writer)`,
119
- expected: 'hydrate-env subcommand or hydrateEnv function declaration',
120
- recovery: `Re-locate the hydrate-env writer in ${BOOTSTRAP_FILE}.`
121
- });
122
-
123
- // ── Source 4: geminiInteractions.js — the (model, thinking) pair owner (§6.7 link) ──
124
- const gemini = await readSourceFile({
125
- cliPaths,
126
- relPath: GEMINI_FILE,
127
- section: `§${SECTION.number} ${SECTION.heading}`
128
- });
129
- const resolverMatch = findInLines({
130
- lines: gemini.lines,
131
- regex: /export\s+function\s+resolveModelThinkingPair\b/,
132
- section: `§${SECTION.number} ${SECTION.heading}`,
133
- source: `${GEMINI_FILE} (resolveModelThinkingPair)`,
134
- expected: 'export function resolveModelThinkingPair(...)',
135
- recovery: `Re-locate resolveModelThinkingPair in ${GEMINI_FILE}.`
136
- });
137
-
138
- // ── Optional grep: count Products readers across services/ ──
139
- let runtimeReadersList = '';
140
- const readers = await grepFiles({
141
- repoRoot: cliPaths.repoRoot,
142
- relPaths: ['DeSciX/DeSciX_Cloud/microservice/services'],
143
- regex: /Products\.doc\(|collection\(['"]Products['"]\)|getProductContext/,
144
- excludePaths: new Set(['/node_modules/', '/.git/'])
145
- });
146
- if (readers.length > 0) {
147
- const unique = [...new Set(readers.map(r => r.file))].slice(0, 8);
148
- runtimeReadersList = unique.map(f => ` - \`${f}\``).join('\n');
149
- }
150
-
151
- // ── M3: live Firestore Products probe (HARD-FAIL on demo/prod, skipped on dev) ──
152
- // Uses Firestore REST API via gcloud-derived access token. Per AC-7
153
- // anti-regression: no @google-cloud/firestore import — this is a different
154
- // API surface (REST + gcloud-CLI token), explicitly permitted.
155
- const probeCitations = [];
156
- let productsLiveNote = '';
157
- if (env === 'dev') {
158
- productsLiveNote = '\n_DEV: Firestore probe skipped (local dev — no cloud Firestore for the descix-dev database in this regen scope)._\n';
159
- } else {
160
- const productsProbe = await probeFirestoreRest({
161
- dbPath: `descix-${env}/documents/Products`,
162
- query: { pageSize: 200, 'mask.fieldPaths': 'app_id' },
163
- env,
164
- section: `§${SECTION.number} ${SECTION.heading}`,
165
- anchor: 'products-collection-list',
166
- expected: `Firestore Products list for env=${env}`,
167
- recovery: `Run 'gcloud auth login' and ensure the account has Firestore read scope. The Products collection cross-check is required for env=${env}.`
168
- });
169
- const docs = (productsProbe.json && productsProbe.json.documents) || [];
170
- const names = docs
171
- .map(d => (d.name || '').split('/').pop())
172
- .filter(Boolean)
173
- .sort();
174
- const sample = names.slice(0, 8);
175
- productsLiveNote = [
176
- '',
177
- `**Live Products collection** (probed \`Firestore REST listDocuments\` against \`descix-${env}/documents/Products\`):`,
178
- `- Docs returned: \`${names.length}\` (pageSize=200; further pages not enumerated this milestone)`,
179
- `- Sample app_ids: ${sample.length > 0 ? sample.map(n => '\`' + n + '\`').join(', ') : '_(none)_'}${names.length > sample.length ? ` (+ ${names.length - sample.length} more)` : ''}`,
180
- ''
181
- ].join('\n');
182
- probeCitations.push(productsProbe.citation);
183
- }
184
-
185
- // ── Render markdown ──
186
- const markdown = [
187
- `\`Products/{app_id}\` in \`descix-{env}\` Firestore holds:`,
188
- `- \`productPath\`: \`Community/{community_id}/Apps/{app_id}\` (operational path)`,
189
- `- \`gcsPath\`: \`gs://descix-assets-public/{env}/{app_id}/\``,
190
- `- \`ip_site_gcs_path_url\`: subdomain URL (set by \`confirm_site_deploy\` AFTER site deploy)`,
191
- `- \`community_id\` (operational metadata)`,
192
- `- \`type\`, \`price\`, \`metadata\``,
193
- ``,
194
- `**Readers at runtime:** \`hydrateCommunityIdFromProducts()\` middleware (canonical at \`${ENTITLEMENTS_FILE}:${hydrateMatch.lineNumber}\`, re-exported at \`${CM_FILE}:${reExportMatch.lineNumber}\`), purchase / entitlement handlers, app-metadata handlers. **ALL AT THE APIFRONT-OR-DOWNSTREAM LAYER.** **NEVER AT THE LB.**`,
195
- ...(runtimeReadersList ? ['', `_Grep of \`services/\` for Products readers:_`, runtimeReadersList] : []),
196
- ``,
197
- `**Writers:** \`${BOOTSTRAP_FILE}\` \`hydrate-env\` (\`:${hydrateEnvMatch.lineNumber}\`), \`confirm_site_deploy\`, migration scripts.`,
198
- ``,
199
- `**Consumer at deploy time:** Products drives bootstrap; platform peer hosts are configured in \`provision-platform-lb.js\` (\`PLATFORM_PEER_APPS\`), not read from Products at deploy time.`,
200
- ``,
201
- `### App-level config layer (§6.7 — added 2026-05-26)`,
202
- ``,
203
- `App-level and KB-level config flows from Firestore (\`Community/{c}/Apps/{a}\` for \`default_app_model\`, \`Community/{c}/Apps/{a}/KnowledgeBases/{k}\` for \`kb_model_override\`) into \`resolveModelThinkingPair()\` at \`${GEMINI_FILE}:${resolverMatch.lineNumber}\` — the ONE owner of the (model, thinking) pair. Both fields are **opt-in** — null means the tier below applies.`,
204
- ``,
205
- MODEL_THINKING_CHAIN,
206
- ``,
207
- `\`app.default_app_model\` no longer shadows an intelligence_level named on the request: a level names a (model, thinking) PAIR and outranks it. It still outranks the KB's own configured level and the platform default. Apps that want per-level routing leave \`default_app_model = null/absent\`.`,
208
- productsLiveNote
209
- ].join('\n');
210
-
211
- const citations = [
212
- makeCitation({ file: ENTITLEMENTS_FILE, lines: String(hydrateMatch.lineNumber), anchor: 'hydrateCommunityIdFromProducts (canonical)', fileLines: ent.lines }),
213
- makeCitation({ file: CM_FILE, lines: String(reExportMatch.lineNumber), anchor: 'hydrate re-export', fileLines: cm.lines }),
214
- makeCitation({ file: BOOTSTRAP_FILE, lines: String(hydrateEnvMatch.lineNumber), anchor: 'hydrate-env writer', fileLines: bootstrap.lines }),
215
- makeCitation({ file: GEMINI_FILE, lines: String(resolverMatch.lineNumber), anchor: 'resolveModelThinkingPair (app-level config bridge)', fileLines: gemini.lines }),
216
- ...probeCitations
217
- ];
218
-
219
- return { markdown, citations };
220
- }