@granular-software/fractory 0.0.0-stage → 0.1.24

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 (273) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +118 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1083 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +86 -0
  40. package/dist/core.js +206 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +66 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +4 -0
  54. package/dist/factory-graph.js +318 -0
  55. package/dist/factory-model.d.ts +97 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/issue-cache.d.ts +9 -0
  76. package/dist/issue-cache.js +68 -0
  77. package/dist/issue-cli.d.ts +1 -0
  78. package/dist/issue-cli.js +89 -0
  79. package/dist/issue-links.d.ts +15 -0
  80. package/dist/issue-links.js +125 -0
  81. package/dist/linear-issues.d.ts +19 -0
  82. package/dist/linear-issues.js +124 -0
  83. package/dist/local-runtime.d.ts +8 -0
  84. package/dist/local-runtime.js +59 -0
  85. package/dist/map-activity.d.ts +73 -0
  86. package/dist/map-activity.js +234 -0
  87. package/dist/map-model.d.ts +5 -0
  88. package/dist/map-model.js +166 -0
  89. package/dist/map-quality.d.ts +14 -0
  90. package/dist/map-quality.js +56 -0
  91. package/dist/mapping-coverage.d.ts +87 -0
  92. package/dist/mapping-coverage.js +404 -0
  93. package/dist/model.d.ts +182 -0
  94. package/dist/model.js +66 -0
  95. package/dist/operation-benchmark-worker.d.ts +2 -0
  96. package/dist/operation-benchmark-worker.js +60 -0
  97. package/dist/operation-benchmark.d.ts +29 -0
  98. package/dist/operation-benchmark.js +1 -0
  99. package/dist/otel-metrics.d.ts +21 -0
  100. package/dist/otel-metrics.js +146 -0
  101. package/dist/performance-model.d.ts +185 -0
  102. package/dist/performance-model.js +396 -0
  103. package/dist/product-map.d.ts +69 -0
  104. package/dist/product-map.js +168 -0
  105. package/dist/provider-access.cjs +207 -0
  106. package/dist/provider-access.d.cts +14 -0
  107. package/dist/reports-cli.d.ts +1 -0
  108. package/dist/reports-cli.js +111 -0
  109. package/dist/reports-model.d.ts +27 -0
  110. package/dist/reports-model.js +39 -0
  111. package/dist/reports.d.ts +23 -0
  112. package/dist/reports.js +223 -0
  113. package/dist/repository-map.d.ts +22 -0
  114. package/dist/repository-map.js +151 -0
  115. package/dist/resource-cache.d.ts +17 -0
  116. package/dist/resource-cache.js +65 -0
  117. package/dist/review-cli.d.ts +19 -0
  118. package/dist/review-cli.js +224 -0
  119. package/dist/review.d.ts +48 -0
  120. package/dist/review.js +289 -0
  121. package/dist/runtime-metrics.d.ts +26 -0
  122. package/dist/runtime-metrics.js +290 -0
  123. package/dist/scope.d.ts +12 -0
  124. package/dist/scope.js +94 -0
  125. package/dist/sentry-activity.d.ts +39 -0
  126. package/dist/sentry-activity.js +174 -0
  127. package/dist/sentry.d.ts +130 -0
  128. package/dist/sentry.js +369 -0
  129. package/dist/service-release.d.ts +16 -0
  130. package/dist/service-release.js +14 -0
  131. package/dist/setup-cli.d.ts +2 -0
  132. package/dist/setup-cli.js +52 -0
  133. package/dist/setup-kit.cjs +163 -0
  134. package/dist/setup-kit.d.cts +32 -0
  135. package/dist/source-index.d.ts +37 -0
  136. package/dist/source-index.js +166 -0
  137. package/dist/source-review-git.d.ts +7 -0
  138. package/dist/source-review-git.js +103 -0
  139. package/dist/source-review.d.ts +16 -0
  140. package/dist/source-review.js +493 -0
  141. package/dist/telemetry.d.ts +17 -0
  142. package/dist/telemetry.js +51 -0
  143. package/dist/time-window.d.ts +9 -0
  144. package/dist/time-window.js +35 -0
  145. package/dist/trace-evidence.d.ts +23 -0
  146. package/dist/trace-evidence.js +55 -0
  147. package/dist/trace-model.d.ts +26 -0
  148. package/dist/trace-model.js +1 -0
  149. package/dist/tracing.d.ts +44 -0
  150. package/dist/tracing.js +123 -0
  151. package/dist/work-check.d.ts +17 -0
  152. package/dist/work-check.js +110 -0
  153. package/dist/work-cli.d.ts +1 -0
  154. package/dist/work-cli.js +148 -0
  155. package/dist/work-context.d.ts +57 -0
  156. package/dist/work-context.js +568 -0
  157. package/dist/work-intents.d.ts +6 -0
  158. package/dist/work-intents.js +140 -0
  159. package/dist/work-items.d.ts +58 -0
  160. package/dist/work-items.js +86 -0
  161. package/dist/work-model.d.ts +110 -0
  162. package/dist/work-model.js +261 -0
  163. package/dist/work-review-git.d.ts +8 -0
  164. package/dist/work-review-git.js +111 -0
  165. package/dist/work-review.d.ts +26 -0
  166. package/dist/work-review.js +426 -0
  167. package/dist/work-switcher-model.d.ts +43 -0
  168. package/dist/work-switcher-model.js +79 -0
  169. package/dist/work-switcher.d.ts +6 -0
  170. package/dist/work-switcher.js +171 -0
  171. package/dist/working-cli.d.ts +1 -0
  172. package/dist/working-cli.js +33 -0
  173. package/dist/working-code.d.ts +74 -0
  174. package/dist/working-code.js +421 -0
  175. package/dist/workspace-notes.d.ts +71 -0
  176. package/dist/workspace-notes.js +177 -0
  177. package/dist/workspace-tests.d.ts +21 -0
  178. package/dist/workspace-tests.js +573 -0
  179. package/package.json +547 -4
  180. package/src/activity-volume.ts +149 -0
  181. package/src/annotations.ts +481 -0
  182. package/src/benchmark-cli.ts +118 -0
  183. package/src/benchmark-worker.ts +22 -0
  184. package/src/benchmarks.ts +493 -0
  185. package/src/bin.ts +54 -0
  186. package/src/block-cli.ts +106 -0
  187. package/src/block-documents.ts +117 -0
  188. package/src/change-impact.ts +280 -0
  189. package/src/check-source.ts +82 -0
  190. package/src/checks-model.ts +108 -0
  191. package/src/cli.ts +440 -0
  192. package/src/code-model.ts +159 -0
  193. package/src/code-store.ts +98 -0
  194. package/src/compare-artifact.ts +314 -0
  195. package/src/compare.ts +440 -0
  196. package/src/compiler.ts +1326 -0
  197. package/src/compose.ts +94 -0
  198. package/src/core.ts +357 -0
  199. package/src/coverage-cli.ts +52 -0
  200. package/src/declaration-sources.ts +69 -0
  201. package/src/declared-graph.ts +74 -0
  202. package/src/display-name.ts +8 -0
  203. package/src/error-heat.ts +161 -0
  204. package/src/evidence.ts +94 -0
  205. package/src/factory-graph.ts +378 -0
  206. package/src/factory-model.ts +73 -0
  207. package/src/git-code.ts +461 -0
  208. package/src/git-refs.ts +43 -0
  209. package/src/history-activity.ts +146 -0
  210. package/src/history-churn.ts +416 -0
  211. package/src/history-git.ts +163 -0
  212. package/src/history-ledger.ts +636 -0
  213. package/src/history-ownership.ts +116 -0
  214. package/src/history-source.ts +117 -0
  215. package/src/integrations-cli.ts +187 -0
  216. package/src/issue-cache.ts +96 -0
  217. package/src/issue-cli.ts +137 -0
  218. package/src/issue-links.ts +153 -0
  219. package/src/linear-issues.ts +154 -0
  220. package/src/local-runtime.ts +70 -0
  221. package/src/map-activity.ts +309 -0
  222. package/src/map-model.ts +213 -0
  223. package/src/map-quality.ts +61 -0
  224. package/src/mapping-coverage.ts +570 -0
  225. package/src/model.ts +221 -0
  226. package/src/operation-benchmark-worker.ts +60 -0
  227. package/src/operation-benchmark.ts +28 -0
  228. package/src/otel-metrics.ts +176 -0
  229. package/src/performance-model.ts +575 -0
  230. package/src/product-map.ts +236 -0
  231. package/src/provider-access.cjs +207 -0
  232. package/src/provider-access.d.cts +14 -0
  233. package/src/reports-cli.ts +125 -0
  234. package/src/reports-model.ts +73 -0
  235. package/src/reports.ts +276 -0
  236. package/src/repository-map.ts +189 -0
  237. package/src/resource-cache.ts +76 -0
  238. package/src/review-cli.ts +256 -0
  239. package/src/review.ts +376 -0
  240. package/src/runtime-metrics.ts +386 -0
  241. package/src/scope.ts +103 -0
  242. package/src/sentry-activity.ts +234 -0
  243. package/src/sentry.ts +545 -0
  244. package/src/service-release.ts +18 -0
  245. package/src/setup-cli.ts +58 -0
  246. package/src/setup-kit.cjs +163 -0
  247. package/src/setup-kit.d.cts +32 -0
  248. package/src/source-index.ts +205 -0
  249. package/src/source-review-git.ts +129 -0
  250. package/src/source-review.ts +637 -0
  251. package/src/telemetry.ts +68 -0
  252. package/src/time-window.ts +51 -0
  253. package/src/trace-evidence.ts +80 -0
  254. package/src/trace-model.ts +26 -0
  255. package/src/tracing.ts +165 -0
  256. package/src/work-check.ts +143 -0
  257. package/src/work-cli.ts +195 -0
  258. package/src/work-context.ts +713 -0
  259. package/src/work-intents.ts +196 -0
  260. package/src/work-items.ts +151 -0
  261. package/src/work-model.ts +400 -0
  262. package/src/work-review-git.ts +130 -0
  263. package/src/work-review.ts +573 -0
  264. package/src/work-switcher-model.ts +121 -0
  265. package/src/work-switcher.ts +191 -0
  266. package/src/working-cli.ts +38 -0
  267. package/src/working-code.ts +582 -0
  268. package/src/workspace-notes.ts +203 -0
  269. package/src/workspace-tests.ts +654 -0
  270. package/toolkit/GUIDE.md +305 -0
  271. package/toolkit/SKILL.md +131 -0
  272. package/toolkit/bin/fractory +2 -0
  273. package/toolkit/build.json +1 -0
package/src/compose.ts ADDED
@@ -0,0 +1,94 @@
1
+ import type { DefinitionGraph } from "./model";
2
+
3
+ export interface DefinitionMount {
4
+ at: string;
5
+ definition: DefinitionGraph;
6
+ /** Mount the contents of this scope. Defaults to the definition's root. */
7
+ root?: string;
8
+ }
9
+
10
+ /** Compose independently versioned definitions without changing their element identities. */
11
+ export function composeDefinitions(
12
+ base: DefinitionGraph,
13
+ mounts: DefinitionMount[],
14
+ ): DefinitionGraph {
15
+ const graph = structuredClone(base);
16
+ const occupied = new Set(graph.elements.map((node) => node.id));
17
+ for (const { at, definition, root = definition.id } of mounts) {
18
+ if (!occupied.has(at)) throw new Error(`Unknown mount target: ${at}`);
19
+ if (!definition.elements.some((node) => node.id === root))
20
+ throw new Error(`Unknown definition scope: ${root}`);
21
+ const included = new Set([root]);
22
+ let changed = true;
23
+ while (changed) {
24
+ changed = false;
25
+ for (const node of definition.elements)
26
+ if (
27
+ node.parent &&
28
+ included.has(node.parent) &&
29
+ !included.has(node.id)
30
+ ) {
31
+ included.add(node.id);
32
+ changed = true;
33
+ }
34
+ }
35
+ const remap = (id: string) => (id === root ? at : id);
36
+ for (const node of definition.elements) {
37
+ if (node.id === root || !included.has(node.id)) continue;
38
+ if (occupied.has(node.id))
39
+ throw new Error(`Duplicate element identity: ${node.id}`);
40
+ occupied.add(node.id);
41
+ graph.elements.push({
42
+ ...node,
43
+ parent: node.parent ? remap(node.parent) : at,
44
+ definitionRevision: node.definitionRevision || definition.revision,
45
+ });
46
+ }
47
+ graph.connections.push(
48
+ ...definition.connections
49
+ .filter(
50
+ (edge) => included.has(edge.source) && included.has(edge.target),
51
+ )
52
+ .map((edge) => ({
53
+ ...edge,
54
+ source: remap(edge.source),
55
+ target: remap(edge.target),
56
+ })),
57
+ );
58
+ graph.tests.push(
59
+ ...definition.tests
60
+ .filter((test) => test.targets.some((id) => included.has(id)))
61
+ .map((test) => ({
62
+ ...test,
63
+ targets: test.targets.filter((id) => included.has(id)).map(remap),
64
+ })),
65
+ );
66
+ graph.failures.push(
67
+ ...definition.failures
68
+ .filter((failure) => included.has(failure.operationId))
69
+ .map((failure) => ({
70
+ ...failure,
71
+ operationId: remap(failure.operationId),
72
+ })),
73
+ );
74
+ graph.gaps.push(...definition.gaps);
75
+ }
76
+ for (const collection of [graph.connections, graph.tests]) {
77
+ const ids = collection.map((entry) => entry.id);
78
+ if (new Set(ids).size !== ids.length)
79
+ throw new Error("Duplicate composed relationship or test identity");
80
+ }
81
+ let hash = BigInt("14695981039346656037");
82
+ for (const byte of new TextEncoder().encode(
83
+ JSON.stringify({
84
+ elements: graph.elements,
85
+ connections: graph.connections,
86
+ tests: graph.tests,
87
+ failures: graph.failures,
88
+ gaps: graph.gaps,
89
+ }),
90
+ ))
91
+ hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * BigInt("1099511628211"));
92
+ graph.revision = hash.toString(16).padStart(16, "0");
93
+ return graph;
94
+ }
package/src/core.ts ADDED
@@ -0,0 +1,357 @@
1
+ /** Browser/Worker-safe decorators. Discovery never imports an application to execute it. */
2
+ export {
3
+ Block,
4
+ Interface,
5
+ Method,
6
+ Process,
7
+ observeFactory,
8
+ installFactoryHost,
9
+ } from "./annotations";
10
+ export type { InterfaceRef, FactoryEvent, FactoryHost } from "./annotations";
11
+ export interface Schema<T> {
12
+ parse(value: unknown): T;
13
+ readonly jsonSchema?: unknown;
14
+ }
15
+ export interface Contract<I, O> {
16
+ id: string;
17
+ input: Schema<I>;
18
+ output: Schema<O>;
19
+ }
20
+ export type Input<C> = C extends Contract<infer I, unknown> ? I : never;
21
+ export type Output<C> = C extends Contract<unknown, infer O> ? O : never;
22
+ export function contract<I, O>(
23
+ id: string,
24
+ schemas: { input: Schema<I>; output: Schema<O> },
25
+ ): Contract<I, O> {
26
+ if (!id.trim()) throw new Error("Contract identity is required");
27
+ return Object.freeze({ id, ...schemas });
28
+ }
29
+ export class ContractViolation extends Error {
30
+ constructor(
31
+ readonly contractId: string,
32
+ readonly phase: "input" | "output",
33
+ readonly cause: unknown,
34
+ ) {
35
+ super(`Invalid ${phase} for contract ${contractId}`);
36
+ this.name = "ContractViolation";
37
+ }
38
+ }
39
+ function validate<T>(
40
+ definition: Contract<unknown, unknown>,
41
+ phase: "input" | "output",
42
+ value: unknown,
43
+ ): T {
44
+ try {
45
+ return definition[phase].parse(value) as T;
46
+ } catch (error) {
47
+ throw new ContractViolation(definition.id, phase, error);
48
+ }
49
+ }
50
+ type Constructor<T extends object = object> = new () => T;
51
+ type AnnotatedClass = abstract new (...args: never[]) => object;
52
+ type Definition = {
53
+ id: string;
54
+ title?: string;
55
+ docs?: string;
56
+ kind?:
57
+ | "factory"
58
+ | "deployment"
59
+ | "system"
60
+ | "interface"
61
+ | "process"
62
+ | "block"
63
+ | "resource"
64
+ | "artifact";
65
+ };
66
+ type Operation = { name: string; contract: Contract<unknown, unknown> };
67
+ const definitions = new WeakMap<Function, Definition>();
68
+ const operations = new WeakMap<object, Operation[]>();
69
+ const owned = new WeakSet<object>();
70
+ const ports = new WeakMap<
71
+ object,
72
+ {
73
+ contract: Contract<unknown, unknown>;
74
+ provider?: (input: unknown) => Promise<unknown>;
75
+ }
76
+ >();
77
+ export interface OperationRuntime {
78
+ invoke<T>(
79
+ boundary: { elementId: string; operation: string; contract: string },
80
+ execute: () => Promise<T>,
81
+ ): Promise<T>;
82
+ }
83
+ const executionBindings = new WeakMap<
84
+ object,
85
+ { id: string; runtime?: OperationRuntime }
86
+ >();
87
+ const observers = new WeakMap<object, (event: BoundaryEvent) => void>();
88
+ export interface BoundaryEvent {
89
+ elementId?: string;
90
+ invocationId: string;
91
+ operation: string;
92
+ contract: string;
93
+ timestamp: number;
94
+ durationMs?: number;
95
+ status: "started" | "completed" | "failed";
96
+ }
97
+
98
+ export function block(definition: Definition) {
99
+ return <T extends AnnotatedClass>(
100
+ target: T,
101
+ _context?: ClassDecoratorContext<T>,
102
+ ) => {
103
+ definitions.set(target, Object.freeze({ ...definition }));
104
+ };
105
+ }
106
+ export function own<T extends object, Args extends unknown[]>(
107
+ type: new (...args: Args) => T,
108
+ ...args: Args
109
+ ): T {
110
+ const instance = new type(...args);
111
+ owned.add(instance);
112
+ return instance;
113
+ }
114
+ export function use<I, O>(
115
+ definition: Contract<I, O>,
116
+ ): (input: I) => Promise<O> {
117
+ const port = async (input: I): Promise<O> => {
118
+ const bound = ports.get(port)!;
119
+ if (!bound.provider)
120
+ throw new Error(`Unbound capability: ${definition.id}`);
121
+ return validate<O>(
122
+ definition,
123
+ "output",
124
+ await bound.provider(validate<I>(definition, "input", input)),
125
+ );
126
+ };
127
+ ports.set(port, { contract: definition as Contract<unknown, unknown> });
128
+ return port;
129
+ }
130
+ export function operation<I, O>(definition: Contract<I, O>) {
131
+ type Method<This> = (this: This, input: I) => Promise<O>;
132
+ function wrap<This extends object>(
133
+ method: Method<This>,
134
+ name: string,
135
+ ): Method<This> {
136
+ return async function (this: This, input: I): Promise<O> {
137
+ const execute = async (): Promise<O> => {
138
+ const invocationId = crypto.randomUUID(),
139
+ startedAt = performance.now();
140
+ const emit = (status: BoundaryEvent["status"]) => {
141
+ // An observer failure must never change an operation's result.
142
+ try {
143
+ observers.get(this)?.({
144
+ invocationId,
145
+ operation: name,
146
+ contract: definition.id,
147
+ timestamp: Date.now(),
148
+ durationMs:
149
+ status === "started"
150
+ ? undefined
151
+ : performance.now() - startedAt,
152
+ status,
153
+ });
154
+ } catch {
155
+ /* observer only */
156
+ }
157
+ };
158
+ emit("started");
159
+ try {
160
+ const output = validate<O>(
161
+ definition,
162
+ "output",
163
+ await method.call(this, validate<I>(definition, "input", input)),
164
+ );
165
+ emit("completed");
166
+ return output;
167
+ } catch (error) {
168
+ emit("failed");
169
+ throw error;
170
+ }
171
+ };
172
+ const binding = executionBindings.get(this);
173
+ return binding?.runtime
174
+ ? binding.runtime.invoke(
175
+ {
176
+ elementId: `${binding.id}#${name}`,
177
+ operation: name,
178
+ contract: definition.id,
179
+ },
180
+ execute,
181
+ )
182
+ : execute();
183
+ };
184
+ }
185
+ function decorate<This extends object>(
186
+ method: Method<This>,
187
+ context: ClassMethodDecoratorContext<This, Method<This>>,
188
+ ): Method<This>;
189
+ function decorate<This extends object>(
190
+ target: This,
191
+ key: string | symbol,
192
+ descriptor: TypedPropertyDescriptor<Method<This>>,
193
+ ): TypedPropertyDescriptor<Method<This>>;
194
+ function decorate<This extends object>(
195
+ target: This | Method<This>,
196
+ context: ClassMethodDecoratorContext<This, Method<This>> | string | symbol,
197
+ descriptor?: TypedPropertyDescriptor<Method<This>>,
198
+ ): unknown {
199
+ const register = (instance: object, name: string) => {
200
+ const list = operations.get(instance) || [];
201
+ list.push({ name, contract: definition as Contract<unknown, unknown> });
202
+ operations.set(instance, list);
203
+ };
204
+ if (typeof context === "object") {
205
+ context.addInitializer(function () {
206
+ register(this, String(context.name));
207
+ });
208
+ return wrap(target as Method<This>, String(context.name));
209
+ }
210
+ // Bun 1.3 emits legacy decorators; TypeScript emits the standard proposal.
211
+ if (!descriptor?.value)
212
+ throw new Error("@operation requires an async method");
213
+ register(target, String(context));
214
+ descriptor.value = wrap(descriptor.value, String(context));
215
+ return descriptor;
216
+ }
217
+ return decorate;
218
+ }
219
+ function blockOperations(instance: object): Operation[] {
220
+ const result = new Map<string, Operation>();
221
+ for (
222
+ let current: object | null = instance;
223
+ current;
224
+ current = Object.getPrototypeOf(current)
225
+ ) {
226
+ for (const item of operations.get(current) || [])
227
+ if (!result.has(item.name)) result.set(item.name, item);
228
+ }
229
+ return [...result.values()];
230
+ }
231
+ export interface InstanceDefinition {
232
+ id: string;
233
+ title: string;
234
+ parent?: string;
235
+ operations: { name: string; contract: string }[];
236
+ requires: string[];
237
+ }
238
+ function walk(
239
+ root: object,
240
+ visit: (instance: object, id: string, parent?: string) => void,
241
+ ) {
242
+ const seen = new Set<object>();
243
+ const next = (instance: object, parent?: string, field?: string) => {
244
+ if (seen.has(instance))
245
+ throw new Error(
246
+ "A block must have one owner; use a capability for shared dependencies",
247
+ );
248
+ seen.add(instance);
249
+ const definition = definitions.get(instance.constructor);
250
+ if (!definition)
251
+ throw new Error(`Undeclared block: ${instance.constructor.name}`);
252
+ const id = parent ? `${parent}/${field}` : definition.id;
253
+ visit(instance, id, parent);
254
+ for (const [key, value] of Object.entries(instance))
255
+ if (value && typeof value === "object" && owned.has(value))
256
+ next(value, id, key);
257
+ };
258
+ next(root);
259
+ }
260
+ export function describe(root: object): InstanceDefinition[] {
261
+ const result: InstanceDefinition[] = [];
262
+ walk(root, (instance, id, parent) =>
263
+ result.push({
264
+ id,
265
+ title:
266
+ definitions.get(instance.constructor)!.title ||
267
+ instance.constructor.name,
268
+ parent,
269
+ operations: blockOperations(instance).map((op) => ({
270
+ name: op.name,
271
+ contract: op.contract.id,
272
+ })),
273
+ requires: Object.values(instance).flatMap((value) =>
274
+ typeof value === "function" && ports.has(value)
275
+ ? [ports.get(value)!.contract.id]
276
+ : [],
277
+ ),
278
+ }),
279
+ );
280
+ return result;
281
+ }
282
+ export interface BindOptions {
283
+ bindings?: ReadonlyMap<string, (input: unknown) => Promise<unknown>>;
284
+ observe?: (event: BoundaryEvent) => void;
285
+ runtime?: OperationRuntime;
286
+ }
287
+ /** Bind actual owned providers; ambiguous providers require an explicit binding. */
288
+ export function bind<T extends object>(
289
+ instance: T,
290
+ options: BindOptions = {},
291
+ ): T {
292
+ const providers = new Map<
293
+ string,
294
+ Array<(input: unknown) => Promise<unknown>>
295
+ >();
296
+ walk(instance, (block) => {
297
+ for (const op of blockOperations(block)) {
298
+ const list = providers.get(op.contract.id) || [];
299
+ list.push((input) =>
300
+ (block as Record<string, (input: unknown) => Promise<unknown>>)[
301
+ op.name
302
+ ](input),
303
+ );
304
+ providers.set(op.contract.id, list);
305
+ }
306
+ });
307
+ walk(instance, (block, id) => {
308
+ executionBindings.set(block, { id, runtime: options.runtime });
309
+ if (options.observe)
310
+ observers.set(block, (event) =>
311
+ options.observe!({ ...event, elementId: `${id}#${event.operation}` }),
312
+ );
313
+ for (const value of Object.values(block))
314
+ if (typeof value === "function" && ports.has(value)) {
315
+ const port = ports.get(value)!;
316
+ const candidates = providers.get(port.contract.id) || [];
317
+ port.provider = options.bindings?.get(port.contract.id);
318
+ if (!port.provider && candidates.length > 1)
319
+ throw new Error(`Ambiguous capability: ${port.contract.id}`);
320
+ port.provider ||= candidates[0];
321
+ if (!port.provider)
322
+ throw new Error(`Unbound capability: ${port.contract.id}`);
323
+ }
324
+ });
325
+ return instance;
326
+ }
327
+
328
+ export function create<T extends object>(
329
+ type: Constructor<T>,
330
+ options: BindOptions = {},
331
+ ): T {
332
+ return bind(new type(), options);
333
+ }
334
+ /** Read declarations from actual ownership; schemas come from the enforced contracts. */
335
+ export function declarations(root: object) {
336
+ const result: Array<{
337
+ id: string;
338
+ parent?: string;
339
+ definition: Definition;
340
+ operations: Operation[];
341
+ requires: string[];
342
+ }> = [];
343
+ walk(root, (instance, id, parent) =>
344
+ result.push({
345
+ id,
346
+ parent,
347
+ definition: definitions.get(instance.constructor)!,
348
+ operations: blockOperations(instance),
349
+ requires: Object.values(instance).flatMap((value) =>
350
+ typeof value === "function" && ports.has(value)
351
+ ? [ports.get(value)!.contract.id]
352
+ : [],
353
+ ),
354
+ }),
355
+ );
356
+ return result;
357
+ }
@@ -0,0 +1,52 @@
1
+ import { readRepositoryMap } from "./repository-map";
2
+ import { readFileSync, existsSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import type { DefinitionGraph } from "./model";
5
+ import { mappingCoverage, coverageSummary } from "./mapping-coverage";
6
+ export async function runCoverage(args: string[]) {
7
+ if (args.includes("--help"))
8
+ return "fractal coverage [--missing | --discarded] [--json] [--root PATH] [--definition PATH]\nVerified TS/JS source ownership in the current checkout; not test coverage. --excluded is an alias for --discarded.";
9
+ const option = (name: string) => {
10
+ const index = args.indexOf(name);
11
+ if (index < 0) return undefined;
12
+ if (!args[index + 1] || args[index + 1].startsWith("--"))
13
+ throw Error(name + " needs a value");
14
+ return args[index + 1];
15
+ };
16
+ const root = resolve(option("--root") || process.cwd());
17
+ const graph = option("--definition")
18
+ ? (JSON.parse(
19
+ readFileSync(join(root, option("--definition")!), "utf8"),
20
+ ) as DefinitionGraph)
21
+ : readRepositoryMap(root);
22
+ if (!graph)
23
+ throw Error("No Fractory map in this repository. Run fractory setup.");
24
+ const report = await mappingCoverage(root, graph),
25
+ summary = coverageSummary(report);
26
+ const items =
27
+ args.includes("--missing") ||
28
+ args.includes("--excluded") ||
29
+ args.includes("--discarded")
30
+ ? report.items.filter(
31
+ (item) =>
32
+ item.excluded ===
33
+ (args.includes("--excluded") || args.includes("--discarded")),
34
+ )
35
+ : undefined;
36
+ if (args.includes("--json"))
37
+ return JSON.stringify({ ...summary, ...(items ? { items } : {}) }, null, 2);
38
+ return [
39
+ `Map coverage · ${report.percent === null ? "no in-scope source" : report.percent.toFixed(1) + "%"}`,
40
+ `${report.mapped.toLocaleString()} mapped / ${(report.mapped + report.missing).toLocaleString()} in-scope TS/JS source lines · ${report.excluded.toLocaleString()} discarded`,
41
+ `${report.mappedDeclarations.toLocaleString()} in declarations · ${report.mappedBlockSource.toLocaleString()} in block implementation files`,
42
+ `${summary.missingRegions} missing regions · ${report.sourceWarnings.length} stale source references · ${report.warnings.length} unmeasured files`,
43
+ ...(items
44
+ ? items.map(
45
+ (item) =>
46
+ `${item.file}:${item.start}-${item.end} · ${item.lines} lines\n ${item.label}${item.exclusionReason ? "\n " + item.exclusionReason : ""}`,
47
+ )
48
+ : [
49
+ "Use --missing to inspect uncovered declarations, or --excluded for dismissed regions.",
50
+ ]),
51
+ ].join("\n");
52
+ }
@@ -0,0 +1,69 @@
1
+ import ts from "typescript";
2
+ import type { DefinitionGraph, SourceRef } from "./model";
3
+ import { sourceDigest } from "./source-index";
4
+
5
+ /** Associate decorator sites by their declared identities, never by filesystem nesting. */
6
+ export function declarationSources(
7
+ graph: DefinitionGraph,
8
+ file: string,
9
+ text: string,
10
+ ): DefinitionGraph {
11
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
12
+ const sources = new Map<string, SourceRef>();
13
+ const digest = sourceDigest(text);
14
+ for (const node of sf.statements) {
15
+ if (!ts.isClassDeclaration(node)) continue;
16
+ const decorator = ts
17
+ .getDecorators(node)
18
+ ?.find(
19
+ (d) =>
20
+ ts.isCallExpression(d.expression) &&
21
+ d.expression.expression.getText(sf) === "block",
22
+ );
23
+ if (!decorator || !ts.isCallExpression(decorator.expression)) continue;
24
+ const config = decorator.expression.arguments[0];
25
+ if (!config || !ts.isObjectLiteralExpression(config)) continue;
26
+ const prop = config.properties.find(
27
+ (p) => ts.isPropertyAssignment(p) && p.name.getText(sf) === "id",
28
+ );
29
+ if (
30
+ !prop ||
31
+ !ts.isPropertyAssignment(prop) ||
32
+ !ts.isStringLiteral(prop.initializer)
33
+ )
34
+ continue;
35
+ const local = prop.initializer.text;
36
+ const blocks = graph.elements.filter(
37
+ (e) => e.id === local || e.id.endsWith(`/${local}`),
38
+ );
39
+ if (blocks.length !== 1) continue;
40
+ const block = blocks[0];
41
+ const ref = (item: ts.Node): SourceRef => ({
42
+ file,
43
+ line: sf.getLineAndCharacterOfPosition(item.getStart(sf)).line + 1,
44
+ digest,
45
+ });
46
+ sources.set(block.id, ref(node));
47
+ for (const member of node.members)
48
+ if (
49
+ ts.isMethodDeclaration(member) &&
50
+ ts
51
+ .getDecorators(member)
52
+ ?.some(
53
+ (d) =>
54
+ ts.isCallExpression(d.expression) &&
55
+ d.expression.expression.getText(sf) === "operation",
56
+ )
57
+ ) {
58
+ const id = `${block.id}#${member.name.getText(sf)}`;
59
+ if (graph.elements.some((e) => e.id === id))
60
+ sources.set(id, ref(member));
61
+ }
62
+ }
63
+ return {
64
+ ...graph,
65
+ elements: graph.elements.map((e) =>
66
+ sources.has(e.id) ? { ...e, source: sources.get(e.id) } : e,
67
+ ),
68
+ };
69
+ }
@@ -0,0 +1,74 @@
1
+ import { declarations } from "./core";
2
+ import type { DefinitionGraph } from "./model";
3
+
4
+ /** This fingerprints the declared structure and schemas, not a deployment's source revision. */
5
+ export function declaredGraph(root: object): DefinitionGraph {
6
+ const blocks = declarations(root);
7
+ const elements: DefinitionGraph["elements"] = blocks.flatMap((b) => [
8
+ {
9
+ id: b.id,
10
+ parent: b.parent,
11
+ label: b.definition.title || b.definition.id,
12
+ kind: b.definition.kind || "block",
13
+ provenance: "declared" as const,
14
+ description: b.definition.docs,
15
+ },
16
+ ...b.operations.map((op) => ({
17
+ id: `${b.id}#${op.name}`,
18
+ parent: b.id,
19
+ label: op.name,
20
+ kind: "operation" as const,
21
+ provenance: "declared" as const,
22
+ ...(b.operations.length === 1 ? { description: b.definition.docs } : {}),
23
+ contract: {
24
+ id: op.contract.id,
25
+ input: op.contract.input.jsonSchema,
26
+ output: op.contract.output.jsonSchema,
27
+ },
28
+ })),
29
+ ]);
30
+ const providers = new Map<string, string[]>();
31
+ for (const b of blocks)
32
+ for (const op of b.operations)
33
+ providers.set(op.contract.id, [
34
+ ...(providers.get(op.contract.id) || []),
35
+ `${b.id}#${op.name}`,
36
+ ]);
37
+ const connections: DefinitionGraph["connections"] = [];
38
+ for (const b of blocks)
39
+ for (const requirement of b.requires) {
40
+ const candidates = providers.get(requirement) || [];
41
+ if (candidates.length !== 1)
42
+ throw new Error(
43
+ `Declared capability ${requirement} needs one provider, found ${candidates.length}`,
44
+ );
45
+ connections.push({
46
+ id: `${b.id}->${candidates[0]}:${requirement}`,
47
+ source:
48
+ b.operations.length === 1 ? `${b.id}#${b.operations[0].name}` : b.id,
49
+ target: candidates[0],
50
+ relation: "requires",
51
+ label: requirement,
52
+ provenance: "declared",
53
+ });
54
+ }
55
+ const content = JSON.stringify({ elements, connections });
56
+ let fingerprint = 14695981039346656037n;
57
+ for (const byte of new TextEncoder().encode(content))
58
+ fingerprint = BigInt.asUintN(
59
+ 64,
60
+ (fingerprint ^ BigInt(byte)) * 1099511628211n,
61
+ );
62
+ return {
63
+ schema: "fractal.definition.v1",
64
+ id: blocks[0].id,
65
+ revision: fingerprint.toString(16).padStart(16, "0"),
66
+ generatedAt: "declaration",
67
+ scope: blocks[0].definition.title || blocks[0].definition.id,
68
+ elements,
69
+ connections,
70
+ tests: [],
71
+ failures: [],
72
+ gaps: [],
73
+ };
74
+ }
@@ -0,0 +1,8 @@
1
+ /** A readable fallback for code symbols. Explicit product labels and identities stay intact. */
2
+ export function displayName(symbol: string) {
3
+ return symbol
4
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
5
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
6
+ .replace(/[_-]+/g, " ")
7
+ .replace(/^./, (letter) => letter.toUpperCase());
8
+ }