@geraldmaron/construct 1.0.17 → 1.0.19

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 (88) hide show
  1. package/README.md +6 -4
  2. package/bin/construct +26 -3
  3. package/commands/design/flow.md +2 -0
  4. package/commands/design/ui.md +2 -0
  5. package/db/schema/003_observation_reconciliation.sql +14 -0
  6. package/lib/bootstrap/resources.mjs +0 -1
  7. package/lib/cli-commands.mjs +33 -5
  8. package/lib/comment-lint.mjs +44 -0
  9. package/lib/contracts/validate.mjs +106 -0
  10. package/lib/decisions/enforced-baseline.json +23 -0
  11. package/lib/decisions/golden.mjs +87 -0
  12. package/lib/decisions/precedence.mjs +46 -0
  13. package/lib/decisions/registry.mjs +469 -0
  14. package/lib/deployment/parity-contract.mjs +148 -0
  15. package/lib/embed/cli.mjs +11 -0
  16. package/lib/embed/conflict-detection.mjs +4 -4
  17. package/lib/embed/customer-profiles.mjs +1 -1
  18. package/lib/embed/reconcile.mjs +60 -0
  19. package/lib/embed/semantic.mjs +5 -3
  20. package/lib/gates-audit.mjs +2 -2
  21. package/lib/hooks/config-protection.mjs +22 -3
  22. package/lib/hooks/guard-bash.mjs +1 -1
  23. package/lib/init-docs.mjs +1 -0
  24. package/lib/mode-commands.mjs +6 -8
  25. package/lib/observation-store.mjs +16 -2
  26. package/lib/opencode-telemetry.mjs +1 -1
  27. package/lib/roles/cli.mjs +10 -2
  28. package/lib/roles/gateway.mjs +50 -1
  29. package/lib/scheduler/index.mjs +31 -0
  30. package/lib/server/index.mjs +13 -3
  31. package/lib/server/static/index.html +1 -1
  32. package/lib/setup.mjs +6 -0
  33. package/lib/storage/hybrid-query.mjs +49 -38
  34. package/lib/storage/rrf.mjs +42 -0
  35. package/lib/storage/vector-client.mjs +18 -3
  36. package/lib/telemetry/backends/local.mjs +1 -1
  37. package/lib/telemetry/skill-calls.mjs +1 -1
  38. package/lib/templates/visual-requirements.mjs +84 -0
  39. package/package.json +12 -5
  40. package/rules/common/comments.md +3 -0
  41. package/rules/common/no-fabrication.md +3 -0
  42. package/rules/common/precedence.md +19 -0
  43. package/rules/common/research-sources.md +32 -0
  44. package/rules/common/research.md +59 -2
  45. package/skills/roles/data-engineer.pipeline.md +13 -1
  46. package/skills/roles/debugger.md +9 -0
  47. package/skills/roles/designer.accessibility.md +13 -3
  48. package/skills/roles/designer.md +10 -0
  49. package/skills/roles/engineer.platform.md +8 -0
  50. package/skills/roles/operator.md +10 -1
  51. package/skills/roles/operator.release.md +8 -0
  52. package/skills/roles/operator.sre.md +10 -1
  53. package/skills/roles/orchestrator.md +9 -2
  54. package/skills/roles/product-manager.business-strategy.md +10 -1
  55. package/skills/roles/researcher.explorer.md +12 -1
  56. package/skills/roles/researcher.ux.md +13 -1
  57. package/skills/roles/reviewer.devil-advocate.md +14 -2
  58. package/skills/roles/reviewer.evaluator.md +17 -4
  59. package/skills/roles/reviewer.trace.md +12 -1
  60. package/skills/roles/security.legal-compliance.md +8 -0
  61. package/skills/roles/security.md +11 -0
  62. package/specialists/contracts.json +18 -0
  63. package/specialists/prompts/cx-architect.md +1 -0
  64. package/specialists/prompts/cx-designer.md +1 -1
  65. package/specialists/prompts/cx-operations.md +1 -0
  66. package/specialists/prompts/cx-rd-lead.md +1 -0
  67. package/specialists/prompts/cx-researcher.md +4 -2
  68. package/specialists/prompts/cx-sre.md +1 -0
  69. package/specialists/registry.json +2 -2
  70. package/templates/docs/backlog-proposal.md +1 -1
  71. package/templates/docs/customer-profile.md +1 -1
  72. package/templates/docs/evidence-brief.md +5 -1
  73. package/templates/docs/incident-report.md +37 -21
  74. package/templates/docs/prfaq.md +2 -2
  75. package/templates/docs/product-intelligence-report.md +1 -1
  76. package/templates/docs/research-brief.md +8 -6
  77. package/templates/docs/research-finding.md +32 -7
  78. package/templates/docs/rfc.md +13 -1
  79. package/templates/docs/runbook.md +20 -1
  80. package/templates/docs/signal-brief.md +4 -1
  81. package/templates/docs/skill-artifact.md +27 -7
  82. package/templates/docs/strategy.md +23 -2
  83. package/templates/docs/test-plan.md +96 -0
  84. package/lib/bootstrap/lazy-install.mjs +0 -161
  85. package/lib/embed/jobs/vector-sync.mjs +0 -198
  86. package/lib/knowledge/postgres-search.mjs +0 -132
  87. package/lib/services/pattern-promotion-service.mjs +0 -167
  88. package/lib/storage/unified-storage.mjs +0 -550
@@ -1,132 +0,0 @@
1
- /**
2
- * lib/knowledge/postgres-search.mjs — Tag-aware vector search via pgvector + GIN.
3
- *
4
- * Runs when DATABASE_URL is configured. Chooses between two execution paths
5
- * based on tag selectivity:
6
- *
7
- * - High selectivity (tag matches <5% of corpus): GIN prefilter first, then
8
- * HNSW ANN on the filtered set.
9
- * - Low selectivity (tag matches ≥5% of corpus): HNSW ANN first with
10
- * hnsw.iterative_scan=relaxed_order, postfilter by tag.
11
- *
12
- * Falls back gracefully when DATABASE_URL is absent or the pgvector extension
13
- * is not installed; callers should use knowledgeSearch() from search.mjs in
14
- * that case.
15
- */
16
-
17
- // Selectivity threshold: if the tagged fraction exceeds this, use postfilter.
18
- const HIGH_SELECTIVITY_THRESHOLD = 0.05;
19
-
20
- /**
21
- * Execute a tag-filtered vector search against Postgres + pgvector.
22
- *
23
- * @param {object} opts
24
- * @param {Float32Array|number[]} opts.queryEmbedding — query vector
25
- * @param {string} opts.project — project id (construct_documents.project)
26
- * @param {string[]} [opts.tags] — tag filter
27
- * @param {'any'|'all'} [opts.tagMatch] — 'any' (default) or 'all'
28
- * @param {number} [opts.topK] — result limit (default 20)
29
- * @param {object} opts.db — postgres client (from lib/db.mjs or postgres pkg)
30
- * @returns {Promise<Array<{id, title, score}>>}
31
- */
32
- export async function postgresTagSearch({ queryEmbedding, project, tags = [], tagMatch = 'any', topK = 20, db }) {
33
- if (!db) throw new Error('postgres-search: db client required');
34
- if (!queryEmbedding?.length) throw new Error('postgres-search: queryEmbedding required');
35
-
36
- const vecLiteral = `[${Array.from(queryEmbedding).join(',')}]`;
37
-
38
- if (!tags.length) {
39
- // No tag filter — plain ANN.
40
- const rows = await db`
41
- select d.id, d.title, e.embedding <=> ${vecLiteral}::vector as distance
42
- from construct_embeddings e
43
- join construct_documents d on d.id = e.document_id
44
- where d.project = ${project}
45
- order by e.embedding <=> ${vecLiteral}::vector
46
- limit ${topK}
47
- `;
48
- return rows.map((r) => ({ id: r.id, title: r.title, score: 1 - parseFloat(r.distance) }));
49
- }
50
-
51
- // Estimate selectivity for this tag set.
52
- const tagJsonb = JSON.stringify(tags);
53
- const [{ total }] = await db`select count(*) as total from construct_documents where project = ${project}`;
54
- const totalCount = parseInt(total, 10) || 1;
55
-
56
- let taggedCount;
57
- if (tagMatch === 'all') {
58
- const [{ cnt }] = await db`
59
- select count(*) as cnt from construct_documents
60
- where project = ${project} and tags @> ${tagJsonb}::jsonb
61
- `;
62
- taggedCount = parseInt(cnt, 10);
63
- } else {
64
- // 'any' — count docs with at least one matching tag.
65
- const [{ cnt }] = await db`
66
- select count(*) as cnt from construct_documents
67
- where project = ${project}
68
- and (${db.unsafe(tags.map((_, i) => `tags ? $${i + 2}`).join(' or '))})
69
- `;
70
- taggedCount = parseInt(cnt, 10);
71
- }
72
-
73
- const selectivity = taggedCount / totalCount;
74
-
75
- if (selectivity < HIGH_SELECTIVITY_THRESHOLD) {
76
- // High selectivity: GIN prefilter → ANN on filtered set.
77
- if (tagMatch === 'all') {
78
- const rows = await db`
79
- with filtered as (
80
- select id from construct_documents
81
- where project = ${project} and tags @> ${tagJsonb}::jsonb
82
- )
83
- select d.id, d.title, e.embedding <=> ${vecLiteral}::vector as distance
84
- from construct_embeddings e
85
- join filtered f on f.id = e.document_id
86
- join construct_documents d on d.id = e.document_id
87
- order by e.embedding <=> ${vecLiteral}::vector
88
- limit ${topK}
89
- `;
90
- return rows.map((r) => ({ id: r.id, title: r.title, score: 1 - parseFloat(r.distance) }));
91
- }
92
- // 'any' — OR-expand tag list.
93
- const tagConditions = tags.map((t) => `tags ? '${t.replace(/'/g, "''")}'`).join(' or ');
94
- const rows = await db.unsafe(`
95
- with filtered as (
96
- select id from construct_documents
97
- where project = $1 and (${tagConditions})
98
- )
99
- select d.id, d.title, e.embedding <=> $2::vector as distance
100
- from construct_embeddings e
101
- join filtered f on f.id = e.document_id
102
- join construct_documents d on d.id = e.document_id
103
- order by e.embedding <=> $2::vector
104
- limit $3
105
- `, [project, vecLiteral, topK]);
106
- return rows.map((r) => ({ id: r.id, title: r.title, score: 1 - parseFloat(r.distance) }));
107
- }
108
-
109
- // Low selectivity: HNSW iterative scan → postfilter.
110
- await db`set hnsw.iterative_scan = relaxed_order`;
111
- if (tagMatch === 'all') {
112
- const rows = await db`
113
- select d.id, d.title, e.embedding <=> ${vecLiteral}::vector as distance
114
- from construct_embeddings e
115
- join construct_documents d on d.id = e.document_id
116
- where d.project = ${project} and d.tags @> ${tagJsonb}::jsonb
117
- order by e.embedding <=> ${vecLiteral}::vector
118
- limit ${topK}
119
- `;
120
- return rows.map((r) => ({ id: r.id, title: r.title, score: 1 - parseFloat(r.distance) }));
121
- }
122
- const tagConditions = tags.map((t) => `d.tags ? '${t.replace(/'/g, "''")}'`).join(' or ');
123
- const rows = await db.unsafe(`
124
- select d.id, d.title, e.embedding <=> $1::vector as distance
125
- from construct_embeddings e
126
- join construct_documents d on d.id = e.document_id
127
- where d.project = $2 and (${tagConditions})
128
- order by e.embedding <=> $1::vector
129
- limit $3
130
- `, [vecLiteral, project, topK]);
131
- return rows.map((r) => ({ id: r.id, title: r.title, score: 1 - parseFloat(r.distance) }));
132
- }
@@ -1,167 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * lib/services/pattern-promotion-service.mjs — Bounded pattern replication engine.
4
- *
5
- * Analyzes observations, scores candidate patterns, promotes high-quality ones to permanent
6
- * learned patterns in role skill files. Prevents unbounded growth with hard limits.
7
- *
8
- * Limits:
9
- * - Max 15 learned patterns per role
10
- * - Min confidence 0.85, usage 3, score 0.8
11
- * - Semantic + exact deduplication
12
- * - Pruning of low-effectiveness patterns
13
- */
14
-
15
- import fs from 'node:fs';
16
- import path from 'node:path';
17
-
18
- const ROOT_DIR = process.cwd();
19
- const SKILLS_DIR = path.join(ROOT_DIR, 'skills', 'roles');
20
- const OBS_DIR = path.join(process.cwd(), '.cx', 'observations', 'agent-outcomes');
21
-
22
- const MAX_PATTERNS = 15;
23
- const MIN_CONFIDENCE = 0.85;
24
- const MIN_USAGE = 3;
25
- const MIN_SCORE = 0.8;
26
- const MAX_TOKENS_FILE = 2500; // Approx tokens
27
-
28
- const LEARNED_SECTION_MARKER = '## Learned Patterns';
29
-
30
- function scorePattern(obs) {
31
- const confidenceWeight = 0.3;
32
- const usageWeight = 0.2;
33
- const successWeight = 0.4;
34
- const crossProjectWeight = 0.1;
35
-
36
- const normalizedUsage = Math.min((obs.usage_count || 0) / 10, 1.0);
37
- const crossProject = (obs.projects && obs.projects.length >= 2) ? 1.0 : 0.5;
38
- const successRate = obs.success_rate || 0.5;
39
-
40
- return (
41
- (obs.confidence || 0) * confidenceWeight +
42
- normalizedUsage * usageWeight +
43
- successRate * successWeight +
44
- crossProject * crossProjectWeight
45
- );
46
- }
47
-
48
- function normalizeSummary(summary) {
49
- return summary.toLowerCase().replace(/[^\w\s]/g, '').trim();
50
- }
51
-
52
- function isDuplicate(newObs, existingPatterns) {
53
- const newNorm = normalizeSummary(newObs.summary);
54
- for (const pat of existingPatterns) {
55
- const patNorm = normalizeSummary(pat.summary);
56
- if (newNorm.includes(patNorm.slice(0, Math.min(50, patNorm.length))) ||
57
- patNorm.includes(newNorm.slice(0, Math.min(50, newNorm.length)))) {
58
- return true;
59
- }
60
- }
61
- return false;
62
- }
63
-
64
- function parseLearnedPatterns(content) {
65
- const match = content.match(new RegExp(`${LEARNED_SECTION_MARKER}[\\s\\S]*?(?=## |$)`));
66
- if (!match) return [];
67
-
68
- const section = match[0];
69
- return section.split('\n\n').slice(1).filter(Boolean).map(block => {
70
- const lines = block.split('\n');
71
- return {
72
- summary: lines[0].replace(/^###\s*L\d+\.\s*/, ''),
73
- content: block
74
- };
75
- });
76
- }
77
-
78
- function generatePatternEntry(obs, index) {
79
- return `### L${index}. ${obs.summary}
80
- **Context**: ${obs.context || 'General'}
81
- **Effective Action**: ${obs.content.slice(0, 120)}...
82
- **Evidence**: Score ${(obs.score || 0).toFixed(2)}, used ${(obs.usage_count || 0)} times, ${(obs.projects || []).length} projects
83
- *Last reinforced: ${new Date().toISOString().split('T')[0]}*
84
-
85
- `;
86
- }
87
-
88
- function updateSkillFile(roleName, candidate) {
89
- const skillFile = path.join(SKILLS_DIR, `${roleName}.md`);
90
- if (!fs.existsSync(skillFile)) {
91
- console.warn(`Skill file not found: ${skillFile}`);
92
- return false;
93
- }
94
-
95
- let content = fs.readFileSync(skillFile, 'utf8');
96
-
97
- // Check token limit (rough char/4)
98
- if (content.length > MAX_TOKENS_FILE * 4) {
99
- console.warn(`Skill file too large: ${skillFile}`);
100
- return false;
101
- }
102
-
103
- const existingPatterns = parseLearnedPatterns(content);
104
- if (existingPatterns.length >= MAX_PATTERNS || isDuplicate(candidate, existingPatterns)) {
105
- console.log(`Skipped ${candidate.summary} (dupe or limit reached)`);
106
- return false;
107
- }
108
-
109
- const entry = generatePatternEntry(candidate, existingPatterns.length + 1);
110
- let newContent;
111
-
112
- const sectionExists = content.includes(LEARNED_SECTION_MARKER);
113
- if (sectionExists) {
114
- const markerIndex = content.indexOf(LEARNED_SECTION_MARKER);
115
- const afterMarker = content.slice(markerIndex);
116
- const endMatch = afterMarker.match(/\n\n## /) || afterMarker.match(/$/);
117
- const insertPos = markerIndex + afterMarker.indexOf(endMatch[0]);
118
- newContent = content.slice(0, insertPos) + '\n\n' + entry + content.slice(insertPos);
119
- } else {
120
- newContent = content + '\n\n' + LEARNED_SECTION_MARKER + '\n\n' + entry;
121
- }
122
-
123
- fs.writeFileSync(skillFile, newContent);
124
- console.log(`Added pattern to ${roleName}.md: ${candidate.summary}`);
125
- return true;
126
- }
127
-
128
- function getCandidates() {
129
- if (!fs.existsSync(OBS_DIR)) return [];
130
-
131
- const files = fs.readdirSync(OBS_DIR).filter(f => f.endsWith('.json'));
132
- const candidates = [];
133
-
134
- for (const file of files) {
135
- try {
136
- const obs = JSON.parse(fs.readFileSync(path.join(OBS_DIR, file), 'utf8'));
137
- if (obs.category === 'pattern' &&
138
- (obs.confidence || 0) >= MIN_CONFIDENCE &&
139
- (obs.usage_count || 0) >= MIN_USAGE) {
140
- obs.score = scorePattern(obs);
141
- if (obs.score >= MIN_SCORE) {
142
- candidates.push(obs);
143
- }
144
- }
145
- } catch (e) {
146
- // Skip invalid
147
- }
148
- }
149
-
150
- return candidates.sort((a, b) => b.score - a.score).slice(0, 5); // Top 5
151
- }
152
-
153
- export function promotePatterns() {
154
- const candidates = getCandidates();
155
- let promoted = 0;
156
-
157
- for (const candidate of candidates) {
158
- const roleName = candidate.role.replace(/^cx-/, '') || 'engineer'; // Fallback
159
- if (updateSkillFile(roleName, candidate)) promoted++;
160
- }
161
-
162
- console.log(`Pattern promotion complete: ${promoted}/${candidates.length} promoted`);
163
- }
164
-
165
- if (import.meta.url === `file://${process.argv[1]}`) {
166
- promotePatterns();
167
- }