@reqvire-org/ads 0.3.28 → 0.3.29
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.
- package/dist/atomic-composition.mjs +2 -1
- package/dist/behaviors.mjs +2 -2
- package/dist/boundaries.mjs +6 -3
- package/dist/check.mjs +3 -0
- package/dist/cli.mjs +13 -0
- package/dist/config.mjs +5 -3
- package/dist/mcp/build-status.mjs +17 -4
- package/dist/mcp/context.mjs +2 -1
- package/dist/mcp/execution-results.mjs +4 -3
- package/dist/mcp/mutations.mjs +5 -43
- package/dist/mcp/preview-watch.mjs +23 -3
- package/dist/mcp/preview-widget.bundle.js +16 -15
- package/dist/mcp/resource-loader.js +40 -12
- package/dist/mcp/server.mjs +74 -36
- package/dist/oxlint.mjs +6 -1
- package/dist/preview-builder.mjs +10 -4
- package/dist/preview-resources.mjs +11 -4
- package/dist/preview-scope.mjs +6 -0
- package/dist/preview-workers.mjs +184 -0
- package/dist/scenario-inspector.mjs +34 -0
- package/dist/scenario-trace.mjs +3 -2
- package/dist/scenarios-compiler.mjs +200 -25
- package/dist/showcase/client.bundle.js +22 -21
- package/dist/showcase/index.html +2 -2
- package/dist/showcase/style.css +2 -1
- package/dist/skills/ads-break-ui/SKILL.md +3 -0
- package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
- package/dist/skills/ads-break-ui/references/validation.md +53 -0
- package/dist/skills/ads-designer/SKILL.md +3 -0
- package/dist/skills/ads-designer/references/runtimes.md +31 -0
- package/dist/skills/ads-designer/references/validation.md +53 -0
- package/dist/skills/ads-import/SKILL.md +3 -0
- package/dist/skills/ads-import/references/runtimes.md +31 -0
- package/dist/skills/ads-import/references/validation.md +53 -0
- package/dist/skills/ads-motion/SKILL.md +3 -0
- package/dist/skills/ads-motion/references/runtimes.md +31 -0
- package/dist/skills/ads-motion/references/validation.md +53 -0
- package/dist/skills/ads-port/SKILL.md +3 -0
- package/dist/skills/ads-port/references/runtimes.md +31 -0
- package/dist/skills/ads-port/references/validation.md +53 -0
- package/dist/source-symbols.mjs +11 -0
- package/dist/source-values.mjs +10 -3
- package/dist/test-boundaries.mjs +95 -0
- package/dist/ui-framework.mjs +2 -1
- package/dist/units.mjs +12 -1
- package/dist/validation-checks.mjs +50 -0
- package/dist/validation.mjs +172 -0
- package/dist/verification/browser.mjs +3 -1
- package/dist/verification.mjs +1 -0
- package/docs/ARCHITECTURE.md +72 -17
- package/docs/CHANGELOG.md +37 -0
- package/docs/MCP.md +68 -9
- package/package.json +1 -1
|
@@ -4,6 +4,7 @@ import postcss from "postcss";
|
|
|
4
4
|
import valueParser from "postcss-value-parser";
|
|
5
5
|
import { isInside } from "./config.mjs";
|
|
6
6
|
import { createAtomicTrace } from "./atomic-trace.mjs";
|
|
7
|
+
import { sourceSymbol } from "./source-symbols.mjs";
|
|
7
8
|
|
|
8
9
|
export const atomicStyleGuide = "ads://guides/atomic-styles";
|
|
9
10
|
|
|
@@ -138,7 +139,7 @@ export function createAtomicCompositionReview(program, options) {
|
|
|
138
139
|
if (!node || seen.has(node)) return false;
|
|
139
140
|
seen = new Set([...seen, node]);
|
|
140
141
|
const base = ts.isPropertyAccessExpression(node) ? node.expression : node;
|
|
141
|
-
const symbol = checker
|
|
142
|
+
const symbol = sourceSymbol(checker, base);
|
|
142
143
|
for (const item of symbol?.declarations ?? []) {
|
|
143
144
|
if (ts.isImportSpecifier(item) && names.includes((item.propertyName ?? item.name).text) && modules.includes(item.parent.parent.parent.moduleSpecifier.text)) return true;
|
|
144
145
|
if (ts.isNamespaceImport(item) && ts.isPropertyAccessExpression(node) && names.includes(node.name.text) && modules.includes(item.parent.parent.moduleSpecifier.text)) return true;
|
package/dist/behaviors.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { isBuiltin } from "node:module";
|
|
4
4
|
import ts from "typescript";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { isBehaviorFile, isDevelopmentFile, isInside, sourceFiles, isReviewFile } from "./config.mjs";
|
|
6
|
+
import { isBehaviorFile, isDevelopmentFile, isInside, sourceFiles, isReviewFile, isTestFile } from "./config.mjs";
|
|
7
7
|
import { importResolver, projectCompilerOptions } from "./boundaries.mjs";
|
|
8
8
|
import { inspectUnits } from "./units.mjs";
|
|
9
9
|
import { scenarioApi } from "./public-api.mjs";
|
|
@@ -81,7 +81,7 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
|
|
|
81
81
|
const cases = new Set();
|
|
82
82
|
for (const [name, check] of Object.entries(value.checks)) {
|
|
83
83
|
const target = owned(check.file, `Check ${name}`);
|
|
84
|
-
if (target && !
|
|
84
|
+
if (target && !isTestFile(target)) report(`Check ${name} must use a development-only test/spec file, not a scenario, fixture or helper.`);
|
|
85
85
|
if (!Object.hasOwn(config.mcp.behaviorProfiles, check.profile)) report(`Check ${name} references unregistered profile ${check.profile}. Register its literal runner command in ds.config.json; checks cannot install packages or assume host globals.`);
|
|
86
86
|
if (check.scenario && !scenarios.some(scenario => scenario.id === check.scenario)) report(`Check ${name} references unknown scenario ${check.scenario}.`);
|
|
87
87
|
const identity = JSON.stringify([check.file, check.case, check.profile]);
|
package/dist/boundaries.mjs
CHANGED
|
@@ -10,7 +10,10 @@ export function projectCompilerOptions({ root, config, dsRoot }) {
|
|
|
10
10
|
let compiler = {};
|
|
11
11
|
if (file && isInside(root, file)) {
|
|
12
12
|
const parsed = ts.readConfigFile(file, ts.sys.readFile);
|
|
13
|
-
|
|
13
|
+
// Only compiler options are consumed here. Expanding include/exclude globs
|
|
14
|
+
// for every lint rule/file needlessly walks the complete project tree.
|
|
15
|
+
// TypeScript still resolves extends (including package configs) normally.
|
|
16
|
+
if (!parsed.error) compiler = ts.parseJsonConfigFileContent(parsed.config, { ...ts.sys, readDirectory: () => [] }, path.dirname(file)).options;
|
|
14
17
|
}
|
|
15
18
|
return config && dsRoot ? { ...compiler, paths: { ...compiler.paths,
|
|
16
19
|
[config.publicAlias]: [path.join(dsRoot, config.publicEntry)],
|
|
@@ -114,9 +117,9 @@ export function styleAccessProperty(node) {
|
|
|
114
117
|
|
|
115
118
|
// Aliases, computed keys, cssText and bulk writes cannot widen an exception.
|
|
116
119
|
export function styleWriteViolation(node, filename, { root, config }) {
|
|
117
|
-
const allowed = config.boundaries.styleWrites.find((boundary) => path.resolve(root, boundary.file) === filename)?.properties ?? [];
|
|
118
120
|
const property = styleAccessProperty(node);
|
|
119
|
-
if (property !== undefined && property !== false && !(property && property !== "css-text"
|
|
121
|
+
if (property !== undefined && property !== false && !(property && property !== "css-text"
|
|
122
|
+
&& config.boundaries.styleWrites.find((boundary) => path.resolve(root, boundary.file) === filename)?.properties?.includes(property))) {
|
|
120
123
|
return "Imperative styles require a file boundary and an explicit property. Bulk writes, computed property names, and style-object escapes are forbidden.";
|
|
121
124
|
}
|
|
122
125
|
if (ts.isCallExpression(node) && isMember(node.expression) && ["setAttribute", "setAttributeNS"].includes(memberName(node.expression))) {
|
package/dist/check.mjs
CHANGED
|
@@ -31,6 +31,7 @@ import { architectureEvidence, failure } from "./evidence.mjs";
|
|
|
31
31
|
import { propertyRegistration } from "./property-registrations.mjs";
|
|
32
32
|
import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
|
|
33
33
|
import { createDesignValues, inspectDesignAliases, isColorKeyword } from "./design-values.mjs";
|
|
34
|
+
import { inspectTestBoundaries } from "./test-boundaries.mjs";
|
|
34
35
|
|
|
35
36
|
const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
|
|
36
37
|
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
|
|
@@ -54,6 +55,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
54
55
|
diagnostics.push(...inspectAssets(options));
|
|
55
56
|
const resolveImport = importResolver(options);
|
|
56
57
|
const units = inspectUnits(options);
|
|
58
|
+
options.testOwner = file => units.owner(units.relative(path.relative(root,file)));
|
|
57
59
|
const rootHtml = path.join(root, "index.html");
|
|
58
60
|
const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...(existsSync(rootHtml) ? [rootHtml] : [])])];
|
|
59
61
|
const boundaryFiles = [...config.inlineStyleFiles, ...config.boundaries.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
|
|
@@ -82,6 +84,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
82
84
|
inspectScenarioCoverage(options, program, report, (file, rule, message) => advisories.push({ file: path.relative(root, file).replaceAll("\\", "/"), rule, message, line: 1, column: 1 }), scenarioTrace);
|
|
83
85
|
const behaviors = inspectBehaviors(options, program);
|
|
84
86
|
diagnostics.push(...behaviors.diagnostics);
|
|
87
|
+
diagnostics.push(...inspectTestBoundaries(options,units,behaviors.contracts,program));
|
|
85
88
|
inspectControllers(options, program, report, behaviors.contracts);
|
|
86
89
|
// The foundation remains a fixed import-only entry, not an extra styling layer.
|
|
87
90
|
const foundationEntry = path.join(dsRoot, config.stylesEntry);
|
package/dist/cli.mjs
CHANGED
|
@@ -11,6 +11,7 @@ Usage: ads init [options] Run inside your project
|
|
|
11
11
|
|
|
12
12
|
init Set up ADS in the current project (requires package.json)
|
|
13
13
|
check [directory] Check tokens, ownership, imports, and showcase coverage
|
|
14
|
+
validate [dir] Audit architecture, lint, project scripts and behavior checks
|
|
14
15
|
behaviors [dir] Inspect behavior contracts and current verification evidence
|
|
15
16
|
verify [directory] Run registered behavior checks (--unit and --check select)
|
|
16
17
|
tokens [directory] Inspect local token values and theme definitions
|
|
@@ -29,6 +30,7 @@ Usage: ads init [options] Run inside your project
|
|
|
29
30
|
--mutations MCP only: enable guarded ADS source editing
|
|
30
31
|
--unit id Verify only: select one discovered behavior contract owner
|
|
31
32
|
--check id Verify only: select a registered check (repeatable)
|
|
33
|
+
--changed Validate only: select affected checks since the last full audit
|
|
32
34
|
|
|
33
35
|
External components and examples are imported using the ADS skills.
|
|
34
36
|
No component library or example catalogue is bundled.
|
|
@@ -46,10 +48,12 @@ async function main(args) {
|
|
|
46
48
|
const selectedChecks = [];
|
|
47
49
|
let showcase = true;
|
|
48
50
|
let mutations = false;
|
|
51
|
+
let changed = false;
|
|
49
52
|
const positional = [];
|
|
50
53
|
for (let index = 0; index < args.length; index++) {
|
|
51
54
|
const argument = args[index];
|
|
52
55
|
if (argument === "--json") json = true;
|
|
56
|
+
else if (argument === "--changed") changed = true;
|
|
53
57
|
else if (argument === "--no-showcase") showcase = false;
|
|
54
58
|
else if (argument === "--mutations") mutations = true;
|
|
55
59
|
else if (argument === "--unit" || argument === "--check") {
|
|
@@ -77,6 +81,7 @@ async function main(args) {
|
|
|
77
81
|
}
|
|
78
82
|
if (positional.length > 2) throw new Error("Extra argument. Run ads --help.");
|
|
79
83
|
const [command, directory] = positional;
|
|
84
|
+
if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
|
|
80
85
|
if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
|
|
81
86
|
if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
|
|
82
87
|
if (mutations && command !== "mcp") throw new Error("--mutations is supported only by mcp.");
|
|
@@ -95,6 +100,13 @@ async function main(args) {
|
|
|
95
100
|
let result;
|
|
96
101
|
if (command === "init") result = initProject(target, { toolPackage, packageManager, framework });
|
|
97
102
|
else if (command === "check") result = checkProject(target);
|
|
103
|
+
else if (command === "validate") {
|
|
104
|
+
const {createValidationController}=await import("./validation.mjs");
|
|
105
|
+
const validation=createValidationController(target);
|
|
106
|
+
const abort=()=>{void validation.close();};process.once("SIGINT",abort);process.once("SIGTERM",abort);
|
|
107
|
+
try {result=await validation.run({scope:changed?"changed":"all"});}
|
|
108
|
+
finally {process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort);await validation.close();}
|
|
109
|
+
}
|
|
98
110
|
else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
|
|
99
111
|
else if (command === "verify") { const {createVerificationController}=await import("./verification.mjs"); const verification=createVerificationController(target); try {result=await verification.run({...(unit?{unit}:{}),...(selectedChecks.length?{checks:selectedChecks}:{})});} finally {await verification.close();} }
|
|
100
112
|
else if (command === "tokens") result = inspectTokens(target);
|
|
@@ -107,6 +119,7 @@ async function main(args) {
|
|
|
107
119
|
else if (command === "lint-config") console.log(`Generated ${result.file}\nProjects initialized with ads init refresh this automatically during lint:ds/build.`);
|
|
108
120
|
else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
|
|
109
121
|
else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
|
|
122
|
+
else if (command === "validate") {console.log(`ADS validation ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
|
|
110
123
|
else if (command === "tokens") {
|
|
111
124
|
for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}: ${entry.value}`).join("; ")}`);
|
|
112
125
|
} else if (result.ok) console.log(`ADS check passed: ${target}`);
|
package/dist/config.mjs
CHANGED
|
@@ -18,6 +18,7 @@ export const defaultConfig = {
|
|
|
18
18
|
boundaries: { styleWrites: [], componentVariables: [] },
|
|
19
19
|
assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null },
|
|
20
20
|
oxlint: { plugins: [], rules: {}, overrides: [] },
|
|
21
|
+
validation: { checks: null },
|
|
21
22
|
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationChecks: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
|
|
22
23
|
};
|
|
23
24
|
|
|
@@ -44,11 +45,12 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
44
45
|
if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
|
|
45
46
|
}
|
|
46
47
|
if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
|
|
47
|
-
for (const field of ["boundaries", "assets", "oxlint", "mcp"]) {
|
|
48
|
+
for (const field of ["boundaries", "assets", "oxlint", "mcp", "validation"]) {
|
|
48
49
|
if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
|
|
49
50
|
for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
|
|
50
51
|
}
|
|
51
|
-
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, mcp: { ...defaultConfig.mcp, ...user.mcp } };
|
|
52
|
+
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp } };
|
|
53
|
+
if (config.validation.checks !== null && (!Array.isArray(config.validation.checks) || config.validation.checks.length > 20 || new Set(config.validation.checks).size !== config.validation.checks.length || config.validation.checks.some(name=>typeof name !== "string" || !/^[\w:.-]+$/.test(name)))) throw new Error("validation.checks must be null or up to 20 unique package script names.");
|
|
52
54
|
if (config.schemaVersion !== 1) throw new Error(`Unsupported ADS config version: ${config.schemaVersion}`);
|
|
53
55
|
if (user.framework !== undefined && !supportedFrameworks.includes(user.framework)) throw new Error("framework must be react or preact.");
|
|
54
56
|
if (typeof config.publicAlias !== "string" || !config.publicAlias.trim()) throw new Error("publicAlias must be a non-empty string.");
|
|
@@ -222,7 +224,7 @@ export function importViolation(specifier, filename, options, resolve) {
|
|
|
222
224
|
if (isReviewFile(filename, options)) return false;
|
|
223
225
|
// Owner-local white-box tests may exercise private helpers without making
|
|
224
226
|
// those helpers public API. Scenarios remain public-API consumers.
|
|
225
|
-
if (isTestFile(filename) && isInside(dsRoot, filename) &&
|
|
227
|
+
if (isTestFile(filename) && isInside(dsRoot, filename) && options.testOwner?.(filename) && options.testOwner(filename) === options.testOwner(file)) return false;
|
|
226
228
|
if (isDevelopmentFile(filename, options) && isDevelopmentFile(file, options)) return false;
|
|
227
229
|
if (isTestFile(filename) && (isInside(path.join(dsRoot, "showcase"), file) || isTestFile(file))) return false;
|
|
228
230
|
if (isInside(path.join(dsRoot, "showcase"), filename) && isInside(path.join(dsRoot, "showcase"), file)) return false;
|
|
@@ -5,7 +5,7 @@ import { z } from "zod";
|
|
|
5
5
|
import { isInside, projectPath, loadConfig } from "../config.mjs";
|
|
6
6
|
import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
7
7
|
import { readPreviewManifest } from "../preview-resources.mjs";
|
|
8
|
-
import { previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
8
|
+
import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
9
9
|
|
|
10
10
|
export const BUILD_URI = "ads://project/build";
|
|
11
11
|
export const buildStatusFile = (root) => path.join(root, ".ds/build-status.json");
|
|
@@ -13,7 +13,8 @@ const maxBytes = 256 * 1024;
|
|
|
13
13
|
const diagnostic = z.object({ message: z.string().max(4000), file: z.string().max(1000).optional(), line: z.number().int().positive().optional(), column: z.number().int().positive().optional(), plugin: z.string().max(200).optional(), code: z.string().max(100).optional() }).strict();
|
|
14
14
|
const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional() }).strict();
|
|
15
15
|
const progressSchema = z.object({ phase: z.enum(["queued", "validation", "compilation", "validation-and-compilation", "publication", "idle"]), startedAt: z.string().datetime(), updatedAt: z.string().datetime() }).strict();
|
|
16
|
-
const
|
|
16
|
+
const liveSchema = z.object({ revision: z.string().regex(/^[a-f0-9]{64}$/), sourceRevision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
|
17
|
+
const snapshot = z.object({ schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
|
|
17
18
|
export const artifactDigest = (file) => {
|
|
18
19
|
if (realpathSync(file) !== file) throw new Error("Preview output cannot resolve through a symlink.");
|
|
19
20
|
if (statSync(file).size > 2 * 1024 * 1024) throw new Error("Preview exceeds 2 MiB.");
|
|
@@ -41,8 +42,10 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
|
|
|
41
42
|
let sequence = 0;
|
|
42
43
|
let diagnostics = [];
|
|
43
44
|
let progress;
|
|
45
|
+
let live, batching = 0;
|
|
44
46
|
function save() {
|
|
45
|
-
|
|
47
|
+
if (batching) return;
|
|
48
|
+
const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
|
|
46
49
|
let text = JSON.stringify(snapshot.parse(value));
|
|
47
50
|
// A shared graph failure applies to every scenario. Store repeated details
|
|
48
51
|
// once only when necessary; ordinary reports retain inline diagnostics.
|
|
@@ -71,6 +74,8 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
|
|
|
71
74
|
save();
|
|
72
75
|
return {
|
|
73
76
|
session,
|
|
77
|
+
batch(run) { ++batching; try { return run(); } finally { --batching; save(); } },
|
|
78
|
+
live(value) { live = value; save(); },
|
|
74
79
|
progress(phase) {
|
|
75
80
|
const now = new Date().toISOString();
|
|
76
81
|
progress = { phase, startedAt: !progress || progress.phase === "idle" ? now : progress.startedAt, updatedAt: now };
|
|
@@ -140,10 +145,17 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
|
|
|
140
145
|
} catch (error) { reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`; }
|
|
141
146
|
let graphError;
|
|
142
147
|
let sourceRevision, sourceError;
|
|
143
|
-
if (report?.previews.some(entry=>entry.state==="ready")) {
|
|
148
|
+
if (report?.live || report?.previews.some(entry=>entry.state==="ready")) {
|
|
144
149
|
try { sourceRevision = previewSourceRevision(loadConfig(root),config.apps); }
|
|
145
150
|
catch (error) { sourceError = `Cannot verify preview inputs: ${error.message}`; }
|
|
146
151
|
}
|
|
152
|
+
let live;
|
|
153
|
+
if (report?.live && !reportError && !sourceError && report.live.sourceRevision === sourceRevision && !report.diagnostics?.length) {
|
|
154
|
+
try {
|
|
155
|
+
const graph = readPreviewManifest(livePreviewOptions(options));
|
|
156
|
+
if (graph?.session === report.session && graph.revision === report.live.revision) live = { ...report.live, scenarios: new Set(graph.scenarios.map(entry => entry.id)) };
|
|
157
|
+
} catch { /* An incomplete/corrupt live graph grants no preview access. */ }
|
|
158
|
+
}
|
|
147
159
|
if (config.previewManifest && report?.previews.some(entry => entry.state === "ready")) {
|
|
148
160
|
try {
|
|
149
161
|
if (!readPreviewManifest(options, { verify: true })) throw new Error("Preview resource manifest is missing.");
|
|
@@ -170,6 +182,7 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
|
|
|
170
182
|
if (["stopped", "stopping", "idle"].includes(processState?.state)) state = "unreported";
|
|
171
183
|
const current = state === "ready";
|
|
172
184
|
return { id: app.id, state, session: report?.session ?? null, revision: value?.revision ?? null, lastSuccessfulRevision: value?.lastSuccessfulRevision ?? null,
|
|
185
|
+
...(!current && state !== "error" && live?.scenarios.has(app.id) ? { live: { revision: live.revision, sourceRevision: live.sourceRevision, validated: false } } : {}),
|
|
173
186
|
current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
|
|
174
187
|
});
|
|
175
188
|
const state = reportError || report?.diagnostics?.length || previews.some((entry) => entry.state === "error") ? "error" : previews.some((entry) => entry.state === "building") ? "building" : previews.some((entry) => entry.state === "unreported") ? "unreported" : previews.some(entry => entry.current) ? "ready" : previews.length ? "idle" : "disabled";
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { developmentRuntime, packageScriptCommand } from "../development-runtime
|
|
|
6
6
|
|
|
7
7
|
export const GUIDE_URI = "ads://project/guide";
|
|
8
8
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
9
|
-
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
9
|
+
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Use ads_validate with scope changed during editing, and the default full scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
10
10
|
|
|
11
11
|
function manager(root, pkg) {
|
|
12
12
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
|
@@ -27,6 +27,7 @@ export function projectContext(options) {
|
|
|
27
27
|
publicEntry: path.join(dsRoot, config.publicEntry), publicEntryUri: existsSync(path.join(dsRoot, config.publicEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.publicEntry)).replaceAll("\\", "/")) : null,
|
|
28
28
|
review: { importFrom: `${config.publicAlias}/review`, entry: path.join(dsRoot, config.reviewEntry), sourceUri: existsSync(path.join(dsRoot, config.reviewEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.reviewEntry)).replaceAll("\\", "/")) : null, developmentOnly: true },
|
|
29
29
|
stylesEntry: path.join(dsRoot, config.stylesEntry), packageManager, commands, guides,
|
|
30
|
+
validation: { tool: "ads_validate", cli: ["ads", "validate"], defaultScope: "all", scopes: ["all","changed"], guideUri: "ads://guides/validation" },
|
|
30
31
|
showcase: { client: "tool-owned-mcp", url: config.mcp.showcaseUrl, title: config.mcp.showcaseTitle ?? `${pkg.name ?? path.basename(root)} · Design System` },
|
|
31
32
|
runtime: { ...developmentRuntime(),
|
|
32
33
|
shellHint: "The agent shell may have a different PATH from MCP. Use this runtime executable/bin directory and the returned project commands; do not search the whole machine or assume another runtime must be installed." } };
|
|
@@ -5,7 +5,7 @@ import { compactAcceptance, compactRow, jsonBytes, resultBudgets, resultPage, re
|
|
|
5
5
|
|
|
6
6
|
export const RESULTS_URI = "ads://project/results";
|
|
7
7
|
export const resultSections = ["outcomes", "checks", "diagnostics", "advisories", "warnings", "changes", "captures", "acceptance", "investigation", "selection"];
|
|
8
|
-
const kinds = ["verification", "mutation"];
|
|
8
|
+
const kinds = ["verification", "mutation", "validation"];
|
|
9
9
|
const maxStoredBytes = 8 * 1024 * 1024;
|
|
10
10
|
const uuid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
11
11
|
const resultUri = id => `ads://results/${id}`;
|
|
@@ -27,13 +27,14 @@ function snapshot(kind, raw) {
|
|
|
27
27
|
outcomes: outcomes.map(outcome),
|
|
28
28
|
checks: (raw.checks ?? []).map(({ results, ...check }) => ({ ...check, ...(results ? { outcomeCount: results.length } : {}) })),
|
|
29
29
|
diagnostics: raw.diagnostics ?? [], advisories: raw.advisories ?? [], warnings: raw.warnings ?? [], changes: raw.changes ?? [],
|
|
30
|
-
captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction}],
|
|
30
|
+
captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction,...raw.selection}],
|
|
31
31
|
acceptance: raw.acceptance ? [raw.acceptance] : [], investigation: raw.investigation ? [raw.investigation] : [],
|
|
32
32
|
};
|
|
33
33
|
const resultId = randomUUID();
|
|
34
34
|
return { schemaVersion: 1, resultId, kind, createdAt: new Date().toISOString(), ok: !!raw.ok,
|
|
35
35
|
...(raw.applied !== undefined ? { applied: raw.applied } : {}), ...(raw.unit ? { unit: raw.unit } : {}),
|
|
36
36
|
...(raw.units ? { units: raw.units } : {}), ...(raw.transaction ? { transaction: true } : {}),
|
|
37
|
+
...(kind === "validation" ? {scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
|
|
37
38
|
acceptance: raw.acceptance, investigation: raw.investigation,
|
|
38
39
|
sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
|
|
39
40
|
counts: { outcomes: count(outcomes), checks: count(sections.checks), diagnostics: sections.diagnostics.length,
|
|
@@ -46,7 +47,7 @@ function summary(value, storageWarning) {
|
|
|
46
47
|
const failedOutcomes = value.sections.outcomes.filter(item => item.status !== "passed");
|
|
47
48
|
const failureRows = failedOutcomes.length ? failedOutcomes : value.sections.diagnostics;
|
|
48
49
|
const section = failedOutcomes.length ? "outcomes" : value.sections.diagnostics.length ? "diagnostics" : value.sections.captures.length ? "captures" : value.sections.outcomes.length ? "outcomes" : "checks";
|
|
49
|
-
const result = { ok, resultId, kind, ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
|
|
50
|
+
const result = { ok, resultId, kind, ...(kind === "validation" ? {scope:value.scope,requestedScope:value.requestedScope,sourceRevision:value.sourceRevision,current:value.current,elapsedMs:value.elapsedMs,...(value.fallback?{fallback:value.fallback}:{})} : {}), ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
|
|
50
51
|
...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
|
|
51
52
|
acceptance: compactAcceptance(value.acceptance), failures: value.failurePreview ?? failureRows.slice(0, 3).map(item => compactRow({recordIndex:item.recordIndex,unit:item.unit,check:item.check,status:item.status,rule:item.rule,file:item.file,failure:item.failure,message:item.message},640)),
|
|
52
53
|
failureCount: value.failureCount ?? failureRows.length, resourceUri,
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
3
2
|
import { createRequire } from "node:module";
|
|
4
3
|
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
5
4
|
import path from "node:path";
|
|
@@ -9,14 +8,14 @@ import { affectedBehaviorUnits, createVerificationController } from "../verifica
|
|
|
9
8
|
import { checkProject } from "../check.mjs";
|
|
10
9
|
import { generateLintConfig } from "../lint-config.mjs";
|
|
11
10
|
import { generateBrandAssets } from "../brand-assets.mjs";
|
|
12
|
-
import { projectContext } from "./context.mjs";
|
|
13
11
|
import { applyFilePatch, parseUnifiedPatch } from "./patch.mjs";
|
|
14
12
|
import { createCaptureController, captureSelections } from "../capture.mjs";
|
|
15
13
|
import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
16
14
|
import { inspectScenarios } from "../scenarios.mjs";
|
|
17
15
|
import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
|
|
18
16
|
import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
|
|
19
|
-
import {
|
|
17
|
+
import { checkCommand, projectChecks as checks } from "../validation-checks.mjs";
|
|
18
|
+
import { preparePreviewCache } from "../scenarios-compiler.mjs";
|
|
20
19
|
|
|
21
20
|
export const mutationLimits = { units: 8, files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 20000, snapshotBytes: 128 * 1024 * 1024 };
|
|
22
21
|
const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
@@ -110,38 +109,6 @@ function snapshot(options, destination) {
|
|
|
110
109
|
return JSON.stringify(entries);
|
|
111
110
|
}
|
|
112
111
|
|
|
113
|
-
function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
|
|
114
|
-
return new Promise((resolve, reject) => {
|
|
115
|
-
if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
|
|
116
|
-
const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
117
|
-
env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
|
|
118
|
-
let output = "", failure;
|
|
119
|
-
const startedAt=Date.now();
|
|
120
|
-
if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
|
|
121
|
-
function kill() {
|
|
122
|
-
if (!child.pid) return;
|
|
123
|
-
if (process.platform === "win32") {
|
|
124
|
-
const stop = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
125
|
-
stop.on("error", () => child.kill("SIGKILL"));
|
|
126
|
-
} else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
|
|
127
|
-
}
|
|
128
|
-
const abort = () => { failure = fail("mutation-cancelled", "Mutation cancelled during validation."); kill(); };
|
|
129
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
130
|
-
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);
|
|
131
|
-
for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
|
|
132
|
-
child.once("error", error => { failure = error; });
|
|
133
|
-
child.once("exit", kill); // Also clean up descendants of a finished launcher.
|
|
134
|
-
child.once("close", code => {
|
|
135
|
-
clearTimeout(timer); signal?.removeEventListener("abort", abort);
|
|
136
|
-
const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
|
|
137
|
-
if (failure || code !== 0) {
|
|
138
|
-
const error=failure??fail("mutation-check", `${path.basename(command)} ${args.join(" ")} failed (${code}).\n${output}`);
|
|
139
|
-
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"})};
|
|
140
|
-
reject(error);
|
|
141
|
-
} else resolve({ ...detail,phase:gate.phase, passed: true });
|
|
142
|
-
});
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
112
|
|
|
146
113
|
function mutationEvidence(result, candidateRevision) {
|
|
147
114
|
const diagnostics=(result.diagnostics??[]).map(diagnostic=>({...diagnostic,failure:diagnostic.failure??evidenceFailure("architecture","mutation-policy",diagnostic.rule)}));
|
|
@@ -150,14 +117,6 @@ function mutationEvidence(result, candidateRevision) {
|
|
|
150
117
|
return {...result,...(result.diagnostics?{diagnostics}:{}),acceptance:accepted,investigation:{target:"candidate",candidateRevision:candidateRevision??null,...(failed?{failure:failed.failure,failingStep:failed.failure.phase,source:failed.file?{file:failed.file,line:failed.line,column:failed.column}:null,...(failed.command?{command:failed.command,args:failed.args,exitCode:failed.exitCode,output:failed.output}:{}),message:failed.message}:{}),acceptance:accepted}};
|
|
151
118
|
}
|
|
152
119
|
|
|
153
|
-
function checks(options) {
|
|
154
|
-
const context = projectContext(options);
|
|
155
|
-
const pkg = JSON.parse(readFileSync(path.join(options.root, "package.json"), "utf8"));
|
|
156
|
-
const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", "build:mcp-previews"].filter(name => typeof pkg.scripts?.[name] === "string");
|
|
157
|
-
if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
|
|
158
|
-
if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
|
|
159
|
-
return scripts.map(script => packageScriptCommand(context.packageManager, script));
|
|
160
|
-
}
|
|
161
120
|
|
|
162
121
|
export function createMutationController(directory, { captures = createCaptureController(directory) } = {}) {
|
|
163
122
|
const root = path.resolve(directory);
|
|
@@ -317,6 +276,8 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
317
276
|
const proposal = digest(Buffer.from(JSON.stringify(changes.map(change => [change.path, change.content === null ? null : digest(Buffer.from(change.content))]))));
|
|
318
277
|
screenshots = await captures.run({ captures: selections, candidateRoot: candidate, proposal, publish: false }, signal, value => { progress = value; notifyProgress?.(value); });
|
|
319
278
|
}
|
|
279
|
+
let preparedPreview;
|
|
280
|
+
if(!dryRun){try{preparedPreview=preparePreviewCache(candidateOptions,loadConfig(root));}catch{/* A missing cache falls back to background compilation. */}}
|
|
320
281
|
if (signal?.aborted) throw fail("mutation-cancelled", "Mutation cancelled before application.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"));
|
|
321
282
|
if (snapshot(candidateOptions) !== expected) throw fail("mutation-check", "A validation command changed source files. Use checks without source-writing side effects.");
|
|
322
283
|
if (snapshot(loadConfig(root)) !== before) throw fail("mutation-conflict", "Project inputs changed during validation; no changes were applied. Read current source and retry.");
|
|
@@ -354,6 +315,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
354
315
|
const warnings = [];
|
|
355
316
|
if (!dryRun && (assets || configuration)) { try { await generateBrandAssets(root); } catch (error) { warnings.push({ rule: "mutation-assets", message: `Source was applied; generated brand output needs recovery: ${error.message}` }); } }
|
|
356
317
|
if (!dryRun && captures.store.fingerprint()) { try { captures.store.promote(previewSourceRevision(loadConfig(root)), inspectScenarios(loadConfig(root)).scenarios); } catch (error) { warnings.push({ rule: "mutation-capture", message: `Source was applied; capture promotion needs recovery: ${error.message}` }); } }
|
|
318
|
+
if (!dryRun && preparedPreview) { try { preparedPreview(); } catch (error) { warnings.push({rule:"mutation-preview-cache",message:`Source was applied; preview warming will rebuild instead: ${error.message}`}); } }
|
|
357
319
|
return lastResult = mutationEvidence({ ok: true, ...(patches ? {units,transaction:true} : {unit}), applied: !dryRun, changes: changes.map(change => ({ path: change.path, operation: change.content === null ? "delete" : change.expectedDigest === null ? "create" : "update", digest: change.content === null ? null : digest(Buffer.from(change.content)) })), checks: verified, ...(result.advisories?.length ? { advisories: result.advisories, advisoryCount: result.advisories.length } : {}), ...(warnings.length ? { warnings } : {}),
|
|
358
320
|
...(screenshots ? { screenshots } : {}),
|
|
359
321
|
preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." },candidateRevision);
|
|
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
|
|
|
6
6
|
import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
|
|
7
7
|
import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
|
|
8
8
|
import { developmentExecutable } from "../development-runtime.mjs";
|
|
9
|
+
import { readPreviewManifest } from "../preview-resources.mjs";
|
|
9
10
|
|
|
10
11
|
function stamp(file) {
|
|
11
12
|
try { const stat = statSync(file); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`; }
|
|
@@ -132,7 +133,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
132
133
|
})().finally(() => { restarting = undefined; });
|
|
133
134
|
}
|
|
134
135
|
|
|
135
|
-
async function ensure(file, signal) {
|
|
136
|
+
async function ensure(file, signal, { waitFor = "verified" } = {}) {
|
|
136
137
|
if (signal?.aborted) throw new Error("Preview request cancelled.");
|
|
137
138
|
if (state === "failed" || restarting || stalled) await restart();
|
|
138
139
|
if (disposed) throw new Error("Preview watcher is stopped.");
|
|
@@ -149,6 +150,15 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
149
150
|
if (!restarted && build?.diagnostics.some(item => item.code === "ADS_PREVIEW_RESTART")) {
|
|
150
151
|
restarted = true; await restart(); request(file); baseline = baselines.get(file) ?? null; continue;
|
|
151
152
|
}
|
|
153
|
+
// Interactive browsing may use compiled feedback or an earlier accepted
|
|
154
|
+
// view. It returns the actual non-current build status, never evidence.
|
|
155
|
+
if (waitFor === "compiled" && config.previewManifest) {
|
|
156
|
+
if (build?.live) return build;
|
|
157
|
+
try {
|
|
158
|
+
const manifest = readPreviewManifest(withPreviewSession({ root, config: { mcp: config } }, resourceSession()));
|
|
159
|
+
if (manifest && (!command || manifest.session === session) && manifest.scenarios.some(entry => entry.id === app?.id)) return build;
|
|
160
|
+
} catch { /* No retained graph: wait for compilation or its error. */ }
|
|
161
|
+
}
|
|
152
162
|
if (build?.state === "error") throw buildFailure(build);
|
|
153
163
|
if (command && state !== "running") throw new Error(error ?? "Preview watcher is stopped.");
|
|
154
164
|
if (build?.current) return build;
|
|
@@ -183,7 +193,16 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
183
193
|
})();
|
|
184
194
|
return stopping;
|
|
185
195
|
}
|
|
186
|
-
return { start, ensure, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async
|
|
196
|
+
return { start, ensure, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
|
|
197
|
+
if (disposed || !command || !files.length) return;
|
|
198
|
+
const selected=active;
|
|
199
|
+
if (state === "failed" || restarting || stalled) await restart();
|
|
200
|
+
if (disposed) return;
|
|
201
|
+
start();
|
|
202
|
+
for (const file of files) requests.add(file);
|
|
203
|
+
// Preparing a graph must not replace the user's active selection.
|
|
204
|
+
request(active ?? selected ?? files[0],true);
|
|
205
|
+
}, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
|
|
187
206
|
for (const app of apps) {
|
|
188
207
|
const file = path.resolve(root, app.file);
|
|
189
208
|
if (!baselines.has(file)) baselines.set(file, stamp(file));
|
|
@@ -200,11 +219,12 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
200
219
|
let pending = Promise.resolve(), replacing = false, stopped = false;
|
|
201
220
|
return {
|
|
202
221
|
start() { if (!stopped && !replacing) current.start(); },
|
|
203
|
-
async ensure(file, signal) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal); },
|
|
222
|
+
async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
|
|
204
223
|
status() { return replacing ? { state: "reconfiguring" } : current.status(); },
|
|
205
224
|
resourceSession() { return current.resourceSession(); },
|
|
206
225
|
buildStatus() { return current.buildStatus(); },
|
|
207
226
|
async invalidate() { await pending; if (!stopped) current.invalidate(); },
|
|
227
|
+
async warm(files) { await pending; if (!stopped) return current.warm(files); },
|
|
208
228
|
setApps(next) { apps = next; current.setApps(next); },
|
|
209
229
|
kill() { current.kill(); },
|
|
210
230
|
reconfigure(next, force = false) {
|