@geraldmaron/construct 1.0.5 → 1.0.7

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 (268) hide show
  1. package/README.md +24 -18
  2. package/agents/contracts.json +617 -2
  3. package/agents/contracts.schema.json +83 -0
  4. package/agents/prompts/cx-accessibility.md +5 -3
  5. package/agents/prompts/cx-ai-engineer.md +9 -7
  6. package/agents/prompts/cx-architect.md +8 -6
  7. package/agents/prompts/cx-business-strategist.md +8 -6
  8. package/agents/prompts/cx-data-analyst.md +9 -7
  9. package/agents/prompts/cx-data-engineer.md +5 -3
  10. package/agents/prompts/cx-debugger.md +8 -6
  11. package/agents/prompts/cx-designer.md +7 -5
  12. package/agents/prompts/cx-devil-advocate.md +6 -4
  13. package/agents/prompts/cx-docs-keeper.md +7 -5
  14. package/agents/prompts/cx-engineer.md +7 -5
  15. package/agents/prompts/cx-evaluator.md +4 -2
  16. package/agents/prompts/cx-explorer.md +10 -8
  17. package/agents/prompts/cx-legal-compliance.md +4 -2
  18. package/agents/prompts/cx-operations.md +7 -5
  19. package/agents/prompts/cx-orchestrator.md +12 -10
  20. package/agents/prompts/cx-platform-engineer.md +7 -5
  21. package/agents/prompts/cx-product-manager.md +6 -4
  22. package/agents/prompts/cx-qa.md +10 -8
  23. package/agents/prompts/cx-rd-lead.md +11 -9
  24. package/agents/prompts/cx-release-manager.md +7 -5
  25. package/agents/prompts/cx-researcher.md +24 -22
  26. package/agents/prompts/cx-reviewer.md +9 -7
  27. package/agents/prompts/cx-security.md +12 -10
  28. package/agents/prompts/cx-sre.md +9 -7
  29. package/agents/prompts/cx-test-automation.md +5 -3
  30. package/agents/prompts/cx-trace-reviewer.md +10 -8
  31. package/agents/prompts/cx-ux-researcher.md +5 -3
  32. package/agents/registry.json +8 -3
  33. package/bin/construct +444 -53
  34. package/commands/build/feature.md +4 -4
  35. package/commands/build/fix.md +8 -8
  36. package/commands/design/access.md +3 -3
  37. package/commands/design/flow.md +3 -3
  38. package/commands/design/ui.md +4 -4
  39. package/commands/measure/experiment.md +5 -5
  40. package/commands/measure/metrics.md +3 -3
  41. package/commands/measure/results.md +4 -4
  42. package/commands/plan/api.md +3 -3
  43. package/commands/plan/challenge.md +3 -3
  44. package/commands/plan/decide.md +3 -3
  45. package/commands/plan/feature.md +7 -7
  46. package/commands/plan/requirements.md +3 -3
  47. package/commands/remember/context.md +5 -5
  48. package/commands/remember/handoff.md +3 -3
  49. package/commands/remember/runbook.md +3 -3
  50. package/commands/review/code.md +8 -8
  51. package/commands/review/quality.md +4 -4
  52. package/commands/review/security.md +3 -3
  53. package/commands/ship/ready.md +3 -3
  54. package/commands/ship/release.md +3 -3
  55. package/commands/ship/status.md +4 -4
  56. package/commands/understand/docs.md +3 -3
  57. package/commands/understand/this.md +4 -4
  58. package/commands/understand/why.md +8 -8
  59. package/commands/work/clean.md +14 -14
  60. package/commands/work/drive.md +10 -10
  61. package/commands/work/optimize-prompts.md +9 -9
  62. package/commands/work/parallel-review.md +8 -8
  63. package/db/schema/006_graph.sql +24 -0
  64. package/examples/provider-plugin/README.md +7 -7
  65. package/examples/seed-observations/README.md +6 -6
  66. package/examples/seed-observations/anti-patterns.md +14 -14
  67. package/examples/seed-observations/decisions.md +4 -4
  68. package/examples/seed-observations/patterns.md +14 -14
  69. package/lib/auto-docs.mjs +13 -8
  70. package/lib/boundary.mjs +126 -0
  71. package/lib/cache-strategy-google.js +26 -31
  72. package/lib/cli-commands.mjs +2 -2
  73. package/lib/comment-lint.mjs +134 -0
  74. package/lib/contracts/validate.mjs +323 -0
  75. package/lib/daemons/contract.mjs +210 -0
  76. package/lib/docs-verify.mjs +59 -6
  77. package/lib/doctor/cli.mjs +16 -1
  78. package/lib/doctor/index.mjs +3 -1
  79. package/lib/doctor/watchers/consistency.mjs +310 -0
  80. package/lib/doctor/watchers/mcp-protocol.mjs +232 -0
  81. package/lib/document-extract.mjs +211 -1
  82. package/lib/embed/cli.mjs +124 -3
  83. package/lib/embed/daemon.mjs +43 -4
  84. package/lib/embed/docs-lifecycle.mjs +1 -1
  85. package/lib/embed/inbox.mjs +2 -0
  86. package/lib/embed/scheduler.mjs +33 -5
  87. package/lib/evaluator-optimizer.mjs +2 -3
  88. package/lib/flavors/loader.mjs +1 -1
  89. package/lib/hooks/comment-lint.mjs +16 -0
  90. package/lib/hooks/mcp-audit.mjs +2 -1
  91. package/lib/hooks/proactive-activation.mjs +0 -14
  92. package/lib/hooks/rule-verifier.mjs +217 -0
  93. package/lib/hooks/session-optimize.mjs +2 -1
  94. package/lib/init-unified.mjs +55 -65
  95. package/lib/intake/classify.mjs +108 -24
  96. package/lib/intake/daemon.mjs +121 -0
  97. package/lib/intake/filesystem-queue.mjs +6 -1
  98. package/lib/intake/intake-config.mjs +2 -1
  99. package/lib/intake/prepare.mjs +0 -1
  100. package/lib/intake/session-prelude.mjs +7 -1
  101. package/lib/intake/traceability.mjs +90 -0
  102. package/lib/knowledge/graph.mjs +213 -0
  103. package/lib/knowledge/research-store.mjs +2 -0
  104. package/lib/maintenance/cleanup.mjs +315 -0
  105. package/lib/mcp/memory-bridge.mjs +276 -0
  106. package/lib/mcp/server.mjs +189 -1
  107. package/lib/mcp/tools/profile.mjs +270 -0
  108. package/lib/mcp/tools/workflow.mjs +25 -0
  109. package/lib/mcp-catalog.json +12 -8
  110. package/lib/mcp-platform-config.mjs +16 -8
  111. package/lib/migrations/index.mjs +106 -0
  112. package/lib/migrations/v1-baseline.mjs +33 -0
  113. package/lib/observation-store.mjs +9 -4
  114. package/lib/outcomes/record.mjs +2 -0
  115. package/lib/profiles/rebrand.mjs +46 -0
  116. package/lib/project-init-shared.mjs +12 -0
  117. package/lib/provider-capabilities.js +20 -7
  118. package/lib/providers/auth-manager.mjs +58 -17
  119. package/lib/reflect.mjs +49 -12
  120. package/lib/server/index.mjs +22 -28
  121. package/lib/session-store.mjs +6 -4
  122. package/lib/setup.mjs +14 -3
  123. package/lib/telemetry/client.mjs +5 -1
  124. package/lib/version.mjs +51 -0
  125. package/lib/worker/trace.mjs +5 -1
  126. package/package.json +4 -1
  127. package/personas/construct.md +3 -1
  128. package/platforms/claude/CLAUDE.md +6 -6
  129. package/rules/common/agents.md +2 -2
  130. package/rules/common/beads-hygiene.md +11 -11
  131. package/rules/common/code-review.md +1 -1
  132. package/rules/common/coding-style.md +1 -1
  133. package/rules/common/comments.md +8 -8
  134. package/rules/common/commit-approval.md +4 -4
  135. package/rules/common/cx-agent-routing.md +2 -2
  136. package/rules/common/cx-skill-routing.md +2 -2
  137. package/rules/common/development-workflow.md +3 -2
  138. package/rules/common/doc-ownership.md +2 -2
  139. package/rules/common/efficiency.md +3 -3
  140. package/rules/common/framing.md +1 -1
  141. package/rules/common/git-workflow.md +1 -1
  142. package/rules/common/no-fabrication.md +69 -0
  143. package/rules/common/patterns.md +1 -1
  144. package/rules/common/performance.md +1 -1
  145. package/rules/common/release-gates.md +7 -7
  146. package/rules/common/research.md +4 -4
  147. package/rules/common/review-before-change.md +58 -0
  148. package/rules/common/security.md +1 -1
  149. package/rules/common/skill-composition.md +8 -8
  150. package/rules/common/testing.md +1 -1
  151. package/rules/golang/coding-style.md +2 -2
  152. package/rules/golang/hooks.md +1 -1
  153. package/rules/golang/patterns.md +1 -1
  154. package/rules/golang/security.md +1 -1
  155. package/rules/golang/testing.md +1 -1
  156. package/rules/python/coding-style.md +1 -1
  157. package/rules/python/hooks.md +1 -1
  158. package/rules/python/patterns.md +1 -1
  159. package/rules/python/security.md +1 -1
  160. package/rules/python/testing.md +1 -1
  161. package/rules/swift/coding-style.md +3 -3
  162. package/rules/swift/hooks.md +2 -2
  163. package/rules/swift/patterns.md +2 -2
  164. package/rules/swift/security.md +4 -4
  165. package/rules/swift/testing.md +2 -2
  166. package/rules/typescript/coding-style.md +1 -1
  167. package/rules/typescript/hooks.md +1 -1
  168. package/rules/typescript/patterns.md +1 -1
  169. package/rules/typescript/security.md +1 -1
  170. package/rules/typescript/testing.md +1 -1
  171. package/rules/web/coding-style.md +1 -1
  172. package/rules/web/design-quality.md +1 -1
  173. package/rules/web/hooks.md +1 -1
  174. package/rules/web/patterns.md +1 -1
  175. package/rules/web/performance.md +1 -1
  176. package/rules/web/security.md +1 -1
  177. package/rules/web/testing.md +1 -1
  178. package/scripts/sync-agents.mjs +45 -14
  179. package/skills/ai/agent-dev.md +1 -1
  180. package/skills/ai/llm-security.md +1 -1
  181. package/skills/ai/ml-ops.md +6 -6
  182. package/skills/ai/orchestration-workflow.md +1 -1
  183. package/skills/ai/prompt-and-eval.md +1 -1
  184. package/skills/ai/prompt-optimizer.md +13 -13
  185. package/skills/ai/rag-system.md +1 -1
  186. package/skills/architecture/api-design.md +1 -1
  187. package/skills/architecture/caching.md +1 -1
  188. package/skills/architecture/cloud-native.md +1 -1
  189. package/skills/architecture/message-queue.md +1 -1
  190. package/skills/architecture/security-arch.md +1 -1
  191. package/skills/compliance/ai-disclosure.md +1 -1
  192. package/skills/compliance/data-privacy.md +1 -1
  193. package/skills/compliance/license-audit.md +2 -2
  194. package/skills/compliance/regulatory-review.md +1 -1
  195. package/skills/development/cpp.md +1 -1
  196. package/skills/development/go.md +1 -1
  197. package/skills/development/java.md +1 -1
  198. package/skills/development/kotlin.md +9 -9
  199. package/skills/development/mobile-crossplatform.md +13 -13
  200. package/skills/development/python.md +1 -1
  201. package/skills/development/rust.md +1 -1
  202. package/skills/development/shell.md +1 -1
  203. package/skills/development/swift.md +6 -6
  204. package/skills/development/typescript.md +1 -1
  205. package/skills/devops/ci-cd.md +5 -5
  206. package/skills/devops/containerization.md +9 -9
  207. package/skills/devops/cost-optimization.md +1 -1
  208. package/skills/devops/data-engineering.md +2 -2
  209. package/skills/devops/database.md +1 -1
  210. package/skills/devops/dependency-management.md +3 -3
  211. package/skills/devops/devsecops.md +1 -1
  212. package/skills/devops/git-workflow.md +1 -1
  213. package/skills/devops/incident-response.md +18 -18
  214. package/skills/devops/monorepo.md +5 -5
  215. package/skills/devops/observability.md +1 -1
  216. package/skills/devops/performance.md +1 -1
  217. package/skills/devops/testing.md +1 -1
  218. package/skills/docs/adr-workflow.md +2 -2
  219. package/skills/docs/backlog-proposal-workflow.md +1 -1
  220. package/skills/docs/customer-profile-workflow.md +1 -1
  221. package/skills/docs/document-ingest-workflow.md +1 -1
  222. package/skills/docs/evidence-ingest-workflow.md +1 -1
  223. package/skills/docs/init-docs.md +15 -15
  224. package/skills/docs/init-project.md +1 -1
  225. package/skills/docs/prd-workflow.md +3 -3
  226. package/skills/docs/prfaq-workflow.md +1 -1
  227. package/skills/docs/product-intelligence-review.md +1 -1
  228. package/skills/docs/product-intelligence-workflow.md +1 -1
  229. package/skills/docs/product-signal-workflow.md +9 -9
  230. package/skills/docs/research-workflow.md +10 -10
  231. package/skills/docs/runbook-workflow.md +2 -2
  232. package/skills/docs/strategy-workflow.md +3 -3
  233. package/skills/exploration/repo-map.md +11 -11
  234. package/skills/frameworks/django.md +15 -15
  235. package/skills/frameworks/nextjs.md +16 -16
  236. package/skills/frameworks/react.md +12 -12
  237. package/skills/frameworks/spring-boot.md +12 -12
  238. package/skills/frontend-design/accessibility.md +6 -6
  239. package/skills/frontend-design/component-patterns.md +1 -1
  240. package/skills/frontend-design/engineering.md +1 -1
  241. package/skills/frontend-design/state-management.md +1 -1
  242. package/skills/frontend-design/ui-aesthetics.md +1 -1
  243. package/skills/frontend-design/ux-principles.md +1 -1
  244. package/skills/operating/orchestration-reference.md +27 -27
  245. package/skills/quality-gates/review-work.md +3 -3
  246. package/skills/quality-gates/verify-change.md +1 -1
  247. package/skills/quality-gates/verify-module.md +1 -1
  248. package/skills/quality-gates/verify-quality.md +1 -1
  249. package/skills/quality-gates/verify-security.md +1 -1
  250. package/skills/routing.md +14 -14
  251. package/skills/security/blue-team.md +1 -1
  252. package/skills/security/code-audit.md +1 -1
  253. package/skills/security/pentest.md +1 -1
  254. package/skills/security/red-team.md +1 -1
  255. package/skills/security/threat-intel.md +1 -1
  256. package/skills/security/vuln-research.md +1 -1
  257. package/skills/utility/clean-code.md +2 -2
  258. package/templates/docs/changelog-entry.md +1 -1
  259. package/templates/docs/construct_guide.md +18 -18
  260. package/templates/docs/meta-prd.md +16 -16
  261. package/templates/docs/one-pager.md +1 -1
  262. package/templates/docs/prd-business.md +1 -1
  263. package/templates/docs/prd-platform.md +1 -1
  264. package/templates/docs/prd.md +17 -17
  265. package/templates/docs/research-brief.md +8 -8
  266. package/templates/docs/rfc.md +1 -1
  267. package/templates/docs/skill-artifact.md +1 -1
  268. package/templates/docs/strategy.md +1 -1
@@ -29,10 +29,29 @@ const MD_HEADER_GLOBS = [
29
29
  /^commands\//,
30
30
  ];
31
31
 
32
+ // Artifact paths receive an additional prose-lint pass for fabrication patterns
33
+ // (manufactured confidence, hand-wave percentages, mind-reading, speculation).
34
+ // Scope is deliberately narrow — READMEs, cookbook, concepts, and reference are
35
+ // unaffected. The patterns live in BANNED_ARTIFACT below; the severity (block
36
+ // vs warn) is controlled by CONSTRUCT_ARTIFACT_LINT_MODE.
37
+ const ARTIFACT_PATH_GLOBS = [
38
+ /^docs\/prd\//,
39
+ /^docs\/adr\//,
40
+ /^docs\/rfc\//,
41
+ /^docs\/research\//,
42
+ /^\.cx\/knowledge\//,
43
+ /^\.cx\/handoffs\//,
44
+ /^\.cx\/research\//,
45
+ ];
46
+
32
47
  function relPath(rootDir, absPath) {
33
48
  return path.relative(rootDir, absPath).replace(/\\/g, '/');
34
49
  }
35
50
 
51
+ function isArtifactPath(rel) {
52
+ return ARTIFACT_PATH_GLOBS.some((r) => r.test(rel));
53
+ }
54
+
36
55
  function requiresHeader(rel) {
37
56
  const ext = path.extname(rel);
38
57
  if (['.yaml', '.yml', '.json', '.jsonl', '.toml'].includes(ext)) return { required: false, type: null };
@@ -88,6 +107,13 @@ const BANNED = [
88
107
  // step markers — only flag in `//` comments. Ordered lists are
89
108
  // conventional inside JSDoc decision-tree and flow documentation.
90
109
  { pattern: /\/\/\s+\d+\.\s+\w/, label: 'step marker: use function names or block structure instead of "// 1. Step"' },
110
+ // deferred-implementation wording: signals incomplete work that should
111
+ // either ship or be removed before release.
112
+ { pattern: new RegExp(`${CMT}.*\\bphase\\s+[abc]\\s+follow-?up\\b`, 'i'), label: 'deferred implementation: "Phase X follow-up" — ship it or remove it' },
113
+ { pattern: new RegExp(`${CMT}.*\\bin a real implementation\\b`, 'i'), label: 'deferred implementation: "in a real implementation" — implement the contract honestly' },
114
+ { pattern: new RegExp(`${CMT}.*\\bwould go here\\b`, 'i'), label: 'deferred implementation: "would go here" — implement or delete the placeholder' },
115
+ { pattern: new RegExp(`${CMT}.*\\bcoming soon\\b`, 'i'), label: 'deferred implementation: "coming soon" — not a release-ready statement' },
116
+ { pattern: new RegExp(`${CMT}.*\\bnot yet supported\\b`, 'i'), label: 'deferred implementation: "not yet supported" — document the supported contract instead' },
91
117
  // markdown equivalents
92
118
  { pattern: /<!--.*\b(?:added for|added recently|just added|new:)\b.*-->/i, label: 'point-in-time in markdown comment' },
93
119
  { pattern: /<!--.*\b(?:used by|called from|only consumer)\b.*-->/i, label: 'caller reference in markdown comment' },
@@ -102,16 +128,111 @@ const BANNED = [
102
128
  const BANNED_CHECK_SKIP = [
103
129
  'lib/comment-lint.mjs',
104
130
  'rules/common/comments.md',
131
+ 'rules/common/no-fabrication.md',
105
132
  'tests/comment-lint.test.mjs',
106
133
  'commands/work/clean.md',
107
134
  'skills/utility/clean-code.md',
108
135
  ];
109
136
 
137
+ // Artifact-prose patterns. Scoped to ARTIFACT_PATH_GLOBS. Each entry can mark
138
+ // requireCitation: true — in that case the violation is suppressed when a
139
+ // citation (`[source: …]`, http URL, or footnote ref) appears in the same line
140
+ // or within 2 lines of context.
141
+ const BANNED_ARTIFACT = [
142
+ {
143
+ pattern: /\b(?:clearly|obviously|undoubtedly|definitely|certainly|surely)\b/i,
144
+ label: 'manufactured confidence: "clearly/obviously/undoubtedly/etc" smuggles certainty without evidence (no-fabrication §4)',
145
+ },
146
+ {
147
+ pattern: /\b\d{1,3}\s*%/,
148
+ label: 'unattributed percentage: quantitative claims require a [source: …] citation (no-fabrication §4)',
149
+ requireCitation: true,
150
+ },
151
+ {
152
+ pattern: /\b(?:users|customers|everyone)\s+(?:want|expect|prefer|agree|need)\b/i,
153
+ label: 'customer mind-reading: "users want / customers expect / everyone agrees" requires a [source: …] citation (no-fabrication §5)',
154
+ requireCitation: true,
155
+ },
156
+ {
157
+ pattern: /\b(?:will\s+(?:likely|probably)|should\s+improve|expected\s+to\s+(?:improve|reduce|increase|drop|rise))\b/i,
158
+ label: 'speculative projection: future-tense claims need a baseline + projection source (no-fabrication §3, §4)',
159
+ requireCitation: true,
160
+ },
161
+ ];
162
+
110
163
  function isBannedCheckSkipped(filePath) {
111
164
  if (!filePath) return false;
112
165
  return BANNED_CHECK_SKIP.some((suffix) => filePath.endsWith(suffix));
113
166
  }
114
167
 
168
+ // Track fenced code blocks ( ``` … ``` ) and YAML frontmatter ( --- … --- )
169
+ // so artifact-prose patterns inside code or metadata are not flagged.
170
+ function buildSkipMap(lines) {
171
+ const skip = new Array(lines.length).fill(false);
172
+ let inFence = false;
173
+ let inFrontmatter = false;
174
+ let frontmatterClosed = false;
175
+ for (let i = 0; i < lines.length; i++) {
176
+ const line = lines[i];
177
+ if (i === 0 && line.trim() === '---') {
178
+ inFrontmatter = true;
179
+ skip[i] = true;
180
+ continue;
181
+ }
182
+ if (inFrontmatter) {
183
+ skip[i] = true;
184
+ if (line.trim() === '---') {
185
+ inFrontmatter = false;
186
+ frontmatterClosed = true;
187
+ }
188
+ continue;
189
+ }
190
+ if (/^```/.test(line)) {
191
+ inFence = !inFence;
192
+ skip[i] = true;
193
+ continue;
194
+ }
195
+ if (inFence) {
196
+ skip[i] = true;
197
+ continue;
198
+ }
199
+ if (/^\s{0,3}#{1,6}\s/.test(line)) skip[i] = true;
200
+ // Markdown table rows (start and end with `|`) are typically targets,
201
+ // specs, or reference lookups, not narrative prose. Skip to keep the
202
+ // pattern bank focused on the prose surface where embellishment lives.
203
+ if (/^\s*\|.*\|\s*$/.test(line)) skip[i] = true;
204
+ }
205
+ void frontmatterClosed;
206
+ return skip;
207
+ }
208
+
209
+ function hasCitationNearby(lines, idx) {
210
+ const lo = Math.max(0, idx - 2);
211
+ const hi = Math.min(lines.length, idx + 3);
212
+ for (let i = lo; i < hi; i++) {
213
+ if (/\[source:|\bhttps?:\/\/|\[\^\d+\]/i.test(lines[i])) return true;
214
+ }
215
+ return false;
216
+ }
217
+
218
+ function checkArtifactBanned(content, rel) {
219
+ if (!isArtifactPath(rel)) return [];
220
+ const lines = content.split('\n');
221
+ const skip = buildSkipMap(lines);
222
+ const violations = [];
223
+ for (let i = 0; i < lines.length; i++) {
224
+ if (skip[i]) continue;
225
+ if (lines[i].includes('construct-lint-ignore')) continue;
226
+ for (const entry of BANNED_ARTIFACT) {
227
+ if (entry.pattern.test(lines[i])) {
228
+ if (entry.requireCitation && hasCitationNearby(lines, i)) continue;
229
+ violations.push({ line: i + 1, label: entry.label, kind: 'artifact' });
230
+ }
231
+ }
232
+ }
233
+ return violations;
234
+ }
235
+
115
236
  function checkBanned(content, filePath) {
116
237
  if (isBannedCheckSkipped(filePath)) return [];
117
238
 
@@ -180,6 +301,19 @@ export function lintFile(filePath, { rootDir = process.cwd(), fix = false } = {}
180
301
  const banned = checkBanned(content, filePath);
181
302
  for (const w of banned) warnings.push(w);
182
303
 
304
+ // Artifact-prose lint applies to markdown files under intake-fed artifact
305
+ // paths (PRD, ADR, RFC, research, knowledge, handoffs). Severity is governed
306
+ // by CONSTRUCT_ARTIFACT_LINT_MODE: 'block' (CLI / release-gate) routes hits
307
+ // to errors[]; 'warn' (PostToolUse hook default) routes to warnings[] with
308
+ // kind:'artifact' so the hook can let the edit through while still surfacing
309
+ // the finding.
310
+ const artifactHits = checkArtifactBanned(content, rel);
311
+ if (artifactHits.length > 0) {
312
+ const mode = process.env.CONSTRUCT_ARTIFACT_LINT_MODE || 'warn';
313
+ const bucket = mode === 'block' ? errors : warnings;
314
+ for (const v of artifactHits) bucket.push(v);
315
+ }
316
+
183
317
  return { path: rel, errors, warnings };
184
318
  }
185
319
 
@@ -0,0 +1,323 @@
1
+ /**
2
+ * lib/contracts/validate.mjs — Validate agents/contracts.json at sync time + at handoff.
3
+ *
4
+ * Three validation tiers:
5
+ * 1. Schema shape: contracts.json conforms to contracts.schema.json (minimal
6
+ * validator — top-level required fields, contract entry required fields).
7
+ * 2. Cross-file refs: every output.schema points to a real file in lib/schemas/,
8
+ * every producer/consumer name resolves to an agent or persona in
9
+ * agents/registry.json, every well-known event/intake string is reachable.
10
+ * 3. Runtime handoff: a single artifact validated against the schema referenced
11
+ * by a producer→consumer contract, with mustContain post-conditions.
12
+ *
13
+ * Surfaces:
14
+ * - scripts/sync-agents.mjs invokes validateContractsFile at sync time.
15
+ * - bin/construct lint:contracts invokes the same path in CI.
16
+ * - workflowContractValidate (runtime) invokes validateHandoff per handoff.
17
+ */
18
+
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import { join, dirname, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
24
+ const CONTRACTS_PATH = join(REPO_ROOT, 'agents', 'contracts.json');
25
+ const CONTRACTS_SCHEMA_PATH = join(REPO_ROOT, 'agents', 'contracts.schema.json');
26
+ const REGISTRY_PATH = join(REPO_ROOT, 'agents', 'registry.json');
27
+
28
+ const WELL_KNOWN_PRODUCERS = new Set(['user', 'oncall', 'incident-system', '*']);
29
+ const WELL_KNOWN_CONSUMERS = new Set(['user', 'construct']);
30
+
31
+ function readJson(path) {
32
+ return JSON.parse(readFileSync(path, 'utf8'));
33
+ }
34
+
35
+ /**
36
+ * Validate agents/contracts.json shape and cross-file references.
37
+ * Returns { ok, errors[] } — errors is empty on success.
38
+ */
39
+ export function validateContractsFile({ contractsPath, registryPath, repoRoot = REPO_ROOT } = {}) {
40
+ const errors = [];
41
+
42
+ // When repoRoot is supplied but explicit paths are not, derive both from it
43
+ // so test fixtures and the consistency watcher can validate slices in a
44
+ // tmpdir without pointing at the live repo.
45
+ const cPath = contractsPath || join(repoRoot, 'agents', 'contracts.json');
46
+ const rPath = registryPath || join(repoRoot, 'agents', 'registry.json');
47
+ const schemaPath = join(repoRoot, 'agents', 'contracts.schema.json');
48
+
49
+ if (!existsSync(cPath)) {
50
+ return { ok: false, errors: [`contracts file not found: ${cPath}`] };
51
+ }
52
+ if (!existsSync(schemaPath)) {
53
+ errors.push(`contracts schema missing: ${schemaPath}`);
54
+ }
55
+
56
+ let contracts;
57
+ try { contracts = readJson(cPath); }
58
+ catch (err) { return { ok: false, errors: [`contracts.json parse error: ${err.message}`] }; }
59
+
60
+ for (const key of ['version', 'terminalStates', 'severities', 'contracts']) {
61
+ if (!(key in contracts)) errors.push(`contracts.json missing top-level field: ${key}`);
62
+ }
63
+
64
+ const knownNames = collectAgentNames(rPath);
65
+
66
+ if (Array.isArray(contracts.contracts)) {
67
+ const ids = new Set();
68
+ contracts.contracts.forEach((c, idx) => {
69
+ const where = `contracts[${idx}]${c.id ? ` (${c.id})` : ''}`;
70
+ if (!c.id) errors.push(`${where}: missing id`);
71
+ else if (!/^[a-z0-9][a-z0-9-]*$/.test(c.id)) errors.push(`${where}: id must be kebab-case`);
72
+ else if (ids.has(c.id)) errors.push(`${where}: duplicate id`);
73
+ else ids.add(c.id);
74
+
75
+ if (!c.producer) errors.push(`${where}: missing producer`);
76
+ if (!c.consumer) errors.push(`${where}: missing consumer`);
77
+ if (!c.input) errors.push(`${where}: missing input`);
78
+
79
+ if (c.producer && !nameResolves(c.producer, knownNames, 'producer')) {
80
+ errors.push(`${where}: producer '${c.producer}' is not an agent/persona in registry.json and is not a well-known producer`);
81
+ }
82
+ if (c.consumer && !nameResolves(c.consumer, knownNames, 'consumer')) {
83
+ errors.push(`${where}: consumer '${c.consumer}' is not an agent/persona in registry.json and is not a well-known consumer`);
84
+ }
85
+
86
+ const schemaRef = c.output?.schema;
87
+ if (schemaRef) {
88
+ const outputSchemaPath = join(repoRoot, schemaRef);
89
+ if (!existsSync(outputSchemaPath)) {
90
+ errors.push(`${where}: output.schema '${schemaRef}' does not exist on disk`);
91
+ } else {
92
+ try { readJson(outputSchemaPath); }
93
+ catch (err) { errors.push(`${where}: output.schema '${schemaRef}' is not valid JSON: ${err.message}`); }
94
+ }
95
+ }
96
+ });
97
+ } else {
98
+ errors.push('contracts.json: contracts must be an array');
99
+ }
100
+
101
+ return { ok: errors.length === 0, errors };
102
+ }
103
+
104
+ function nameResolves(name, knownNames, role) {
105
+ if (WELL_KNOWN_PRODUCERS.has(name) && role === 'producer') return true;
106
+ if (WELL_KNOWN_CONSUMERS.has(name) && role === 'consumer') return true;
107
+ if (knownNames.has(name)) return true;
108
+ // Persona registry stores names without the cx- prefix; contracts.json
109
+ // conventionally uses the cx-prefixed form. Normalize both directions.
110
+ const stripped = name.startsWith('cx-') ? name.slice(3) : `cx-${name}`;
111
+ return knownNames.has(stripped);
112
+ }
113
+
114
+ function collectAgentNames(registryPath) {
115
+ const names = new Set();
116
+ if (!existsSync(registryPath)) return names;
117
+ try {
118
+ const registry = readJson(registryPath);
119
+ for (const a of registry.agents || []) {
120
+ if (a?.name) names.add(a.name);
121
+ if (a?.displayName) names.add(a.displayName);
122
+ }
123
+ for (const p of registry.personas || []) {
124
+ if (p?.name) names.add(p.name);
125
+ if (p?.displayName) names.add(p.displayName);
126
+ }
127
+ } catch { /* fall through with whatever names we collected */ }
128
+ return names;
129
+ }
130
+
131
+ /**
132
+ * Look up a contract by producer/consumer pair (and optional id).
133
+ */
134
+ export function findContract({ producer, consumer, id, contractsPath = CONTRACTS_PATH }) {
135
+ if (!existsSync(contractsPath)) return null;
136
+ let contracts;
137
+ try { contracts = readJson(contractsPath); } catch { return null; }
138
+ const list = contracts.contracts || [];
139
+ if (id) return list.find((c) => c.id === id) || null;
140
+ return list.find((c) => c.producer === producer && c.consumer === consumer) || null;
141
+ }
142
+
143
+ /**
144
+ * Validate a single artifact against its contract at handoff time.
145
+ *
146
+ * Returns one of:
147
+ * { ok: true, contract }
148
+ * { ok: false, status: 'BLOCKED_CONTRACT', errors[], contract }
149
+ *
150
+ * Enforcement defaults to the value of process.env.CONSTRUCT_CONTRACT_ENFORCEMENT
151
+ * ('warn' or 'block'), and may be overridden by the caller. In warn mode the
152
+ * result includes errors but ok stays true so a session is not blocked.
153
+ */
154
+ export function validateHandoff({
155
+ producer,
156
+ consumer,
157
+ id,
158
+ artifact,
159
+ contractsPath = CONTRACTS_PATH,
160
+ repoRoot = REPO_ROOT,
161
+ enforcement = process.env.CONSTRUCT_CONTRACT_ENFORCEMENT || 'warn',
162
+ }) {
163
+ const contract = findContract({ producer, consumer, id, contractsPath });
164
+ if (!contract) {
165
+ return enforcement === 'block'
166
+ ? { ok: false, status: 'BLOCKED_CONTRACT', errors: [`no contract found for ${producer}→${consumer}${id ? ` id=${id}` : ''}`], contract: null }
167
+ : { ok: true, warnings: [`no contract found for ${producer}→${consumer}`], contract: null };
168
+ }
169
+
170
+ const errors = [];
171
+
172
+ // A handoff carries a producer's output, which is the consumer's input. The
173
+ // input contract is what the consumer expects to receive; check mustContain
174
+ // against that first. Output.schema validation only applies when the artifact
175
+ // declares the matching `type` (e.g. the consumer is forwarding its own
176
+ // produced artifact downstream).
177
+ const inputMustContain = contract.input?.mustContain || [];
178
+ for (const field of inputMustContain) {
179
+ if (!hasField(artifact, field)) {
180
+ errors.push(`artifact missing required field: ${field}`);
181
+ }
182
+ }
183
+
184
+ const outputType = contract.output?.type;
185
+ const schemaRef = contract.output?.schema;
186
+ if (schemaRef && outputType && artifact && artifact.type === outputType) {
187
+ const schemaPath = join(repoRoot, schemaRef);
188
+ if (!existsSync(schemaPath)) {
189
+ errors.push(`contract output.schema '${schemaRef}' does not exist on disk`);
190
+ } else {
191
+ const schema = readJson(schemaPath);
192
+ for (const field of schema.required || []) {
193
+ if (!hasField(artifact, field)) errors.push(`artifact missing schema-required field: ${field}`);
194
+ }
195
+ }
196
+ }
197
+
198
+ // Postcondition checks run against the artifact file on disk when the
199
+ // handoff envelope declares `artifactPath`. Resolved relative to repoRoot.
200
+ const declaredArtifactPath = artifact?.artifactPath || artifact?.output?.artifactPath;
201
+ if (declaredArtifactPath) {
202
+ const absPath = isAbsolutePath(declaredArtifactPath)
203
+ ? declaredArtifactPath
204
+ : join(repoRoot, declaredArtifactPath);
205
+ const pcErrors = validatePostconditions({ contract, artifactPath: absPath });
206
+ for (const e of pcErrors) errors.push(e);
207
+ }
208
+
209
+ if (errors.length === 0) return { ok: true, contract };
210
+ if (enforcement === 'block') return { ok: false, status: 'BLOCKED_CONTRACT', errors, contract };
211
+ return { ok: true, warnings: errors, contract };
212
+ }
213
+
214
+ function isAbsolutePath(p) {
215
+ return p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p);
216
+ }
217
+
218
+ function hasField(obj, field) {
219
+ if (obj == null) return false;
220
+ if (typeof obj !== 'object') return false;
221
+ return Object.prototype.hasOwnProperty.call(obj, field) && obj[field] != null && obj[field] !== '';
222
+ }
223
+
224
+ const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?/;
225
+
226
+ function parseArtifactFrontmatter(text) {
227
+ const m = text.match(FRONTMATTER_RE);
228
+ if (!m) return { frontmatter: {}, body: text };
229
+ const fm = {};
230
+ for (const line of m[1].split('\n')) {
231
+ if (!line.trim() || line.trim().startsWith('#')) continue;
232
+ const idx = line.indexOf(':');
233
+ if (idx === -1) continue;
234
+ const key = line.slice(0, idx).trim();
235
+ const rawValue = line.slice(idx + 1).trim();
236
+ if (key) fm[key] = rawValue.replace(/^["']|["']$/g, '');
237
+ }
238
+ return { frontmatter: fm, body: text.slice(m[0].length) };
239
+ }
240
+
241
+ function hasSection(body, sectionTitle) {
242
+ const target = sectionTitle.trim().toLowerCase();
243
+ const headingRe = /^#{1,6}\s+(.+)$/gm;
244
+ let m;
245
+ while ((m = headingRe.exec(body))) {
246
+ if (m[1].trim().toLowerCase() === target) return true;
247
+ }
248
+ return false;
249
+ }
250
+
251
+ function claimsHaveCitations(body) {
252
+ const lines = body.split('\n');
253
+ const offenders = [];
254
+ let inFence = false;
255
+ let inTable = false;
256
+ for (let i = 0; i < lines.length; i++) {
257
+ const line = lines[i];
258
+ if (/^```/.test(line)) { inFence = !inFence; continue; }
259
+ if (inFence) continue;
260
+ inTable = /^\s*\|.*\|\s*$/.test(line);
261
+ if (inTable) continue;
262
+ if (/\b\d{1,3}\s*%/.test(line) || /\b\d{2,}x\b/i.test(line)) {
263
+ const window = [lines[i - 1] || '', line, lines[i + 1] || ''].join('\n');
264
+ if (!/\[source:|\bhttps?:\/\/|\[\^\d+\]/i.test(window)) {
265
+ offenders.push({ line: i + 1, snippet: line.trim().slice(0, 80) });
266
+ }
267
+ }
268
+ }
269
+ return offenders;
270
+ }
271
+
272
+ /**
273
+ * Run structured postcondition checks against a handoff's output artifact on
274
+ * disk. Postconditions can be strings (descriptive, ignored here) or objects
275
+ * with { id, check, field?, section? }. Returns an array of error strings.
276
+ */
277
+ export function validatePostconditions({ contract, artifactPath }) {
278
+ if (!contract?.postconditions?.length) return [];
279
+ if (!artifactPath || !existsSync(artifactPath)) {
280
+ const structured = contract.postconditions.filter((p) => typeof p === 'object');
281
+ if (structured.length === 0) return [];
282
+ return [`postcondition checks declared but artifact not found on disk: ${artifactPath}`];
283
+ }
284
+ const text = readFileSync(artifactPath, 'utf8');
285
+ const { frontmatter, body } = parseArtifactFrontmatter(text);
286
+ const errors = [];
287
+ for (const pc of contract.postconditions) {
288
+ if (typeof pc !== 'object') continue;
289
+ const tag = pc.id || pc.check;
290
+ switch (pc.check) {
291
+ case 'artifact-has-frontmatter-field': {
292
+ if (!pc.field) {
293
+ errors.push(`[${tag}] postcondition missing 'field' for artifact-has-frontmatter-field`);
294
+ break;
295
+ }
296
+ if (!frontmatter[pc.field]) {
297
+ errors.push(`[${tag}] artifact missing frontmatter field: ${pc.field}`);
298
+ }
299
+ break;
300
+ }
301
+ case 'artifact-has-section': {
302
+ if (!pc.section) {
303
+ errors.push(`[${tag}] postcondition missing 'section' for artifact-has-section`);
304
+ break;
305
+ }
306
+ if (!hasSection(body, pc.section)) {
307
+ errors.push(`[${tag}] artifact missing required section: "${pc.section}"`);
308
+ }
309
+ break;
310
+ }
311
+ case 'artifact-claims-cited': {
312
+ const offenders = claimsHaveCitations(body);
313
+ for (const o of offenders) {
314
+ errors.push(`[${tag}] uncited numeric claim at line ${o.line}: ${o.snippet}`);
315
+ }
316
+ break;
317
+ }
318
+ default:
319
+ errors.push(`[${tag}] unknown postcondition check: ${pc.check}`);
320
+ }
321
+ }
322
+ return errors;
323
+ }