@geraldmaron/construct 1.0.21 → 1.0.24

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 (150) hide show
  1. package/README.md +23 -7
  2. package/bin/construct +206 -228
  3. package/bin/construct-postinstall.mjs +25 -15
  4. package/lib/acp/server.mjs +113 -0
  5. package/lib/agent-instructions/inject.mjs +94 -0
  6. package/lib/auto-docs.mjs +10 -2
  7. package/lib/cli-commands.mjs +43 -15
  8. package/lib/comment-lint.mjs +115 -0
  9. package/lib/completions.mjs +7 -1
  10. package/lib/config/schema.mjs +4 -0
  11. package/lib/decisions/enforced-baseline.json +2 -0
  12. package/lib/docs-verify.mjs +15 -18
  13. package/lib/doctor/cli.mjs +8 -1
  14. package/lib/document-export.mjs +124 -0
  15. package/lib/embed/daemon.mjs +1 -1
  16. package/lib/embed/inbox.mjs +31 -10
  17. package/lib/embed/recommendation-store.mjs +7 -289
  18. package/lib/embed/reconcile.mjs +2 -2
  19. package/lib/features.mjs +11 -11
  20. package/lib/git-hooks-path.mjs +61 -0
  21. package/lib/home-namespace.mjs +60 -0
  22. package/lib/hooks/ci-status-check.mjs +62 -40
  23. package/lib/hooks/config-protection.mjs +4 -4
  24. package/lib/hooks/orchestration-dispatch-guard.mjs +153 -0
  25. package/lib/hooks/pre-push-gate.mjs +15 -6
  26. package/lib/hooks/session-reflect.mjs +5 -1
  27. package/lib/hooks/stop-notify.mjs +32 -17
  28. package/lib/hooks/stop-typecheck.mjs +7 -2
  29. package/lib/host-capabilities.mjs +24 -8
  30. package/lib/host-disposition.mjs +76 -0
  31. package/lib/ingest/provider-extract.mjs +1 -1
  32. package/lib/init-docs.mjs +1 -1
  33. package/lib/init-unified.mjs +320 -219
  34. package/lib/init-update.mjs +4 -84
  35. package/lib/init.mjs +9 -25
  36. package/lib/install/stage-project.mjs +8 -2
  37. package/lib/intake/git-queue.mjs +195 -0
  38. package/lib/intake/queue.mjs +9 -16
  39. package/lib/intent-classifier.mjs +1 -1
  40. package/lib/knowledge/search.mjs +52 -3
  41. package/lib/mcp/server.mjs +57 -14
  42. package/lib/mcp/tools/memory.mjs +2 -2
  43. package/lib/mcp/tools/orchestration-run.mjs +125 -0
  44. package/lib/mcp/tools/storage.mjs +2 -3
  45. package/lib/mcp-catalog.json +3 -3
  46. package/lib/mcp-manager.mjs +59 -3
  47. package/lib/model-registry.mjs +40 -33
  48. package/lib/observation-store.mjs +39 -163
  49. package/lib/opencode-config.mjs +1 -1
  50. package/lib/orchestration/events.mjs +66 -0
  51. package/lib/orchestration/runtime.mjs +72 -10
  52. package/lib/orchestration/worker.mjs +69 -21
  53. package/lib/orchestration-policy.mjs +27 -3
  54. package/lib/parity.mjs +46 -24
  55. package/lib/policy/unified-gates.mjs +96 -0
  56. package/lib/project-init-shared.mjs +0 -173
  57. package/lib/reconcile/adapter-prune.mjs +105 -0
  58. package/lib/reconcile/agent-instructions-rewrap.mjs +98 -0
  59. package/lib/reconcile/gitignore-coverage.mjs +88 -0
  60. package/lib/reconcile/index.mjs +169 -0
  61. package/lib/reconcile/legacy-doctrine-strip.mjs +139 -0
  62. package/lib/reconcile/legacy-guide-decommit.mjs +67 -0
  63. package/lib/reconcile/legacy-skills-cleanup.mjs +200 -0
  64. package/lib/reconcile/mcp-entry-reconcile.mjs +142 -0
  65. package/lib/runtime/uv-bootstrap.mjs +27 -3
  66. package/lib/schema-infer.mjs +16 -2
  67. package/lib/server/csrf.mjs +14 -2
  68. package/lib/server/index.mjs +95 -0
  69. package/lib/service-manager.mjs +59 -252
  70. package/lib/setup-prompts.mjs +2 -1
  71. package/lib/setup.mjs +104 -480
  72. package/lib/status.mjs +3 -6
  73. package/lib/storage/admin.mjs +48 -325
  74. package/lib/storage/backend.mjs +10 -43
  75. package/lib/storage/hybrid-query.mjs +15 -196
  76. package/lib/storage/sync.mjs +36 -177
  77. package/lib/storage/vector-client.mjs +256 -235
  78. package/lib/strategy-store.mjs +35 -286
  79. package/lib/template-registry.mjs +73 -0
  80. package/lib/term-format.mjs +75 -0
  81. package/lib/uninstall/uninstall.mjs +180 -7
  82. package/lib/worker/entrypoint.mjs +6 -14
  83. package/package.json +7 -6
  84. package/personas/construct.md +7 -8
  85. package/platforms/claude/settings.template.json +30 -11
  86. package/platforms/opencode/config.template.json +2 -2
  87. package/rules/common/neurodivergent-output.md +66 -0
  88. package/rules/common/tool-invisibility.md +37 -0
  89. package/scripts/sync-specialists.mjs +427 -107
  90. package/skills/operating/orchestration-reference.md +2 -16
  91. package/specialists/policy-inventory.json +14 -0
  92. package/specialists/prompts/cx-accessibility.md +2 -6
  93. package/specialists/prompts/cx-ai-engineer.md +0 -4
  94. package/specialists/prompts/cx-architect.md +3 -5
  95. package/specialists/prompts/cx-business-strategist.md +0 -5
  96. package/specialists/prompts/cx-data-analyst.md +0 -4
  97. package/specialists/prompts/cx-data-engineer.md +0 -4
  98. package/specialists/prompts/cx-debugger.md +2 -6
  99. package/specialists/prompts/cx-designer.md +0 -8
  100. package/specialists/prompts/cx-devil-advocate.md +2 -2
  101. package/specialists/prompts/cx-docs-keeper.md +0 -13
  102. package/specialists/prompts/cx-engineer.md +0 -13
  103. package/specialists/prompts/cx-evaluator.md +2 -2
  104. package/specialists/prompts/cx-explorer.md +4 -5
  105. package/specialists/prompts/cx-legal-compliance.md +4 -5
  106. package/specialists/prompts/cx-operations.md +0 -5
  107. package/specialists/prompts/cx-orchestrator.md +0 -4
  108. package/specialists/prompts/cx-platform-engineer.md +0 -8
  109. package/specialists/prompts/cx-product-manager.md +0 -8
  110. package/specialists/prompts/cx-qa.md +3 -12
  111. package/specialists/prompts/cx-rd-lead.md +0 -5
  112. package/specialists/prompts/cx-release-manager.md +0 -8
  113. package/specialists/prompts/cx-researcher.md +5 -29
  114. package/specialists/prompts/cx-reviewer.md +2 -6
  115. package/specialists/prompts/cx-security.md +2 -11
  116. package/specialists/prompts/cx-sre.md +0 -15
  117. package/specialists/prompts/cx-test-automation.md +0 -4
  118. package/specialists/prompts/cx-trace-reviewer.md +2 -2
  119. package/specialists/prompts/cx-ux-researcher.md +0 -4
  120. package/specialists/registry.json +28 -36
  121. package/templates/distribution/run.mjs +36 -7
  122. package/templates/docs/accessibility-audit.md +56 -0
  123. package/templates/docs/architecture-review.md +59 -0
  124. package/templates/docs/code-review-report.md +46 -0
  125. package/templates/docs/construct_guide.md +15 -15
  126. package/templates/docs/debug-investigation.md +53 -0
  127. package/templates/docs/qa-report.md +48 -0
  128. package/templates/docs/security-audit-report.md +48 -0
  129. package/templates/docs/task-packet.md +49 -0
  130. package/templates/docs/verdict.md +40 -0
  131. package/db/schema/001_init.sql +0 -40
  132. package/db/schema/002_pgvector.sql +0 -182
  133. package/db/schema/003_intake.sql +0 -47
  134. package/db/schema/003_observation_reconciliation.sql +0 -14
  135. package/db/schema/004_recommendations.sql +0 -46
  136. package/db/schema/005_strategy.sql +0 -21
  137. package/db/schema/006_graph.sql +0 -24
  138. package/db/schema/007_tags.sql +0 -30
  139. package/db/schema/008_skill_usage.sql +0 -24
  140. package/db/schema/009_scheduler.sql +0 -14
  141. package/db/schema/010_cx_scores.sql +0 -51
  142. package/lib/intake/postgres-queue.mjs +0 -240
  143. package/lib/server/static/index.html +0 -1
  144. package/lib/services/local-postgres.mjs +0 -15
  145. package/lib/storage/backup.mjs +0 -347
  146. package/lib/storage/migrations.mjs +0 -187
  147. package/lib/storage/postgres-backup.mjs +0 -124
  148. package/lib/storage/sql-store.mjs +0 -45
  149. package/lib/storage/store-version.mjs +0 -115
  150. package/lib/storage/vector-store.mjs +0 -100
@@ -1,187 +0,0 @@
1
- /**
2
- * lib/storage/migrations.mjs — Postgres migration runner with hash tracking.
3
- *
4
- * Walks `db/schema/*.sql` in lexical order and applies any not yet
5
- * recorded in `construct_schema_migrations`. Each applied file's SHA256 is
6
- * stored alongside the filename. Re-running the runner against an unchanged
7
- * tree is a no-op.
8
- *
9
- * Drift detection: if an applied file's SHA changes between runs, the runner
10
- * fails fast with a precise error. SQL files are append-only by convention —
11
- * to evolve schema after a migration ships, write a new file with a higher
12
- * sequence number.
13
- *
14
- * Repair mode: long-lived developer databases pre-date the append-only policy
15
- * and carry stale SHAs for files that have since evolved. Call runMigrations
16
- * with `repair: true` (or `construct storage repair-migrations`) to re-apply
17
- * each drifted file. The repair refuses on any file containing a destructive
18
- * statement (`DROP`, `TRUNCATE`, `ALTER … DROP`) so the safety bar stays
19
- * "only fully-idempotent migrations may be re-recorded."
20
- *
21
- * The bookkeeping table (`construct_schema_migrations`) is created inline
22
- * before applied state is checked, so the runner self-bootstraps and a fresh
23
- * database can run from any starting migration without a prerequisite file.
24
- */
25
-
26
- import { readdirSync, readFileSync } from 'node:fs';
27
- import { join, dirname } from 'node:path';
28
- import { fileURLToPath } from 'node:url';
29
- import { createHash } from 'node:crypto';
30
-
31
- const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
32
- const DEFAULT_MIGRATIONS_DIR = join(MODULE_DIR, '..', '..', 'db', 'schema');
33
-
34
- function sha256(text) {
35
- return createHash('sha256').update(text).digest('hex');
36
- }
37
-
38
- function listMigrationFiles(dir) {
39
- return readdirSync(dir)
40
- .filter((name) => name.endsWith('.sql'))
41
- .sort();
42
- }
43
-
44
- const BOOKKEEPING_DDL = `
45
- CREATE TABLE IF NOT EXISTS construct_schema_migrations (
46
- filename TEXT PRIMARY KEY,
47
- sha TEXT NOT NULL,
48
- applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
49
- );
50
- `;
51
-
52
- // Heuristic: a migration is safe to re-apply (idempotent) when it contains no
53
- // destructive statements. Comments are stripped first so a `-- DROP …` note in
54
- // a docstring does not falsely flag the file.
55
- const DESTRUCTIVE_RE = /\b(drop\s+(table|index|view|column|schema|extension|function|sequence)\b|truncate\b|alter\s+table\s+[^;]*?\bdrop\b|delete\s+from\b)/i;
56
-
57
- function stripSqlComments(sql) {
58
- return sql
59
- .replace(/--[^\n]*/g, '')
60
- .replace(/\/\*[\s\S]*?\*\//g, '');
61
- }
62
-
63
- export function isIdempotentMigration(sql) {
64
- return !DESTRUCTIVE_RE.test(stripSqlComments(sql));
65
- }
66
-
67
- /**
68
- * Apply pending migrations. Returns a per-file outcome summary.
69
- *
70
- * @param {object} client — postgres client (from createSqlClient)
71
- * @param {object} [opts]
72
- * @param {string} [opts.dir] — schema/migrations directory, defaults to db/schema
73
- * @param {boolean} [opts.repair] — when true, re-apply drifted files that are
74
- * verifiably idempotent and update their recorded SHA. Destructive drift
75
- * still throws. Default false.
76
- * @returns {Promise<{ applied: string[], skipped: string[], repaired: string[], drift: Array<{ filename: string, expected: string, actual: string, idempotent: boolean }> }>}
77
- */
78
- export async function runMigrations(client, { dir = DEFAULT_MIGRATIONS_DIR, repair = false } = {}) {
79
- if (!client) throw new Error('runMigrations requires a postgres client');
80
-
81
- await client.unsafe(BOOKKEEPING_DDL);
82
-
83
- const recorded = await client`
84
- SELECT filename, sha FROM construct_schema_migrations
85
- `;
86
- const recordedMap = new Map(recorded.map((r) => [r.filename, r.sha]));
87
-
88
- const files = listMigrationFiles(dir);
89
- const applied = [];
90
- const skipped = [];
91
- const repaired = [];
92
- const drift = [];
93
-
94
- for (const filename of files) {
95
- const path = join(dir, filename);
96
- const contents = readFileSync(path, 'utf8');
97
- const sha = sha256(contents);
98
-
99
- const prev = recordedMap.get(filename);
100
- if (prev) {
101
- if (prev !== sha) {
102
- const idempotent = isIdempotentMigration(contents);
103
- if (repair && idempotent) {
104
- // Re-apply the migration (its IF NOT EXISTS clauses make this a
105
- // no-op against the live schema) and update the recorded SHA.
106
- await client.begin(async (tx) => {
107
- await tx.unsafe(contents);
108
- await tx`
109
- UPDATE construct_schema_migrations
110
- SET sha = ${sha}, applied_at = now()
111
- WHERE filename = ${filename}
112
- `;
113
- });
114
- repaired.push(filename);
115
- } else {
116
- drift.push({ filename, expected: prev, actual: sha, idempotent });
117
- }
118
- } else {
119
- skipped.push(filename);
120
- }
121
- continue;
122
- }
123
-
124
- await client.begin(async (tx) => {
125
- await tx.unsafe(contents);
126
- await tx`
127
- INSERT INTO construct_schema_migrations (filename, sha)
128
- VALUES (${filename}, ${sha})
129
- ON CONFLICT (filename) DO UPDATE SET sha = EXCLUDED.sha, applied_at = now()
130
- `;
131
- });
132
- applied.push(filename);
133
- }
134
-
135
- if (drift.length > 0) {
136
- const detail = drift
137
- .map((d) => ` ${d.filename}: applied SHA ${d.expected.slice(0, 12)}…, on-disk SHA ${d.actual.slice(0, 12)}…${d.idempotent ? ' (idempotent — repairable via `construct storage repair-migrations`)' : ' (NOT idempotent — write a new migration file)'}`)
138
- .join('\n');
139
- throw new Error(
140
- `Migration drift detected (a previously-applied migration file has changed). ` +
141
- `Migrations are append-only — write a new file with a higher sequence number ` +
142
- `to evolve the schema. Drift:\n${detail}`
143
- );
144
- }
145
-
146
- return { applied, skipped, repaired, drift };
147
- }
148
-
149
- /**
150
- * Diagnostic for `construct doctor`: returns last applied filename, count,
151
- * and any drift, without throwing.
152
- */
153
- export async function describeMigrations(client, { dir = DEFAULT_MIGRATIONS_DIR } = {}) {
154
- if (!client) return { ok: false, reason: 'no_sql_client' };
155
- try {
156
- await client.unsafe(BOOKKEEPING_DDL);
157
- const rows = await client`
158
- SELECT filename, sha, applied_at
159
- FROM construct_schema_migrations
160
- ORDER BY applied_at DESC, filename DESC
161
- LIMIT 1
162
- `;
163
- const onDisk = listMigrationFiles(dir);
164
- const applied = await client`SELECT count(*)::int AS n FROM construct_schema_migrations`;
165
- const recorded = await client`SELECT filename, sha FROM construct_schema_migrations`;
166
- const recordedMap = new Map(recorded.map((r) => [r.filename, r.sha]));
167
- const drift = [];
168
- for (const filename of onDisk) {
169
- const contents = readFileSync(join(dir, filename), 'utf8');
170
- const sha = sha256(contents);
171
- const prev = recordedMap.get(filename);
172
- if (prev && prev !== sha) {
173
- drift.push({ filename, idempotent: isIdempotentMigration(contents) });
174
- }
175
- }
176
- return {
177
- ok: true,
178
- lastApplied: rows[0]?.filename || null,
179
- lastAppliedAt: rows[0]?.applied_at || null,
180
- appliedCount: applied[0]?.n ?? 0,
181
- onDiskCount: onDisk.length,
182
- drift,
183
- };
184
- } catch (err) {
185
- return { ok: false, reason: err?.message || 'describe-migrations failed' };
186
- }
187
- }
@@ -1,124 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * lib/storage/postgres-backup.mjs — durable stash/restore for the managed construct-postgres container.
4
- *
5
- * Mirrors the telemetry backup pattern in service-manager.mjs. Entry points:
6
- * - construct down → stashConstructDb (dump before container stop)
7
- * - construct init → restoreConstructDb (reload after fresh container start)
8
- *
9
- * Dumps are stored in ~/.construct/backups/postgres/ as pg_dump custom-format
10
- * files. The N most recent are kept; older ones are pruned automatically.
11
- */
12
- import fs from 'node:fs';
13
- import os from 'node:os';
14
- import path from 'node:path';
15
- import { spawnSync } from 'node:child_process';
16
-
17
- const POSTGRES_CONTAINER = 'construct-postgres';
18
- const POSTGRES_USER = 'construct';
19
- const POSTGRES_DB = 'construct';
20
- const DEFAULT_KEEP = 5;
21
-
22
- function pruneBackupDir(dir, keep) {
23
- try {
24
- const dumps = fs.readdirSync(dir)
25
- .filter((f) => f.startsWith('construct-') && f.endsWith('.dump'))
26
- .sort()
27
- .reverse();
28
- for (const dump of dumps.slice(keep)) {
29
- fs.rmSync(path.join(dir, dump), { force: true });
30
- fs.rmSync(path.join(dir, dump.replace('.dump', '.json')), { force: true });
31
- }
32
- } catch { /* non-critical */ }
33
- }
34
-
35
- /**
36
- * Dump the construct Postgres database to a timestamped file under
37
- * ~/.construct/backups/postgres/. Safe to call when the container is not
38
- * running — returns { status: 'no-data' } silently.
39
- */
40
- export function stashConstructDb({
41
- homeDir = os.homedir(),
42
- spawnSyncFn = spawnSync,
43
- keep = DEFAULT_KEEP,
44
- } = {}) {
45
- const stashDir = path.join(homeDir, '.construct', 'backups', 'postgres');
46
- fs.mkdirSync(stashDir, { recursive: true });
47
-
48
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
49
- const dumpFile = path.join(stashDir, `construct-${timestamp}.dump`);
50
- const manifestFile = path.join(stashDir, `construct-${timestamp}.json`);
51
-
52
- const dump = spawnSyncFn('docker', [
53
- 'exec', POSTGRES_CONTAINER,
54
- 'pg_dump', '-U', POSTGRES_USER, '-d', POSTGRES_DB,
55
- '-Fc', '--data-only',
56
- ], { stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 200 * 1024 * 1024 });
57
-
58
- const hasData = dump.status === 0 && dump.stdout?.length > 100;
59
- if (!hasData) return { status: 'no-data', stashPath: null };
60
-
61
- fs.writeFileSync(dumpFile, dump.stdout);
62
- fs.writeFileSync(manifestFile, JSON.stringify({
63
- version: 1,
64
- createdAt: new Date().toISOString(),
65
- reason: 'pre-shutdown-stash',
66
- dumpFile: path.basename(dumpFile),
67
- dumpBytes: dump.stdout.length,
68
- }, null, 2) + '\n');
69
-
70
- pruneBackupDir(stashDir, keep);
71
- return { status: 'ok', stashPath: dumpFile, bytes: dump.stdout.length };
72
- }
73
-
74
- /**
75
- * Restore the most recent stash into a running construct-postgres container.
76
- * Safe to call when no stash exists — returns { status: 'no-stash' } silently.
77
- * The schema must already exist (run migration before calling this).
78
- */
79
- export function restoreConstructDb({
80
- homeDir = os.homedir(),
81
- spawnSyncFn = spawnSync,
82
- } = {}) {
83
- const stashDir = path.join(homeDir, '.construct', 'backups', 'postgres');
84
- if (!fs.existsSync(stashDir)) return { status: 'no-stash' };
85
-
86
- const dumps = fs.readdirSync(stashDir)
87
- .filter((f) => f.startsWith('construct-') && f.endsWith('.dump'))
88
- .sort()
89
- .reverse();
90
- if (dumps.length === 0) return { status: 'no-stash' };
91
-
92
- const latestDump = path.join(stashDir, dumps[0]);
93
-
94
- const cp = spawnSyncFn('docker', [
95
- 'cp', latestDump, `${POSTGRES_CONTAINER}:/tmp/construct.dump`,
96
- ], { stdio: 'ignore' });
97
- if (cp.status !== 0) return { status: 'copy-failed', stashPath: latestDump };
98
-
99
- const restore = spawnSyncFn('docker', [
100
- 'exec', POSTGRES_CONTAINER,
101
- 'pg_restore', '-U', POSTGRES_USER, '-d', POSTGRES_DB,
102
- '--data-only', '--disable-triggers', '--no-owner',
103
- '--if-exists',
104
- '/tmp/construct.dump',
105
- ], { stdio: 'ignore' });
106
-
107
- return {
108
- status: restore.status === 0 ? 'restored' : 'restore-failed',
109
- stashPath: latestDump,
110
- exitCode: restore.status,
111
- };
112
- }
113
-
114
- /**
115
- * Delete all stashed backups under ~/.construct/backups/postgres/.
116
- * Called by `construct storage reset` and uninstall flows.
117
- */
118
- export function purgeConstructDbStashes({ homeDir = os.homedir() } = {}) {
119
- const stashDir = path.join(homeDir, '.construct', 'backups', 'postgres');
120
- if (!fs.existsSync(stashDir)) return { status: 'ok', deletedCount: 0 };
121
- const files = fs.readdirSync(stashDir).map((f) => path.join(stashDir, f));
122
- for (const f of files) fs.rmSync(f, { force: true });
123
- return { status: 'ok', deletedCount: files.length };
124
- }
@@ -1,45 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * lib/storage/sql-store.mjs — lightweight shared SQL storage facade.
4
- */
5
- import { createSqlClient, probeSqlClient } from './backend.mjs';
6
- import { resolveDatabaseUrl } from '../env-config.mjs';
7
-
8
- export function hasSqlStore(env = process.env) {
9
- return Boolean(resolveDatabaseUrl(env));
10
- }
11
-
12
- export function detectStoreMode(env = process.env) {
13
- if (resolveDatabaseUrl(env)) return 'postgres';
14
- return 'file';
15
- }
16
-
17
- export function describeSqlStore(env = process.env) {
18
- const mode = detectStoreMode(env);
19
- return {
20
- mode,
21
- configured: mode !== 'file',
22
- sharedReady: mode === 'postgres',
23
- fallbackAvailable: mode === 'file',
24
- hasDatabaseUrl: Boolean(resolveDatabaseUrl(env)),
25
- };
26
- }
27
-
28
- export async function describeSqlStoreHealth(env = process.env) {
29
- const store = describeSqlStore(env);
30
- if (store.mode !== 'postgres') return sqlStoreHealth(env);
31
- const client = createSqlClient(env);
32
- try {
33
- return await probeSqlClient(client);
34
- } finally {
35
- if (client) await client.end({ timeout: 5 }).catch(() => {});
36
- }
37
- }
38
-
39
- export function sqlStoreHealth(env = process.env) {
40
- const store = describeSqlStore(env);
41
- if (store.mode === 'postgres') {
42
- return { status: 'configured', message: 'Shared Postgres store is configured' };
43
- }
44
- return { status: 'unavailable', message: 'No SQL store configured; using file-state only' };
45
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * lib/storage/store-version.mjs — versioned schema for the JSON stores.
3
- *
4
- * The observation, entity, and session stores write JSON arrays (or objects)
5
- * to disk. Until now, the on-disk format had no version stamp, which meant
6
- * any future schema change had to either fork the file or risk silently
7
- * breaking older data. This module provides a thin, opt-in versioning
8
- * layer:
9
- *
10
- * readVersioned(filePath, storeId)
11
- * Returns the on-disk records, lazily upgrading them through the
12
- * store's migration chain if the embedded version is older than the
13
- * current one. Existing unversioned files (plain arrays) are treated
14
- * as version 1 and stamped on the next write.
15
- *
16
- * writeVersioned(filePath, storeId, records)
17
- * Wraps the records in `{ schemaVersion, storeId, records }` and
18
- * writes atomically. Callers always read/write through this helper
19
- * so the on-disk format stays canonical.
20
- *
21
- * registerMigration(storeId, fromVersion, toVersion, migrate)
22
- * Record a one-step migration. The runtime walks migrations in
23
- * order until the records reach the current version.
24
- *
25
- * Migrations are pure functions over records; they cannot reach the network,
26
- * fork processes, or call other stores. That keeps lazy upgrade safe to run
27
- * inside a hot Read path.
28
- */
29
-
30
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
31
- import { dirname } from 'node:path';
32
-
33
- const CURRENT_VERSIONS = {
34
- observations: 1,
35
- observations_vectors: 1,
36
- observations_index: 1,
37
- entities: 1,
38
- entity_vectors: 1,
39
- sessions: 1,
40
- session_vectors: 1,
41
- };
42
-
43
- const MIGRATIONS = new Map();
44
-
45
- export function registerMigration(storeId, fromVersion, migrate) {
46
- const key = `${storeId}@${fromVersion}`;
47
- if (MIGRATIONS.has(key)) {
48
- throw new Error(`Migration already registered: ${key}`);
49
- }
50
- MIGRATIONS.set(key, migrate);
51
- }
52
-
53
- export function currentVersion(storeId) {
54
- return CURRENT_VERSIONS[storeId] ?? 1;
55
- }
56
-
57
- function unwrap(parsed) {
58
- if (parsed && typeof parsed === 'object' && Array.isArray(parsed.records)) {
59
- return {
60
- schemaVersion: Number.isInteger(parsed.schemaVersion) ? parsed.schemaVersion : 1,
61
- records: parsed.records,
62
- };
63
- }
64
- if (Array.isArray(parsed)) {
65
- return { schemaVersion: 1, records: parsed };
66
- }
67
- return { schemaVersion: 1, records: [] };
68
- }
69
-
70
- function migrateOnce(storeId, schemaVersion, records) {
71
- const migrate = MIGRATIONS.get(`${storeId}@${schemaVersion}`);
72
- if (!migrate) return null;
73
- const next = migrate(records);
74
- if (!Array.isArray(next)) {
75
- throw new Error(`Migration ${storeId}@${schemaVersion}→ must return an array of records`);
76
- }
77
- return next;
78
- }
79
-
80
- /**
81
- * Read a versioned JSON store. Lazily applies migrations to bring records up
82
- * to the current version. Returns plain records (caller doesn't see the
83
- * version envelope).
84
- */
85
- export function readVersioned(filePath, storeId, fallback = []) {
86
- if (!existsSync(filePath)) return fallback;
87
- let parsed;
88
- try { parsed = JSON.parse(readFileSync(filePath, 'utf8')); }
89
- catch { return fallback; }
90
-
91
- let { schemaVersion, records } = unwrap(parsed);
92
- const target = currentVersion(storeId);
93
-
94
- while (schemaVersion < target) {
95
- const next = migrateOnce(storeId, schemaVersion, records);
96
- if (next === null) break;
97
- records = next;
98
- schemaVersion += 1;
99
- }
100
-
101
- return records;
102
- }
103
-
104
- /**
105
- * Write a versioned JSON store. Always stamps the current version.
106
- */
107
- export function writeVersioned(filePath, storeId, records) {
108
- mkdirSync(dirname(filePath), { recursive: true });
109
- const payload = {
110
- schemaVersion: currentVersion(storeId),
111
- storeId,
112
- records: Array.isArray(records) ? records : [],
113
- };
114
- writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n');
115
- }
@@ -1,100 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * lib/storage/vector-store.mjs — Local JSON vector index facade.
4
- *
5
- * Stores vector records on disk for fallback retrieval when no SQL backend is
6
- * available. The model field is metadata supplied by the caller — this module
7
- * does not embed; it only persists what the engine produces.
8
- *
9
- * Search APIs accept a pre-computed query embedding so the embedding model is
10
- * the caller's choice and there is no implicit dependency on a specific model
11
- * inside this module.
12
- */
13
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
14
- import { dirname, resolve } from 'node:path';
15
- import { scoreByEmbedding, rankByBm25 } from './embeddings.mjs';
16
- import { embedSync } from './embeddings-legacy.mjs';
17
-
18
- export function vectorStoreMode(env = process.env) {
19
- if (env.CONSTRUCT_VECTOR_URL) return 'remote';
20
- if (env.CONSTRUCT_VECTOR_INDEX_PATH) return 'local';
21
- return 'file';
22
- }
23
-
24
- export function describeVectorStore(env = process.env) {
25
- const mode = vectorStoreMode(env);
26
- return {
27
- mode,
28
- configured: mode !== 'file',
29
- sharedReady: mode === 'remote',
30
- fallbackAvailable: true,
31
- endpoint: env.CONSTRUCT_VECTOR_URL || null,
32
- indexPath: env.CONSTRUCT_VECTOR_INDEX_PATH || null,
33
- model: env.CONSTRUCT_VECTOR_MODEL || null,
34
- };
35
- }
36
-
37
- export function readLocalVectorIndex(indexPath) {
38
- const resolvedPath = resolve(String(indexPath || ''));
39
- if (!resolvedPath || !existsSync(resolvedPath)) {
40
- return { version: 1, model: null, updatedAt: null, records: [] };
41
- }
42
-
43
- try {
44
- const parsed = JSON.parse(readFileSync(resolvedPath, 'utf8'));
45
- return {
46
- version: parsed.version ?? 1,
47
- model: parsed.model || null,
48
- updatedAt: parsed.updatedAt || null,
49
- records: Array.isArray(parsed.records) ? parsed.records : [],
50
- };
51
- } catch {
52
- return { version: 1, model: null, updatedAt: null, records: [] };
53
- }
54
- }
55
-
56
- export function writeLocalVectorIndex(indexPath, records = [], { model } = {}) {
57
- const resolvedPath = resolve(String(indexPath || ''));
58
- if (!resolvedPath) throw new Error('Missing local vector index path');
59
- if (!model) throw new Error('writeLocalVectorIndex requires an explicit model id (caller must supply)');
60
- mkdirSync(dirname(resolvedPath), { recursive: true });
61
- const payload = {
62
- version: 1,
63
- model,
64
- updatedAt: new Date().toISOString(),
65
- records,
66
- };
67
- writeFileSync(resolvedPath, `${JSON.stringify(payload, null, 2)}\n`);
68
- return payload;
69
- }
70
-
71
- /**
72
- * Search the local vector index. Accepts either a query string (which is
73
- * embedded via the legacy hashing adapter inline — fast, deterministic, no
74
- * engine init) or a pre-computed query embedding for engine-aligned callers.
75
- *
76
- * The hashing path matches what `addObservation` and `syncFileStateToSql`
77
- * write to disk when no SQL backend is configured, so dimensions agree.
78
- * Callers that store engine-dim vectors should pass an explicit Float32Array.
79
- */
80
- export function searchLocalVectorIndex(indexPath, query, { limit = 10 } = {}) {
81
- const index = readLocalVectorIndex(indexPath);
82
- const queryEmbedding = typeof query === 'string'
83
- ? embedSync(query)
84
- : (query instanceof Float32Array ? Array.from(query) : (query || []));
85
- return scoreByEmbedding(index.records, queryEmbedding, { limit });
86
- }
87
-
88
- export function vectorSearchLocal(records = [], query = '', { limit = 10 } = {}) {
89
- const bm25Docs = records.map((record) => ({
90
- ...record,
91
- text: [
92
- record.title,
93
- record.summary,
94
- record.body,
95
- record.text,
96
- Array.isArray(record.tags) ? record.tags.join(' ') : '',
97
- ].filter(Boolean).join('\n'),
98
- }));
99
- return rankByBm25(bm25Docs, query, { limit });
100
- }