@topogram/cli 0.3.34

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 (257) hide show
  1. package/ARCHITECTURE.md +67 -0
  2. package/CHANGELOG.md +240 -0
  3. package/README.md +223 -0
  4. package/package.json +51 -0
  5. package/src/adoption/index.js +3 -0
  6. package/src/adoption/plan.js +702 -0
  7. package/src/adoption/reporting.js +464 -0
  8. package/src/adoption/review-groups.js +313 -0
  9. package/src/agent-ops/query-builders.js +5012 -0
  10. package/src/archive/archive.js +141 -0
  11. package/src/archive/compact.js +26 -0
  12. package/src/archive/jsonl.js +70 -0
  13. package/src/archive/resolver-bridge.js +82 -0
  14. package/src/archive/schema.js +87 -0
  15. package/src/archive/unarchive.js +108 -0
  16. package/src/catalog.js +752 -0
  17. package/src/cli/catalog-alias.js +166 -0
  18. package/src/cli.js +9738 -0
  19. package/src/component-behavior.js +173 -0
  20. package/src/example-implementation.js +91 -0
  21. package/src/format.js +19 -0
  22. package/src/generator/adapters.d.ts +4 -0
  23. package/src/generator/adapters.js +325 -0
  24. package/src/generator/api.d.ts +1 -0
  25. package/src/generator/api.js +1196 -0
  26. package/src/generator/check.js +355 -0
  27. package/src/generator/component-conformance.js +767 -0
  28. package/src/generator/components.js +39 -0
  29. package/src/generator/context/bundle.js +291 -0
  30. package/src/generator/context/diff.js +256 -0
  31. package/src/generator/context/digest.js +182 -0
  32. package/src/generator/context/domain-coverage.js +94 -0
  33. package/src/generator/context/domain-page.js +137 -0
  34. package/src/generator/context/index.js +42 -0
  35. package/src/generator/context/report.js +121 -0
  36. package/src/generator/context/shared.js +1397 -0
  37. package/src/generator/context/slice.js +703 -0
  38. package/src/generator/context/task-mode.js +466 -0
  39. package/src/generator/docs.js +327 -0
  40. package/src/generator/index.js +161 -0
  41. package/src/generator/native/parity-bundle.js +311 -0
  42. package/src/generator/output.js +300 -0
  43. package/src/generator/registry.js +482 -0
  44. package/src/generator/runtime/app-bundle.js +456 -0
  45. package/src/generator/runtime/bundle-shared.js +166 -0
  46. package/src/generator/runtime/compile-check.js +163 -0
  47. package/src/generator/runtime/deployment.js +287 -0
  48. package/src/generator/runtime/environment.js +635 -0
  49. package/src/generator/runtime/index.js +32 -0
  50. package/src/generator/runtime/runtime-check.js +554 -0
  51. package/src/generator/runtime/shared.js +515 -0
  52. package/src/generator/runtime/smoke.js +219 -0
  53. package/src/generator/schema.js +204 -0
  54. package/src/generator/sdlc/board.js +66 -0
  55. package/src/generator/sdlc/doc-page.js +53 -0
  56. package/src/generator/sdlc/index.js +23 -0
  57. package/src/generator/sdlc/release-notes.js +62 -0
  58. package/src/generator/sdlc/traceability-matrix.js +65 -0
  59. package/src/generator/shared.js +29 -0
  60. package/src/generator/surfaces/contracts.js +146 -0
  61. package/src/generator/surfaces/databases/contract.js +40 -0
  62. package/src/generator/surfaces/databases/index.js +84 -0
  63. package/src/generator/surfaces/databases/lifecycle-shared.d.ts +1 -0
  64. package/src/generator/surfaces/databases/lifecycle-shared.js +612 -0
  65. package/src/generator/surfaces/databases/migration-plan.js +281 -0
  66. package/src/generator/surfaces/databases/postgres/capabilities.js +14 -0
  67. package/src/generator/surfaces/databases/postgres/drizzle.js +99 -0
  68. package/src/generator/surfaces/databases/postgres/index.js +9 -0
  69. package/src/generator/surfaces/databases/postgres/lifecycle.js +16 -0
  70. package/src/generator/surfaces/databases/postgres/prisma.js +159 -0
  71. package/src/generator/surfaces/databases/postgres/sql-migration.js +102 -0
  72. package/src/generator/surfaces/databases/postgres/sql-schema.js +34 -0
  73. package/src/generator/surfaces/databases/shared.d.ts +1 -0
  74. package/src/generator/surfaces/databases/shared.js +350 -0
  75. package/src/generator/surfaces/databases/snapshot.js +96 -0
  76. package/src/generator/surfaces/databases/sqlite/capabilities.js +14 -0
  77. package/src/generator/surfaces/databases/sqlite/index.js +8 -0
  78. package/src/generator/surfaces/databases/sqlite/lifecycle.js +16 -0
  79. package/src/generator/surfaces/databases/sqlite/prisma.js +143 -0
  80. package/src/generator/surfaces/databases/sqlite/sql-migration.js +65 -0
  81. package/src/generator/surfaces/databases/sqlite/sql-schema.js +27 -0
  82. package/src/generator/surfaces/index.js +25 -0
  83. package/src/generator/surfaces/native/swiftui-app.js +38 -0
  84. package/src/generator/surfaces/native/swiftui-templates/Package.swift.txt +20 -0
  85. package/src/generator/surfaces/native/swiftui-templates/README.generated.md +26 -0
  86. package/src/generator/surfaces/native/swiftui-templates/runtime/DynamicScreens.swift +682 -0
  87. package/src/generator/surfaces/native/swiftui-templates/runtime/TodoAPIClient.swift +156 -0
  88. package/src/generator/surfaces/native/swiftui-templates/runtime/TodoSwiftUIApp.swift +44 -0
  89. package/src/generator/surfaces/native/swiftui-templates/runtime/Visibility.swift +183 -0
  90. package/src/generator/surfaces/services/express.d.ts +1 -0
  91. package/src/generator/surfaces/services/express.js +766 -0
  92. package/src/generator/surfaces/services/hono.d.ts +1 -0
  93. package/src/generator/surfaces/services/hono.js +204 -0
  94. package/src/generator/surfaces/services/index.js +42 -0
  95. package/src/generator/surfaces/services/persistence-wiring.js +240 -0
  96. package/src/generator/surfaces/services/runtime-helpers.js +631 -0
  97. package/src/generator/surfaces/services/server-contract.js +80 -0
  98. package/src/generator/surfaces/services/stateless.d.ts +1 -0
  99. package/src/generator/surfaces/services/stateless.js +97 -0
  100. package/src/generator/surfaces/shared.js +64 -0
  101. package/src/generator/surfaces/web/api-client.js +1 -0
  102. package/src/generator/surfaces/web/forms.js +1 -0
  103. package/src/generator/surfaces/web/index.d.ts +2 -0
  104. package/src/generator/surfaces/web/index.js +53 -0
  105. package/src/generator/surfaces/web/react-components.js +248 -0
  106. package/src/generator/surfaces/web/react.js +538 -0
  107. package/src/generator/surfaces/web/routes.js +1 -0
  108. package/src/generator/surfaces/web/screens.js +1 -0
  109. package/src/generator/surfaces/web/shared.js +369 -0
  110. package/src/generator/surfaces/web/sveltekit-actions.js +28 -0
  111. package/src/generator/surfaces/web/sveltekit-components.js +234 -0
  112. package/src/generator/surfaces/web/sveltekit.js +426 -0
  113. package/src/generator/surfaces/web/ui-web-contract.js +65 -0
  114. package/src/generator/surfaces/web/vanilla.js +239 -0
  115. package/src/generator/verification.js +84 -0
  116. package/src/generator.js +1 -0
  117. package/src/import/core/context.js +52 -0
  118. package/src/import/core/contracts.js +23 -0
  119. package/src/import/core/registry.js +81 -0
  120. package/src/import/core/runner.js +646 -0
  121. package/src/import/core/shared.js +910 -0
  122. package/src/import/enrichers/auth-session.js +18 -0
  123. package/src/import/enrichers/django-rest.js +226 -0
  124. package/src/import/enrichers/doc-linking.js +20 -0
  125. package/src/import/enrichers/rails-controllers.js +246 -0
  126. package/src/import/enrichers/rails-models.js +130 -0
  127. package/src/import/enrichers/workflow-target-state.js +10 -0
  128. package/src/import/extractors/api/aspnet-core.js +304 -0
  129. package/src/import/extractors/api/django-routes.js +318 -0
  130. package/src/import/extractors/api/express.js +154 -0
  131. package/src/import/extractors/api/fastify.js +371 -0
  132. package/src/import/extractors/api/flutter-dio.js +135 -0
  133. package/src/import/extractors/api/generic-route-fallback.js +90 -0
  134. package/src/import/extractors/api/graphql-code-first.js +565 -0
  135. package/src/import/extractors/api/graphql-sdl.js +309 -0
  136. package/src/import/extractors/api/jaxrs.js +303 -0
  137. package/src/import/extractors/api/micronaut.js +213 -0
  138. package/src/import/extractors/api/next-route.js +50 -0
  139. package/src/import/extractors/api/next-server-action.js +51 -0
  140. package/src/import/extractors/api/nextauth.js +52 -0
  141. package/src/import/extractors/api/openapi-code.js +242 -0
  142. package/src/import/extractors/api/openapi.js +232 -0
  143. package/src/import/extractors/api/rails-routes.js +230 -0
  144. package/src/import/extractors/api/react-native-repository.js +128 -0
  145. package/src/import/extractors/api/retrofit.js +103 -0
  146. package/src/import/extractors/api/spring-web.js +372 -0
  147. package/src/import/extractors/api/swift-webapi.js +116 -0
  148. package/src/import/extractors/api/trpc.js +212 -0
  149. package/src/import/extractors/db/django-models.js +232 -0
  150. package/src/import/extractors/db/dotnet-models.js +93 -0
  151. package/src/import/extractors/db/drizzle.js +242 -0
  152. package/src/import/extractors/db/ef-core.js +221 -0
  153. package/src/import/extractors/db/flutter-entities.js +120 -0
  154. package/src/import/extractors/db/jpa.js +120 -0
  155. package/src/import/extractors/db/liquibase.js +180 -0
  156. package/src/import/extractors/db/mybatis-xml.js +145 -0
  157. package/src/import/extractors/db/prisma.js +185 -0
  158. package/src/import/extractors/db/rails-schema.js +175 -0
  159. package/src/import/extractors/db/react-native-entities.js +95 -0
  160. package/src/import/extractors/db/room.js +193 -0
  161. package/src/import/extractors/db/snapshot.js +112 -0
  162. package/src/import/extractors/db/sql.js +180 -0
  163. package/src/import/extractors/db/swiftdata.js +137 -0
  164. package/src/import/extractors/ui/android-compose.js +230 -0
  165. package/src/import/extractors/ui/backend-only.js +70 -0
  166. package/src/import/extractors/ui/blazor.js +227 -0
  167. package/src/import/extractors/ui/flutter-screens.js +152 -0
  168. package/src/import/extractors/ui/maui-xaml.js +135 -0
  169. package/src/import/extractors/ui/next-app-router.js +83 -0
  170. package/src/import/extractors/ui/next-pages-router.js +141 -0
  171. package/src/import/extractors/ui/razor-pages.js +181 -0
  172. package/src/import/extractors/ui/react-native-screens.js +166 -0
  173. package/src/import/extractors/ui/react-router.js +139 -0
  174. package/src/import/extractors/ui/sveltekit.js +123 -0
  175. package/src/import/extractors/ui/swiftui.js +193 -0
  176. package/src/import/extractors/ui/uikit.js +175 -0
  177. package/src/import/extractors/verification/generic.js +290 -0
  178. package/src/import/extractors/workflows/generic.js +137 -0
  179. package/src/import/index.js +7 -0
  180. package/src/import/provenance.js +158 -0
  181. package/src/new-project.js +2107 -0
  182. package/src/parser.js +439 -0
  183. package/src/policy/review-boundaries.js +165 -0
  184. package/src/project-config.js +535 -0
  185. package/src/proofs/backend-parity.js +19 -0
  186. package/src/proofs/contract-audit.js +220 -0
  187. package/src/proofs/ios-parity.js +7 -0
  188. package/src/proofs/issues-parity.js +10 -0
  189. package/src/proofs/web-parity.js +50 -0
  190. package/src/realization/api/build-api-realization.js +5 -0
  191. package/src/realization/api/index.js +1 -0
  192. package/src/realization/backend/build-backend-runtime-realization.js +82 -0
  193. package/src/realization/backend/index.d.ts +1 -0
  194. package/src/realization/backend/index.js +4 -0
  195. package/src/realization/db/build-db-realization.js +17 -0
  196. package/src/realization/db/index.js +3 -0
  197. package/src/realization/db/migration-plan.js +5 -0
  198. package/src/realization/db/snapshot.js +5 -0
  199. package/src/realization/ui/build-ui-shared-realization.js +305 -0
  200. package/src/realization/ui/build-web-realization.js +189 -0
  201. package/src/realization/ui/index.js +2 -0
  202. package/src/reconcile/docs.js +280 -0
  203. package/src/reconcile/index.js +3 -0
  204. package/src/reconcile/journeys.js +441 -0
  205. package/src/resolver/docs.js +1 -0
  206. package/src/resolver/enrich/acceptance-criterion.js +14 -0
  207. package/src/resolver/enrich/bug.js +12 -0
  208. package/src/resolver/enrich/component.js +2 -0
  209. package/src/resolver/enrich/index.js +1 -0
  210. package/src/resolver/enrich/pitch.js +18 -0
  211. package/src/resolver/enrich/requirement.js +20 -0
  212. package/src/resolver/enrich/task.js +16 -0
  213. package/src/resolver/expressions.js +1 -0
  214. package/src/resolver/index.js +2422 -0
  215. package/src/resolver/normalize.js +1 -0
  216. package/src/resolver.js +1 -0
  217. package/src/sdlc/adopt.js +65 -0
  218. package/src/sdlc/check.js +86 -0
  219. package/src/sdlc/dod/acceptance-criterion.js +22 -0
  220. package/src/sdlc/dod/bug.js +26 -0
  221. package/src/sdlc/dod/document.js +23 -0
  222. package/src/sdlc/dod/index.js +25 -0
  223. package/src/sdlc/dod/pitch.js +23 -0
  224. package/src/sdlc/dod/requirement.js +34 -0
  225. package/src/sdlc/dod/task.js +39 -0
  226. package/src/sdlc/explain.js +116 -0
  227. package/src/sdlc/history.js +80 -0
  228. package/src/sdlc/paths.js +11 -0
  229. package/src/sdlc/release.js +106 -0
  230. package/src/sdlc/scaffold.js +89 -0
  231. package/src/sdlc/status-filter.js +54 -0
  232. package/src/sdlc/transition.js +112 -0
  233. package/src/sdlc/transitions/acceptance-criterion.js +28 -0
  234. package/src/sdlc/transitions/bug.js +31 -0
  235. package/src/sdlc/transitions/document.js +29 -0
  236. package/src/sdlc/transitions/index.js +56 -0
  237. package/src/sdlc/transitions/pitch.js +34 -0
  238. package/src/sdlc/transitions/requirement.js +31 -0
  239. package/src/sdlc/transitions/task.js +34 -0
  240. package/src/template-trust.js +597 -0
  241. package/src/validator/expressions.js +1 -0
  242. package/src/validator/index.js +3424 -0
  243. package/src/validator/kinds.js +346 -0
  244. package/src/validator/per-kind/acceptance-criterion.js +91 -0
  245. package/src/validator/per-kind/bug.js +77 -0
  246. package/src/validator/per-kind/component.js +274 -0
  247. package/src/validator/per-kind/domain.js +205 -0
  248. package/src/validator/per-kind/pitch.js +101 -0
  249. package/src/validator/per-kind/requirement.js +75 -0
  250. package/src/validator/per-kind/task.js +96 -0
  251. package/src/validator/registry.js +1 -0
  252. package/src/validator/utils.js +12 -0
  253. package/src/validator.js +1 -0
  254. package/src/workflows.js +7597 -0
  255. package/src/workspace-docs.js +265 -0
  256. package/template-helpers/react.js +5 -0
  257. package/template-helpers/sveltekit.js +5 -0
@@ -0,0 +1,702 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ ADOPTION_STATE_VOCABULARY,
6
+ reviewBoundaryForImportProposal
7
+ } from "../policy/review-boundaries.js";
8
+
9
+ const ADOPT_SELECTORS = new Set(["from-plan", "actors", "roles", "enums", "shapes", "entities", "capabilities", "docs", "journeys", "workflows", "verification", "ui"]);
10
+
11
+ function stableSortedStrings(values) {
12
+ return [...new Set((values || []).filter(Boolean))].sort();
13
+ }
14
+
15
+ function severityRank(status) {
16
+ if (status === "no_go") return 3;
17
+ if (status === "manual_decision") return 2;
18
+ if (status === "review_required") return 1;
19
+ return 0;
20
+ }
21
+
22
+ function importProposalDependencyIds(proposalSurface = {}) {
23
+ return stableSortedStrings([
24
+ proposalSurface.item,
25
+ ...(proposalSurface.requirements?.related_capabilities || []),
26
+ ...(proposalSurface.requirements?.related_rules || []),
27
+ ...(proposalSurface.requirements?.related_workflows || []),
28
+ ...(proposalSurface.requirements?.related_docs || []),
29
+ ...((proposalSurface.projection_impacts || []).map((impact) => impact.projection_id)),
30
+ ...((proposalSurface.ui_impacts || []).map((impact) => impact.projection_id)),
31
+ ...((proposalSurface.workflow_impacts || []).map((impact) => impact.id))
32
+ ]);
33
+ }
34
+
35
+ function normalizePath(input) {
36
+ return String(input || "")
37
+ .replaceAll("\\", "/")
38
+ .replace(/^\.\//, "")
39
+ .replace(/\/+/g, "/");
40
+ }
41
+
42
+ function trimGlobSuffix(pathValue) {
43
+ return normalizePath(pathValue).replace(/\/\*\*$/, "").replace(/\/\*$/, "");
44
+ }
45
+
46
+ function pathPrefixMatches(filePath, rootPath) {
47
+ if (!filePath || !rootPath) return false;
48
+ const normalizedFile = normalizePath(filePath);
49
+ const normalizedRoot = trimGlobSuffix(rootPath);
50
+ return normalizedRoot.length > 0 && normalizedFile.startsWith(normalizedRoot);
51
+ }
52
+
53
+ function pathTokens(pathValue) {
54
+ const normalized = normalizePath(pathValue).replace(/\.[^.\/]+$/, "");
55
+ const camelExpanded = normalized.replace(/([a-z0-9])([A-Z])/g, "$1 $2");
56
+ const tokens = camelExpanded
57
+ .toLowerCase()
58
+ .split(/[^a-z0-9]+/)
59
+ .filter((token) =>
60
+ token.length > 1 &&
61
+ !["app", "src", "docs", "model", "bundles", "candidates", "topogram", "cap", "tg", "md"].includes(token)
62
+ );
63
+
64
+ return stableSortedStrings(tokens.flatMap((token) => {
65
+ const variants = [token];
66
+ if (token.endsWith("ies") && token.length > 4) {
67
+ variants.push(`${token.slice(0, -3)}y`);
68
+ } else if (token.endsWith("s") && token.length > 3) {
69
+ variants.push(token.slice(0, -1));
70
+ }
71
+ return variants;
72
+ }));
73
+ }
74
+
75
+ function sharedTokens(left, right) {
76
+ const rightSet = new Set(right || []);
77
+ return stableSortedStrings((left || []).filter((token) => rightSet.has(token)));
78
+ }
79
+
80
+ function semanticEvidenceForProposal(proposalSurface, seam) {
81
+ const dependencyIds = importProposalDependencyIds(proposalSurface);
82
+ const seamDependencies = stableSortedStrings(seam.emitted_dependencies || []);
83
+ const matchedDependencies = seamDependencies.filter((dependency) => dependencyIds.includes(dependency));
84
+
85
+ if (matchedDependencies.length === 0) {
86
+ return {
87
+ matched_dependencies: [],
88
+ score: 0,
89
+ reasons: []
90
+ };
91
+ }
92
+
93
+ const specificity = matchedDependencies.length / Math.max(
94
+ matchedDependencies.length,
95
+ seamDependencies.length || 1,
96
+ dependencyIds.length || 1
97
+ );
98
+ const score = 0.22 + Math.min(0.16, matchedDependencies.length * 0.08) + Math.min(0.2, specificity * 0.24) + (matchedDependencies.length >= 2 ? 0.04 : 0);
99
+ return {
100
+ matched_dependencies: matchedDependencies,
101
+ score,
102
+ reasons: [
103
+ `semantic overlap: ${matchedDependencies.map((dependency) => `\`${dependency}\``).join(", ")}`
104
+ ]
105
+ };
106
+ }
107
+
108
+ function pathEvidenceForProposal(proposalSurface, seam) {
109
+ const proposalPaths = stableSortedStrings([
110
+ proposalSurface.source_path,
111
+ proposalSurface.canonical_rel_path
112
+ ]);
113
+ const proposalTokenSet = stableSortedStrings(proposalPaths.flatMap((candidatePath) => pathTokens(candidatePath)));
114
+ const maintainedModules = stableSortedStrings(seam.maintained_modules || []);
115
+
116
+ let exactModuleMatches = [];
117
+ let prefixModuleMatches = [];
118
+ let tokenMatchedModules = [];
119
+ let tokenMatchCount = 0;
120
+
121
+ for (const modulePath of maintainedModules) {
122
+ const moduleTokens = pathTokens(modulePath);
123
+ const matchedTokens = sharedTokens(proposalTokenSet, moduleTokens);
124
+ if (proposalPaths.some((candidatePath) => normalizePath(candidatePath) === normalizePath(modulePath))) {
125
+ exactModuleMatches.push(modulePath);
126
+ continue;
127
+ }
128
+ if (proposalPaths.some((candidatePath) =>
129
+ pathPrefixMatches(candidatePath, modulePath) || pathPrefixMatches(modulePath, candidatePath)
130
+ )) {
131
+ prefixModuleMatches.push(modulePath);
132
+ }
133
+ if (matchedTokens.length > 0) {
134
+ tokenMatchedModules.push({ modulePath, matchedTokens });
135
+ tokenMatchCount = Math.max(tokenMatchCount, matchedTokens.length);
136
+ }
137
+ }
138
+
139
+ const reasons = [];
140
+ let score = 0;
141
+
142
+ if (exactModuleMatches.length > 0) {
143
+ score += 0.28;
144
+ reasons.push(
145
+ `exact maintained module match: ${stableSortedStrings(exactModuleMatches).map((modulePath) => `\`${modulePath}\``).join(", ")}`
146
+ );
147
+ }
148
+ if (prefixModuleMatches.length > 0) {
149
+ score += 0.18;
150
+ reasons.push(
151
+ `maintained module path proximity: ${stableSortedStrings(prefixModuleMatches).map((modulePath) => `\`${modulePath}\``).join(", ")}`
152
+ );
153
+ }
154
+ if (tokenMatchCount > 0) {
155
+ score += Math.min(0.18, 0.08 + (tokenMatchCount * 0.04));
156
+ reasons.push(
157
+ `path token corroboration: ${stableSortedStrings(tokenMatchedModules.flatMap((entry) => entry.matchedTokens)).map((token) => `\`${token}\``).join(", ")}`
158
+ );
159
+ }
160
+
161
+ return {
162
+ score,
163
+ reasons,
164
+ token_match_count: tokenMatchCount
165
+ };
166
+ }
167
+
168
+ function outputEvidenceForProposal(proposalSurface, seam, outputRecord = null) {
169
+ const proposalPaths = stableSortedStrings([
170
+ proposalSurface.source_path,
171
+ proposalSurface.canonical_rel_path
172
+ ]);
173
+ const proposalTokenSet = stableSortedStrings(proposalPaths.flatMap((candidatePath) => pathTokens(candidatePath)));
174
+ const matchedOutputRoots = stableSortedStrings((outputRecord?.root_paths || []).filter((rootPath) =>
175
+ proposalPaths.some((candidatePath) => pathPrefixMatches(candidatePath, rootPath))
176
+ ));
177
+ const outputTokenMatches = stableSortedStrings((outputRecord?.root_paths || []).flatMap((rootPath) =>
178
+ sharedTokens(proposalTokenSet, pathTokens(rootPath))
179
+ ));
180
+
181
+ let score = 0;
182
+ const reasons = [];
183
+
184
+ if (matchedOutputRoots.length > 0) {
185
+ score += 0.16;
186
+ reasons.push(
187
+ `output root alignment: ${matchedOutputRoots.map((rootPath) => `\`${rootPath}\``).join(", ")}`
188
+ );
189
+ } else if (outputTokenMatches.length > 0) {
190
+ score += Math.min(0.1, 0.04 + (outputTokenMatches.length * 0.02));
191
+ reasons.push(
192
+ `output path corroboration: ${outputTokenMatches.map((token) => `\`${token}\``).join(", ")}`
193
+ );
194
+ }
195
+
196
+ const proposalTrack = proposalSurface.track || null;
197
+ const proposalKind = proposalSurface.kind || null;
198
+ const seamKind = seam.kind || null;
199
+ const kindAligned =
200
+ ((proposalTrack === "ui" || proposalKind === "ui") && ["ui_presenter", "route_glue", "workflow_affordance"].includes(seamKind)) ||
201
+ ((proposalTrack === "model" || proposalTrack === "capability" || proposalKind === "capability") && ["api_adapter", "route_glue", "policy_interpretation", "workflow_affordance"].includes(seamKind)) ||
202
+ ((proposalTrack === "workflows" || proposalKind === "decision") && seamKind === "workflow_affordance");
203
+
204
+ if (kindAligned) {
205
+ score += 0.08;
206
+ reasons.push(`proposal/seam kind alignment: \`${proposalTrack || proposalKind}\` -> \`${seamKind}\``);
207
+ }
208
+
209
+ return {
210
+ score,
211
+ reasons
212
+ };
213
+ }
214
+
215
+ function dedupeReasons(reasons = []) {
216
+ return stableSortedStrings(reasons);
217
+ }
218
+
219
+ function inferMaintainedSeamCandidates(proposalSurface, maintainedBoundaryArtifact = null) {
220
+ if (!maintainedBoundaryArtifact || !Array.isArray(maintainedBoundaryArtifact.seams) || maintainedBoundaryArtifact.seams.length === 0) {
221
+ return [];
222
+ }
223
+
224
+ const outputsById = new Map((maintainedBoundaryArtifact.outputs || []).map((output) => [output.output_id, output]));
225
+
226
+ const provisionalCandidates = maintainedBoundaryArtifact.seams.map((seam) => {
227
+ const outputRecord = outputsById.get(seam.output_id) || null;
228
+ const semanticEvidence = semanticEvidenceForProposal(proposalSurface, seam);
229
+ const pathEvidence = pathEvidenceForProposal(proposalSurface, seam);
230
+ const outputEvidence = outputEvidenceForProposal(proposalSurface, seam, outputRecord);
231
+ const rawScore = semanticEvidence.score + pathEvidence.score + outputEvidence.score;
232
+
233
+ return {
234
+ seam,
235
+ rawScore,
236
+ semantic_match_count: semanticEvidence.matched_dependencies.length,
237
+ seam_id: seam.seam_id,
238
+ output_id: seam.output_id || null,
239
+ label: seam.label || null,
240
+ kind: seam.kind || null,
241
+ ownership_class: seam.ownership_class || null,
242
+ status: seam.status || null,
243
+ maintained_modules: stableSortedStrings(seam.maintained_modules || []),
244
+ emitted_dependencies: stableSortedStrings(seam.emitted_dependencies || []),
245
+ allowed_change_classes: stableSortedStrings(seam.allowed_change_classes || []),
246
+ drift_signals: stableSortedStrings(seam.drift_signals || []),
247
+ match_reasons: dedupeReasons([
248
+ ...semanticEvidence.reasons,
249
+ ...pathEvidence.reasons,
250
+ ...outputEvidence.reasons
251
+ ]),
252
+ confidence: Math.min(1, Number(rawScore.toFixed(2)))
253
+ };
254
+ });
255
+
256
+ const candidates = provisionalCandidates
257
+ .map((candidate) => {
258
+ const siblingCandidates = provisionalCandidates.filter((entry) =>
259
+ entry.output_id &&
260
+ entry.output_id === candidate.output_id &&
261
+ entry.seam_id !== candidate.seam_id
262
+ );
263
+ const ambiguousSibling = siblingCandidates.find((sibling) =>
264
+ sibling.rawScore >= 0.48 &&
265
+ Math.abs(sibling.rawScore - candidate.rawScore) <= 0.12 &&
266
+ Math.max(candidate.semantic_match_count, sibling.semantic_match_count) <= 1
267
+ );
268
+ const penalty = ambiguousSibling ? 0.18 : 0;
269
+
270
+ return {
271
+ ...candidate,
272
+ match_reasons: ambiguousSibling
273
+ ? [...candidate.match_reasons, `ambiguity penalty: sibling seam evidence in \`${candidate.output_id}\` is too similar`]
274
+ : candidate.match_reasons,
275
+ confidence: Math.max(0, Number((candidate.rawScore - penalty).toFixed(2)))
276
+ };
277
+ })
278
+ .filter((candidate) => candidate.confidence >= 0.6 && candidate.match_reasons.length > 0)
279
+ .sort((a, b) => {
280
+ const severityCompare = severityRank(b.status) - severityRank(a.status);
281
+ if (severityCompare !== 0) return severityCompare;
282
+ if (b.confidence !== a.confidence) return b.confidence - a.confidence;
283
+ return String(a.seam_id || "").localeCompare(String(b.seam_id || ""));
284
+ });
285
+
286
+ return candidates.map(({ seam, rawScore, semantic_match_count, ...candidate }) => candidate);
287
+ }
288
+
289
+ export function selectorReviewGroupId(selector) {
290
+ if (!selector) {
291
+ return null;
292
+ }
293
+ if (selector.startsWith("projection-review:")) {
294
+ return `projection_review:${selector.slice("projection-review:".length)}`;
295
+ }
296
+ if (selector.startsWith("ui-review:")) {
297
+ return `ui_review:${selector.slice("ui-review:".length)}`;
298
+ }
299
+ if (selector.startsWith("workflow-review:")) {
300
+ return `workflow_review:${selector.slice("workflow-review:".length)}`;
301
+ }
302
+ return null;
303
+ }
304
+
305
+ export function selectorBundleReviewSlug(selector) {
306
+ if (!selector) {
307
+ return null;
308
+ }
309
+ if (selector.startsWith("bundle-review:")) {
310
+ const slug = selector.slice("bundle-review:".length);
311
+ return slug || null;
312
+ }
313
+ return null;
314
+ }
315
+
316
+ export function parseAdoptSelector(value) {
317
+ if (!value) {
318
+ return null;
319
+ }
320
+ const selector = String(value).trim();
321
+ if (ADOPT_SELECTORS.has(selector)) {
322
+ return selector;
323
+ }
324
+ if (selectorReviewGroupId(selector)) {
325
+ return selector;
326
+ }
327
+ if (selectorBundleReviewSlug(selector)) {
328
+ return selector;
329
+ }
330
+ if (selector.startsWith("bundle:") && selector.length > "bundle:".length) {
331
+ return selector;
332
+ }
333
+ throw new Error(`Unsupported adopt selector '${selector}'`);
334
+ }
335
+
336
+ export function adoptionItemKey(item) {
337
+ return `${item.bundle}:${item.kind}:${item.item}`;
338
+ }
339
+
340
+ export function selectorMatchesItem(selector, item) {
341
+ if (!selector) {
342
+ return false;
343
+ }
344
+ const reviewGroupId = selectorReviewGroupId(selector);
345
+ const bundleReviewSlug = selectorBundleReviewSlug(selector);
346
+ if (reviewGroupId) {
347
+ return (item.blocking_dependencies || []).some((dependency) => dependency.id === reviewGroupId);
348
+ }
349
+ if (bundleReviewSlug) {
350
+ return item.bundle === bundleReviewSlug;
351
+ }
352
+ if (selector === "actors") return item.kind === "actor";
353
+ if (selector === "roles") return item.kind === "role";
354
+ if (selector === "enums") return item.kind === "enum";
355
+ if (selector === "shapes") return item.kind === "shape";
356
+ if (selector === "entities") return item.kind === "entity";
357
+ if (selector === "capabilities") return item.kind === "capability";
358
+ if (selector === "docs") return item.track === "docs";
359
+ if (selector === "journeys") return item.track === "docs" && String(item.canonical_rel_path || "").startsWith("docs/journeys/");
360
+ if (selector === "workflows") return item.track === "workflows" || item.kind === "decision";
361
+ if (selector === "verification") return item.kind === "verification";
362
+ if (selector === "ui") return item.track === "ui";
363
+ if (selector.startsWith("bundle:")) return item.bundle === selector.slice("bundle:".length);
364
+ return false;
365
+ }
366
+
367
+ function blockedStatusForItem(item) {
368
+ if ((item.projection_impacts || []).length > 0) {
369
+ return "needs_projection_review";
370
+ }
371
+ if ((item.blocking_dependencies || []).some((dependency) => dependency.type === "projection_review")) {
372
+ return "needs_projection_review";
373
+ }
374
+ if ((item.ui_impacts || []).length > 0) {
375
+ return "needs_ui_review";
376
+ }
377
+ if ((item.blocking_dependencies || []).some((dependency) => dependency.type === "ui_review")) {
378
+ return "needs_ui_review";
379
+ }
380
+ if ((item.workflow_impacts || []).length > 0) {
381
+ return "needs_workflow_review";
382
+ }
383
+ if ((item.blocking_dependencies || []).some((dependency) => dependency.type === "workflow_review")) {
384
+ return "needs_workflow_review";
385
+ }
386
+ return "pending";
387
+ }
388
+
389
+ export function refreshDerivedStatuses(items, approvedReviewGroups = []) {
390
+ const approvedSet = new Set(approvedReviewGroups || []);
391
+ return items.map((item) => {
392
+ if (item.status === "applied" || item.status === "skipped" || item.status === "approved") {
393
+ return item;
394
+ }
395
+ const blockingDependencies = item.blocking_dependencies || [];
396
+ if (blockingDependencies.length === 0) {
397
+ return { ...item, status: item.status === "pending" ? "pending" : blockedStatusForItem(item) };
398
+ }
399
+ const fullyApproved = blockingDependencies.every((dependency) => approvedSet.has(dependency.id));
400
+ return {
401
+ ...item,
402
+ status: fullyApproved ? "approved" : blockedStatusForItem(item)
403
+ };
404
+ });
405
+ }
406
+
407
+ export function mergeAdoptionPlanState(baseItems, existingPlan, topogramRoot) {
408
+ const existingItems = new Map(
409
+ (existingPlan?.items || []).map((item) => [`${item.bundle}:${item.kind}:${item.item}`, item])
410
+ );
411
+ const merged = baseItems.map((item) => {
412
+ const existing = existingItems.get(`${item.bundle}:${item.kind}:${item.item}`);
413
+ const mergedItem = existing ? { ...item, status: existing.status || item.status } : item;
414
+ if (
415
+ mergedItem.status !== "applied" &&
416
+ mergedItem.status !== "skipped" &&
417
+ mergedItem.suggested_action !== "apply_doc_link_patch" &&
418
+ mergedItem.suggested_action !== "apply_doc_metadata_patch" &&
419
+ mergedItem.suggested_action !== "apply_projection_permission_patch" &&
420
+ mergedItem.suggested_action !== "apply_projection_auth_patch" &&
421
+ mergedItem.suggested_action !== "apply_projection_ownership_patch" &&
422
+ mergedItem.canonical_rel_path &&
423
+ topogramRoot &&
424
+ fs.existsSync(path.join(topogramRoot, mergedItem.canonical_rel_path))
425
+ ) {
426
+ return { ...mergedItem, status: "applied" };
427
+ }
428
+ return mergedItem;
429
+ });
430
+ for (const existing of existingPlan?.items || []) {
431
+ const key = `${existing.bundle}:${existing.kind}:${existing.item}`;
432
+ if (!merged.some((item) => adoptionItemKey(item) === key) && existing.status === "applied") {
433
+ merged.push({ ...existing });
434
+ }
435
+ }
436
+ return refreshDerivedStatuses(merged, existingPlan?.approved_review_groups || []);
437
+ }
438
+
439
+ function reviewGroupIdsForBundle(items, bundleSlug) {
440
+ const ids = new Set();
441
+ for (const item of items) {
442
+ if (item.bundle !== bundleSlug) {
443
+ continue;
444
+ }
445
+ for (const dependency of item.blocking_dependencies || []) {
446
+ ids.add(dependency.id);
447
+ }
448
+ }
449
+ return [...ids].sort();
450
+ }
451
+
452
+ export function applyAdoptionSelector(adoptionPlan, selector, writeMode) {
453
+ const appliedItems = [];
454
+ const approvedItems = [];
455
+ const skippedItems = [];
456
+ const blockedItems = [];
457
+ const selectedItems = [];
458
+ const reviewGroupId = selectorReviewGroupId(selector);
459
+ const bundleReviewSlug = selectorBundleReviewSlug(selector);
460
+ const updatedPlan = {
461
+ ...adoptionPlan,
462
+ approved_review_groups: [...new Set(adoptionPlan.approved_review_groups || [])],
463
+ items: adoptionPlan.items.map((item) => ({ ...item }))
464
+ };
465
+ let updatedItems = updatedPlan.items;
466
+
467
+ const expandSelectedItemsForDependentShapes = (keys) => {
468
+ const expanded = new Set(keys);
469
+ const selectedCapabilityBundles = new Set(
470
+ [...expanded]
471
+ .map((key) => updatedItems.find((item) => adoptionItemKey(item) === key))
472
+ .filter((item) => item?.kind === "capability")
473
+ .map((item) => item.bundle)
474
+ );
475
+ for (const item of updatedItems) {
476
+ if (item.kind === "shape" && item.status !== "skipped" && selectedCapabilityBundles.has(item.bundle)) {
477
+ expanded.add(adoptionItemKey(item));
478
+ }
479
+ }
480
+ return [...expanded];
481
+ };
482
+
483
+ if (!selector) {
484
+ return { plan: updatedPlan, appliedItems, approvedItems, skippedItems, blockedItems, selectedItems };
485
+ }
486
+
487
+ if (reviewGroupId || bundleReviewSlug) {
488
+ const reviewGroupIds = reviewGroupId
489
+ ? [reviewGroupId]
490
+ : reviewGroupIdsForBundle(updatedItems, bundleReviewSlug);
491
+ for (const id of reviewGroupIds) {
492
+ if (!updatedPlan.approved_review_groups.includes(id)) {
493
+ updatedPlan.approved_review_groups.push(id);
494
+ }
495
+ }
496
+ updatedItems = refreshDerivedStatuses(updatedItems, updatedPlan.approved_review_groups);
497
+ updatedPlan.items = updatedItems;
498
+ for (const item of updatedItems) {
499
+ if (!selectorMatchesItem(selector, item)) {
500
+ continue;
501
+ }
502
+ if (item.status === "approved") {
503
+ approvedItems.push(item.item);
504
+ } else if (["needs_projection_review", "needs_ui_review", "needs_workflow_review"].includes(item.status)) {
505
+ blockedItems.push(item.item);
506
+ }
507
+ }
508
+ return { plan: updatedPlan, appliedItems, approvedItems, skippedItems, blockedItems, selectedItems };
509
+ }
510
+
511
+ if (selector === "from-plan") {
512
+ const initiallySelected = [];
513
+ for (const item of updatedItems) {
514
+ if (item.status === "approved" || item.status === "pending") {
515
+ initiallySelected.push(adoptionItemKey(item));
516
+ } else if (item.status === "skipped") {
517
+ skippedItems.push(item.item);
518
+ } else if (["needs_projection_review", "needs_ui_review", "needs_workflow_review"].includes(item.status)) {
519
+ blockedItems.push(item.item);
520
+ }
521
+ }
522
+ const expandedSelected = expandSelectedItemsForDependentShapes(initiallySelected);
523
+ for (const key of expandedSelected) {
524
+ const item = updatedItems.find((entry) => adoptionItemKey(entry) === key);
525
+ if (!item || item.status === "skipped") continue;
526
+ selectedItems.push(key);
527
+ appliedItems.push(item.item);
528
+ if (writeMode) {
529
+ item.status = "applied";
530
+ }
531
+ }
532
+ updatedPlan.items = updatedItems;
533
+ return { plan: updatedPlan, appliedItems, approvedItems, skippedItems, blockedItems, selectedItems };
534
+ }
535
+
536
+ const initiallySelected = [];
537
+ for (const item of updatedItems) {
538
+ if (item.status === "skipped") {
539
+ skippedItems.push(item.item);
540
+ continue;
541
+ }
542
+ if (["needs_projection_review", "needs_ui_review", "needs_workflow_review"].includes(item.status)) {
543
+ if (selectorMatchesItem(selector, item)) {
544
+ blockedItems.push(item.item);
545
+ }
546
+ continue;
547
+ }
548
+ if (selectorMatchesItem(selector, item)) {
549
+ initiallySelected.push(adoptionItemKey(item));
550
+ }
551
+ }
552
+ const expandedSelected = expandSelectedItemsForDependentShapes(initiallySelected);
553
+ for (const key of expandedSelected) {
554
+ const item = updatedItems.find((entry) => adoptionItemKey(entry) === key);
555
+ if (!item || item.status === "skipped") {
556
+ continue;
557
+ }
558
+ selectedItems.push(key);
559
+ appliedItems.push(item.item);
560
+ if (writeMode) {
561
+ item.status = "applied";
562
+ }
563
+ }
564
+ updatedPlan.items = updatedItems;
565
+ return { plan: updatedPlan, appliedItems, approvedItems, skippedItems, blockedItems, selectedItems };
566
+ }
567
+
568
+ export function summarizeAdoptionPlanItems(items) {
569
+ const summary = {
570
+ approved_items: [],
571
+ applied_items: [],
572
+ skipped_items: [],
573
+ blocked_items: []
574
+ };
575
+ for (const item of items || []) {
576
+ if (item.status === "approved") {
577
+ summary.approved_items.push(item.item);
578
+ } else if (item.status === "applied") {
579
+ summary.applied_items.push(item.item);
580
+ } else if (item.status === "skipped") {
581
+ summary.skipped_items.push(item.item);
582
+ } else if (["needs_projection_review", "needs_ui_review", "needs_workflow_review"].includes(item.status)) {
583
+ summary.blocked_items.push(item.item);
584
+ }
585
+ }
586
+ for (const key of Object.keys(summary)) {
587
+ summary[key] = [...new Set(summary[key])].sort();
588
+ }
589
+ return summary;
590
+ }
591
+
592
+ function inferRecommendedAdoptionState(item) {
593
+ if (item.status === "skipped") {
594
+ return "reject";
595
+ }
596
+ if (item.status === "applied") {
597
+ return "accept";
598
+ }
599
+ if ((item.projection_impacts || []).length > 0 || (item.ui_impacts || []).length > 0 || (item.workflow_impacts || []).length > 0) {
600
+ return "customize";
601
+ }
602
+ if (item.suggested_action && String(item.suggested_action).includes("_patch")) {
603
+ return "customize";
604
+ }
605
+ return "accept";
606
+ }
607
+
608
+ function inferCurrentAdoptionState(item) {
609
+ if (item.status === "skipped") {
610
+ return "reject";
611
+ }
612
+ if (item.status === "applied") {
613
+ return "accept";
614
+ }
615
+ return "stage";
616
+ }
617
+
618
+ function mappingSuggestionsForItem(item) {
619
+ const suggestions = [];
620
+ for (const dependency of item.blocking_dependencies || []) {
621
+ suggestions.push({
622
+ type: dependency.type || "review",
623
+ id: dependency.id,
624
+ reason: dependency.reason || null
625
+ });
626
+ }
627
+ return suggestions;
628
+ }
629
+
630
+ export function buildAgentAdoptionPlan(adoptionPlan, maintainedBoundaryArtifact = null) {
631
+ const items = (adoptionPlan?.items || []).map((item) => {
632
+ const currentState = inferCurrentAdoptionState(item);
633
+ const maintainedSeamCandidates = inferMaintainedSeamCandidates({
634
+ item: item.item || null,
635
+ kind: item.kind || null,
636
+ track: item.track || null,
637
+ source_path: item.source_path || null,
638
+ canonical_rel_path: item.canonical_rel_path || null,
639
+ requirements: {
640
+ related_docs: [...new Set(item.related_docs || [])].sort(),
641
+ related_capabilities: [...new Set(item.related_capabilities || [])].sort(),
642
+ related_rules: [...new Set(item.related_rules || [])].sort(),
643
+ related_workflows: [...new Set(item.related_workflows || [])].sort()
644
+ },
645
+ projection_impacts: [...(item.projection_impacts || [])],
646
+ ui_impacts: [...(item.ui_impacts || [])],
647
+ workflow_impacts: [...(item.workflow_impacts || [])]
648
+ }, maintainedBoundaryArtifact);
649
+ return {
650
+ id: adoptionItemKey(item),
651
+ bundle: item.bundle,
652
+ item: item.item,
653
+ kind: item.kind,
654
+ track: item.track || null,
655
+ source_path: item.source_path || null,
656
+ canonical_rel_path: item.canonical_rel_path || null,
657
+ review_boundary: reviewBoundaryForImportProposal(item),
658
+ current_state: currentState,
659
+ recommended_state: inferRecommendedAdoptionState(item),
660
+ supported_states: ADOPTION_STATE_VOCABULARY,
661
+ human_review_required:
662
+ currentState === "stage" ||
663
+ ["needs_projection_review", "needs_ui_review", "needs_workflow_review"].includes(item.status),
664
+ provenance: {
665
+ bundle: item.bundle,
666
+ source_path: item.source_path || null,
667
+ canonical_rel_path: item.canonical_rel_path || null
668
+ },
669
+ requirements: {
670
+ related_docs: [...new Set(item.related_docs || [])].sort(),
671
+ related_capabilities: [...new Set(item.related_capabilities || [])].sort(),
672
+ related_rules: [...new Set(item.related_rules || [])].sort(),
673
+ related_workflows: [...new Set(item.related_workflows || [])].sort(),
674
+ blocking_dependencies: [...(item.blocking_dependencies || [])]
675
+ },
676
+ projection_impacts: [...(item.projection_impacts || [])],
677
+ ui_impacts: [...(item.ui_impacts || [])],
678
+ workflow_impacts: [...(item.workflow_impacts || [])],
679
+ maintained_seam_candidates: maintainedSeamCandidates,
680
+ mapping_suggestions: mappingSuggestionsForItem(item),
681
+ available_actions: ADOPTION_STATE_VOCABULARY
682
+ };
683
+ });
684
+
685
+ return {
686
+ type: "agent_adoption_plan",
687
+ version: 1,
688
+ workspace: adoptionPlan?.workspace || null,
689
+ source_plan_type: adoptionPlan?.type || null,
690
+ adoption_state_vocabulary: ADOPTION_STATE_VOCABULARY,
691
+ terminology: {
692
+ candidate_workspace_term: "candidate",
693
+ non_canonical_adoption_state: "stage"
694
+ },
695
+ approved_review_groups: [...new Set(adoptionPlan?.approved_review_groups || [])].sort(),
696
+ imported_proposal_surfaces: items,
697
+ staged_items: items.filter((item) => item.current_state === "stage").map((item) => item.id),
698
+ accepted_items: items.filter((item) => item.current_state === "accept").map((item) => item.id),
699
+ rejected_items: items.filter((item) => item.current_state === "reject").map((item) => item.id),
700
+ requires_human_review: items.filter((item) => item.human_review_required).map((item) => item.id)
701
+ };
702
+ }