@astrale-os/cli 1.0.0-beta.1 → 1.0.0-beta.2

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 (180) hide show
  1. package/README.md +7 -11
  2. package/dist/astrale.js +3737 -3523
  3. package/dist/public/connect-core.js +396 -392
  4. package/dist/public/keys/index.js +371 -378
  5. package/dist/public/paths/index.js +371 -378
  6. package/dist/types/lib/idp.d.ts +6 -0
  7. package/dist/types/lib/meta.d.ts +2 -2
  8. package/package.json +6 -4
  9. package/src/admin/binding.ts +168 -0
  10. package/src/admin/catalog/__tests__/client.test.ts +2 -2
  11. package/src/admin/catalog/client.ts +4 -9
  12. package/src/admin/instance/__tests__/client.test.ts +2 -2
  13. package/src/admin/instance/client.ts +6 -11
  14. package/src/commands/__tests__/auth-login.test.ts +54 -1
  15. package/src/commands/__tests__/call.test.ts +5 -1
  16. package/src/commands/__tests__/domain-install-operation.test.ts +23 -7
  17. package/src/commands/__tests__/domain-install-owned.test.ts +5 -1
  18. package/src/commands/__tests__/domain-list.test.ts +83 -4
  19. package/src/commands/__tests__/install-identity-override.test.ts +30 -19
  20. package/src/commands/__tests__/studio-descriptor.test.ts +22 -0
  21. package/src/commands/__tests__/update.test.ts +23 -16
  22. package/src/commands/domain/install.ts +11 -15
  23. package/src/commands/domain/list.ts +17 -12
  24. package/src/commands/studio.ts +20 -0
  25. package/src/commands/update.ts +9 -5
  26. package/src/connection/__tests__/errors.test.ts +16 -12
  27. package/src/connection/__tests__/exchange.test.ts +6 -5
  28. package/src/connection/exchange.ts +5 -4
  29. package/src/lib/__tests__/domain-publication.test.ts +144 -0
  30. package/src/lib/__tests__/idp-session.test.ts +22 -0
  31. package/src/lib/__tests__/idp.test.ts +2 -0
  32. package/src/lib/__tests__/instance.test.ts +6 -0
  33. package/src/lib/__tests__/studio-server-deps.test.ts +53 -16
  34. package/src/lib/__tests__/update.test.ts +12 -0
  35. package/src/lib/domain-publication.ts +102 -0
  36. package/src/lib/idp.ts +5 -1
  37. package/src/lib/instance.ts +6 -1
  38. package/src/lib/login-flow.ts +13 -3
  39. package/src/lib/meta.ts +2 -2
  40. package/src/lib/update.ts +4 -4
  41. package/src/program/__tests__/program.test.ts +1 -1
  42. package/studio/client/dist/assets/{elk-api-D2xgMJvi.js → elk-api-lwhFo7vB.js} +1 -1
  43. package/studio/client/dist/assets/index-B-c-smo9.js +8 -0
  44. package/studio/client/dist/assets/index-BckHuAWk.js +81 -0
  45. package/studio/client/dist/assets/index-C4aNQ6dz.css +1 -0
  46. package/studio/client/dist/index.html +2 -2
  47. package/studio/package.json +3 -1
  48. package/studio/server/agent/bridge/stdio.ts +8 -1
  49. package/studio/server/agent/conversation.test.ts +10 -5
  50. package/studio/server/agent/conversation.ts +56 -8
  51. package/studio/server/agent/harness/codex/loadout.ts +18 -21
  52. package/studio/server/agent/harness/gateway/config.ts +20 -18
  53. package/studio/server/agent/harness/selection.ts +9 -1
  54. package/studio/server/agent/prompts/system.ts +3 -2
  55. package/studio/server/agent/prompts/turn.ts +13 -4
  56. package/studio/server/agent/run/completion.ts +2 -2
  57. package/studio/server/agent/run/preparation.ts +6 -5
  58. package/studio/server/agent/run/transcript.test.ts +35 -1
  59. package/studio/server/agent/run/transcript.ts +169 -3
  60. package/studio/server/agent/run/usage.test.ts +24 -0
  61. package/studio/server/agent/run/usage.ts +26 -1
  62. package/studio/server/api/canvas.ts +44 -0
  63. package/studio/server/api/comments.ts +85 -0
  64. package/studio/server/api/context.ts +61 -0
  65. package/studio/server/api/deployment.ts +39 -0
  66. package/studio/server/api/documents.ts +55 -0
  67. package/studio/server/api/domain.ts +59 -0
  68. package/studio/server/api/http.ts +45 -0
  69. package/studio/server/api/project.ts +57 -0
  70. package/studio/server/api/schema.ts +12 -0
  71. package/studio/server/api/views.ts +57 -0
  72. package/studio/server/api/workspace.ts +60 -0
  73. package/studio/server/api.test.ts +147 -0
  74. package/studio/server/api.ts +20 -422
  75. package/studio/server/cache.test.ts +111 -0
  76. package/studio/server/cache.ts +163 -9
  77. package/studio/server/cli-consumers.test.ts +494 -0
  78. package/studio/server/cli.test.ts +88 -0
  79. package/studio/server/cli.ts +240 -0
  80. package/studio/server/client-package.ts +25 -1
  81. package/studio/server/domain.test.ts +30 -2
  82. package/studio/server/domain.ts +14 -2
  83. package/studio/server/environment/dotenv-preview.test.ts +39 -0
  84. package/studio/server/environment/dotenv-preview.ts +27 -0
  85. package/studio/server/environment/files.test.ts +53 -0
  86. package/studio/server/{state/env.ts → environment/files.ts} +7 -48
  87. package/studio/server/{state → handoff}/copy.ts +21 -6
  88. package/studio/server/handoff/service.test.ts +22 -0
  89. package/studio/server/{state/handoff.ts → handoff/service.ts} +21 -14
  90. package/studio/server/instances/active.ts +72 -0
  91. package/studio/server/instances/deploy-record.test.ts +31 -0
  92. package/studio/server/instances/deploy-record.ts +37 -0
  93. package/studio/server/instances/deploy.ts +56 -0
  94. package/studio/server/{state/instance.test.ts → instances/probe.test.ts} +25 -21
  95. package/studio/server/instances/probe.ts +67 -0
  96. package/studio/server/instances/status.test.ts +12 -0
  97. package/studio/server/instances/status.ts +49 -0
  98. package/studio/server/introspect/anatomy/client-tree.ts +57 -0
  99. package/studio/server/introspect/anatomy/env-fields.ts +66 -0
  100. package/studio/server/introspect/anatomy/schema-definition.ts +53 -0
  101. package/studio/server/introspect/anatomy/source.ts +181 -0
  102. package/studio/server/introspect/anatomy/views/legacy.ts +232 -0
  103. package/studio/server/introspect/anatomy/views/routes.ts +105 -0
  104. package/studio/server/introspect/anatomy/views.ts +58 -0
  105. package/studio/server/introspect/anatomy-extras.test.ts +91 -4
  106. package/studio/server/introspect/anatomy-extras.ts +7 -726
  107. package/studio/server/introspect/anatomy.ts +46 -19
  108. package/studio/server/introspect/bundle.ts +15 -6
  109. package/studio/server/introspect/canonical-schema.test.ts +79 -0
  110. package/studio/server/introspect/canonical-schema.ts +80 -18
  111. package/studio/server/introspect/config-preview.test.ts +32 -0
  112. package/studio/server/introspect/config-preview.ts +119 -0
  113. package/studio/server/introspect/diff.test.ts +7 -11
  114. package/studio/server/introspect/diff.ts +28 -37
  115. package/studio/server/introspect/extractor.ts +8 -6
  116. package/studio/server/introspect/hash.ts +5 -2
  117. package/studio/server/introspect/overlay-tsmorph.ts +7 -1305
  118. package/studio/server/introspect/revision.test.ts +54 -0
  119. package/studio/server/introspect/revision.ts +49 -0
  120. package/studio/server/introspect/runtime.test.ts +63 -5
  121. package/studio/server/introspect/runtime.ts +49 -3
  122. package/studio/server/introspect/schema-ir-json.ts +181 -0
  123. package/studio/server/introspect/source-overlay/annotations.ts +14 -0
  124. package/studio/server/introspect/source-overlay/handlers.ts +681 -0
  125. package/studio/server/introspect/source-overlay/kernel-calls.ts +49 -0
  126. package/studio/server/introspect/source-overlay/project.ts +248 -0
  127. package/studio/server/introspect/source-overlay/spans.ts +360 -0
  128. package/studio/server/json.ts +46 -0
  129. package/studio/server/lifecycle.ts +5 -1
  130. package/studio/server/sse.test.ts +26 -0
  131. package/studio/server/sse.ts +4 -1
  132. package/studio/server/state/baseline.test.ts +212 -1
  133. package/studio/server/state/baseline.ts +145 -29
  134. package/studio/server/state/comments.test.ts +66 -1
  135. package/studio/server/state/comments.ts +173 -10
  136. package/studio/server/state/context.ts +34 -2
  137. package/studio/server/state/documents.ts +42 -1
  138. package/studio/server/state/integrations.ts +27 -1
  139. package/studio/server/state/layout.test.ts +34 -0
  140. package/studio/server/state/layout.ts +44 -17
  141. package/studio/server/state/settings.ts +29 -22
  142. package/studio/server/state/store.test.ts +122 -0
  143. package/studio/server/state/store.ts +66 -17
  144. package/studio/server/state/visibility.ts +22 -7
  145. package/studio/server/views/model.test.ts +57 -0
  146. package/studio/server/views/model.ts +66 -0
  147. package/studio/server/views/runtime.ts +40 -0
  148. package/studio/server/views/selection-repository.test.ts +31 -0
  149. package/studio/server/views/selection-repository.ts +60 -0
  150. package/studio/server/views/session.test.ts +73 -0
  151. package/studio/server/views/session.ts +166 -0
  152. package/studio/server/{state/views.test.ts → views/target.test.ts} +8 -159
  153. package/studio/server/views/target.ts +248 -0
  154. package/studio/server/watch.ts +1 -1
  155. package/studio/server/workspace/catalog.test.ts +17 -0
  156. package/studio/server/workspace/catalog.ts +43 -0
  157. package/studio/server/{state → workspace}/create.test.ts +1 -1
  158. package/studio/server/{state → workspace}/create.ts +1 -1
  159. package/studio/server/{state → workspace}/git.ts +1 -1
  160. package/studio/server/workspace/updates.ts +83 -0
  161. package/studio/server/workspace-state.ts +1 -1
  162. package/studio/shared/contracts/README.md +16 -0
  163. package/studio/shared/contracts/agent.ts +270 -0
  164. package/studio/shared/contracts/runtime.ts +50 -0
  165. package/studio/shared/contracts/schema.ts +462 -0
  166. package/studio/shared/contracts/surface.test.ts +319 -0
  167. package/studio/shared/contracts/workspace.ts +274 -0
  168. package/studio/shared/layout.test.ts +116 -0
  169. package/studio/shared/schema/identity.test.ts +58 -0
  170. package/studio/shared/schema/identity.ts +82 -0
  171. package/studio/shared/types.ts +11 -1099
  172. package/studio/tsconfig.json +1 -1
  173. package/viewer/dist/main.js +35 -35
  174. package/studio/client/dist/assets/index-BMdnsIJA.css +0 -1
  175. package/studio/client/dist/assets/index-D-vRV8w7.js +0 -8
  176. package/studio/client/dist/assets/index-LGSWRrk8.js +0 -81
  177. package/studio/server/state/catalog.ts +0 -117
  178. package/studio/server/state/instance.ts +0 -280
  179. package/studio/server/state/updates.ts +0 -63
  180. package/studio/server/state/views.ts +0 -535
@@ -0,0 +1,681 @@
1
+ /**
2
+ * Handler wiring overlay for canonical implementation maps and legacy runtime helpers.
3
+ */
4
+ import { resolve as resolvePath } from 'node:path'
5
+ import { Node, SyntaxKind, type CallExpression } from 'ts-morph'
6
+
7
+ import type { HandlerLink, SchemaIR } from '../../../shared/types'
8
+
9
+ import { scanKernelCalls } from './kernel-calls'
10
+ import {
11
+ calleeName,
12
+ firstValueDeclaration,
13
+ getProp,
14
+ newProject,
15
+ objectPropertyValue,
16
+ propertyKey,
17
+ relToRoot,
18
+ resolveModuleFile,
19
+ resolveObjectLiteral,
20
+ stringLiteralOfProp,
21
+ tryAddFile,
22
+ unwrapExpression,
23
+ valueOfIdentifier,
24
+ } from './project'
25
+
26
+ /** Unwrap a string literal argument to its value. */
27
+ function stringArg(call: CallExpression, index: number): string | undefined {
28
+ const arg = call.getArguments()[index]
29
+ if (!arg) return undefined
30
+ if (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg)) {
31
+ return arg.getLiteralText()
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ // ───────────────────────────── handler links ─────────────────────────────
37
+
38
+ /** Recognized method-wiring calls after normalizing single-method and grouped helpers. */
39
+ interface WiredMethod {
40
+ owner: string
41
+ method: string
42
+ /** the object literal / call expression carrying the handler config */
43
+ config: Node
44
+ wiringLine: number
45
+ wiringFile: string
46
+ ownerKind?: 'class' | 'interface' | 'function'
47
+ style?: 'legacy-config' | 'direct-handler'
48
+ }
49
+
50
+ const SINGLE_METHOD_HELPERS = new Set(['method', 'remoteMethod'])
51
+ const GROUP_HELPERS = new Set([
52
+ 'classMethods',
53
+ 'interfaceMethods',
54
+ 'remoteClassMethods',
55
+ 'remoteInterfaceMethods',
56
+ ])
57
+
58
+ /**
59
+ * Resolve a method-config node (object literal `{ authorize, execute }` or a
60
+ * call like `todo('…')`) down to: the symbol that carries the real logic, plus
61
+ * whether it is a NotImplemented stub and the authorize flavour.
62
+ */
63
+ interface ConfigResolution {
64
+ /** the node whose `execute` body we follow to a handler file */
65
+ executeNode?: Node
66
+ implemented: boolean
67
+ /** declared auth policy; defaults to 'required' when the prop is absent. */
68
+ auth?: 'public' | 'optional' | 'required'
69
+ /** authorize hook shape: 'absent' | 'noop' | 'custom'. */
70
+ authorize?: 'absent' | 'noop' | 'custom'
71
+ authorizeSnippet?: string
72
+ unlinkedReason?: 'no-config'
73
+ }
74
+
75
+ function resolveConfigObject(configNode: Node, seen = new Set<string>()): ConfigResolution {
76
+ const node = unwrapExpression(configNode)
77
+ const key = `${node.getSourceFile().getFilePath()}:${node.getStart()}`
78
+ if (seen.has(key)) return { implemented: false, unlinkedReason: 'no-config' }
79
+ seen.add(key)
80
+
81
+ if (Node.isCallExpression(node)) {
82
+ // Curried SDK helpers carry the handler config in their final argument:
83
+ // `remoteMethod()(schema, 'Issue', 'delete', { authorize, execute })`.
84
+ const lastArg = node.getArguments().at(-1)
85
+ if (lastArg) {
86
+ const candidate = unwrapExpression(lastArg)
87
+ if (Node.isObjectLiteralExpression(candidate) || Node.isIdentifier(candidate)) {
88
+ return resolveConfigObject(candidate, seen)
89
+ }
90
+ }
91
+
92
+ // Local factories such as `todo('Owner.name')` return the config object themselves.
93
+ const obj = followFactoryToObject(node)
94
+ if (obj) return classifyObjectLiteral(obj)
95
+ return { implemented: false, unlinkedReason: 'no-config' }
96
+ }
97
+ if (Node.isObjectLiteralExpression(node)) {
98
+ return classifyObjectLiteral(node)
99
+ }
100
+ // Handler maps normally reference a local or imported `remoteMethod` value.
101
+ if (Node.isIdentifier(node)) {
102
+ const value = valueOfIdentifier(node)
103
+ if (value) return resolveConfigObject(value, seen)
104
+ }
105
+ return { implemented: false, unlinkedReason: 'no-config' }
106
+ }
107
+
108
+ /** Given `todo('x')`, find the factory's `return { … }` object literal. */
109
+ function followFactoryToObject(call: CallExpression): Node | undefined {
110
+ const expr = call.getExpression()
111
+ if (!Node.isIdentifier(expr)) return undefined
112
+ const decl = firstValueDeclaration(expr)
113
+ if (!decl) return undefined
114
+ let body: Node | undefined
115
+ if (Node.isVariableDeclaration(decl)) {
116
+ body = decl.getInitializer()
117
+ } else if (Node.isFunctionDeclaration(decl)) {
118
+ body = decl
119
+ }
120
+ if (!body) return undefined
121
+ // Arrow returning an object literal directly: `(name) => ({ … })`.
122
+ if (Node.isArrowFunction(body)) {
123
+ const arrowBody = body.getBody()
124
+ if (Node.isParenthesizedExpression(arrowBody)) {
125
+ const inner = arrowBody.getExpression()
126
+ if (Node.isObjectLiteralExpression(inner)) return inner
127
+ }
128
+ if (Node.isObjectLiteralExpression(arrowBody)) return arrowBody
129
+ // Block body with a `return { … }`.
130
+ const ret = arrowBody.getFirstDescendantByKind?.(SyntaxKind.ReturnStatement)
131
+ const retExpr = ret?.getExpression()
132
+ if (retExpr && Node.isObjectLiteralExpression(retExpr)) return retExpr
133
+ }
134
+ if (Node.isFunctionDeclaration(body) || Node.isFunctionExpression(body)) {
135
+ const ret = body.getFirstDescendantByKind(SyntaxKind.ReturnStatement)
136
+ const retExpr = ret?.getExpression()
137
+ if (retExpr && Node.isObjectLiteralExpression(retExpr)) return retExpr
138
+ }
139
+ return undefined
140
+ }
141
+
142
+ /** Inspect `{ auth, authorize, execute }` for the auth policy, authorize shape,
143
+ * parsed permission checks, source snippets, and execute stub-ness. */
144
+ function classifyObjectLiteral(obj: Node): ConfigResolution {
145
+ if (!Node.isObjectLiteralExpression(obj)) {
146
+ return { implemented: false, unlinkedReason: 'no-config' }
147
+ }
148
+ const executeProp = getProp(obj, 'execute')
149
+ const authorizeProp = getProp(obj, 'authorize')
150
+
151
+ const auth = authPolicy(obj)
152
+ const authorize = authorizeProp ? authorizeFlavour(authorizeProp) : 'absent'
153
+ const authorizeSnippet = authorizeProp ? snippetOf(authorizeProp) : undefined
154
+ const common = { auth, authorize, authorizeSnippet } as const
155
+
156
+ if (!executeProp) {
157
+ return { implemented: false, ...common, unlinkedReason: 'no-config' }
158
+ }
159
+ const implemented = !isStubFunction(executeProp)
160
+ return { executeNode: executeProp, implemented, ...common }
161
+ }
162
+
163
+ /** The declared `auth` policy on a method config; defaults to 'required'. */
164
+ function authPolicy(obj: Node): 'public' | 'optional' | 'required' {
165
+ const v = stringLiteralOfProp(obj, 'auth')
166
+ return v === 'public' || v === 'optional' ? v : 'required'
167
+ }
168
+
169
+ const SNIPPET_CAP = 1200
170
+
171
+ /** Source text of a node, capped for a hover preview. */
172
+ function snippetOf(node: Node): string {
173
+ const t = node.getText()
174
+ return t.length > SNIPPET_CAP ? `${t.slice(0, SNIPPET_CAP)}\n/* … */` : t
175
+ }
176
+
177
+ /** 'noop' when the authorize body just returns undefined/void, else 'custom'.
178
+ * Follows identifier references (e.g. `authorize: allow` → `const allow = …`). */
179
+ function authorizeFlavour(node: Node): 'noop' | 'custom' {
180
+ const fnBody = functionBodyOf(node)
181
+ if (fnBody === undefined) return 'custom' // opaque (unresolved identifier) → assume real
182
+ if (fnBody === null) return 'noop' // expression arrow returning `undefined`
183
+ const text = fnBody.getText().replace(/[{}]/g, '').trim()
184
+ // Empty block, or a single `return;` / `return undefined;`.
185
+ if (text === '' || /^return\s*(undefined)?\s*;?$/.test(text)) return 'noop'
186
+ return 'custom'
187
+ }
188
+
189
+ /**
190
+ * For a function-like node return its block body (Node), or `null` if it is an
191
+ * expression-bodied arrow whose expression is `undefined`/void, or `undefined`
192
+ * if it is not function-like.
193
+ */
194
+ function functionBodyOf(node: Node): Node | null | undefined {
195
+ let fn: Node | undefined
196
+ if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) fn = node
197
+ else if (Node.isMethodDeclaration(node)) fn = node
198
+ else if (Node.isIdentifier(node)) {
199
+ const value = valueOfIdentifier(node)
200
+ if (value) return functionBodyOf(value)
201
+ return undefined
202
+ }
203
+ if (!fn) return undefined
204
+ const body = (fn as unknown as { getBody?: () => Node | undefined }).getBody?.()
205
+ if (!body) return undefined
206
+ if (Node.isBlock(body)) return body
207
+ // Expression body: `async () => undefined`.
208
+ if (body.getKind() === SyntaxKind.UndefinedKeyword || body.getText() === 'undefined') {
209
+ return null
210
+ }
211
+ return body
212
+ }
213
+
214
+ /** A handler body that is a NotImplemented stub: only throws / `todo()`. */
215
+ function isStubFunction(node: Node): boolean {
216
+ const body = functionBodyOf(node)
217
+ if (!body || body === null) return false
218
+ if (!Node.isBlock(body)) return false
219
+ const statements = body.getStatements()
220
+ if (statements.length === 0) return false
221
+ // Stub iff every statement is a throw, and there is at least one throw.
222
+ let throws = 0
223
+ for (const st of statements) {
224
+ if (Node.isThrowStatement(st)) {
225
+ throws++
226
+ continue
227
+ }
228
+ return false
229
+ }
230
+ return throws > 0
231
+ }
232
+
233
+ /**
234
+ * Follow an `execute` arrow → the delegated logic function it calls → that
235
+ * function's defining file:line, chasing through barrel re-exports.
236
+ */
237
+ function resolveExecuteTarget(executeNode: Node): { file: string; line: number } | undefined {
238
+ // Find the call inside the execute body that targets an imported symbol.
239
+ const body = functionBodyOf(executeNode)
240
+ const searchRoot = body && Node.isBlock(body) ? body : executeNode
241
+ const calls = searchRoot.getDescendantsOfKind(SyntaxKind.CallExpression)
242
+ for (const call of calls) {
243
+ const expr = call.getExpression()
244
+ if (!Node.isIdentifier(expr)) continue
245
+ const resolved = resolveImportedFunction(expr)
246
+ if (resolved) return resolved
247
+ }
248
+ return undefined
249
+ }
250
+
251
+ /** Resolve an identifier (a delegated logic fn) to its defining file:line. */
252
+ function resolveImportedFunction(id: Node): { file: string; line: number } | undefined {
253
+ if (!Node.isIdentifier(id)) return undefined
254
+ const symbol = id.getSymbol()
255
+ if (!symbol) return undefined
256
+ // Walk through alias chains (import { x as y } / barrel re-export `export { x }`).
257
+ let current = symbol
258
+ const seen = new Set<string>()
259
+ for (let i = 0; i < 12; i++) {
260
+ const decls = current.getDeclarations()
261
+ for (const decl of decls) {
262
+ // A concrete function/variable declaration in a real file → done.
263
+ if (Node.isFunctionDeclaration(decl)) {
264
+ return { file: decl.getSourceFile().getFilePath(), line: decl.getStartLineNumber() }
265
+ }
266
+ if (Node.isVariableDeclaration(decl)) {
267
+ const init = decl.getInitializer()
268
+ if (init && (Node.isArrowFunction(init) || Node.isFunctionExpression(init))) {
269
+ return { file: decl.getSourceFile().getFilePath(), line: decl.getStartLineNumber() }
270
+ }
271
+ }
272
+ }
273
+ // Try to hop to the aliased symbol (import specifier / export specifier).
274
+ const aliased = trySymbolHop(current)
275
+ if (!aliased) break
276
+ const key = aliased
277
+ .getDeclarations()
278
+ .map((d) => d.getSourceFile().getFilePath() + ':' + d.getStartLineNumber())
279
+ .join(',')
280
+ if (seen.has(key)) break
281
+ seen.add(key)
282
+ current = aliased
283
+ }
284
+ // Last resort: resolve the module specifier of the import and grep the file.
285
+ return resolveViaModuleSpecifier(id)
286
+ }
287
+
288
+ /** Hop one alias link via ts-morph's getAliasedSymbol, if any. */
289
+ function trySymbolHop(symbol: import('ts-morph').Symbol): import('ts-morph').Symbol | undefined {
290
+ try {
291
+ const aliased = symbol.getAliasedSymbol?.()
292
+ if (aliased && aliased !== symbol) return aliased
293
+ } catch {
294
+ /* not an alias */
295
+ }
296
+ return undefined
297
+ }
298
+
299
+ /**
300
+ * Fallback resolution: find the import declaration that brought `id` in, load
301
+ * the target module (and barrel re-exports), and locate the exported function.
302
+ */
303
+ function resolveViaModuleSpecifier(id: Node): { file: string; line: number } | undefined {
304
+ if (!Node.isIdentifier(id)) return undefined
305
+ const sourceFile = id.getSourceFile()
306
+ const name = id.getText()
307
+ for (const imp of sourceFile.getImportDeclarations()) {
308
+ // Match the local binding name, capturing the original export name.
309
+ let exportName: string | undefined
310
+ for (const named of imp.getNamedImports()) {
311
+ const local = named.getAliasNode()?.getText() ?? named.getName()
312
+ if (local === name) {
313
+ exportName = named.getName()
314
+ break
315
+ }
316
+ }
317
+ if (!exportName) continue
318
+ const modPath = resolveModuleFile(sourceFile, imp.getModuleSpecifierValue())
319
+ if (!modPath) continue
320
+ const found = findExportInFile(modPath, exportName, new Set())
321
+ if (found) return found
322
+ }
323
+ return undefined
324
+ }
325
+
326
+ /**
327
+ * Find where `exportName` is *defined* within `file`, following barrel
328
+ * `export { x } from './y'` / `export * from './y'` re-exports.
329
+ */
330
+ function findExportInFile(
331
+ file: string,
332
+ exportName: string,
333
+ seen: Set<string>,
334
+ ): { file: string; line: number } | undefined {
335
+ if (seen.has(file)) return undefined
336
+ seen.add(file)
337
+ const project = newProject()
338
+ const sf = tryAddFile(project, file)
339
+ if (!sf) return undefined
340
+
341
+ // 1) A local function declaration with that name.
342
+ for (const fn of sf.getFunctions()) {
343
+ if (fn.getName() === exportName && fn.isExported()) {
344
+ return { file, line: fn.getStartLineNumber() }
345
+ }
346
+ }
347
+ // 2) A local exported variable bound to a function.
348
+ for (const v of sf.getVariableDeclarations()) {
349
+ if (v.getName() === exportName && v.isExported()) {
350
+ return { file, line: v.getStartLineNumber() }
351
+ }
352
+ }
353
+ // 3) Re-export: `export { a, b as exportName } from './mod'`.
354
+ for (const ex of sf.getExportDeclarations()) {
355
+ const modSpec = ex.getModuleSpecifierValue()
356
+ const target = modSpec ? resolveModuleFile(sf, modSpec) : undefined
357
+ const named = ex.getNamedExports()
358
+ if (named.length > 0) {
359
+ for (const ne of named) {
360
+ const exposed = ne.getAliasNode()?.getText() ?? ne.getName()
361
+ if (exposed !== exportName) continue
362
+ const original = ne.getName()
363
+ if (target) {
364
+ const found = findExportInFile(target, original, seen)
365
+ if (found) return found
366
+ }
367
+ }
368
+ } else if (target) {
369
+ // `export * from './mod'` — search the target for the same name.
370
+ const found = findExportInFile(target, exportName, seen)
371
+ if (found) return found
372
+ }
373
+ }
374
+ return undefined
375
+ }
376
+
377
+ /**
378
+ * Collect every (owner, method, config) wiring from runtime/index.ts, across
379
+ * both fixture styles, then build a HandlerLink per method.
380
+ */
381
+ export function buildHandlerLinks(args: {
382
+ ir: SchemaIR | null
383
+ domainRoot: string
384
+ }): HandlerLink[] {
385
+ const { ir, domainRoot } = args
386
+ if (!domainRoot) return []
387
+ const project = newProject()
388
+ const legacyWiringRel = 'runtime/index.ts'
389
+ const legacySf = tryAddFile(project, resolvePath(domainRoot, legacyWiringRel))
390
+
391
+ const interfaceNames = new Set(ir ? Object.keys(ir.interfaces ?? {}) : [])
392
+
393
+ const wired: WiredMethod[] = []
394
+
395
+ if (legacySf) {
396
+ for (const call of legacySf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
397
+ const name = calleeName(call)
398
+ if (!name) continue
399
+
400
+ // Style A: single-method helper — method(schema, 'Owner', 'name', { … }).
401
+ if (SINGLE_METHOD_HELPERS.has(name)) {
402
+ const owner = stringArg(call, 1)
403
+ const method = stringArg(call, 2)
404
+ const config = call.getArguments()[3]
405
+ if (owner && method && config) {
406
+ wired.push({
407
+ owner,
408
+ method,
409
+ config,
410
+ wiringLine: call.getStartLineNumber(),
411
+ wiringFile: legacyWiringRel,
412
+ style: 'legacy-config',
413
+ })
414
+ }
415
+ continue
416
+ }
417
+
418
+ // Style B: group helper — classMethods(schema, 'Owner', { name: cfg, … }).
419
+ if (GROUP_HELPERS.has(name)) {
420
+ const owner = stringArg(call, 1)
421
+ const mapArg = call.getArguments()[2]
422
+ if (!owner || !mapArg || !Node.isObjectLiteralExpression(mapArg)) continue
423
+ for (const prop of mapArg.getProperties()) {
424
+ const valueNode = objectPropertyValue(prop)
425
+ const methodName = propertyKey(prop)
426
+ if (!methodName || !valueNode) continue
427
+ wired.push({
428
+ owner,
429
+ method: methodName,
430
+ config: valueNode,
431
+ wiringLine: prop.getStartLineNumber(),
432
+ wiringFile: legacyWiringRel,
433
+ style: 'legacy-config',
434
+ })
435
+ }
436
+ continue
437
+ }
438
+ }
439
+ }
440
+
441
+ // Current SDK layout: `implementation.ts` owns a plain
442
+ // `handlers: { classes, interfaces, functions }` object passed to
443
+ // `defineDomain` / `defineDomain.public`. Start from that call so inline
444
+ // handler maps and arbitrarily named handler variables are both visible.
445
+ // Class/interface entries point directly at handler functions; there is no
446
+ // legacy `{ authorize, execute }` wrapper.
447
+ for (const wiringRel of ['implementation.ts', 'domain.ts']) {
448
+ const sf = tryAddFile(project, resolvePath(domainRoot, wiringRel))
449
+ if (!sf) continue
450
+
451
+ const handlerObjects: import('ts-morph').ObjectLiteralExpression[] = []
452
+ const seenHandlerObjects = new Set<string>()
453
+ const addHandlerObject = (candidate: Node | undefined) => {
454
+ const handlersObject = candidate ? resolveObjectLiteral(candidate) : undefined
455
+ if (!handlersObject) return
456
+ const key = `${handlersObject.getSourceFile().getFilePath()}:${handlersObject.getStart()}`
457
+ if (seenHandlerObjects.has(key)) return
458
+ seenHandlerObjects.add(key)
459
+ handlerObjects.push(handlersObject)
460
+ }
461
+
462
+ for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
463
+ if (!isDefineDomainCall(call)) continue
464
+ const input = call.getArguments()[0]
465
+ const inputObject = input ? resolveObjectLiteral(input) : undefined
466
+ addHandlerObject(inputObject ? getProp(inputObject, 'handlers') : undefined)
467
+ }
468
+
469
+ // Tolerate pre-composition fixtures that expose a conventional `handlers`
470
+ // variable without a parseable defineDomain call.
471
+ const handlersDecl = sf.getVariableDeclaration('handlers')
472
+ addHandlerObject(handlersDecl?.getInitializer())
473
+
474
+ for (const handlersObject of handlerObjects) {
475
+ const handlersFile = relToRoot(domainRoot, handlersObject.getSourceFile().getFilePath())
476
+ collectDirectHandlerSection(wired, handlersObject, 'classes', 'class', handlersFile)
477
+ collectDirectHandlerSection(wired, handlersObject, 'interfaces', 'interface', handlersFile)
478
+ collectDirectFunctionHandlers(wired, handlersObject, ir?.domain ?? 'domain', handlersFile)
479
+ }
480
+ }
481
+
482
+ // Deduplicate (owner, method): the group helper restates entries the single
483
+ // helper already produced (e.g. my-domain wires each method, then groups them).
484
+ // Prefer the entry whose config resolves to a real object (the single helper),
485
+ // falling back to the group entry (which references a variable / todo()).
486
+ const byKey = new Map<string, WiredMethod>()
487
+ for (const w of wired) {
488
+ const key = `${w.ownerKind ?? 'legacy'}:${w.owner}.${w.method}`
489
+ const existing = byKey.get(key)
490
+ if (!existing) {
491
+ byKey.set(key, w)
492
+ continue
493
+ }
494
+ // Prefer the one whose config is an object literal (richer info).
495
+ const existingIsObj = Node.isObjectLiteralExpression(existing.config)
496
+ const candidateIsObj = Node.isObjectLiteralExpression(w.config)
497
+ if (candidateIsObj && !existingIsObj) byKey.set(key, w)
498
+ }
499
+
500
+ const links: HandlerLink[] = []
501
+ for (const w of byKey.values()) {
502
+ const ownerKind: 'class' | 'interface' | 'function' =
503
+ w.ownerKind ?? (interfaceNames.has(w.owner) ? 'interface' : 'class')
504
+ const isStatic = irMethodStatic(ir, w.owner, w.method, ownerKind)
505
+
506
+ const link: HandlerLink = {
507
+ owner: w.owner,
508
+ ownerKind,
509
+ method: w.method,
510
+ static: isStatic,
511
+ wiringFile: w.wiringFile,
512
+ wiringLine: w.wiringLine,
513
+ implemented: true,
514
+ }
515
+
516
+ let target: { file: string; line: number } | undefined
517
+ if (w.style === 'direct-handler') {
518
+ const direct = resolveDirectHandler(w.config)
519
+ link.implemented = direct.implemented
520
+ target = direct.target
521
+ applyCanonicalMethodAuth(link, ir, w.owner, w.method, ownerKind)
522
+ } else {
523
+ const resolution = resolveConfigObject(w.config)
524
+ link.implemented = resolution.implemented
525
+ if (resolution.auth) link.auth = resolution.auth
526
+ if (resolution.authorize) link.authorize = resolution.authorize
527
+ if (resolution.authorizeSnippet) link.authorizeSnippet = resolution.authorizeSnippet
528
+ if (resolution.executeNode) target = resolveExecuteTarget(resolution.executeNode)
529
+ }
530
+
531
+ if (target) {
532
+ link.handlerFile = relToRoot(domainRoot, target.file)
533
+ link.handlerLine = target.line
534
+ const kernelCalls = scanKernelCalls(target.file)
535
+ if (kernelCalls.length > 0) link.kernelCalls = kernelCalls
536
+ } else {
537
+ link.unlinked = true
538
+ }
539
+
540
+ links.push(link)
541
+ }
542
+
543
+ // Stable order: by owner, then method.
544
+ links.sort((a, b) =>
545
+ a.owner === b.owner ? a.method.localeCompare(b.method) : a.owner.localeCompare(b.owner),
546
+ )
547
+ return links
548
+ }
549
+
550
+ /** Whether a call is the current SDK composition entrypoint. */
551
+ function isDefineDomainCall(call: CallExpression): boolean {
552
+ const expression = unwrapExpression(call.getExpression())
553
+ if (Node.isIdentifier(expression)) return expression.getText() === 'defineDomain'
554
+ if (!Node.isPropertyAccessExpression(expression) || expression.getName() !== 'public') {
555
+ return false
556
+ }
557
+ const receiver = unwrapExpression(expression.getExpression())
558
+ return Node.isIdentifier(receiver) && receiver.getText() === 'defineDomain'
559
+ }
560
+
561
+ /** Collect current `handlers.classes/interfaces.Owner.method = fn` bindings. */
562
+ function collectDirectHandlerSection(
563
+ out: WiredMethod[],
564
+ handlers: import('ts-morph').ObjectLiteralExpression,
565
+ section: 'classes' | 'interfaces',
566
+ ownerKind: 'class' | 'interface',
567
+ wiringFile: string,
568
+ ): void {
569
+ const sectionValue = getProp(handlers, section)
570
+ const sectionObject = sectionValue ? resolveObjectLiteral(sectionValue) : undefined
571
+ if (!sectionObject) return
572
+ for (const ownerProp of sectionObject.getProperties()) {
573
+ const owner = propertyKey(ownerProp)
574
+ const ownerValue = objectPropertyValue(ownerProp)
575
+ const ownerObject = ownerValue ? resolveObjectLiteral(ownerValue) : undefined
576
+ if (!owner || !ownerObject) continue
577
+ for (const methodProp of ownerObject.getProperties()) {
578
+ const method = propertyKey(methodProp)
579
+ const handler = objectPropertyValue(methodProp)
580
+ if (!method || !handler) continue
581
+ out.push({
582
+ owner,
583
+ ownerKind,
584
+ method,
585
+ config: handler,
586
+ wiringLine: methodProp.getStartLineNumber(),
587
+ wiringFile,
588
+ style: 'direct-handler',
589
+ })
590
+ }
591
+ }
592
+ }
593
+
594
+ /** Collect current standalone `handlers.functions.name = fn` bindings. */
595
+ function collectDirectFunctionHandlers(
596
+ out: WiredMethod[],
597
+ handlers: import('ts-morph').ObjectLiteralExpression,
598
+ owner: string,
599
+ wiringFile: string,
600
+ ): void {
601
+ const functionsValue = getProp(handlers, 'functions')
602
+ const functions = functionsValue ? resolveObjectLiteral(functionsValue) : undefined
603
+ if (!functions) return
604
+ for (const functionProp of functions.getProperties()) {
605
+ const method = propertyKey(functionProp)
606
+ const handler = objectPropertyValue(functionProp)
607
+ if (!method || !handler) continue
608
+ out.push({
609
+ owner,
610
+ ownerKind: 'function',
611
+ method,
612
+ config: handler,
613
+ wiringLine: functionProp.getStartLineNumber(),
614
+ wiringFile,
615
+ style: 'direct-handler',
616
+ })
617
+ }
618
+ }
619
+
620
+ /** Follow a direct SDK handler to its defining source node. */
621
+ function resolveDirectHandler(config: Node): {
622
+ implemented: boolean
623
+ target?: { file: string; line: number }
624
+ } {
625
+ let value = unwrapExpression(config)
626
+ if (Node.isIdentifier(value)) value = valueOfIdentifier(value) ?? value
627
+ value = unwrapExpression(value)
628
+ const concrete =
629
+ Node.isArrowFunction(value) ||
630
+ Node.isFunctionExpression(value) ||
631
+ Node.isFunctionDeclaration(value) ||
632
+ Node.isMethodDeclaration(value) ||
633
+ Node.isCallExpression(value)
634
+ if (!concrete) return { implemented: false }
635
+ return {
636
+ implemented: Node.isCallExpression(value) ? true : !isStubFunction(value),
637
+ target: { file: value.getSourceFile().getFilePath(), line: value.getStartLineNumber() },
638
+ }
639
+ }
640
+
641
+ /** Map the canonical callable auth declaration onto the existing Studio badge model. */
642
+ function applyCanonicalMethodAuth(
643
+ link: HandlerLink,
644
+ ir: SchemaIR | null,
645
+ owner: string,
646
+ method: string,
647
+ ownerKind: 'class' | 'interface' | 'function',
648
+ ): void {
649
+ const callable =
650
+ ownerKind === 'function'
651
+ ? ir?.functions?.[method]
652
+ : ownerKind === 'interface'
653
+ ? ir?.interfaces?.[owner]?.methods?.[method]
654
+ : ir?.classes?.[owner]?.methods?.[method]
655
+ const auth = callable?.auth
656
+ if (auth) link.callableAuth = auth
657
+ if (auth === 'anonymous') {
658
+ link.auth = 'public'
659
+ link.authorize = 'absent'
660
+ } else if (auth === 'authorized') {
661
+ link.auth = 'required'
662
+ link.authorize = 'custom'
663
+ } else if (auth === 'authenticated') {
664
+ link.auth = 'required'
665
+ link.authorize = 'absent'
666
+ }
667
+ }
668
+
669
+ /** Look up a method's `static` flag from the IR (class or interface bucket). */
670
+ function irMethodStatic(
671
+ ir: SchemaIR | null,
672
+ owner: string,
673
+ method: string,
674
+ ownerKind: 'class' | 'interface' | 'function',
675
+ ): boolean {
676
+ if (!ir) return false
677
+ if (ownerKind === 'function') return true
678
+ const bucket = ownerKind === 'interface' ? ir.interfaces?.[owner] : ir.classes?.[owner]
679
+ const m = bucket?.methods?.[method]
680
+ return m ? m.static === true : false
681
+ }