@granular-software/fractory 0.1.24 → 0.1.25

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 (63) hide show
  1. package/dist/annotations.d.ts +4 -0
  2. package/dist/compiler.js +161 -4
  3. package/dist/core.d.ts +1 -0
  4. package/dist/core.js +1 -0
  5. package/dist/declared-graph.js +2 -1
  6. package/dist/factory-graph.d.ts +4 -1
  7. package/dist/factory-graph.js +77 -6
  8. package/dist/factory-model.d.ts +14 -0
  9. package/dist/git-code.js +1 -1
  10. package/dist/interface-map.d.ts +15 -0
  11. package/dist/interface-map.js +125 -0
  12. package/dist/map-quality.d.ts +6 -0
  13. package/dist/map-quality.js +5 -0
  14. package/dist/model.d.ts +6 -2
  15. package/dist/product-map.d.ts +2 -0
  16. package/dist/product-map.js +33 -4
  17. package/dist/public-boundaries.d.ts +13 -0
  18. package/dist/public-boundaries.js +115 -0
  19. package/dist/repository-map.js +3 -1
  20. package/dist/scope.d.ts +2 -0
  21. package/dist/scope.js +77 -3
  22. package/dist/source-index.js +4 -0
  23. package/dist/source-review-git.js +3 -1
  24. package/dist/source-review.d.ts +3 -1
  25. package/dist/source-review.js +94 -14
  26. package/dist/work-check.d.ts +1 -0
  27. package/dist/work-check.js +6 -1
  28. package/dist/work-cli.js +29 -1
  29. package/dist/work-context.d.ts +2 -0
  30. package/dist/work-context.js +30 -4
  31. package/dist/work-lock-check.d.ts +12 -0
  32. package/dist/work-lock-check.js +339 -0
  33. package/dist/work-locks.d.ts +10 -0
  34. package/dist/work-locks.js +98 -0
  35. package/dist/work-model.d.ts +9 -0
  36. package/dist/work-model.js +50 -1
  37. package/package.json +1 -1
  38. package/src/annotations.ts +4 -0
  39. package/src/compiler.ts +190 -4
  40. package/src/core.ts +4 -0
  41. package/src/declared-graph.ts +2 -1
  42. package/src/factory-graph.ts +89 -5
  43. package/src/factory-model.ts +9 -0
  44. package/src/git-code.ts +1 -1
  45. package/src/interface-map.ts +166 -0
  46. package/src/map-quality.ts +5 -0
  47. package/src/model.ts +10 -3
  48. package/src/product-map.ts +51 -16
  49. package/src/public-boundaries.ts +143 -0
  50. package/src/repository-map.ts +3 -1
  51. package/src/scope.ts +92 -3
  52. package/src/source-index.ts +3 -0
  53. package/src/source-review-git.ts +3 -1
  54. package/src/source-review.ts +112 -13
  55. package/src/work-check.ts +7 -1
  56. package/src/work-cli.ts +35 -1
  57. package/src/work-context.ts +43 -3
  58. package/src/work-lock-check.ts +549 -0
  59. package/src/work-locks.ts +108 -0
  60. package/src/work-model.ts +67 -1
  61. package/toolkit/GUIDE.md +72 -23
  62. package/toolkit/SKILL.md +16 -5
  63. package/toolkit/build.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { interfaceMap } from "./interface-map.js";
1
2
  /** Convert a reviewed inventory into the same graph used by the runtime viewer. */
2
3
  export function buildProductMap(catalog) {
3
4
  const sources = (ids) => [...new Set(ids)].map((id) => {
@@ -29,6 +30,7 @@ export function buildProductMap(catalog) {
29
30
  description: catalog.basis,
30
31
  },
31
32
  ];
33
+ const entries = [];
32
34
  for (const system of catalog.systems) {
33
35
  const evidence = sources(system.parts.flatMap((part) => part.evidence));
34
36
  elements.push({
@@ -62,8 +64,30 @@ export function buildProductMap(catalog) {
62
64
  provenance: "source",
63
65
  description: part.summary,
64
66
  signature: part.signature,
65
- source: evidence[0],
66
- sources: evidence,
67
+ ...(part.entryFor
68
+ ? {
69
+ contract: {
70
+ id,
71
+ input: {
72
+ language: "reviewed-source",
73
+ signature: part.signature,
74
+ declarations: evidence.map((source) => ({
75
+ source,
76
+ declaration: source.symbol,
77
+ })),
78
+ },
79
+ },
80
+ }
81
+ : {}),
82
+ source: part.entryFor
83
+ ? { ...evidence[0], scope: "contract" }
84
+ : evidence[0],
85
+ sources: part.entryFor
86
+ ? evidence.map((source) => ({
87
+ ...source,
88
+ scope: "contract",
89
+ }))
90
+ : evidence,
67
91
  resources: part.resources?.map((resource) => ({
68
92
  id: resource.id,
69
93
  label: resource.name,
@@ -81,6 +105,11 @@ export function buildProductMap(catalog) {
81
105
  provenance: "source",
82
106
  })),
83
107
  });
108
+ if (part.entryFor)
109
+ entries.push({
110
+ implementation: part.entryFor,
111
+ interface: elements[elements.length - 1],
112
+ });
84
113
  addParts(part.parts || [], id);
85
114
  }
86
115
  };
@@ -151,7 +180,7 @@ export function buildProductMap(catalog) {
151
180
  let hash = 14695981039346656037n;
152
181
  for (const byte of new TextEncoder().encode(content))
153
182
  hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 1099511628211n);
154
- return {
183
+ return interfaceMap({
155
184
  schema: "fractal.definition.v1",
156
185
  id: catalog.id,
157
186
  revision: hash.toString(16).padStart(16, "0"),
@@ -164,5 +193,5 @@ export function buildProductMap(catalog) {
164
193
  tests: [],
165
194
  failures: [],
166
195
  gaps: [],
167
- };
196
+ }, entries, { exposeAncestors: true });
168
197
  }
@@ -0,0 +1,13 @@
1
+ import type { DefinitionGraph, Connection } from "./model.js";
2
+ /** Outside is relative to each enclosing black box. Never fabricate an interface
3
+ * to make a direct implementation call look encapsulated. Pure source diagnosis. */
4
+ export declare function boundaryViolations(graph: DefinitionGraph): {
5
+ connection: string;
6
+ block: string;
7
+ target: string;
8
+ reason: string;
9
+ }[];
10
+ /** New definitions and plan edits are rejected at the model boundary. Readers
11
+ * can still inspect older snapshots and report their original violations. */
12
+ export declare function assertPublicConnections(graph: DefinitionGraph): void;
13
+ export declare function publicConnectionError(graph: DefinitionGraph, edge: Connection): string | undefined;
@@ -0,0 +1,115 @@
1
+ const transfers = new Set([
2
+ "calls",
3
+ "renders",
4
+ "callbacks",
5
+ "delegates",
6
+ "resumes",
7
+ "requires",
8
+ "flows",
9
+ "reads",
10
+ "writes",
11
+ "loads",
12
+ "produces",
13
+ "exposes",
14
+ ]);
15
+ /** Outside is relative to each enclosing black box. Never fabricate an interface
16
+ * to make a direct implementation call look encapsulated. Pure source diagnosis. */
17
+ export function boundaryViolations(graph) {
18
+ const byId = new Map(graph.elements.map((n) => [n.id, n]));
19
+ const path = (id) => {
20
+ const result = [], seen = new Set();
21
+ while (byId.has(id) && !seen.has(id)) {
22
+ seen.add(id);
23
+ result.push(id);
24
+ id = byId.get(id)?.parent || "";
25
+ }
26
+ return result;
27
+ };
28
+ const paths = new Map(graph.elements.map((n) => [n.id, path(n.id)]));
29
+ const exposures = new Map();
30
+ for (const e of graph.connections)
31
+ if (e.relation === "exposes" && byId.get(e.target)?.kind === "interface") {
32
+ if (!exposures.has(e.source))
33
+ exposures.set(e.source, new Set());
34
+ exposures.get(e.source).add(e.target);
35
+ }
36
+ return graph.connections.flatMap((edge) => {
37
+ if (!transfers.has(edge.relation))
38
+ return [];
39
+ const sourcePath = new Set(paths.get(edge.source) || []), targetPath = paths.get(edge.target) || [];
40
+ // A receiver itself can be an interface; methods inside it also belong to its contract.
41
+ const issues = [];
42
+ const receiver = byId.get(edge.target);
43
+ if (edge.relation === "exposes") {
44
+ return receiver?.kind === "interface"
45
+ ? []
46
+ : [
47
+ {
48
+ connection: edge.id,
49
+ block: edge.source,
50
+ target: edge.target,
51
+ reason: "Only an interface can be publicly exposed.",
52
+ },
53
+ ];
54
+ }
55
+ const owner = targetPath.find((id) => {
56
+ const node = byId.get(id);
57
+ return ![
58
+ "interface",
59
+ "method",
60
+ "operation",
61
+ "resource",
62
+ "artifact",
63
+ ].includes(node.kind);
64
+ });
65
+ if (receiver &&
66
+ owner &&
67
+ !sourcePath.has(owner) &&
68
+ !["interface", "resource", "artifact"].includes(receiver.kind))
69
+ issues.push({
70
+ connection: edge.id,
71
+ block: owner,
72
+ target: edge.target,
73
+ reason: `Connect to a public interface of ${byId.get(owner).label}, not its internal ${receiver.label}.`,
74
+ });
75
+ for (let i = 0; i < targetPath.length; i++) {
76
+ const id = targetPath[i], node = byId.get(id);
77
+ if (sourcePath.has(id))
78
+ break;
79
+ if (["interface", "method", "operation", "resource", "artifact"].includes(node.kind) ||
80
+ id === graph.id)
81
+ continue;
82
+ const entry = i > 0 ? byId.get(targetPath[i - 1]) : undefined;
83
+ // An interface is public to its immediate owner. An inner interface is
84
+ // not implicitly exposed on every ancestor.
85
+ const exposed = entry?.kind === "interface" ||
86
+ targetPath.slice(0, i).some((target) => exposures.get(id)?.has(target));
87
+ if (!exposed && !issues.some((issue) => issue.block === id))
88
+ issues.push({
89
+ connection: edge.id,
90
+ block: id,
91
+ target: edge.target,
92
+ reason: `Call bypasses the public interface of ${node.label}.`,
93
+ });
94
+ }
95
+ return issues;
96
+ });
97
+ }
98
+ /** New definitions and plan edits are rejected at the model boundary. Readers
99
+ * can still inspect older snapshots and report their original violations. */
100
+ export function assertPublicConnections(graph) {
101
+ const issues = boundaryViolations(graph);
102
+ if (issues.length)
103
+ throw Error(issues.map((issue) => `${issue.connection}: ${issue.reason}`).join("\n"));
104
+ }
105
+ export function publicConnectionError(graph, edge) {
106
+ if (![edge.source, edge.target].every((id) => graph.elements.some((node) => node.id === id)))
107
+ return "Choose an existing block and a public interface.";
108
+ return boundaryViolations({
109
+ ...graph,
110
+ connections: [
111
+ ...graph.connections.filter((item) => item.relation === "exposes" && item.id !== edge.id),
112
+ edge,
113
+ ],
114
+ }).find((issue) => issue.connection === edge.id)?.reason;
115
+ }
@@ -92,7 +92,9 @@ export function mapFromArtifacts(config, read) {
92
92
  const graph = composeDefinitions(JSON.parse(base), mounts);
93
93
  const annotations = map.annotations && read(map.annotations);
94
94
  return annotations
95
- ? factoryGraph(JSON.parse(annotations), graph)
95
+ ? factoryGraph(JSON.parse(annotations), graph, {
96
+ legacySnapshot: true,
97
+ })
96
98
  : graph;
97
99
  }
98
100
  export function readRepositoryMap(root) {
package/dist/scope.d.ts CHANGED
@@ -8,5 +8,7 @@ export declare function scopeGraph(graph: DefinitionGraph, focus: string, expand
8
8
  originalTarget: string;
9
9
  })[];
10
10
  external: Set<string>;
11
+ frontier: Set<string>;
12
+ implementation: Set<string>;
11
13
  contextLabel: (node: Element) => string;
12
14
  };
package/dist/scope.js CHANGED
@@ -20,6 +20,42 @@ export function scopeGraph(graph, focus, expanded) {
20
20
  const nodes = graph.elements.filter((node) => node.id !== scope.id && inside(node.id) && visibleInside(node));
21
21
  const shown = new Set(nodes.map((node) => node.id));
22
22
  const external = new Set();
23
+ const frontier = new Set(nodes.filter((node) => node.kind === "interface").map((node) => node.id));
24
+ const incoming = new Set(graph.connections
25
+ .filter((edge) => edge.relation !== "exposes" &&
26
+ !inside(edge.source) &&
27
+ inside(edge.target))
28
+ .map((edge) => edge.target));
29
+ // Explicitly exposed nested contracts appear on this boundary themselves;
30
+ // a presentation projection must not replace them with a bare owner box.
31
+ for (const edge of graph.connections) {
32
+ const api = byId.get(edge.target);
33
+ if (edge.relation === "exposes" &&
34
+ edge.source === scope.id &&
35
+ api?.kind === "interface" &&
36
+ inside(api.id) &&
37
+ incoming.has(api.id)) {
38
+ frontier.add(api.id);
39
+ if (!shown.has(api.id)) {
40
+ nodes.push(api);
41
+ shown.add(api.id);
42
+ }
43
+ }
44
+ }
45
+ const implementation = new Set();
46
+ let owner = byId.get(scope.parent || "");
47
+ while (owner && ["interface", "method", "operation"].includes(owner.kind))
48
+ owner = byId.get(owner.parent || "");
49
+ const implementationPeer = (id) => {
50
+ const seen = new Set();
51
+ while (owner && byId.has(id) && !seen.has(id)) {
52
+ if (id === owner.id)
53
+ return true;
54
+ seen.add(id);
55
+ id = byId.get(id).parent || "";
56
+ }
57
+ return false;
58
+ };
23
59
  const contextLabel = (node) => {
24
60
  const names = [];
25
61
  let current = node.parent ? byId.get(node.parent) : undefined;
@@ -58,7 +94,7 @@ export function scopeGraph(graph, focus, expanded) {
58
94
  // At a product-area zoom level, outside peers are product areas too. Keep
59
95
  // fine-grained endpoints on the wire instead of filling the canvas with
60
96
  // external methods. Deeper views still meet public interfaces directly.
61
- if (scope.parent === graph.id) {
97
+ if (scope.kind !== "interface" && scope.parent === graph.id) {
62
98
  while (current.parent && current.parent !== graph.id) {
63
99
  const parent = byId.get(current.parent);
64
100
  if (!parent)
@@ -71,14 +107,44 @@ export function scopeGraph(graph, focus, expanded) {
71
107
  nodes.push(current);
72
108
  shown.add(id);
73
109
  external.add(id);
110
+ if (scope.kind === "interface" && implementationPeer(id))
111
+ implementation.add(id);
74
112
  }
75
113
  return id;
76
114
  };
77
115
  const edges = [];
116
+ // The canonical receiver stays the public API. When that API is open, show
117
+ // the known implementation endpoint through its boundary, rather than two
118
+ // unrelated wires ending and starting at different points on the enclosure.
119
+ const entrypoints = new Map(graph.connections.flatMap((edge) => scope.kind === "interface" &&
120
+ edge.target === scope.id &&
121
+ !inside(edge.source) &&
122
+ edge.provenance !== "proposed" &&
123
+ edge.entrypoint &&
124
+ edge.entrypoint !== scope.id &&
125
+ inside(edge.entrypoint)
126
+ ? [[edge.id, edge.entrypoint]]
127
+ : []));
128
+ const reached = new Set(entrypoints.values());
78
129
  for (const edge of graph.connections) {
130
+ // Exposure is a contract declaration, shown by the real frontier card.
131
+ // It is not an invocation and should not become another canvas wire.
132
+ if (edge.relation === "exposes")
133
+ continue;
134
+ // This generated fallback only supplies the interior half when the exact
135
+ // caller-to-member wire is not already visible. Keep authored delegations.
136
+ if (edge.source === scope.id &&
137
+ reached.has(edge.target) &&
138
+ edge.id === `interface-implementation:${scope.id}:${edge.target}`)
139
+ continue;
140
+ if (edge.relation === "delegates" &&
141
+ edge.target === scope.id &&
142
+ byId.get(edge.source)?.kind === "interface" &&
143
+ byId.get(edge.source)?.parent === scope.id)
144
+ continue;
79
145
  if (!inside(edge.source) && !inside(edge.target))
80
146
  continue;
81
- const source = endpoint(edge.source), target = endpoint(edge.target);
147
+ const source = endpoint(edge.source), target = endpoint(entrypoints.get(edge.id) || edge.target);
82
148
  if (source && target && source !== target)
83
149
  edges.push({
84
150
  ...edge,
@@ -90,5 +156,13 @@ export function scopeGraph(graph, focus, expanded) {
90
156
  }
91
157
  if (!nodes.length && scope.id !== graph.id)
92
158
  nodes.push(scope);
93
- return { scope, nodes, edges, external, contextLabel };
159
+ return {
160
+ scope,
161
+ nodes,
162
+ edges,
163
+ external,
164
+ frontier,
165
+ implementation,
166
+ contextLabel,
167
+ };
94
168
  }
@@ -40,6 +40,10 @@ export function indexSources(graph, read, cache, options = {}) {
40
40
  for (const element of graph.elements) {
41
41
  for (const ref of element.sources ||
42
42
  (element.source ? [element.source] : [])) {
43
+ // A public signature points to its implementation for contract review,
44
+ // but does not own the body or the rest of an enclosing class/file.
45
+ if (ref.scope === "contract")
46
+ continue;
43
47
  if (!safeFile(ref.file))
44
48
  throw new Error("Source paths must be repository relative");
45
49
  const list = refs.get(ref.file) || [];
@@ -95,7 +95,9 @@ export function revisionSourceMap(root, definition, areas, ref) {
95
95
  if (cached)
96
96
  return cached;
97
97
  const source = readMapSources(root, definition, areas, revision);
98
- const graph = sourceReviewMap(definition, source.files, areas, revision);
98
+ const graph = sourceReviewMap(definition, source.files, areas, revision, {
99
+ legacySnapshot: true,
100
+ });
99
101
  revisions.set(key, graph);
100
102
  if (revisions.size > 4)
101
103
  revisions.delete(revisions.keys().next().value);
@@ -13,4 +13,6 @@ export interface SourceArea {
13
13
  /** Explicit import aliases supplied by the repository adapter; never guessed. */
14
14
  aliases?: Record<string, string>;
15
15
  }
16
- export declare function sourceReviewMap(definition: DefinitionGraph, files: Map<string, string>, areas: SourceArea[], revision?: string): DefinitionGraph;
16
+ export declare function sourceReviewMap(definition: DefinitionGraph, files: Map<string, string>, areas: SourceArea[], revision?: string, options?: {
17
+ legacySnapshot?: boolean;
18
+ }): DefinitionGraph;
@@ -6,9 +6,10 @@ import { displayName } from "./display-name.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { posix } from "node:path";
8
8
  import ts from "typescript";
9
+ import { interfaceMap } from "./interface-map.js";
9
10
  const hash = (text) => createHash("sha256").update(text).digest("hex");
10
11
  const isTest = (file) => /\.(?:test|spec|vitest)\.[cm]?[jt]sx?$/.test(file);
11
- export function sourceReviewMap(definition, files, areas, revision) {
12
+ export function sourceReviewMap(definition, files, areas, revision, options = {}) {
12
13
  const graph = structuredClone(definition);
13
14
  const areaIds = new Set(areas.map((area) => area.id));
14
15
  const discoveredAreas = new Set(areas
@@ -19,10 +20,14 @@ export function sourceReviewMap(definition, files, areas, revision) {
19
20
  graph.elements = graph.elements.filter((n) => !(n.provenance === "source" &&
20
21
  (discoveredAreas.has(n.id) ||
21
22
  (/\/[a-f0-9]{12}$/.test(n.id) &&
22
- discoveredAreas.has(n.parent || "")) ||
23
+ (discoveredAreas.has(n.parent || "") ||
24
+ discoveredAreas.has((n.parent || "").replace(/::exports$/, "")))) ||
23
25
  (areaIds.has(n.id) &&
24
26
  n.source?.scope === "file" &&
25
- n.sources?.every((source) => source.scope === "file")))));
27
+ n.sources?.every((source) => source.scope === "file")) ||
28
+ (n.kind === "interface" &&
29
+ n.id.endsWith("::exports") &&
30
+ areaIds.has(n.parent || "")))));
26
31
  graph.elements = graph.elements.map((node) => !areaIds.has(node.id)
27
32
  ? node
28
33
  : {
@@ -114,7 +119,10 @@ export function sourceReviewMap(definition, files, areas, revision) {
114
119
  ts.isArrowFunction(value.arguments[0]))) {
115
120
  const imported = ast.statements.some((item) => ts.isImportDeclaration(item) &&
116
121
  ts.isStringLiteral(item.moduleSpecifier) &&
117
- ["@granular-software/fractal/annotations", "@granular-software/fractory/annotations"].includes(item.moduleSpecifier.text) &&
122
+ [
123
+ "@granular-software/fractal/annotations",
124
+ "@granular-software/fractory/annotations",
125
+ ].includes(item.moduleSpecifier.text) &&
118
126
  item.importClause?.namedBindings &&
119
127
  ts.isNamedImports(item.importClause.namedBindings) &&
120
128
  item.importClause.namedBindings.elements.some((name) => name.name.text ===
@@ -200,11 +208,15 @@ export function sourceReviewMap(definition, files, areas, revision) {
200
208
  }
201
209
  }
202
210
  const resolveImport = (file, spec) => {
203
- const aliases = areas.find(area => area.matches(file))?.aliases || {};
204
- const alias = Object.keys(aliases).sort((a, b) => b.length - a.length).find(prefix => spec.startsWith(prefix));
211
+ const aliases = areas.find((area) => area.matches(file))?.aliases || {};
212
+ const alias = Object.keys(aliases)
213
+ .sort((a, b) => b.length - a.length)
214
+ .find((prefix) => spec.startsWith(prefix));
205
215
  const base = spec.startsWith(".")
206
216
  ? posix.normalize(posix.join(posix.dirname(file), spec))
207
- : alias ? posix.normalize(aliases[alias] + spec.slice(alias.length)) : undefined;
217
+ : alias
218
+ ? posix.normalize(aliases[alias] + spec.slice(alias.length))
219
+ : undefined;
208
220
  if (!base)
209
221
  return;
210
222
  return [
@@ -218,14 +230,20 @@ export function sourceReviewMap(definition, files, areas, revision) {
218
230
  };
219
231
  // Bind lexical symbols without loading dependencies or executing code. A local
220
232
  // parameter named like an import must not become a fabricated cross-block call.
221
- const host = ts.createCompilerHost({ noLib: true, noResolve: true });
233
+ const compilerOptions = {
234
+ noLib: true,
235
+ noResolve: true,
236
+ allowJs: true,
237
+ checkJs: false,
238
+ };
239
+ const host = ts.createCompilerHost(compilerOptions);
222
240
  const clean = (path) => path.replace(/^\//, "");
223
241
  host.getCurrentDirectory = () => "/";
224
242
  host.getSourceFile = (file) => parsed.get(clean(file));
225
243
  host.fileExists = (file) => parsed.has(clean(file));
226
244
  host.readFile = (file) => files.get(clean(file));
227
245
  const checker = ts
228
- .createProgram([...parsed.keys()], { noLib: true, noResolve: true }, host)
246
+ .createProgram([...parsed.keys()], compilerOptions, host)
229
247
  .getTypeChecker();
230
248
  const connections = new Map();
231
249
  const enclosingOwner = (node, file, fallback) => {
@@ -481,13 +499,75 @@ export function sourceReviewMap(definition, files, areas, revision) {
481
499
  });
482
500
  }
483
501
  graph.connections.push(...connections.values());
502
+ const entries = [];
503
+ for (const area of areas.filter((area) => active.has(area.id) && byId.get(area.id)?.kind !== "interface")) {
504
+ const members = [...parsed]
505
+ .filter(([file]) => owners.get(file) === area.id && !isTest(file))
506
+ .flatMap(([file, ast]) => ast.statements.flatMap((statement) => {
507
+ if (ts.isInterfaceDeclaration(statement) ||
508
+ ts.isTypeAliasDeclaration(statement) ||
509
+ (ts.isExportDeclaration(statement) && statement.isTypeOnly))
510
+ return [];
511
+ const exported = ts.isExportAssignment(statement) ||
512
+ ts.isExportDeclaration(statement) ||
513
+ (ts.canHaveModifiers(statement) &&
514
+ ts
515
+ .getModifiers(statement)
516
+ ?.some((item) => item.kind === ts.SyntaxKind.ExportKeyword));
517
+ // CommonJS exports are public module entries too; plain private functions are not.
518
+ const commonJS = ts.isExpressionStatement(statement) &&
519
+ /^(module\.exports|exports\.)/.test(statement.expression.getText(ast));
520
+ if (!exported && !commonJS)
521
+ return [];
522
+ const source = {
523
+ ...refs.get(file),
524
+ line: ast.getLineAndCharacterOfPosition(statement.getStart(ast)).line +
525
+ 1,
526
+ };
527
+ const signature = ts.isFunctionDeclaration(statement) && statement.body
528
+ ? statement
529
+ .getText(ast)
530
+ .slice(0, statement.body.getStart(ast) - statement.getStart(ast))
531
+ .trim()
532
+ : statement.getText(ast).split("\n")[0].slice(0, 240);
533
+ return [{ source, signature }];
534
+ }));
535
+ if (!members.length)
536
+ continue;
537
+ const id = `${area.id}::exports`;
538
+ const api = {
539
+ id,
540
+ parent: area.id,
541
+ label: `${area.label} API`,
542
+ kind: "interface",
543
+ provenance: "source",
544
+ description: `Exported contracts of ${area.label}. Open to inspect the public entries and their implementation.`,
545
+ source: { ...members[0].source, scope: "contract" },
546
+ sources: members.map((member) => ({
547
+ ...member.source,
548
+ scope: "contract",
549
+ })),
550
+ contract: { id, input: { language: "typescript", members } },
551
+ };
552
+ // Public functions live in their interface; their source ownership remains exact.
553
+ for (const method of graph.elements.filter((node) => node.kind === "method" &&
554
+ node.parent === area.id &&
555
+ node.provenance === "source"))
556
+ method.parent = id;
557
+ entries.push({ implementation: area.id, interface: api });
558
+ }
559
+ const surfaced = interfaceMap(graph, entries, {
560
+ exposeAncestors: true,
561
+ validate: !options.legacySnapshot,
562
+ });
484
563
  graph.revision = hash(JSON.stringify({
485
564
  base: definition.revision,
486
565
  revision,
487
- elements: graph.elements,
488
- connections: graph.connections,
489
- tests: graph.tests,
566
+ elements: surfaced.elements,
567
+ connections: surfaced.connections,
568
+ tests: surfaced.tests,
490
569
  }));
491
- graph.codeRevision = revision;
492
- return graph;
570
+ surfaced.revision = graph.revision;
571
+ surfaced.codeRevision = revision;
572
+ return surfaced;
493
573
  }
@@ -5,6 +5,7 @@ export declare function checkWorkScope(root: string, id: string, currentGraph: D
5
5
  base: string;
6
6
  head: string;
7
7
  pass: boolean;
8
+ locks: import("./work-lock-check.js").LockResult[];
8
9
  files: {
9
10
  path: string;
10
11
  status: string;
@@ -5,6 +5,7 @@ import { readGit, resolveComparisonRef } from "./git-refs.js";
5
5
  import { parseWorkingStatus } from "./working-code.js";
6
6
  import { readWorkPlan, workBaseline } from "./work-context.js";
7
7
  import { scopeBlocks } from "./work-model.js";
8
+ import { checkWorkLocks } from "./work-lock-check.js";
8
9
  /** Conservative file ownership check. Shared and unknown ownership never produce a pass. */
9
10
  export async function checkWorkScope(root, id, currentGraph) {
10
11
  const { entry, plan } = readWorkPlan(root, id);
@@ -81,11 +82,15 @@ export async function checkWorkScope(root, id, currentGraph) {
81
82
  });
82
83
  const uncertain = files.filter((file) => ["unassigned", "shared"].includes(file.status));
83
84
  const outside = files.filter((file) => file.status === "outside");
85
+ const locks = checkWorkLocks(entry.root, plan, baseline, currentGraph, paths);
84
86
  return {
85
87
  work: id,
86
88
  base: plan.baseCommit,
87
89
  head,
88
- pass: !outside.length && !uncertain.length,
90
+ pass: !outside.length &&
91
+ !uncertain.length &&
92
+ locks.every((l) => l.status === "unchanged"),
93
+ locks,
89
94
  files,
90
95
  outside: outside.length,
91
96
  uncertain: uncertain.length,
package/dist/work-cli.js CHANGED
@@ -2,12 +2,13 @@ import { readFileSync, statSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { createWorkContext, adoptWorkContext, listWorkContexts, mainReference, readFactoryMap, resolveWorkContext, updateWorkPlan, workBaseline, workDeepLink, workHandoff, updateWorkIntent, } from "./work-context.js";
5
+ import { lockBrief } from "./work-locks.js";
5
6
  import { workIntentStates } from "./work-intents.js";
6
7
  import { readGit } from "./git-refs.js";
7
8
  import { checkWorkScope } from "./work-check.js";
8
9
  export async function runWork(args) {
9
10
  if (args.includes("--help"))
10
- return `fractory work list\nfractory work create --title TITLE --block ID [--block ID] [--from REF]\nfractory work adopt ID --block ID [--block ID] [--title TITLE]\nfractory work show ID\nfractory work handoff ID\nfractory work open ID\nfractory work plan ID --file PLAN.json --revision REVISION\nfractory work check ID\nfractory work review ID\nfractory work intent ID --proposal PROPOSAL_ID --status planned|done|dropped --revision REV [--implementation BLOCK_OR_CONNECTION_ID]\nfractory work pr ID --url URL --title TITLE\nUse --root PATH to select a repository. Creating a work adds a worktree; it never switches the current checkout. Plan JSON contains a proposals array and optional scope. Shared or unknown file ownership makes check fail.`;
11
+ return `fractory work list\nfractory work create --title TITLE --block ID [--block ID] [--from REF]\nfractory work adopt ID --block ID [--block ID] [--title TITLE]\nfractory work show ID\nfractory work handoff ID\nfractory work open ID\nfractory work plan ID --file PLAN.json --revision REVISION\nfractory work check ID\nfractory work lock ID --block BLOCK_ID --revision REVISION [--note REASON]\nfractory work unlock ID --block BLOCK_ID --revision REVISION\nfractory work review ID\nfractory work intent ID --proposal PROPOSAL_ID --status planned|done|dropped --revision REV [--implementation BLOCK_OR_CONNECTION_ID]\nfractory work pr ID --url URL --title TITLE\nUse --root PATH to select a repository. Creating a work adds a worktree; it never switches the current checkout. Plan JSON contains a proposals array and optional scope. Shared or unknown file ownership makes check fail.`;
11
12
  const option = (name) => {
12
13
  const i = args.indexOf(name);
13
14
  if (i < 0)
@@ -77,6 +78,25 @@ export async function runWork(args) {
77
78
  }
78
79
  if (action === "handoff")
79
80
  return workHandoff(work, graph);
81
+ if (action === "lock" || action === "unlock") {
82
+ if (!work.plan || !option("--revision") || !option("--block"))
83
+ throw Error("Use --block ID and --revision from work show.");
84
+ const target = option("--block");
85
+ const node = graph.elements.find((n) => n.id === target);
86
+ if (action === "lock" && !node)
87
+ throw Error("Choose a mapped block or interface.");
88
+ const locks = (work.plan.locks || []).filter((l) => l.target !== target);
89
+ if (action === "lock")
90
+ locks.push({
91
+ target,
92
+ kind: node.kind === "interface" ? "contract" : "subtree",
93
+ ...(option("--note") ? { note: option("--note") } : {}),
94
+ });
95
+ return JSON.stringify(updateWorkPlan(root, id, graph, {
96
+ revision: option("--revision"),
97
+ locks,
98
+ }), null, 2);
99
+ }
80
100
  if (action === "open") {
81
101
  const url = workDeepLink(root, id);
82
102
  execFileSync("open", [url], { stdio: "ignore", timeout: 5000 });
@@ -96,6 +116,13 @@ export async function runWork(args) {
96
116
  `Scope: ${(work.plan?.scope || []).map((id) => labels.get(id) || id).join(", ")}`,
97
117
  "",
98
118
  `Scope check: ${report.pass ? "passed" : `${report.outside} outside; ${report.uncertain} shared or unmapped`}`,
119
+ ...lockBrief(graph, work.plan?.locks || []),
120
+ ...report.locks.flatMap((l) => l.status === "unchanged"
121
+ ? []
122
+ : [
123
+ `Lock ${l.target}: ${l.status}`,
124
+ ...l.issues.map((i) => `- ${i.file || "Map"}: ${i.message}`),
125
+ ]),
99
126
  "",
100
127
  "| Change | Files |",
101
128
  "| --- | ---: |",
@@ -133,6 +160,7 @@ export async function runWork(args) {
133
160
  proposals: value.proposals || work.plan.proposals,
134
161
  scope: value.scope,
135
162
  excluded: value.excluded,
163
+ locks: value.locks,
136
164
  ...(action === "pr"
137
165
  ? {
138
166
  pullRequest: {
@@ -1,5 +1,6 @@
1
1
  import { type WorkContext, type WorkPlan, type WorkTarget } from "./work-model.js";
2
2
  import type { DefinitionGraph } from "./model.js";
3
+ import type { WorkLock } from "./work-model.js";
3
4
  export declare function workDirectory(root: string): string;
4
5
  export declare function mainReference(root: string): {
5
6
  ref: string;
@@ -43,6 +44,7 @@ export declare function updateWorkPlan(root: string, id: string, graph: Definiti
43
44
  proposals?: unknown;
44
45
  scope?: string[];
45
46
  excluded?: string[];
47
+ locks?: WorkLock[];
46
48
  pullRequest?: WorkPlan["pullRequest"];
47
49
  }, snapshot?: WorkContext): WorkContext;
48
50
  /** Explicit confirmation, with evidence read from this checkout and the pinned baseline. */