@neurcode-ai/cli 0.9.65 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/commands/bootstrap-policy.d.ts +29 -0
  2. package/dist/commands/bootstrap-policy.d.ts.map +1 -0
  3. package/dist/commands/bootstrap-policy.js +334 -0
  4. package/dist/commands/bootstrap-policy.js.map +1 -0
  5. package/dist/commands/doctor.d.ts.map +1 -1
  6. package/dist/commands/doctor.js +82 -0
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/governance.d.ts +3 -0
  9. package/dist/commands/governance.d.ts.map +1 -0
  10. package/dist/commands/governance.js +390 -0
  11. package/dist/commands/governance.js.map +1 -0
  12. package/dist/commands/quickstart.d.ts +21 -0
  13. package/dist/commands/quickstart.d.ts.map +1 -0
  14. package/dist/commands/quickstart.js +178 -0
  15. package/dist/commands/quickstart.js.map +1 -0
  16. package/dist/commands/remediate-export.d.ts +36 -0
  17. package/dist/commands/remediate-export.d.ts.map +1 -0
  18. package/dist/commands/remediate-export.js +1072 -0
  19. package/dist/commands/remediate-export.js.map +1 -0
  20. package/dist/commands/replay.d.ts.map +1 -1
  21. package/dist/commands/replay.js +14 -0
  22. package/dist/commands/replay.js.map +1 -1
  23. package/dist/commands/session.d.ts +7 -0
  24. package/dist/commands/session.d.ts.map +1 -1
  25. package/dist/commands/session.js +156 -0
  26. package/dist/commands/session.js.map +1 -1
  27. package/dist/commands/start-intent.d.ts.map +1 -1
  28. package/dist/commands/start-intent.js +61 -11
  29. package/dist/commands/start-intent.js.map +1 -1
  30. package/dist/commands/verify-guidance.d.ts +5 -0
  31. package/dist/commands/verify-guidance.d.ts.map +1 -0
  32. package/dist/commands/verify-guidance.js +49 -0
  33. package/dist/commands/verify-guidance.js.map +1 -0
  34. package/dist/commands/verify-output.d.ts +37 -0
  35. package/dist/commands/verify-output.d.ts.map +1 -0
  36. package/dist/commands/verify-output.js +572 -0
  37. package/dist/commands/verify-output.js.map +1 -0
  38. package/dist/commands/verify-render.d.ts +41 -0
  39. package/dist/commands/verify-render.d.ts.map +1 -0
  40. package/dist/commands/verify-render.js +457 -0
  41. package/dist/commands/verify-render.js.map +1 -0
  42. package/dist/commands/verify.d.ts.map +1 -1
  43. package/dist/commands/verify.js +384 -1091
  44. package/dist/commands/verify.js.map +1 -1
  45. package/dist/commands/workspace.d.ts.map +1 -1
  46. package/dist/commands/workspace.js +3 -14
  47. package/dist/commands/workspace.js.map +1 -1
  48. package/dist/context-engine/graph.d.ts.map +1 -1
  49. package/dist/context-engine/graph.js +69 -7
  50. package/dist/context-engine/graph.js.map +1 -1
  51. package/dist/context-engine/scanner.d.ts.map +1 -1
  52. package/dist/context-engine/scanner.js +9 -2
  53. package/dist/context-engine/scanner.js.map +1 -1
  54. package/dist/daemon/compatibility/execution.d.ts +42 -0
  55. package/dist/daemon/compatibility/execution.d.ts.map +1 -0
  56. package/dist/daemon/compatibility/execution.js +183 -0
  57. package/dist/daemon/compatibility/execution.js.map +1 -0
  58. package/dist/daemon/compatibility/mutation.d.ts +24 -0
  59. package/dist/daemon/compatibility/mutation.d.ts.map +1 -0
  60. package/dist/daemon/compatibility/mutation.js +724 -0
  61. package/dist/daemon/compatibility/mutation.js.map +1 -0
  62. package/dist/daemon/routes.d.ts +19 -0
  63. package/dist/daemon/routes.d.ts.map +1 -0
  64. package/dist/daemon/routes.js +123 -0
  65. package/dist/daemon/routes.js.map +1 -0
  66. package/dist/daemon/runtime/execution-bus.d.ts +217 -0
  67. package/dist/daemon/runtime/execution-bus.d.ts.map +1 -0
  68. package/dist/daemon/runtime/execution-bus.js +1420 -0
  69. package/dist/daemon/runtime/execution-bus.js.map +1 -0
  70. package/dist/daemon/runtime/workspace-runtime.d.ts +280 -0
  71. package/dist/daemon/runtime/workspace-runtime.d.ts.map +1 -0
  72. package/dist/daemon/runtime/workspace-runtime.js +1473 -0
  73. package/dist/daemon/runtime/workspace-runtime.js.map +1 -0
  74. package/dist/daemon/server.d.ts.map +1 -1
  75. package/dist/daemon/server.js +171 -874
  76. package/dist/daemon/server.js.map +1 -1
  77. package/dist/daemon/shaping.d.ts +11 -0
  78. package/dist/daemon/shaping.d.ts.map +1 -0
  79. package/dist/daemon/shaping.js +240 -0
  80. package/dist/daemon/shaping.js.map +1 -0
  81. package/dist/governance/canonical-invariants.d.ts +88 -0
  82. package/dist/governance/canonical-invariants.d.ts.map +1 -0
  83. package/dist/governance/canonical-invariants.js +197 -0
  84. package/dist/governance/canonical-invariants.js.map +1 -0
  85. package/dist/governance/canonical-ordering.d.ts +76 -0
  86. package/dist/governance/canonical-ordering.d.ts.map +1 -0
  87. package/dist/governance/canonical-ordering.js +189 -0
  88. package/dist/governance/canonical-ordering.js.map +1 -0
  89. package/dist/governance/canonical-pipeline.d.ts +9 -1
  90. package/dist/governance/canonical-pipeline.d.ts.map +1 -1
  91. package/dist/governance/canonical-pipeline.js +367 -24
  92. package/dist/governance/canonical-pipeline.js.map +1 -1
  93. package/dist/governance/diff-line-provenance.d.ts +59 -0
  94. package/dist/governance/diff-line-provenance.d.ts.map +1 -0
  95. package/dist/governance/diff-line-provenance.js +118 -0
  96. package/dist/governance/diff-line-provenance.js.map +1 -0
  97. package/dist/governance/pilot-readiness.d.ts +34 -0
  98. package/dist/governance/pilot-readiness.d.ts.map +1 -0
  99. package/dist/governance/pilot-readiness.js +226 -0
  100. package/dist/governance/pilot-readiness.js.map +1 -0
  101. package/dist/governance/policy-parity-validator.d.ts +62 -0
  102. package/dist/governance/policy-parity-validator.d.ts.map +1 -0
  103. package/dist/governance/policy-parity-validator.js +137 -0
  104. package/dist/governance/policy-parity-validator.js.map +1 -0
  105. package/dist/governance/remediation-boundary.d.ts +55 -0
  106. package/dist/governance/remediation-boundary.d.ts.map +1 -0
  107. package/dist/governance/remediation-boundary.js +120 -0
  108. package/dist/governance/remediation-boundary.js.map +1 -0
  109. package/dist/governance/structural-cache.d.ts +103 -0
  110. package/dist/governance/structural-cache.d.ts.map +1 -0
  111. package/dist/governance/structural-cache.js +235 -0
  112. package/dist/governance/structural-cache.js.map +1 -0
  113. package/dist/governance/structural-on-diff.d.ts +22 -2
  114. package/dist/governance/structural-on-diff.d.ts.map +1 -1
  115. package/dist/governance/structural-on-diff.js +36 -4
  116. package/dist/governance/structural-on-diff.js.map +1 -1
  117. package/dist/governance/structural-policy-merge.d.ts +8 -0
  118. package/dist/governance/structural-policy-merge.d.ts.map +1 -1
  119. package/dist/governance/structural-policy-merge.js +7 -0
  120. package/dist/governance/structural-policy-merge.js.map +1 -1
  121. package/dist/governance/verify-runtime-guard.d.ts +99 -0
  122. package/dist/governance/verify-runtime-guard.d.ts.map +1 -0
  123. package/dist/governance/verify-runtime-guard.js +129 -0
  124. package/dist/governance/verify-runtime-guard.js.map +1 -0
  125. package/dist/index.js +277 -77
  126. package/dist/index.js.map +1 -1
  127. package/dist/intent-engine/repo-classifier.d.ts +64 -0
  128. package/dist/intent-engine/repo-classifier.d.ts.map +1 -0
  129. package/dist/intent-engine/repo-classifier.js +178 -0
  130. package/dist/intent-engine/repo-classifier.js.map +1 -0
  131. package/dist/structural-rules/index.d.ts +4 -0
  132. package/dist/structural-rules/index.d.ts.map +1 -1
  133. package/dist/structural-rules/index.js +18 -1
  134. package/dist/structural-rules/index.js.map +1 -1
  135. package/dist/structural-rules/python/PY003-broad-except-clause.d.ts +21 -0
  136. package/dist/structural-rules/python/PY003-broad-except-clause.d.ts.map +1 -1
  137. package/dist/structural-rules/python/PY003-broad-except-clause.js +212 -21
  138. package/dist/structural-rules/python/PY003-broad-except-clause.js.map +1 -1
  139. package/dist/structural-rules/python/PY011-thread-lifecycle.d.ts +11 -0
  140. package/dist/structural-rules/python/PY011-thread-lifecycle.d.ts.map +1 -0
  141. package/dist/structural-rules/python/PY011-thread-lifecycle.js +97 -0
  142. package/dist/structural-rules/python/PY011-thread-lifecycle.js.map +1 -0
  143. package/dist/structural-rules/python/PY012-asyncio-run-misuse.d.ts +11 -0
  144. package/dist/structural-rules/python/PY012-asyncio-run-misuse.d.ts.map +1 -0
  145. package/dist/structural-rules/python/PY012-asyncio-run-misuse.js +83 -0
  146. package/dist/structural-rules/python/PY012-asyncio-run-misuse.js.map +1 -0
  147. package/dist/structural-rules/python/PY013-mutable-default-arg.d.ts +11 -0
  148. package/dist/structural-rules/python/PY013-mutable-default-arg.d.ts.map +1 -0
  149. package/dist/structural-rules/python/PY013-mutable-default-arg.js +73 -0
  150. package/dist/structural-rules/python/PY013-mutable-default-arg.js.map +1 -0
  151. package/dist/structural-rules/python/PY014-fixed-sleep-retry.d.ts +11 -0
  152. package/dist/structural-rules/python/PY014-fixed-sleep-retry.d.ts.map +1 -0
  153. package/dist/structural-rules/python/PY014-fixed-sleep-retry.js +115 -0
  154. package/dist/structural-rules/python/PY014-fixed-sleep-retry.js.map +1 -0
  155. package/dist/structural-rules/types.d.ts +12 -0
  156. package/dist/structural-rules/types.d.ts.map +1 -1
  157. package/dist/utils/active-engineering-context.d.ts +12 -0
  158. package/dist/utils/active-engineering-context.d.ts.map +1 -0
  159. package/dist/utils/active-engineering-context.js +67 -0
  160. package/dist/utils/active-engineering-context.js.map +1 -0
  161. package/dist/utils/artifact-io.d.ts +33 -0
  162. package/dist/utils/artifact-io.d.ts.map +1 -0
  163. package/dist/utils/artifact-io.js +183 -0
  164. package/dist/utils/artifact-io.js.map +1 -0
  165. package/dist/utils/change-contract.d.ts +6 -2
  166. package/dist/utils/change-contract.d.ts.map +1 -1
  167. package/dist/utils/change-contract.js +175 -0
  168. package/dist/utils/change-contract.js.map +1 -1
  169. package/dist/utils/context-pack.d.ts +12 -0
  170. package/dist/utils/context-pack.d.ts.map +1 -0
  171. package/dist/utils/context-pack.js +147 -0
  172. package/dist/utils/context-pack.js.map +1 -0
  173. package/dist/utils/control-plane.d.ts +18 -0
  174. package/dist/utils/control-plane.d.ts.map +1 -1
  175. package/dist/utils/control-plane.js +31 -4
  176. package/dist/utils/control-plane.js.map +1 -1
  177. package/dist/utils/drift-intelligence.d.ts +47 -0
  178. package/dist/utils/drift-intelligence.d.ts.map +1 -0
  179. package/dist/utils/drift-intelligence.js +2099 -0
  180. package/dist/utils/drift-intelligence.js.map +1 -0
  181. package/dist/utils/execution-actions.d.ts +22 -0
  182. package/dist/utils/execution-actions.d.ts.map +1 -0
  183. package/dist/utils/execution-actions.js +103 -0
  184. package/dist/utils/execution-actions.js.map +1 -0
  185. package/dist/utils/execution-bus.d.ts +1 -214
  186. package/dist/utils/execution-bus.d.ts.map +1 -1
  187. package/dist/utils/execution-bus.js +15 -1359
  188. package/dist/utils/execution-bus.js.map +1 -1
  189. package/dist/utils/git.d.ts +1 -0
  190. package/dist/utils/git.d.ts.map +1 -1
  191. package/dist/utils/git.js +13 -3
  192. package/dist/utils/git.js.map +1 -1
  193. package/dist/utils/governance-decisions.d.ts +75 -0
  194. package/dist/utils/governance-decisions.d.ts.map +1 -0
  195. package/dist/utils/governance-decisions.js +412 -0
  196. package/dist/utils/governance-decisions.js.map +1 -0
  197. package/dist/utils/governance-provenance.d.ts +1 -1
  198. package/dist/utils/governance-provenance.d.ts.map +1 -1
  199. package/dist/utils/governance-provenance.js +5 -7
  200. package/dist/utils/governance-provenance.js.map +1 -1
  201. package/dist/utils/governance.d.ts +108 -0
  202. package/dist/utils/governance.d.ts.map +1 -1
  203. package/dist/utils/governance.js +209 -7
  204. package/dist/utils/governance.js.map +1 -1
  205. package/dist/utils/intelligence-runtime-common.d.ts +30 -0
  206. package/dist/utils/intelligence-runtime-common.d.ts.map +1 -0
  207. package/dist/utils/intelligence-runtime-common.js +156 -0
  208. package/dist/utils/intelligence-runtime-common.js.map +1 -0
  209. package/dist/utils/intent-contract-diagnostics.d.ts +9 -0
  210. package/dist/utils/intent-contract-diagnostics.d.ts.map +1 -0
  211. package/dist/utils/intent-contract-diagnostics.js +322 -0
  212. package/dist/utils/intent-contract-diagnostics.js.map +1 -0
  213. package/dist/utils/intent-pack.d.ts +15 -0
  214. package/dist/utils/intent-pack.d.ts.map +1 -0
  215. package/dist/utils/intent-pack.js +196 -0
  216. package/dist/utils/intent-pack.js.map +1 -0
  217. package/dist/utils/plan-sync.d.ts +1 -0
  218. package/dist/utils/plan-sync.d.ts.map +1 -1
  219. package/dist/utils/plan-sync.js +23 -0
  220. package/dist/utils/plan-sync.js.map +1 -1
  221. package/dist/utils/policy-decision.d.ts +5 -0
  222. package/dist/utils/policy-decision.d.ts.map +1 -0
  223. package/dist/utils/policy-decision.js +17 -0
  224. package/dist/utils/policy-decision.js.map +1 -0
  225. package/dist/utils/replay-custody.d.ts +43 -0
  226. package/dist/utils/replay-custody.d.ts.map +1 -0
  227. package/dist/utils/replay-custody.js +168 -0
  228. package/dist/utils/replay-custody.js.map +1 -0
  229. package/dist/utils/replay-runtime.d.ts +13 -0
  230. package/dist/utils/replay-runtime.d.ts.map +1 -1
  231. package/dist/utils/replay-runtime.js +96 -9
  232. package/dist/utils/replay-runtime.js.map +1 -1
  233. package/dist/utils/repository-intelligence.d.ts +9 -0
  234. package/dist/utils/repository-intelligence.d.ts.map +1 -0
  235. package/dist/utils/repository-intelligence.js +372 -0
  236. package/dist/utils/repository-intelligence.js.map +1 -0
  237. package/dist/utils/runtime-events.d.ts.map +1 -1
  238. package/dist/utils/runtime-events.js +25 -6
  239. package/dist/utils/runtime-events.js.map +1 -1
  240. package/dist/utils/semantic-contract-intelligence.d.ts +20 -0
  241. package/dist/utils/semantic-contract-intelligence.d.ts.map +1 -0
  242. package/dist/utils/semantic-contract-intelligence.js +825 -0
  243. package/dist/utils/semantic-contract-intelligence.js.map +1 -0
  244. package/dist/utils/session-continuity.d.ts +56 -0
  245. package/dist/utils/session-continuity.d.ts.map +1 -0
  246. package/dist/utils/session-continuity.js +318 -0
  247. package/dist/utils/session-continuity.js.map +1 -0
  248. package/dist/utils/verification-evidence.d.ts.map +1 -1
  249. package/dist/utils/verification-evidence.js +4 -1
  250. package/dist/utils/verification-evidence.js.map +1 -1
  251. package/dist/utils/verify-runtime-stability.d.ts +142 -0
  252. package/dist/utils/verify-runtime-stability.d.ts.map +1 -0
  253. package/dist/utils/verify-runtime-stability.js +230 -0
  254. package/dist/utils/verify-runtime-stability.js.map +1 -0
  255. package/dist/utils/workspace-runtime.d.ts +1 -266
  256. package/dist/utils/workspace-runtime.d.ts.map +1 -1
  257. package/dist/utils/workspace-runtime.js +15 -1412
  258. package/dist/utils/workspace-runtime.js.map +1 -1
  259. package/package.json +11 -10
  260. package/LICENSE +0 -201
@@ -0,0 +1,825 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildRepositorySemanticModel = buildRepositorySemanticModel;
4
+ exports.buildEngineeringInvariantMemory = buildEngineeringInvariantMemory;
5
+ exports.recordDriftInInvariantMemory = recordDriftInInvariantMemory;
6
+ const fs_1 = require("fs");
7
+ const path_1 = require("path");
8
+ const intelligence_runtime_common_1 = require("./intelligence-runtime-common");
9
+ function dedupeSorted(values) {
10
+ return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean))).sort((a, b) => a.localeCompare(b));
11
+ }
12
+ function dedupeSortedPaths(values) {
13
+ return dedupeSorted(values.map(intelligence_runtime_common_1.normalizeRepoPath));
14
+ }
15
+ function lowerPath(pathValue) {
16
+ return (0, intelligence_runtime_common_1.normalizeRepoPath)(pathValue).toLowerCase();
17
+ }
18
+ function deriveDomainLabel(pathValue) {
19
+ const normalized = lowerPath(pathValue);
20
+ if (/(^|\/)(auth|identity|iam|rbac|permission)(\/|$)/.test(normalized))
21
+ return 'identity';
22
+ if (/(^|\/)(billing|payment|invoice|refund)(\/|$)/.test(normalized))
23
+ return 'payments';
24
+ if (/(^|\/)(notification|notify|email|sms|alert|webhook)(\/|$)/.test(normalized))
25
+ return 'notifications';
26
+ if (/(^|\/)(queue|event|worker|job|consumer)(\/|$)/.test(normalized))
27
+ return 'event-processing';
28
+ if (/(^|\/)(infra|terraform|helm|k8s|deploy|docker)(\/|$)/.test(normalized))
29
+ return 'delivery';
30
+ if (/(^|\/)(db|database|model|models|migration|prisma)(\/|$)/.test(normalized))
31
+ return 'persistence';
32
+ if (/(^|\/)(api|gateway|route|controller|handler)(\/|$)/.test(normalized))
33
+ return 'api';
34
+ if (/(^|\/)(ui|web|frontend|component|page|view)(\/|$)/.test(normalized))
35
+ return 'presentation';
36
+ if (/(^|\/)(shared|common|lib|libs)(\/|$)/.test(normalized))
37
+ return 'shared-platform';
38
+ const parts = normalized.split('/').filter(Boolean);
39
+ return parts[parts.length - 1] || 'repository';
40
+ }
41
+ function inferBoundaryProfile(pathValue, category) {
42
+ const normalized = lowerPath(pathValue);
43
+ const cat = (category || '').toLowerCase();
44
+ if (/(^|\/)(auth|identity|iam|rbac|permission|token)(\/|$)/.test(normalized)) {
45
+ return {
46
+ kind: 'auth',
47
+ domain: 'identity',
48
+ responsibilities: ['authentication', 'authorization', 'credential-validation'],
49
+ forbiddenResponsibilities: ['payment-orchestration', 'notification-dispatch', 'deployment-control'],
50
+ criticality: 'critical',
51
+ allowedDependencyKinds: ['auth', 'shared', 'contract', 'data', 'service'],
52
+ forbiddenDependencyKinds: ['payment', 'infra', 'ci', 'deployment', 'ui'],
53
+ };
54
+ }
55
+ if (/(^|\/)(billing|payment|invoice|refund|checkout)(\/|$)/.test(normalized)) {
56
+ return {
57
+ kind: 'payment',
58
+ domain: 'payments',
59
+ responsibilities: ['payment-orchestration', 'billing-state', 'settlement-coordination'],
60
+ forbiddenResponsibilities: ['credential-governance', 'identity-policy', 'deployment-control'],
61
+ criticality: 'critical',
62
+ allowedDependencyKinds: ['payment', 'shared', 'contract', 'data', 'service'],
63
+ forbiddenDependencyKinds: ['auth', 'infra', 'ci', 'deployment', 'ui'],
64
+ };
65
+ }
66
+ if (/(^|\/)(notification|notify|email|sms|alert|webhook)(\/|$)/.test(normalized)) {
67
+ return {
68
+ kind: 'notification',
69
+ domain: 'notifications',
70
+ responsibilities: ['notification-delivery', 'message-formatting', 'event-fanout'],
71
+ forbiddenResponsibilities: ['auth-state-mutation', 'payment-settlement', 'deployment-control'],
72
+ criticality: 'sensitive',
73
+ allowedDependencyKinds: ['notification', 'worker', 'shared', 'contract', 'service'],
74
+ forbiddenDependencyKinds: ['auth', 'payment', 'infra', 'ci', 'deployment', 'data'],
75
+ };
76
+ }
77
+ if (cat === 'infra' || /(^|\/)(infra|terraform|helm|k8s|docker|deploy)(\/|$)/.test(normalized)) {
78
+ return {
79
+ kind: 'infra',
80
+ domain: 'delivery',
81
+ responsibilities: ['deployment-topology', 'infrastructure-configuration', 'runtime-delivery'],
82
+ forbiddenResponsibilities: ['business-orchestration', 'domain-state-mutation', 'request-routing'],
83
+ criticality: 'critical',
84
+ allowedDependencyKinds: ['infra', 'ci', 'deployment', 'shared'],
85
+ forbiddenDependencyKinds: ['auth', 'payment', 'api', 'service', 'worker', 'data', 'ui'],
86
+ };
87
+ }
88
+ if (cat === 'ui' || /(^|\/)(ui|web|frontend|component|page|view)(\/|$)/.test(normalized)) {
89
+ return {
90
+ kind: 'ui',
91
+ domain: 'presentation',
92
+ responsibilities: ['presentation', 'interaction-handling', 'view-composition'],
93
+ forbiddenResponsibilities: ['direct-persistence-mutation', 'credential-authority', 'deployment-control'],
94
+ criticality: 'standard',
95
+ allowedDependencyKinds: ['ui', 'shared', 'contract', 'api'],
96
+ forbiddenDependencyKinds: ['data', 'infra', 'ci', 'deployment'],
97
+ };
98
+ }
99
+ if (cat === 'api' || /(^|\/)(api|gateway|route|controller|handler)(\/|$)/.test(normalized)) {
100
+ return {
101
+ kind: 'api',
102
+ domain: 'api',
103
+ responsibilities: ['request-routing', 'contract-translation', 'boundary-validation'],
104
+ forbiddenResponsibilities: ['direct-persistence-mutation', 'deployment-control', 'payment-orchestration'],
105
+ criticality: 'sensitive',
106
+ allowedDependencyKinds: ['api', 'service', 'shared', 'contract'],
107
+ forbiddenDependencyKinds: ['infra', 'ci', 'deployment', 'ui', 'data'],
108
+ };
109
+ }
110
+ if (cat === 'worker' || /(^|\/)(worker|queue|event|job|consumer)(\/|$)/.test(normalized)) {
111
+ return {
112
+ kind: 'worker',
113
+ domain: 'event-processing',
114
+ responsibilities: ['background-processing', 'event-consumption', 'async-coordination'],
115
+ forbiddenResponsibilities: ['auth-state-mutation', 'deployment-control', 'ui-presentation'],
116
+ criticality: 'sensitive',
117
+ allowedDependencyKinds: ['worker', 'service', 'shared', 'contract', 'notification'],
118
+ forbiddenDependencyKinds: ['ui', 'infra', 'ci', 'deployment'],
119
+ };
120
+ }
121
+ if (cat === 'shared' || /(^|\/)(shared|common|lib|libs)(\/|$)/.test(normalized)) {
122
+ return {
123
+ kind: 'shared',
124
+ domain: 'shared-platform',
125
+ responsibilities: ['shared-utilities', 'cross-cutting-support', 'common-types'],
126
+ forbiddenResponsibilities: ['domain-orchestration', 'credential-authority', 'deployment-control'],
127
+ criticality: 'standard',
128
+ allowedDependencyKinds: ['shared', 'contract'],
129
+ forbiddenDependencyKinds: ['auth', 'payment', 'api', 'service', 'worker', 'infra', 'ci', 'deployment', 'data'],
130
+ };
131
+ }
132
+ if (cat === 'service' && /(^|\/)(db|database|model|models|migration|prisma|sequelize)(\/|$)/.test(normalized)) {
133
+ return {
134
+ kind: 'data',
135
+ domain: 'persistence',
136
+ responsibilities: ['persistence-modeling', 'data-access', 'storage-schema'],
137
+ forbiddenResponsibilities: ['request-routing', 'deployment-control', 'presentation'],
138
+ criticality: 'sensitive',
139
+ allowedDependencyKinds: ['data', 'shared', 'contract'],
140
+ forbiddenDependencyKinds: ['ui', 'infra', 'ci', 'deployment'],
141
+ };
142
+ }
143
+ return {
144
+ kind: 'service',
145
+ domain: deriveDomainLabel(pathValue),
146
+ responsibilities: ['service-domain-logic', 'bounded-business-behavior'],
147
+ forbiddenResponsibilities: ['deployment-control', 'ui-presentation', 'cross-domain-orchestration'],
148
+ criticality: 'standard',
149
+ allowedDependencyKinds: ['service', 'shared', 'contract', 'data'],
150
+ forbiddenDependencyKinds: ['ui', 'infra', 'ci', 'deployment'],
151
+ };
152
+ }
153
+ function escapeRegex(value) {
154
+ return value.replace(/[|\\{}()[\]^$+?.]/g, '\\$&');
155
+ }
156
+ function globToRegex(pattern) {
157
+ const normalized = (0, intelligence_runtime_common_1.normalizeRepoPath)(pattern.replace(/^\/+/, ''));
158
+ const escaped = escapeRegex(normalized)
159
+ .replace(/\*\*/g, '.*')
160
+ .replace(/\*/g, '[^/]*');
161
+ if (normalized.endsWith('/')) {
162
+ return new RegExp(`^${escaped}`);
163
+ }
164
+ if (!normalized.includes('*')) {
165
+ return new RegExp(`^${escaped}(?:$|/)`);
166
+ }
167
+ return new RegExp(`^${escaped}$`);
168
+ }
169
+ function loadCodeOwners(projectRoot) {
170
+ const candidates = ['CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS'];
171
+ const rules = [];
172
+ let order = 0;
173
+ for (const candidate of candidates) {
174
+ const fullPath = (0, path_1.join)(projectRoot, candidate);
175
+ if (!(0, fs_1.existsSync)(fullPath)) {
176
+ continue;
177
+ }
178
+ const content = (0, fs_1.readFileSync)(fullPath, 'utf-8');
179
+ for (const rawLine of content.split(/\r?\n/)) {
180
+ const line = rawLine.trim();
181
+ if (!line || line.startsWith('#')) {
182
+ continue;
183
+ }
184
+ const [pattern, ...owners] = line.split(/\s+/);
185
+ if (!pattern || owners.length === 0) {
186
+ continue;
187
+ }
188
+ rules.push({
189
+ regex: globToRegex(pattern),
190
+ owners: owners.map((owner) => owner.trim()).filter(Boolean),
191
+ order: order += 1,
192
+ });
193
+ }
194
+ }
195
+ return rules;
196
+ }
197
+ function matchCodeOwners(rules, pathValue) {
198
+ const normalized = (0, intelligence_runtime_common_1.normalizeRepoPath)(pathValue);
199
+ let matched = [];
200
+ let matchedOrder = -1;
201
+ for (const rule of rules) {
202
+ if (rule.order < matchedOrder) {
203
+ continue;
204
+ }
205
+ if (rule.regex.test(normalized)) {
206
+ matched = rule.owners;
207
+ matchedOrder = rule.order;
208
+ }
209
+ }
210
+ return matched;
211
+ }
212
+ function buildOwnershipBoundary(moduleNode, codeOwnerRules) {
213
+ const modulePath = (0, intelligence_runtime_common_1.normalizeRepoPath)(moduleNode.path || moduleNode.label);
214
+ const profile = inferBoundaryProfile(modulePath, moduleNode.category);
215
+ const codeOwners = matchCodeOwners(codeOwnerRules, modulePath);
216
+ const stewardship = {
217
+ primaryOwner: codeOwners[0] || profile.domain,
218
+ codeOwners,
219
+ };
220
+ const fingerprintPayload = {
221
+ modulePath,
222
+ kind: profile.kind,
223
+ domain: profile.domain,
224
+ primaryOwner: stewardship.primaryOwner,
225
+ responsibilities: profile.responsibilities,
226
+ forbiddenResponsibilities: profile.forbiddenResponsibilities,
227
+ };
228
+ return {
229
+ id: `owner-${(0, intelligence_runtime_common_1.fingerprintValue)(fingerprintPayload).slice(0, 16)}`,
230
+ name: modulePath,
231
+ path: modulePath,
232
+ kind: profile.kind,
233
+ domain: profile.domain,
234
+ stewardship,
235
+ responsibilities: profile.responsibilities,
236
+ forbiddenResponsibilities: profile.forbiddenResponsibilities,
237
+ criticality: profile.criticality,
238
+ confidence: codeOwners.length > 0 ? 'high' : profile.criticality === 'critical' ? 'medium' : 'low',
239
+ };
240
+ }
241
+ function buildContractsForBoundary(boundary) {
242
+ const profile = inferBoundaryProfile(boundary.path, boundary.kind);
243
+ const serviceContract = {
244
+ id: `contract-${(0, intelligence_runtime_common_1.fingerprintValue)(['service', boundary.id, ...boundary.responsibilities]).slice(0, 16)}`,
245
+ name: `${boundary.name} service contract`,
246
+ kind: 'service-contract',
247
+ boundaryId: boundary.id,
248
+ boundaryName: boundary.name,
249
+ subjectPath: boundary.path,
250
+ expectedResponsibilities: boundary.responsibilities,
251
+ forbiddenResponsibilities: boundary.forbiddenResponsibilities,
252
+ allowedDependencyKinds: profile.allowedDependencyKinds,
253
+ forbiddenDependencyKinds: profile.forbiddenDependencyKinds,
254
+ rationale: `${boundary.name} should remain focused on ${boundary.responsibilities.join(', ')} and avoid ${boundary.forbiddenResponsibilities.join(', ')}.`,
255
+ evidence: [boundary.path, boundary.kind, boundary.domain],
256
+ confidence: boundary.confidence,
257
+ };
258
+ const layeringContract = {
259
+ id: `contract-${(0, intelligence_runtime_common_1.fingerprintValue)(['layering', boundary.id, ...profile.forbiddenDependencyKinds]).slice(0, 16)}`,
260
+ name: `${boundary.name} layering contract`,
261
+ kind: boundary.kind === 'infra' || boundary.kind === 'deployment' || boundary.kind === 'ci'
262
+ ? 'deployment-boundary'
263
+ : 'layering',
264
+ boundaryId: boundary.id,
265
+ boundaryName: boundary.name,
266
+ subjectPath: boundary.path,
267
+ expectedResponsibilities: boundary.responsibilities,
268
+ forbiddenResponsibilities: boundary.forbiddenResponsibilities,
269
+ allowedDependencyKinds: profile.allowedDependencyKinds,
270
+ forbiddenDependencyKinds: profile.forbiddenDependencyKinds,
271
+ rationale: `${boundary.name} should depend only on ${profile.allowedDependencyKinds.join(', ')} surfaces and avoid ${profile.forbiddenDependencyKinds.join(', ')} coupling.`,
272
+ evidence: [boundary.path, ...profile.allowedDependencyKinds.slice(0, 4)],
273
+ confidence: boundary.confidence === 'low' ? 'medium' : boundary.confidence,
274
+ };
275
+ return [serviceContract, layeringContract];
276
+ }
277
+ function buildInvariantsForBoundary(boundary, contracts) {
278
+ const serviceContract = contracts.find((contract) => contract.kind === 'service-contract') || null;
279
+ const layeringContract = contracts.find((contract) => contract.kind !== 'service-contract') || null;
280
+ const invariants = [];
281
+ if (serviceContract) {
282
+ invariants.push({
283
+ id: `invariant-${(0, intelligence_runtime_common_1.fingerprintValue)(['responsibility', boundary.id, serviceContract.id]).slice(0, 16)}`,
284
+ name: `${boundary.name} responsibility invariant`,
285
+ category: 'service-responsibility',
286
+ scope: 'module',
287
+ subjectPath: boundary.path,
288
+ boundaryId: boundary.id,
289
+ boundaryName: boundary.name,
290
+ expectation: `${boundary.name} should remain responsible for ${boundary.responsibilities.join(', ')} and avoid ${boundary.forbiddenResponsibilities.join(', ')}.`,
291
+ impact: boundary.criticality === 'critical' ? 'critical' : boundary.criticality === 'sensitive' ? 'high' : 'medium',
292
+ rationale: serviceContract.rationale,
293
+ relatedContractIds: [serviceContract.id],
294
+ evidence: [boundary.path, ...boundary.responsibilities],
295
+ confidence: serviceContract.confidence,
296
+ });
297
+ }
298
+ if (layeringContract) {
299
+ invariants.push({
300
+ id: `invariant-${(0, intelligence_runtime_common_1.fingerprintValue)(['layer', boundary.id, layeringContract.id]).slice(0, 16)}`,
301
+ name: `${boundary.name} layering invariant`,
302
+ category: boundary.kind === 'infra' || boundary.kind === 'deployment' || boundary.kind === 'ci'
303
+ ? 'deployment'
304
+ : 'layering',
305
+ scope: 'module',
306
+ subjectPath: boundary.path,
307
+ boundaryId: boundary.id,
308
+ boundaryName: boundary.name,
309
+ expectation: `${boundary.name} should not directly couple to ${layeringContract.forbiddenDependencyKinds.join(', ')} layers.`,
310
+ impact: boundary.criticality === 'critical' ? 'critical' : 'high',
311
+ rationale: layeringContract.rationale,
312
+ relatedContractIds: [layeringContract.id],
313
+ evidence: [boundary.path, ...layeringContract.forbiddenDependencyKinds.slice(0, 6)],
314
+ confidence: layeringContract.confidence,
315
+ });
316
+ }
317
+ return invariants;
318
+ }
319
+ function buildRepositoryLevelInvariants(ownershipBoundaries) {
320
+ const domains = new Map();
321
+ for (const boundary of ownershipBoundaries) {
322
+ const list = domains.get(boundary.domain) || [];
323
+ list.push(boundary);
324
+ domains.set(boundary.domain, list);
325
+ }
326
+ const invariants = [];
327
+ const authBoundaries = ownershipBoundaries.filter((boundary) => boundary.kind === 'auth');
328
+ const paymentBoundaries = ownershipBoundaries.filter((boundary) => boundary.kind === 'payment');
329
+ if (authBoundaries.length > 0 && paymentBoundaries.length > 0) {
330
+ invariants.push({
331
+ id: `invariant-${(0, intelligence_runtime_common_1.fingerprintValue)(['auth-payment-separation', authBoundaries[0].id, paymentBoundaries[0].id]).slice(0, 16)}`,
332
+ name: 'Identity and payment boundaries stay separated',
333
+ category: 'ownership',
334
+ scope: 'repository',
335
+ subjectPath: '.',
336
+ boundaryId: null,
337
+ boundaryName: null,
338
+ expectation: 'Auth and payment boundaries should remain isolated so credential authority does not accumulate payment orchestration responsibilities.',
339
+ impact: 'critical',
340
+ rationale: 'Senior platform teams expect identity and payment control planes to remain independent in AI-assisted changes.',
341
+ relatedContractIds: [],
342
+ evidence: [...authBoundaries.map((item) => item.path), ...paymentBoundaries.map((item) => item.path)],
343
+ confidence: 'medium',
344
+ });
345
+ }
346
+ for (const [domain, boundaries] of domains.entries()) {
347
+ if (boundaries.length < 2) {
348
+ continue;
349
+ }
350
+ invariants.push({
351
+ id: `invariant-${(0, intelligence_runtime_common_1.fingerprintValue)(['domain-consistency', domain, ...boundaries.map((item) => item.id)]).slice(0, 16)}`,
352
+ name: `${domain} ownership remains coherent`,
353
+ category: 'ownership',
354
+ scope: 'service',
355
+ subjectPath: boundaries[0]?.path || '.',
356
+ boundaryId: null,
357
+ boundaryName: domain,
358
+ expectation: `${domain} responsibilities should remain coherent across ${boundaries.length} related boundary path(s) without leaking into unrelated domains.`,
359
+ impact: boundaries.some((item) => item.criticality !== 'standard') ? 'high' : 'medium',
360
+ rationale: 'Boundary coherence makes AI-generated cross-service edits easier to review and less likely to accumulate accidental ownership drift.',
361
+ relatedContractIds: [],
362
+ evidence: boundaries.map((item) => item.path),
363
+ confidence: 'low',
364
+ });
365
+ }
366
+ return invariants;
367
+ }
368
+ const MAX_RUNTIME_FILES_PER_BOUNDARY = 14;
369
+ const MAX_RUNTIME_BYTES_PER_BOUNDARY = 64_000;
370
+ const RUNTIME_BEHAVIOR_PATTERNS = [
371
+ {
372
+ kind: 'api-provider',
373
+ patterns: [
374
+ /\b(app|get|post|put|patch|delete)\s*\(/i,
375
+ /\brouter\.(get|post|put|patch|delete)\b/i,
376
+ /\b(FastAPI|APIRouter|Blueprint|ServeHTTP|grpc\.Server)\b/i,
377
+ ],
378
+ },
379
+ {
380
+ kind: 'api-consumer',
381
+ patterns: [
382
+ /\b(fetch|axios|httpx|requests\.(get|post|put|patch|delete)|grpc\.Dial|new\s+URL)\b/i,
383
+ /https?:\/\//i,
384
+ ],
385
+ },
386
+ {
387
+ kind: 'event-producer',
388
+ patterns: [
389
+ /\b(publish|emit|enqueue|sendMessage|send_task|kafka\.producer|sns\.publish|sqs\.send)\b/i,
390
+ ],
391
+ },
392
+ {
393
+ kind: 'event-consumer',
394
+ patterns: [
395
+ /\b(consume|consumer|subscribe|on_message|process_job|celery\.task|queue\.process)\b/i,
396
+ ],
397
+ },
398
+ {
399
+ kind: 'state-owner',
400
+ patterns: [
401
+ /\b(prisma|sequelize|typeorm|knex|redis|postgres|mysql|mongo|migration|entity|model)\b/i,
402
+ ],
403
+ },
404
+ {
405
+ kind: 'state-mutator',
406
+ patterns: [
407
+ /\b(insert|update|delete|save|commit|transaction|createMany|updateMany|upsert)\b/i,
408
+ ],
409
+ },
410
+ {
411
+ kind: 'workflow-orchestrator',
412
+ patterns: [
413
+ /\b(orchestrate|workflow|coordinator|pipeline|saga|dispatch|fanout|step function)\b/i,
414
+ ],
415
+ },
416
+ {
417
+ kind: 'external-side-effect',
418
+ patterns: [
419
+ /\b(webhook|email|sms|slack|twilio|ses|publish|notify|httpx|axios|fetch)\b/i,
420
+ ],
421
+ },
422
+ {
423
+ kind: 'deployment-aware',
424
+ patterns: [
425
+ /\b(terraform|helm|k8s|deployment|serviceaccount|docker-compose|workflow_dispatch)\b/i,
426
+ ],
427
+ },
428
+ {
429
+ kind: 'runtime-config-consumer',
430
+ patterns: [
431
+ /\b(process\.env|os\.environ|getenv|ConfigMap|Secret|dotenv)\b/i,
432
+ ],
433
+ },
434
+ ];
435
+ const SIDE_EFFECT_PATTERNS = [
436
+ { label: 'http', patterns: [/\b(fetch|axios|httpx|requests\.)\b/i, /https?:\/\//i] },
437
+ { label: 'webhook', patterns: [/\bwebhook\b/i] },
438
+ { label: 'email', patterns: [/\b(email|ses|smtp|sendgrid)\b/i] },
439
+ { label: 'sms', patterns: [/\b(sms|twilio)\b/i] },
440
+ { label: 'queue', patterns: [/\b(kafka|sns|sqs|rabbit|pubsub|bullmq|celery)\b/i] },
441
+ { label: 'config', patterns: [/\b(process\.env|getenv|ConfigMap|Secret|dotenv)\b/i] },
442
+ ];
443
+ const STATE_SURFACE_PATTERNS = [
444
+ { label: 'sql', patterns: [/\b(prisma|sequelize|typeorm|knex|postgres|mysql|sqlalchemy)\b/i] },
445
+ { label: 'cache', patterns: [/\b(redis|memcache)\b/i] },
446
+ { label: 'document-store', patterns: [/\b(mongo|dynamo)\b/i] },
447
+ { label: 'migration', patterns: [/\b(migration|ddl|schema)\b/i] },
448
+ ];
449
+ const RUNTIME_ENV_PATTERNS = [
450
+ { label: 'production', patterns: [/\b(prod|production)\b/i] },
451
+ { label: 'staging', patterns: [/\b(stage|staging)\b/i] },
452
+ { label: 'development', patterns: [/\b(dev|development|local)\b/i] },
453
+ ];
454
+ function safeReadFile(projectRoot, filePath, maxBytes = 16_000) {
455
+ const fullPath = (0, path_1.join)(projectRoot, (0, intelligence_runtime_common_1.normalizeRepoPath)(filePath));
456
+ if (!(0, fs_1.existsSync)(fullPath)) {
457
+ return null;
458
+ }
459
+ try {
460
+ return (0, fs_1.readFileSync)(fullPath, 'utf-8').slice(0, maxBytes);
461
+ }
462
+ catch {
463
+ return null;
464
+ }
465
+ }
466
+ function collectModuleFiles(sourceFiles) {
467
+ const result = new Map();
468
+ for (const file of sourceFiles) {
469
+ const normalized = (0, intelligence_runtime_common_1.normalizeRepoPath)(file);
470
+ const parts = normalized.split('/').filter(Boolean);
471
+ const modulePath = parts.length <= 1
472
+ ? parts[0] || normalized
473
+ : ['src', 'app', 'apps', 'services', 'packages', 'libs', 'lib', 'web'].includes(parts[0]) && parts.length >= 2
474
+ ? `${parts[0]}/${parts[1]}`
475
+ : parts[0];
476
+ const list = result.get(modulePath) || [];
477
+ list.push(normalized);
478
+ result.set(modulePath, list);
479
+ }
480
+ return result;
481
+ }
482
+ function extractTokenSet(content, patterns) {
483
+ return dedupeSorted(patterns
484
+ .filter((entry) => entry.patterns.some((pattern) => pattern.test(content)))
485
+ .map((entry) => entry.label));
486
+ }
487
+ function buildBehaviorProfile(projectRoot, boundary, files) {
488
+ const selectedFiles = files.slice(0, MAX_RUNTIME_FILES_PER_BOUNDARY);
489
+ let remainingBudget = MAX_RUNTIME_BYTES_PER_BOUNDARY;
490
+ const contentParts = [];
491
+ for (const file of selectedFiles) {
492
+ if (remainingBudget <= 0) {
493
+ break;
494
+ }
495
+ const content = safeReadFile(projectRoot, file, Math.min(16_000, remainingBudget));
496
+ if (!content) {
497
+ continue;
498
+ }
499
+ remainingBudget -= content.length;
500
+ contentParts.push(content);
501
+ }
502
+ const combined = contentParts.join('\n');
503
+ const behaviorKinds = dedupeSorted(RUNTIME_BEHAVIOR_PATTERNS
504
+ .filter((entry) => entry.patterns.some((pattern) => pattern.test(combined) || selectedFiles.some((file) => pattern.test(file))))
505
+ .map((entry) => entry.kind));
506
+ const sideEffectKinds = extractTokenSet(combined, SIDE_EFFECT_PATTERNS);
507
+ const stateSurfaces = extractTokenSet(combined, STATE_SURFACE_PATTERNS);
508
+ const runtimeEnvironments = extractTokenSet(combined, RUNTIME_ENV_PATTERNS);
509
+ const rolloutUnits = dedupeSorted(selectedFiles
510
+ .filter((file) => /(deployment|service|worker|api|web|queue|job)/i.test(file))
511
+ .map((file) => file.split('/').slice(-2).join('/'))).slice(0, 8);
512
+ const externalDependencies = dedupeSorted([
513
+ ...sideEffectKinds,
514
+ ...runtimeEnvironments.map((env) => `env:${env}`),
515
+ ...stateSurfaces.map((surface) => `state:${surface}`),
516
+ ]).slice(0, 12);
517
+ const criticalFlows = dedupeSorted([
518
+ behaviorKinds.includes('api-provider') && behaviorKinds.includes('state-mutator')
519
+ ? `${boundary.name} handles request -> state mutation`
520
+ : '',
521
+ behaviorKinds.includes('workflow-orchestrator') && behaviorKinds.includes('event-producer')
522
+ ? `${boundary.name} orchestrates workflow fanout`
523
+ : '',
524
+ behaviorKinds.includes('deployment-aware')
525
+ ? `${boundary.name} is deployment-aware`
526
+ : '',
527
+ ]);
528
+ return {
529
+ boundaryId: boundary.id,
530
+ boundaryName: boundary.name,
531
+ domain: boundary.domain,
532
+ behaviorKinds,
533
+ sideEffectKinds,
534
+ externalDependencies,
535
+ stateSurfaces,
536
+ rolloutUnits,
537
+ runtimeEnvironments,
538
+ criticalFlows,
539
+ confidence: behaviorKinds.length >= 3
540
+ ? 'high'
541
+ : behaviorKinds.length >= 1 || sideEffectKinds.length > 0 || stateSurfaces.length > 0
542
+ ? 'medium'
543
+ : 'low',
544
+ };
545
+ }
546
+ function detectDeploymentBoundaryType(pathValue) {
547
+ const normalized = lowerPath(pathValue);
548
+ if (normalized.startsWith('helm/') || normalized.includes('/charts/'))
549
+ return 'helm';
550
+ if (normalized.startsWith('terraform/') || normalized.endsWith('.tf'))
551
+ return 'terraform';
552
+ if (normalized.startsWith('k8s/') || normalized.includes('/manifests/'))
553
+ return 'kubernetes';
554
+ if (normalized.startsWith('.github/workflows/') || normalized.includes('/ci/'))
555
+ return 'ci';
556
+ if (normalized.includes('docker') || normalized.endsWith('docker-compose.yml') || normalized.endsWith('docker-compose.yaml'))
557
+ return 'docker';
558
+ return 'manifest';
559
+ }
560
+ function buildDeploymentBoundaries(projectRoot, ownershipBoundaries, boundaryPaths) {
561
+ const boundaries = ownershipBoundaries.map((boundary) => ({
562
+ id: boundary.id,
563
+ name: boundary.name,
564
+ searchTokens: dedupeSorted([
565
+ boundary.name,
566
+ boundary.name.split('/').slice(-1)[0] || '',
567
+ boundary.domain,
568
+ ]).filter((token) => token.length >= 2),
569
+ }));
570
+ const deploymentBoundaries = [];
571
+ for (const boundaryPath of boundaryPaths) {
572
+ const content = safeReadFile(projectRoot, boundaryPath, 24_000) || '';
573
+ const dependentBoundaries = boundaries.filter((boundary) => boundary.searchTokens.some((token) => token && new RegExp(`\\b${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i').test(content)));
574
+ const rolloutUnits = dedupeSorted(dependentBoundaries.map((boundary) => boundary.name).concat(/(rollout|deployment|daemonset|statefulset|cronjob|job)/i.test(content)
575
+ ? [(0, intelligence_runtime_common_1.normalizeRepoPath)(boundaryPath)]
576
+ : [])).slice(0, 12);
577
+ const runtimeEnvironments = extractTokenSet(content, RUNTIME_ENV_PATTERNS);
578
+ const payload = {
579
+ path: boundaryPath,
580
+ rolloutUnits,
581
+ runtimeEnvironments,
582
+ dependents: dependentBoundaries.map((boundary) => boundary.id),
583
+ };
584
+ deploymentBoundaries.push({
585
+ id: `deploy-${(0, intelligence_runtime_common_1.fingerprintValue)(payload).slice(0, 16)}`,
586
+ name: (0, intelligence_runtime_common_1.normalizeRepoPath)(boundaryPath),
587
+ path: (0, intelligence_runtime_common_1.normalizeRepoPath)(boundaryPath),
588
+ type: detectDeploymentBoundaryType(boundaryPath),
589
+ rolloutUnits,
590
+ runtimeEnvironments,
591
+ dependentBoundaryIds: dependentBoundaries.map((boundary) => boundary.id),
592
+ dependentBoundaryNames: dependentBoundaries.map((boundary) => boundary.name),
593
+ confidence: dependentBoundaries.length > 0 ? 'high' : content.length > 0 ? 'medium' : 'low',
594
+ });
595
+ }
596
+ return deploymentBoundaries.sort((left, right) => left.name.localeCompare(right.name));
597
+ }
598
+ function buildRuntimeInteractions(ownershipBoundaries, behaviorProfiles, deploymentBoundaries, edges) {
599
+ const boundaryByPath = new Map(ownershipBoundaries.map((boundary) => [boundary.path, boundary]));
600
+ const behaviorById = new Map(behaviorProfiles.map((profile) => [profile.boundaryId, profile]));
601
+ const interactions = [];
602
+ const seen = new Set();
603
+ for (const edge of edges) {
604
+ if (edge.type !== 'imports' || !edge.from.startsWith('module:') || !edge.to.startsWith('module:')) {
605
+ continue;
606
+ }
607
+ const fromBoundary = boundaryByPath.get(edge.from.slice('module:'.length));
608
+ const toBoundary = boundaryByPath.get(edge.to.slice('module:'.length));
609
+ if (!fromBoundary || !toBoundary || fromBoundary.id === toBoundary.id) {
610
+ continue;
611
+ }
612
+ const fromBehavior = behaviorById.get(fromBoundary.id);
613
+ const toBehavior = behaviorById.get(toBoundary.id);
614
+ let kind = null;
615
+ let subject = edge.evidence || `${fromBoundary.name}->${toBoundary.name}`;
616
+ let rationale = 'Module import topology indicates runtime adjacency between these ownership boundaries.';
617
+ if (fromBehavior?.behaviorKinds.includes('api-consumer') && toBehavior?.behaviorKinds.includes('api-provider')) {
618
+ kind = 'api-call';
619
+ rationale = 'The source consumes API-like behavior and the target exposes provider-like behavior.';
620
+ }
621
+ else if (fromBehavior?.behaviorKinds.includes('event-producer') && toBehavior?.behaviorKinds.includes('event-consumer')) {
622
+ kind = 'event-flow';
623
+ rationale = 'The source produces event-like side effects and the target consumes queue or event semantics.';
624
+ }
625
+ else if (fromBehavior?.behaviorKinds.includes('state-mutator') && toBehavior?.behaviorKinds.includes('state-owner')) {
626
+ kind = 'state-mutation';
627
+ rationale = 'The source mutates state while the target owns persistence-like surfaces.';
628
+ }
629
+ else if (fromBehavior?.behaviorKinds.includes('workflow-orchestrator') || toBehavior?.behaviorKinds.includes('workflow-orchestrator')) {
630
+ kind = 'operational-coupling';
631
+ rationale = 'Workflow or coordinator behavior amplifies runtime dependence across boundaries.';
632
+ }
633
+ else if (fromBehavior?.behaviorKinds.includes('state-owner') || toBehavior?.behaviorKinds.includes('state-owner')) {
634
+ kind = 'state-access';
635
+ rationale = 'Imports now connect a boundary with persistence/state ownership semantics.';
636
+ }
637
+ if (!kind) {
638
+ continue;
639
+ }
640
+ const key = `${kind}:${fromBoundary.id}:${toBoundary.id}:${subject}`;
641
+ if (seen.has(key)) {
642
+ continue;
643
+ }
644
+ seen.add(key);
645
+ interactions.push({
646
+ id: `rtx-${(0, intelligence_runtime_common_1.fingerprintValue)(key).slice(0, 16)}`,
647
+ kind,
648
+ fromBoundaryId: fromBoundary.id,
649
+ fromBoundaryName: fromBoundary.name,
650
+ toBoundaryId: toBoundary.id,
651
+ toBoundaryName: toBoundary.name,
652
+ subject,
653
+ rationale,
654
+ confidence: fromBehavior?.confidence === 'high' && toBehavior?.confidence === 'high' ? 'high' : 'medium',
655
+ });
656
+ }
657
+ for (const deploymentBoundary of deploymentBoundaries) {
658
+ for (const dependentId of deploymentBoundary.dependentBoundaryIds) {
659
+ const dependentBoundary = ownershipBoundaries.find((boundary) => boundary.id === dependentId);
660
+ if (!dependentBoundary) {
661
+ continue;
662
+ }
663
+ const key = `deployment:${deploymentBoundary.id}:${dependentId}`;
664
+ if (seen.has(key)) {
665
+ continue;
666
+ }
667
+ seen.add(key);
668
+ interactions.push({
669
+ id: `rtx-${(0, intelligence_runtime_common_1.fingerprintValue)(key).slice(0, 16)}`,
670
+ kind: 'deployment-dependency',
671
+ fromBoundaryId: dependentBoundary.id,
672
+ fromBoundaryName: dependentBoundary.name,
673
+ toBoundaryId: null,
674
+ toBoundaryName: deploymentBoundary.name,
675
+ subject: deploymentBoundary.path,
676
+ rationale: 'Deployment or CI manifests reference this ownership boundary, so rollout semantics propagate into production delivery.',
677
+ confidence: deploymentBoundary.confidence,
678
+ });
679
+ }
680
+ }
681
+ return interactions.sort((left, right) => left.id.localeCompare(right.id));
682
+ }
683
+ function buildRepositorySemanticModel(input) {
684
+ const codeOwnerRules = loadCodeOwners(input.projectRoot);
685
+ const moduleFiles = collectModuleFiles(input.sourceFiles);
686
+ const moduleNodes = input.nodes
687
+ .filter((node) => (node.type === 'module' || node.type === 'service') && typeof node.path === 'string' && node.path.trim().length > 0)
688
+ .sort((left, right) => left.id.localeCompare(right.id));
689
+ const ownershipBoundaries = moduleNodes.map((node) => buildOwnershipBoundary(node, codeOwnerRules));
690
+ const contracts = ownershipBoundaries.flatMap((boundary) => buildContractsForBoundary(boundary));
691
+ const invariants = ownershipBoundaries.flatMap((boundary) => buildInvariantsForBoundary(boundary, contracts.filter((contract) => contract.boundaryId === boundary.id)));
692
+ const repositoryLevelInvariants = buildRepositoryLevelInvariants(ownershipBoundaries);
693
+ const criticalDomains = ownershipBoundaries
694
+ .filter((boundary) => boundary.criticality !== 'standard')
695
+ .map((boundary) => boundary.domain);
696
+ const behaviorProfiles = ownershipBoundaries.map((boundary) => buildBehaviorProfile(input.projectRoot, boundary, moduleFiles.get(boundary.path) || []));
697
+ const deploymentBoundaries = buildDeploymentBoundaries(input.projectRoot, ownershipBoundaries, dedupeSortedPaths([...input.boundaries.infraPaths, ...input.boundaries.ciPaths]));
698
+ const runtimeInteractions = buildRuntimeInteractions(ownershipBoundaries, behaviorProfiles, deploymentBoundaries, input.edges);
699
+ const criticalFlows = dedupeSorted([
700
+ ...behaviorProfiles.flatMap((profile) => profile.criticalFlows),
701
+ ...runtimeInteractions
702
+ .filter((interaction) => interaction.kind === 'deployment-dependency'
703
+ || interaction.kind === 'state-mutation'
704
+ || interaction.kind === 'operational-coupling')
705
+ .map((interaction) => `${interaction.fromBoundaryName} -> ${interaction.toBoundaryName || interaction.subject}`),
706
+ ]);
707
+ return {
708
+ ownershipBoundaries: ownershipBoundaries.sort((left, right) => left.name.localeCompare(right.name)),
709
+ contracts: contracts.sort((left, right) => left.id.localeCompare(right.id)),
710
+ invariants: [...invariants, ...repositoryLevelInvariants].sort((left, right) => left.id.localeCompare(right.id)),
711
+ criticalDomains: dedupeSorted(criticalDomains),
712
+ runtime: {
713
+ behaviorProfiles: behaviorProfiles.sort((left, right) => left.boundaryName.localeCompare(right.boundaryName)),
714
+ interactions: runtimeInteractions,
715
+ deploymentBoundaries,
716
+ criticalFlows,
717
+ blindSpots: dedupeSorted([
718
+ 'Dynamic service discovery and runtime-only traffic policies remain advisory blind spots.',
719
+ 'Network policies, feature flags, and external SaaS callbacks are inferred structurally, not observed live.',
720
+ ]),
721
+ },
722
+ };
723
+ }
724
+ function buildEngineeringInvariantMemory(input) {
725
+ const generatedAt = (0, intelligence_runtime_common_1.nowIso)();
726
+ const payloadWithoutFingerprint = {
727
+ schemaVersion: intelligence_runtime_common_1.LOCAL_INTELLIGENCE_SCHEMA_VERSION,
728
+ generatedAt,
729
+ updatedAt: generatedAt,
730
+ sessionId: input.sessionRuntime.sessionId,
731
+ intentPackId: input.intentPack.intentPackId,
732
+ repositoryGraphId: input.repositoryGraph.graphId,
733
+ branchName: input.sessionRuntime.branchName,
734
+ headSha: input.sessionRuntime.headSha,
735
+ ownershipBoundaries: input.repositoryGraph.semantic?.ownershipBoundaries || [],
736
+ contracts: input.repositoryGraph.semantic?.contracts || [],
737
+ invariants: input.repositoryGraph.semantic?.invariants || [],
738
+ runtimeBehaviorProfiles: input.repositoryGraph.semantic?.runtime.behaviorProfiles || [],
739
+ runtimeInteractions: input.repositoryGraph.semantic?.runtime.interactions || [],
740
+ deploymentBoundaries: input.repositoryGraph.semantic?.runtime.deploymentBoundaries || [],
741
+ acceptedBoundaries: {
742
+ approvedModules: [...input.intentPack.approvedScope.modules],
743
+ approvedServices: [...input.intentPack.approvedScope.services],
744
+ forbiddenBoundaries: input.intentPack.forbiddenBoundaries.map((item) => `${item.type}:${item.path}`),
745
+ },
746
+ lineage: {
747
+ previousSessionId: input.sessionRuntime.continuity.previousSessionId,
748
+ sessionLineage: [...input.sessionRuntime.continuity.lineage],
749
+ previousInvariantMemoryId: input.previousMemory?.invariantMemoryId || null,
750
+ },
751
+ historicalDriftPatterns: input.previousMemory?.historicalDriftPatterns || [],
752
+ recentObservationHashes: input.previousMemory?.recentObservationHashes || [],
753
+ };
754
+ const fingerprint = (0, intelligence_runtime_common_1.fingerprintValue)(payloadWithoutFingerprint);
755
+ return {
756
+ ...payloadWithoutFingerprint,
757
+ invariantMemoryId: `invariants-${fingerprint.slice(0, 16)}`,
758
+ fingerprint,
759
+ };
760
+ }
761
+ function recordDriftInInvariantMemory(projectRoot, sessionRuntime, invariantMemory, drift) {
762
+ if (!invariantMemory || !drift || (!drift.narratives.length && !drift.findings.length)) {
763
+ return invariantMemory;
764
+ }
765
+ const now = (0, intelligence_runtime_common_1.nowIso)();
766
+ const observationHash = (0, intelligence_runtime_common_1.fingerprintValue)({
767
+ sessionId: sessionRuntime.sessionId,
768
+ source: drift.source,
769
+ changedFiles: drift.changedFiles,
770
+ changedModules: drift.changedModules,
771
+ narrativeCategories: drift.narratives.map((entry) => entry.category),
772
+ findingCategories: drift.findings.map((entry) => entry.category),
773
+ summary: drift.riskSynthesis.summary,
774
+ });
775
+ if ((invariantMemory.recentObservationHashes || []).includes(observationHash)) {
776
+ return invariantMemory;
777
+ }
778
+ const nextPatterns = new Map((invariantMemory.historicalDriftPatterns || []).map((entry) => [entry.id, { ...entry }]));
779
+ const signals = drift.narratives.length > 0
780
+ ? drift.narratives.map((entry) => ({
781
+ category: entry.category,
782
+ summary: entry.summary,
783
+ severity: entry.severity,
784
+ }))
785
+ : drift.findings.map((entry) => ({
786
+ category: entry.category,
787
+ summary: entry.message,
788
+ severity: entry.severity,
789
+ }));
790
+ for (const signal of signals) {
791
+ const id = `pattern-${signal.category}`;
792
+ const current = nextPatterns.get(id);
793
+ nextPatterns.set(id, {
794
+ id,
795
+ category: signal.category,
796
+ count: (current?.count || 0) + 1,
797
+ lastObservedAt: now,
798
+ latestSummary: signal.summary,
799
+ latestSeverity: signal.severity,
800
+ });
801
+ }
802
+ const payloadWithoutFingerprint = {
803
+ ...invariantMemory,
804
+ updatedAt: now,
805
+ historicalDriftPatterns: Array.from(nextPatterns.values()).sort((left, right) => left.category.localeCompare(right.category)),
806
+ recentObservationHashes: [
807
+ ...(invariantMemory.recentObservationHashes || []),
808
+ observationHash,
809
+ ].slice(-24),
810
+ };
811
+ const next = {
812
+ ...payloadWithoutFingerprint,
813
+ fingerprint: (0, intelligence_runtime_common_1.fingerprintValue)({
814
+ ...payloadWithoutFingerprint,
815
+ fingerprint: undefined,
816
+ }),
817
+ };
818
+ const activePath = sessionRuntime.artifactPaths.invariantMemory
819
+ || (0, path_1.join)(projectRoot, '.neurcode', intelligence_runtime_common_1.ACTIVE_INVARIANT_MEMORY_FILENAME);
820
+ (0, intelligence_runtime_common_1.writeJsonFile)(activePath, next);
821
+ const sessionSnapshotPath = (0, path_1.join)((0, intelligence_runtime_common_1.ensureSessionsDir)(projectRoot), sessionRuntime.sessionId, intelligence_runtime_common_1.ACTIVE_INVARIANT_MEMORY_FILENAME);
822
+ (0, intelligence_runtime_common_1.writeJsonFile)(sessionSnapshotPath, next);
823
+ return next;
824
+ }
825
+ //# sourceMappingURL=semantic-contract-intelligence.js.map