@reqvire-org/ads 0.3.28 → 0.3.31

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 (68) hide show
  1. package/dist/atomic-composition.mjs +2 -1
  2. package/dist/behaviors.mjs +2 -2
  3. package/dist/boundaries.mjs +6 -3
  4. package/dist/check.mjs +3 -0
  5. package/dist/cli.mjs +13 -0
  6. package/dist/config.mjs +11 -4
  7. package/dist/mcp/build-status.mjs +18 -5
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +53 -51
  11. package/dist/mcp/preview-watch.mjs +23 -3
  12. package/dist/mcp/preview-widget.bundle.js +16 -15
  13. package/dist/mcp/resource-loader.js +40 -12
  14. package/dist/mcp/server.mjs +88 -46
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-files.mjs +19 -12
  18. package/dist/preview-inputs.mjs +6 -17
  19. package/dist/preview-resources.mjs +36 -7
  20. package/dist/preview-scope.mjs +6 -0
  21. package/dist/preview-workers.mjs +184 -0
  22. package/dist/project-documents.mjs +4 -0
  23. package/dist/scenario-inspector.mjs +34 -0
  24. package/dist/scenario-trace.mjs +5 -3
  25. package/dist/scenarios-compiler.mjs +200 -25
  26. package/dist/showcase/client.bundle.js +23 -22
  27. package/dist/showcase/index.html +2 -2
  28. package/dist/showcase/style.css +5 -1
  29. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  30. package/dist/skills/ads-break-ui/references/behaviors.md +2 -0
  31. package/dist/skills/ads-break-ui/references/layers.md +6 -0
  32. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  33. package/dist/skills/ads-break-ui/references/validation.md +69 -0
  34. package/dist/skills/ads-designer/SKILL.md +3 -0
  35. package/dist/skills/ads-designer/references/behaviors.md +2 -0
  36. package/dist/skills/ads-designer/references/layers.md +6 -0
  37. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  38. package/dist/skills/ads-designer/references/validation.md +69 -0
  39. package/dist/skills/ads-import/SKILL.md +3 -0
  40. package/dist/skills/ads-import/references/behaviors.md +2 -0
  41. package/dist/skills/ads-import/references/layers.md +6 -0
  42. package/dist/skills/ads-import/references/runtimes.md +31 -0
  43. package/dist/skills/ads-import/references/validation.md +69 -0
  44. package/dist/skills/ads-motion/SKILL.md +3 -0
  45. package/dist/skills/ads-motion/references/behaviors.md +2 -0
  46. package/dist/skills/ads-motion/references/layers.md +6 -0
  47. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  48. package/dist/skills/ads-motion/references/validation.md +69 -0
  49. package/dist/skills/ads-port/SKILL.md +3 -0
  50. package/dist/skills/ads-port/references/behaviors.md +2 -0
  51. package/dist/skills/ads-port/references/layers.md +6 -0
  52. package/dist/skills/ads-port/references/runtimes.md +31 -0
  53. package/dist/skills/ads-port/references/validation.md +69 -0
  54. package/dist/source-symbols.mjs +11 -0
  55. package/dist/source-values.mjs +10 -3
  56. package/dist/test-boundaries.mjs +96 -0
  57. package/dist/ui-framework.mjs +2 -1
  58. package/dist/units.mjs +12 -1
  59. package/dist/validation-checks.mjs +50 -0
  60. package/dist/validation-inputs.mjs +132 -0
  61. package/dist/validation.mjs +158 -0
  62. package/dist/verification/browser.mjs +3 -1
  63. package/dist/verification.mjs +1 -0
  64. package/docs/ARCHITECTURE.md +96 -20
  65. package/docs/BEHAVIORS.md +2 -0
  66. package/docs/CHANGELOG.md +74 -0
  67. package/docs/MCP.md +105 -12
  68. package/package.json +1 -1
@@ -166,6 +166,8 @@ do not run. It preserves the project's worker configuration.
166
166
 
167
167
  `timeoutMs` bounds the complete runner process for one profile, including runner
168
168
  startup, hooks, retries and all selected cases. It is not a per-test timeout.
169
+ The default is 60000 ms; explicit budgets may range from 100 to 900000 ms
170
+ (fifteen minutes), so larger catalogues can complete a full run.
169
171
  Playwright's own test/hook timeouts remain separate project settings. Set the
170
172
  profile budget from measured suite durations with headroom; increasing it does
171
173
  not repair a stalled assertion or cleanup.
@@ -17,6 +17,12 @@ Layout parts may arrange `children` without importing several components.
17
17
  Patterns may compose other patterns. A native wrapper or a large implementation
18
18
  does not decide the layer.
19
19
 
20
+ A product workflow's essential controls belong to its pattern. Require their
21
+ typed models and callbacks; reserve optional action slots for extensions. Its
22
+ independent scenario and registered checks must exercise those controls instead
23
+ of adding them only in composition fixtures. ADS enforces the declared API and
24
+ checks; it cannot infer application requirements that were never modeled.
25
+
20
26
  An **application adapter** supplies domain data, store access, route state and
21
27
  navigation/service callbacks. Domain-shaped inputs are valid in project-owned
22
28
  patterns; importing a particular application store/router is not.
@@ -103,6 +103,37 @@ compiler. Existing custom adapters still work; they must adopt the helper to gai
103
103
  incremental transforms. Upgrade the project dependency and restart the builder.
104
104
  Keep the full validation callback and production build behavior.
105
105
 
106
+ The shared watched builder reuses completed self-contained IIFE worker bundles
107
+ for constructor URLs and standard `?worker`/`?worker&url` imports. It uses Vite's
108
+ configured worker plugins, deduplicates pending requests, tracks real worker and
109
+ configuration dependencies and checks resolution-directory changes. Assets are
110
+ included on every refresh. Changing a transitive worker import rebuilds its
111
+ bundle; failed or superseded work cannot populate the cache. Nested, inline and
112
+ split workers keep the normal Vite path. Keep worker lifetimes/cancellation in
113
+ their owning component/controller; compiler reuse does not keep runtime workers
114
+ alive. Do not add project-specific worker names or lists to ADS.
115
+
116
+ Watched resource builds publish explicitly unverified live feedback while full
117
+ checks and semantic registry inspection run in the background. Rapid edits
118
+ coalesce behind one verification run. The showcase can browse that feedback
119
+ without a blocking loading overlay; a quiet header indicator exposes checking,
120
+ reload, failure and fallback details. A failed edit restores the last verified
121
+ view. Preview minification is disabled only for watched builds.
122
+
123
+ `ads_show_scenario` and `ads_show_tokens` default to `waitFor: "verified"`.
124
+ Interactive browsing can request `waitFor: "compiled"`, which may return live or
125
+ retained output with `build.current: false`. `build.live.validated: false` and
126
+ `ads://preview/live` are never proof of passing checks. Captures, behavior checks
127
+ and guarded publication still require accepted, current output. Do not replace
128
+ the validation callback with a faster incomplete check to speed up the viewer.
129
+
130
+ Accepted MCP edits prepare previews without requiring a viewer request. Matching
131
+ checked candidate graphs and registry metadata reuse the existing project cache;
132
+ incompatible output falls back to background compilation. The connected showcase
133
+ can prefetch changed peers' static bytes without evaluating or mounting them.
134
+ Reuse depends on content and dependencies, with no time-based expiry. Preparation
135
+ does not establish additional behavior or visual evidence.
136
+
106
137
  The App preserves selected form/scroll state across accepted unrelated graph
107
138
  updates, reruns audits and remounts when its own module/style/asset closure changes.
108
139
  Do not promise component-level HMR. Guarded edits select affected behavior owners
@@ -0,0 +1,69 @@
1
+ # Validation scope
2
+
3
+ Use `ads_validate({})` for the complete project audit, equivalent to `ads validate`.
4
+ Use `ads_validate({scope:"changed"})`, equivalent to `ads validate --changed`, during
5
+ editing when a successful full baseline exists. Both interfaces call the same
6
+ engine. Full is the default.
7
+
8
+ - During local editing, use existing guarded edits and affected behavior checks.
9
+ Reuse completed guards for unchanged source rather than repeatedly auditing all
10
+ owners. Direct edits need `ads_check` and appropriate project/behavior checks.
11
+ - After test migrations, ownership changes or validation/runner configuration
12
+ changes, run full validation. Also run it before a release or an explicit request
13
+ to validate everything. It validates the current source, not a prepared draft.
14
+ - Inspect failures through `ads_results` using the returned resultId and sections
15
+ diagnostics, checks or outcomes. For browser failures, use the outcome's exact
16
+ unit/check/runId with `ads_investigate`. Fix the owner and rerun the appropriate scope.
17
+ - Report the actual scope and revision. Scoped, stale, cancelled or incomplete
18
+ runs cannot establish successful full validation. Passing covers registered
19
+ checks and configured scripts, not arbitrary assertions, visual parity or every
20
+ application state.
21
+
22
+ Full validation runs core architecture/test-boundary guards, registered Oxlint,
23
+ project scripts and every registered behavior contract. Defaults use the existing
24
+ mutation-check scripts plus a project's `test` and build scripts when present.
25
+ Build selection prefers `build:lib`, then `build:app`, then `build`.
26
+ Projects can declare `validation.checks` as a list of package
27
+ script names for the complete audit; core/Oxlint and registered behaviors remain
28
+ mandatory. Commands are trusted project configuration, never MCP arguments.
29
+ Use scripts that check/build without changing source. Avoid calling `ads validate`
30
+ from a script selected by validation.
31
+
32
+ Freshness tracks ADS and consuming UI roots, public assets, their local dependency
33
+ chains, registered configuration/command entrypoints, package files, and supported
34
+ project tests plus helpers. Unrelated native/backend/docs edits can continue during
35
+ validation. Patched files are always fenced. For selected commands that read files
36
+ dynamically, declare those project-relative source files or directories in
37
+ `validation.inputs`, for example `["schemas/ui.json", "tools/check-data"]`. These
38
+ paths add to mandatory inputs; use no globs, generated output, dependencies or
39
+ metadata. A missing declared path is tracked when it is created later. Do not
40
+ remove a real input to make stale evidence pass. After changing this configuration,
41
+ run full validation.
42
+
43
+ Guarded edits copy these inputs and patched files into an isolated candidate,
44
+ with a 100,000-file / 2 GiB allowance. Native build artifacts outside the input
45
+ graph consume no copy budget. Selected commands must declare opaque data they
46
+ read outside the UI graph. The whole candidate is checked for source rewrites.
47
+
48
+ Changed mode compares current content, including added/deleted files, with the
49
+ last successful full baseline in `.ds/validation-baseline.json`. No Git history is
50
+ required. A missing/incompatible baseline or a change to configuration, foundation,
51
+ ownership that no longer resolves, or unclassified input expands to full and
52
+ reports the reason. Scoped runs leave the full baseline unchanged. Core architecture
53
+ checks and opaque project commands still run in full; behavior selection narrows
54
+ to affected owner contracts. This is not a per-test-result cache.
55
+
56
+ ADS tests live with their component, pattern, controller, composition or review
57
+ owner. Private imports must resolve to that owner, including through helpers;
58
+ peer implementations use the public API. Marked behavior specs must be registered
59
+ in an owner contract. Pure ADS tests outside those owners fail the boundary guard.
60
+ Application integration tests may exercise public UI alongside their real application
61
+ runtime subject. Ordinary local unit tests retain their project's runner; full
62
+ validation includes the configured test script. Registration is enforced for ADS
63
+ behavior specs, not inferred for every case in an arbitrary runner.
64
+
65
+ During execution `ads_status.validation` reports progress. MCP summaries retain a
66
+ separate latest validation result, alongside verification and mutation results.
67
+ Source changes during execution reject success and leave the previous full
68
+ baseline intact. Skipped registered behavior cases never pass; a project with no
69
+ registered behavior contracts reports that stage as skipped with a reason.
@@ -0,0 +1,11 @@
1
+ // TypeScript programs/checkers are immutable inspection snapshots. Share only
2
+ // context-free symbol lookups, including misses, within that checker. A new
3
+ // inspection gets a new checker; no filesystem result or diagnostic is retained.
4
+ const snapshots = new WeakMap();
5
+
6
+ export function sourceSymbol(checker, node) {
7
+ let symbols = snapshots.get(checker);
8
+ if (!symbols) snapshots.set(checker, symbols = new WeakMap());
9
+ if (!symbols.has(node)) symbols.set(node, checker.getSymbolAtLocation(node));
10
+ return symbols.get(node);
11
+ }
@@ -1,6 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { isInside } from "./config.mjs";
3
3
  import { uiOperation } from "./ui-framework.mjs";
4
+ import { sourceSymbol } from "./source-symbols.mjs";
4
5
 
5
6
  export const unknown = reason => ({ kind: "unknown", reason });
6
7
  export const literal = value => ({ kind: "literal", value });
@@ -16,8 +17,14 @@ export function unwrap(node) {
16
17
  /** Bounded symbolic source traversal. No project code is imported or executed. */
17
18
  export function createSourceValues(program, options, { preserveCall = () => false, strict = false } = {}) {
18
19
  const checker = program.getTypeChecker();
20
+ const ownedFiles = new Map();
21
+ function owned(node) {
22
+ const file = node.getSourceFile().fileName;
23
+ if (!ownedFiles.has(file)) ownedFiles.set(file, isInside(options.dsRoot, file));
24
+ return ownedFiles.get(file);
25
+ }
19
26
  const symbol = node => {
20
- const value = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(node) ? node.name : node);
27
+ const value = sourceSymbol(checker, ts.isPropertyAccessExpression(node) ? node.name : node);
21
28
  return value?.valueDeclaration && ts.isShorthandPropertyAssignment(value.valueDeclaration) ? checker.getShorthandAssignmentValueSymbol(value.valueDeclaration) ?? value : value;
22
29
  };
23
30
  function declaration(node) {
@@ -180,7 +187,7 @@ export function createSourceValues(program, options, { preserveCall = () => fals
180
187
  return strict && escapes.has(symbol(node)) && (result.kind === "object" || result.kind === "array" || result.kind === "node" && (ts.isObjectLiteralExpression(result.node) || ts.isArrayLiteralExpression(result.node))) ? unknown("An object passed to another call may have been mutated.") : result;
181
188
  }
182
189
  const owner = declaration(node);
183
- if (owner && isInside(options.dsRoot, owner.getSourceFile().fileName)) {
190
+ if (owner && owned(owner)) {
184
191
  if (isFunction(owner)) return reference(owner, env, via);
185
192
  if (ts.isVariableDeclaration(owner) && owner.initializer && owner.parent.flags & ts.NodeFlags.Const) {
186
193
  const result = resolve(reference(owner.initializer, env, via), next(context));
@@ -196,7 +203,7 @@ export function createSourceValues(program, options, { preserveCall = () => fals
196
203
  if (key.kind === "literal") {
197
204
  const selected = get(object, String(key.value), next(context));
198
205
  const owner = declaration(node);
199
- if (selected.kind === "unknown" && owner && isInside(options.dsRoot, owner.getSourceFile().fileName)) {
206
+ if (selected.kind === "unknown" && owner && owned(owner)) {
200
207
  if (isFunction(owner)) return reference(owner, env, via);
201
208
  if (ts.isVariableDeclaration(owner) && owner.initializer && owner.parent.flags & ts.NodeFlags.Const) return resolve(reference(owner.initializer, env, via), next(context));
202
209
  }
@@ -0,0 +1,96 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
+ import { adsFileRole, isInside, isDevelopmentFile, isTestFile } from "./config.mjs";
5
+ import { importResolver } from "./boundaries.mjs";
6
+ import { createPreviewFileFilter } from "./preview-files.mjs";
7
+
8
+ /** Test ownership is structural; arbitrary assertion intent remains the runner's concern. */
9
+ export function inspectTestBoundaries(options, inventory, contracts, program) {
10
+ const diagnostics = [], resolve = importResolver(options), parsed = new Map(), tests = [];
11
+ const ignored = createPreviewFileFilter(options);
12
+ const owner = file => inventory.owner(inventory.relative(path.relative(options.root,file)));
13
+ function source(file) {
14
+ if (!parsed.has(file)) parsed.set(file,program?.getSourceFile(file) ?? ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true));
15
+ return parsed.get(file);
16
+ }
17
+ function walk(directory) {
18
+ for (const entry of readdirSync(directory,{withFileTypes:true})) {
19
+ const file = path.join(directory,entry.name);
20
+ if (entry.isSymbolicLink() || ignored(file) || ["output","test-results","playwright-report",".playwright-cli"].includes(entry.name)) continue;
21
+ if (entry.isDirectory()) walk(file);
22
+ else if (entry.isFile() && /\.[cm]?[jt]sx?$/.test(file) && isTestFile(file)) {
23
+ let executable=/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file);
24
+ const names=new Set(["test","it","describe"]);
25
+ const ast=source(file);
26
+ for(const statement of ast.statements) if(ts.isImportDeclaration(statement)&&ts.isStringLiteralLike(statement.moduleSpecifier)&&/^(?:vitest|@playwright\/test|node:test|bun:test|@jest\/globals)$/.test(statement.moduleSpecifier.text)) {
27
+ const bindings=statement.importClause?.namedBindings;
28
+ if(statement.importClause?.name)names.add(statement.importClause.name.text);
29
+ if(bindings&&ts.isNamespaceImport(bindings))names.add(bindings.name.text);
30
+ if(bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if(["test","it","describe"].includes((item.propertyName??item.name).text))names.add(item.name.text);
31
+ }
32
+ function visit(node){if(ts.isCallExpression(node)){let base=node.expression;while(ts.isPropertyAccessExpression(base)||ts.isCallExpression(base))base=base.expression;if(ts.isIdentifier(base)&&names.has(base.text))executable=true;}if(!executable)ts.forEachChild(node,visit);}
33
+ if(!executable)visit(ast);
34
+ if(executable)tests.push(file);
35
+ }
36
+ }
37
+ }
38
+ walk(options.root);
39
+ const registered = new Set(contracts.flatMap(contract=>Object.values(contract.checks).map(check=>path.resolve(options.root,path.dirname(contract.file),check.file))));
40
+ function imports(file) {
41
+ const edges = [];
42
+ function visit(node) {
43
+ let specifier;
44
+ if ((ts.isImportDeclaration(node)||ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) specifier=node.moduleSpecifier.text;
45
+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression)&&node.expression.text === "require") && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) specifier=node.arguments[0].text;
46
+ const typeOnly=ts.isImportDeclaration(node)&&(node.importClause?.isTypeOnly||node.importClause?.namedBindings&&ts.isNamedImports(node.importClause.namedBindings)&&!node.importClause.name&&node.importClause.namedBindings.elements.length&&node.importClause.namedBindings.elements.every(item=>item.isTypeOnly))||ts.isExportDeclaration(node)&&node.isTypeOnly;
47
+ if (specifier&&!typeOnly) for (const target of resolve(specifier,file)) if (existsSync(target) && isInside(options.root,target) && !target.split(path.sep).includes("node_modules") && /\.[cm]?[jt]sx?$/.test(target)) edges.push({specifier,target,node});
48
+ ts.forEachChild(node,visit);
49
+ }
50
+ visit(source(file));return edges;
51
+ }
52
+ function report(file,rule,message) { diagnostics.push({file:path.relative(options.root,file).replaceAll("\\","/"),rule,line:1,column:1,message}); }
53
+ for (const file of tests) {
54
+ const own = owner(file), inside = isInside(options.dsRoot,file);
55
+ const edges = imports(file);
56
+ const marked = adsFileRole(file) === "behavior.spec" || /@ads:[\w.-]+/.test(source(file).text);
57
+ if (marked && !registered.has(file)) report(file,"test-registration","ADS behavior specs must be registered by their owning contract. Register this file or remove the obsolete spec.");
58
+ if (inside) {
59
+ const unit = inventory.units.find(unit=>unit.id===own);
60
+ const real = ["configuration","foundation","tokens"].includes(own) || unit?.files.some(relative=>{const target=path.resolve(options.root,relative);return !isDevelopmentFile(target,options) || own?.startsWith("composition/") && /\.scenario\.[cm]?[jt]sx?$/.test(target);});
61
+ if (!real) report(file,"test-ownership","ADS tests belong beside a real runtime or composition owner. A test/helper file alone cannot create an owner.");
62
+ }
63
+ if (!inside) {
64
+ // Application tests may integrate public UI alongside application runtime.
65
+ // Helpers under test/ do not masquerade as the application subject.
66
+ let hasAppSubject = edges.some(edge=>isInside(options.sourceRoot,edge.target)&&!isInside(options.dsRoot,edge.target)&&!isDevelopmentFile(edge.target,options));
67
+ const seen = new Set(); let usesAds = marked;
68
+ function trace(target) {
69
+ if (seen.has(target)) return;seen.add(target);
70
+ for (const edge of imports(target)) {
71
+ if (isInside(options.dsRoot,edge.target)) usesAds=true;
72
+ else if (isDevelopmentFile(edge.target,options)) trace(edge.target);
73
+ else if (isInside(options.sourceRoot,edge.target)) hasAppSubject=true;
74
+ }
75
+ }
76
+ trace(file);
77
+ if (usesAds && !hasAppSubject) report(file,"test-ownership","This test exercises ADS without an application runtime subject. Move it beside its owning component/pattern or composition; application integration tests stay beside their application subject.");
78
+ }
79
+ // Development helpers cannot hide a private import across owners. Public
80
+ // barrel imports are permitted and stop at the declared API boundary.
81
+ if (inside) {
82
+ const seen = new Set();
83
+ function trace(target) {
84
+ if (seen.has(target)) return;seen.add(target);
85
+ for (const edge of imports(target)) {
86
+ if (edge.specifier === options.config.publicAlias || edge.specifier === `${options.config.publicAlias}/review`) continue;
87
+ if (!isInside(options.dsRoot,edge.target)) continue;
88
+ if (isDevelopmentFile(edge.target,options)) { trace(edge.target);continue; }
89
+ if (owner(edge.target) !== own && edge.target !== path.join(options.dsRoot,options.config.stylesEntry)) report(file,"test-private-import",`Test ${own} reaches private source owned by ${owner(edge.target)} through ${path.relative(options.root,target)}. Use the public ADS API for peers; private helpers stay with their owner.`);
90
+ }
91
+ }
92
+ trace(file);
93
+ }
94
+ }
95
+ return diagnostics;
96
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import ts from "typescript";
4
+ import { sourceSymbol } from "./source-symbols.mjs";
4
5
 
5
6
  const modules = new Set(["react", "preact", "preact/compat", "preact/jsx-runtime"]);
6
7
 
@@ -37,7 +38,7 @@ export function importedUiApi(expression, checker) {
37
38
  base = base.left ?? base.expression;
38
39
  }
39
40
  if (!ts.isIdentifier(base)) return null;
40
- for (const declaration of checker.getSymbolAtLocation(base)?.declarations ?? []) {
41
+ for (const declaration of sourceSymbol(checker, base)?.declarations ?? []) {
41
42
  if (ts.isImportSpecifier(declaration) && modules.has(declaration.parent.parent.parent.moduleSpecifier.text)) {
42
43
  return { name: [(declaration.propertyName ?? declaration.name).text, ...parts].join("."), module: declaration.parent.parent.parent.moduleSpecifier.text };
43
44
  }
package/dist/units.mjs CHANGED
@@ -66,7 +66,7 @@ export function configurationFiles(options) {
66
66
  for (const match of command.matchAll(/\b(?:npm|bun)\s+run\s+([\w:.-]+)/g)) script(match[1]);
67
67
  for (const match of command.matchAll(/\b(?:node|bun|tsx|ts-node)\s+([^\s;&|]+\.[cm]?[jt]sx?)(?=\s|$)/g)) visit(path.resolve(root, match[1]), true);
68
68
  }
69
- for (const name of ["lint:ds", "lint:style", "lint:project", "typecheck", "build:mcp-previews", "generate:icons", ...(config.mcp.mutationChecks ?? [])]) script(name);
69
+ for (const name of ["lint:ds", "lint:style", "lint:project", "typecheck", "test", "build", "build:mcp-previews", "generate:icons", "build:lib", "build:app", ...(config.validation?.checks ?? []), ...(config.mcp.mutationChecks ?? [])]) script(name);
70
70
  const watch = config.mcp.previewWatch;
71
71
  if (watch) {
72
72
  if (["npm", "bun"].includes(watch.command) && watch.args[0] === "run") script(watch.args[1]);
@@ -76,6 +76,17 @@ export function configurationFiles(options) {
76
76
  if (["npm", "bun"].includes(profile.command) && profile.args[0] === "run") script(profile.args[1]);
77
77
  else for (const argument of [profile.command, ...profile.args]) if (/\.[cm]?[jt]sx?$/.test(argument)) visit(path.resolve(root, argument), true);
78
78
  }
79
+ // Build/configuration tests follow their actual setup source, without
80
+ // capturing component tests invoked by a registered runner.
81
+ const setupSources = [...files];
82
+ for (const file of setupSources) {
83
+ if (!source.test(file)) continue;
84
+ const stem=file.replace(/\.[cm]?[jt]sx?$/,"");
85
+ for (const role of ["test","spec"]) for (const extension of ["ts","tsx","js","mjs","mts"]) {
86
+ const sidecar=`${stem}.ads.${role}.${extension}`;
87
+ if (existsSync(path.join(root,sidecar))) files.add(sidecar);
88
+ }
89
+ }
79
90
  return files;
80
91
  }
81
92
 
@@ -0,0 +1,50 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { projectContext } from "./mcp/context.mjs";
5
+ import { packageScriptCommand } from "./development-runtime.mjs";
6
+ import { failure as evidenceFailure } from "./evidence.mjs";
7
+ const fail = (rule, message, file, failure) => Object.assign(new Error(message), { diagnostic: {rule, message, ...(file ? {file} : {}), ...(failure ? {failure} : {})} });
8
+
9
+ export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
10
+ return new Promise((resolve, reject) => {
11
+ if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
12
+ const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
13
+ env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
14
+ let output = "", failure;
15
+ const startedAt=Date.now();
16
+ if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
17
+ function kill() {
18
+ if (!child.pid) return;
19
+ if (process.platform === "win32") {
20
+ const stop = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
21
+ stop.on("error", () => child.kill("SIGKILL"));
22
+ } else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
23
+ }
24
+ const abort = () => { failure = fail("mutation-cancelled", "Mutation cancelled during validation."); kill(); };
25
+ signal?.addEventListener("abort", abort, { once: true });
26
+ const timer = setTimeout(() => { failure = fail("mutation-check", `${path.basename(command)} ${args.join(" ")} exceeded its ${timeoutMs} ms command budget.`); failure.code="ADS_COMMAND_TIMEOUT"; kill(); }, timeoutMs);
27
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
28
+ child.once("error", error => { failure = error; });
29
+ child.once("exit", kill); // Also clean up descendants of a finished launcher.
30
+ child.once("close", code => {
31
+ clearTimeout(timer); signal?.removeEventListener("abort", abort);
32
+ const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
33
+ if (failure || code !== 0) {
34
+ const error=failure??fail("mutation-check", `${path.basename(command)} ${args.join(" ")} failed (${code}).\n${output}`);
35
+ error.diagnostic={...(error.diagnostic??{rule:"mutation-check",message:error.message}),...detail,output:output.slice(-4000),failure:evidenceFailure(failure?"runner":gate.category,gate.phase,failure?.code??(failure?"ADS_COMMAND_INTERRUPTED":"ADS_COMMAND_EXIT"),{certainty:"observed-boundary"})};
36
+ reject(error);
37
+ } else resolve({ ...detail,phase:gate.phase, passed: true });
38
+ });
39
+ });
40
+ }
41
+
42
+
43
+ export function projectChecks(options) {
44
+ const context = projectContext(options);
45
+ const pkg = JSON.parse(readFileSync(path.join(options.root, "package.json"), "utf8"));
46
+ const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", "build:mcp-previews"].filter(name => typeof pkg.scripts?.[name] === "string");
47
+ if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
48
+ if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
49
+ return scripts.map(script => packageScriptCommand(context.packageManager, script));
50
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import ts from "typescript";
5
+ import postcss from "postcss";
6
+ import valueParser from "postcss-value-parser";
7
+ import { defaultConfig, isInside, isTestFile } from "./config.mjs";
8
+ import { importResolver } from "./boundaries.mjs";
9
+ import { configurationFiles } from "./units.mjs";
10
+ import { createPreviewFileFilter } from "./preview-files.mjs";
11
+ import { projectNoticeFiles } from "./project-documents.mjs";
12
+
13
+ const digest = file => `sha256:${createHash("sha256").update(readFileSync(file)).digest("hex")}`;
14
+ const ignored = new Set(["output", "test-results", "playwright-report", ".playwright-cli"]);
15
+ const script = /\.[cm]?[jt]sx?$/;
16
+ const slash = file => file.replaceAll("\\", "/");
17
+ // Cache only parsed references by content, never freshness or file resolution.
18
+ // Every inventory still reads bytes and resolves against the current project.
19
+ const parsedScripts = new Map();
20
+ function references(file, content, revision) {
21
+ const key=`${path.extname(file)}:${revision}`;
22
+ if (parsedScripts.has(key)) return parsedScripts.get(key);
23
+ const imports=[],assets=[],ast=ts.createSourceFile(file,content.toString("utf8"),ts.ScriptTarget.Latest,true);
24
+ function walk(node) {
25
+ if ((ts.isImportDeclaration(node)||ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) imports.push(node.moduleSpecifier.text);
26
+ if (ts.isCallExpression(node) && (node.expression.kind===ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression)&&node.expression.text==="require" || ts.isPropertyAccessExpression(node.expression)&&node.expression.getText(ast)==="require.resolve") && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) imports.push(node.arguments[0].text);
27
+ if (ts.isNewExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="URL"&&node.arguments?.[0]&&ts.isStringLiteralLike(node.arguments[0])) assets.push(node.arguments[0].text);
28
+ ts.forEachChild(node,walk);
29
+ }
30
+ walk(ast);
31
+ if (parsedScripts.size>=2048) parsedScripts.delete(parsedScripts.keys().next().value);
32
+ const result={imports,assets};parsedScripts.set(key,result);return result;
33
+ }
34
+
35
+ /** Mandatory UI/guard inputs, real local dependencies and declared opaque inputs. */
36
+ export function validationInputFiles(options, extraFiles = [], {maxFiles=Infinity,maxBytes=Infinity} = {}) {
37
+ const supplied=options.config;
38
+ const normalized={...defaultConfig,...supplied,assets:{...defaultConfig.assets,...supplied.assets},mcp:{...defaultConfig.mcp,...supplied.mcp},oxlint:{...defaultConfig.oxlint,...supplied.oxlint}};
39
+ options = { ...options, config:normalized, dsRoot: options.dsRoot ?? path.resolve(options.root,normalized.dsDir), sourceRoot: options.sourceRoot ?? path.resolve(options.root,normalized.sourceDir) };
40
+ const { root, config } = options, files = new Map(), visited = new Set(), resolve = importResolver(options);
41
+ const previewIgnored = createPreviewFileFilter(options);
42
+ let inputBytes=0,inputCount=0;
43
+ const safeDirectories=new Set([root]);
44
+ function checkParent(directory) {
45
+ if (safeDirectories.has(directory)) return;
46
+ checkParent(path.dirname(directory));
47
+ const stat=lstatSync(directory);
48
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`Validation input cannot resolve through a symlink: ${slash(path.relative(root,directory))}`);
49
+ safeDirectories.add(directory);
50
+ }
51
+ const outputs = new Set((config.mcp.apps??[]).map(app => path.resolve(root, app.file)));
52
+ const covered=[options.dsRoot,options.sourceRoot,...config.assets.publicDirs.map(file=>path.resolve(root,file))];
53
+ const forced = new Set(extraFiles.filter(file=>file!=="installed-dependencies").map(file=>path.resolve(root,file)));
54
+ function excluded(file) {
55
+ return previewIgnored(file) || outputs.has(file) || path.relative(root,file).split(path.sep).some(name=>ignored.has(name)) || [".gitkeep",".keep"].includes(path.basename(file)) || file.endsWith(".tsbuildinfo");
56
+ }
57
+ for (const file of config.validation?.inputs??[]) if (excluded(path.resolve(root,file))) throw new Error(`validation.inputs must name source inputs, not generated output or metadata: ${file}`);
58
+ function visit(file) {
59
+ file = path.resolve(file);
60
+ if (!isInside(root, file) || !forced.has(file) && excluded(file)) return;
61
+ const relative = slash(path.relative(root, file));
62
+ if (visited.has(file)) return;
63
+ visited.add(file);
64
+ let stat;
65
+ try { stat=lstatSync(file); } catch(error) { if(error.code!=="ENOENT"&&error.code!=="ENOTDIR")throw error;files.set(relative,null);return; }
66
+ if (file!==root) checkParent(path.dirname(file));
67
+ if (stat.isSymbolicLink()) throw new Error(`Validation input cannot resolve through a symlink: ${relative}`);
68
+ if (stat.isDirectory()) {
69
+ safeDirectories.add(file);
70
+ for (const entry of readdirSync(file).sort()) visit(path.join(file,entry));
71
+ return;
72
+ }
73
+ if (!stat.isFile()) return;
74
+ if (++inputCount>maxFiles || (inputBytes+=stat.size)>maxBytes) throw Object.assign(new Error("Relevant inputs exceed the bounded validation snapshot limit."),{code:"ADS_INPUT_LIMIT"});
75
+ const content=readFileSync(file),revision=`sha256:${createHash("sha256").update(content).digest("hex")}`;
76
+ files.set(relative, revision);
77
+ for (let directory=path.dirname(file);isInside(root,directory);directory=path.dirname(directory)) {
78
+ const manifest=path.join(directory,"package.json");
79
+ if (existsSync(manifest)) { visit(manifest); break; }
80
+ if (directory===root) break;
81
+ }
82
+ function local(specifier) {
83
+ if (!specifier || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(specifier)) return;
84
+ visit(path.resolve(path.dirname(file),specifier.replace(/[?#].*$/,"")));
85
+ }
86
+ if (script.test(file)) {
87
+ const refs=references(file,content,revision);
88
+ for (const specifier of refs.imports) {
89
+ // Entire mandatory roots are already inventoried. Avoid resolving every
90
+ // colocated import again; directory/package imports still need resolution
91
+ // because a package entry can lead outside its containing root.
92
+ if ([config.publicAlias,`${config.publicAlias}/review`].includes(specifier)) continue;
93
+ if (specifier.startsWith(".")) {
94
+ const base=path.resolve(path.dirname(file),specifier.replace(/[?#].*$/,""));
95
+ if (covered.some(directory=>isInside(directory,base)) && [base,...[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"].map(extension=>base+extension)].some(target=>existsSync(target)&&lstatSync(target).isFile())) continue;
96
+ }
97
+ if (!/^[a-z][\w+.-]*:/i.test(specifier)) for (const dependency of resolve(specifier,file)) {
98
+ const target=existsSync(dependency) ? realpathSync(dependency) : dependency;
99
+ if (!target.split(path.sep).includes("node_modules")) visit(target);
100
+ }
101
+ }
102
+ for (const asset of refs.assets) local(asset);
103
+ } else if (file.endsWith(".css")) {
104
+ const css=postcss.parse(content.toString("utf8"),{from:file});
105
+ css.walkAtRules("import",rule=>{const first=valueParser(rule.params).nodes.find(node=>!["space","comment"].includes(node.type));if(first?.type==="string")local(first.value);});
106
+ css.walk(node=>{if(node.type==="decl"||node.type==="atrule")valueParser(node.type==="decl"?node.value:node.params).walk(value=>{if(value.type==="function"&&value.value.toLowerCase()==="url")local(value.nodes.filter(part=>part.type!=="space").map(part=>part.value).join(""));});});
107
+ } else if (file.endsWith(".html")) {
108
+ for (const match of content.toString("utf8").matchAll(/\b(?:src|href)\s*=\s*["']([^"']+)["']/g)) local(match[1]);
109
+ }
110
+ }
111
+ // These roots cannot be excluded through optional declarations.
112
+ for (const file of [options.dsRoot,options.sourceRoot,...config.assets.publicDirs.map(file=>path.resolve(root,file)),...configurationFiles(options)].map(file=>path.resolve(root,file))) visit(file);
113
+ for (const file of projectNoticeFiles(root)) visit(path.resolve(root,file));
114
+ for (const file of ["index.html","package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb","bunfig.toml",".npmrc",".yarnrc.yml",...(config.validation?.inputs??[]),...extraFiles]) if(file!=="installed-dependencies") visit(path.resolve(root,file));
115
+ const manifest=path.join(root,"package.json");
116
+ const pkg=existsSync(manifest)?JSON.parse(readFileSync(manifest,"utf8")):{};
117
+ for (const file of Object.values(pkg.patchedDependencies??{})) if(typeof file==="string")visit(path.resolve(root,file));
118
+ // The architecture guard discovers tests anywhere in the project. Retain that
119
+ // coverage, including added tests and their helper/dependency chains.
120
+ function tests(directory) {
121
+ for (const entry of readdirSync(directory,{withFileTypes:true})) {
122
+ const file=path.join(directory,entry.name);
123
+ if(entry.isSymbolicLink()||ignored.has(entry.name)||previewIgnored(file))continue;
124
+ if(entry.isDirectory())tests(file);
125
+ else if(entry.isFile()&&script.test(file)&&isTestFile(file))visit(file);
126
+ }
127
+ }
128
+ tests(root);
129
+ const installed=path.join(root,"node_modules/.package-lock.json");
130
+ files.set("installed-dependencies",existsSync(installed)?digest(installed):null);
131
+ return Object.fromEntries([...files].sort(([a],[b])=>a.localeCompare(b)));
132
+ }