@reqvire-org/ads 0.3.5 → 0.3.6
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/README.md +5 -1
- package/dist/bootstrap-ds/ADS.md +9 -3
- package/dist/bootstrap-ds/README.md +10 -0
- package/dist/boundaries.mjs +3 -0
- package/dist/check.mjs +13 -0
- package/dist/config.mjs +6 -2
- package/dist/mcp/build-status.mjs +7 -4
- package/dist/mcp/context.mjs +2 -2
- package/dist/mcp/edit-preparation.mjs +111 -0
- package/dist/mcp/mutations.mjs +54 -38
- package/dist/mcp/preview-watch.mjs +10 -4
- package/dist/mcp/server.mjs +32 -22
- package/dist/mcp/text-diff.mjs +19 -0
- package/dist/preview-resources.mjs +45 -8
- package/dist/preview-scope.mjs +30 -0
- package/dist/scenarios-compiler.mjs +24 -17
- package/dist/scenarios.mjs +46 -4
- package/dist/scoped-tokens.mjs +57 -0
- package/dist/skills/ads-break-ui/SKILL.md +4 -2
- package/dist/skills/ads-break-ui/references/guarded-editing.md +44 -0
- package/dist/skills/ads-break-ui/references/verification.md +6 -0
- package/dist/skills/ads-designer/SKILL.md +4 -2
- package/dist/skills/ads-designer/assets/bootstrap-ds/ADS.md +9 -3
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +10 -0
- package/dist/skills/ads-designer/references/guarded-editing.md +44 -0
- package/dist/skills/ads-import/SKILL.md +4 -2
- package/dist/skills/ads-import/references/guarded-editing.md +44 -0
- package/dist/skills/ads-import/references/tokens.md +4 -2
- package/dist/skills/ads-migrate/SKILL.md +4 -2
- package/dist/skills/ads-migrate/references/guarded-editing.md +44 -0
- package/dist/skills/ads-motion/SKILL.md +4 -2
- package/dist/skills/ads-motion/references/guarded-editing.md +44 -0
- package/dist/token-fixtures.mjs +30 -0
- package/dist/tokens.mjs +8 -2
- package/dist/units.mjs +15 -0
- package/dist/verification.mjs +1 -1
- package/docs/ADS.md +45 -2
- package/docs/ARCHITECTURE.md +21 -0
- package/docs/BEHAVIORS.md +11 -0
- package/docs/CHANGELOG.md +20 -0
- package/docs/GUIDE.md +8 -3
- package/docs/MCP.md +60 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -91,7 +91,11 @@ for config files and Claude Desktop setup.
|
|
|
91
91
|
To let the agent edit the ADS through enforced checks, append `--mutations` to
|
|
92
92
|
the MCP command. It accepts a Git patch for one ADS unit, including its owned scenarios and
|
|
93
93
|
fixtures, and runs the guards before applying it. Foundation styles, original
|
|
94
|
-
assets, guides and project configuration/guard extensions have editable units too.
|
|
94
|
+
assets, guides and project configuration/guard extensions have editable units too.
|
|
95
|
+
Coupled changes use bounded owner transactions with checks on the complete final
|
|
96
|
+
candidate. Local owner drafts and token-sample preparation reduce patch setup;
|
|
97
|
+
they keep source writes behind the same guards. See
|
|
98
|
+
[guarded editing](docs/MCP.md#guarded-editing).
|
|
95
99
|
|
|
96
100
|
The server exposes public components/patterns, token values,
|
|
97
101
|
source guides, controllers/hooks, architecture checks, behavioral verification,
|
package/dist/bootstrap-ds/ADS.md
CHANGED
|
@@ -36,8 +36,14 @@ Projects sharing this ADS use the same token names, meanings, and value types;
|
|
|
36
36
|
their concrete values and theme overrides can differ. Reuse existing local values
|
|
37
37
|
when importing components/patterns, add missing shared definitions, and import
|
|
38
38
|
source token values only when adopting that theme is requested.
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
Shared token names and prefixes follow the ADS contract. A component/pattern may
|
|
40
|
+
register one unique local namespace in colocated `tokens.json` and define it in
|
|
41
|
+
`tokens.css`, imported by its runtime. Flat owners use `<Owner>.tokens.json` and
|
|
42
|
+
`<Owner>.tokens.css`. These definition-only sheets contain root/theme custom
|
|
43
|
+
properties, not UI selectors or ordinary styles. Other owners consume shared
|
|
44
|
+
tokens; they cannot override or consume a peer's local namespace. A colocated
|
|
45
|
+
`kind:"tokens"` scenario needs real samples for every local token. Shared
|
|
46
|
+
assignments remain in the shared token files. Components own
|
|
41
47
|
`--ds-*`, patterns `--ux-*`, and the showcase `--showcase-*`; token files cannot
|
|
42
48
|
assign those local variables or override component state.
|
|
43
49
|
|
|
@@ -183,7 +189,7 @@ mounting, correct props, every branch/state or visual parity. The older
|
|
|
183
189
|
|
|
184
190
|
`token-scenario-reference` rejects undeclared token names in metadata and reachable
|
|
185
191
|
inputs. `token-scenario-render` rejects claimed tokens with no reachable input
|
|
186
|
-
reference; `token-scenario-coverage` requires every discovered
|
|
192
|
+
reference; `token-scenario-coverage` requires every discovered shared or owner-local token
|
|
187
193
|
to have coverage. A new or removed token therefore needs a scenario/fixture
|
|
188
194
|
update. All three are errors in `ads check`, run by `lint:ds` and the build.
|
|
189
195
|
Coverage is static reachability, not proof that every branch actually renders
|
|
@@ -62,6 +62,10 @@ the public `TokenPreview` pattern owns their presentation and applies the real C
|
|
|
62
62
|
variables. Add/remove samples alongside token definitions. `ads check` rejects
|
|
63
63
|
missing coverage and invented names; the App verifies the declared CSS bindings
|
|
64
64
|
in the browser. Extend or replace the project-owned pattern as your tokens evolve.
|
|
65
|
+
`ads_prepare_token_samples` can prepare a fixture patch from explicit project
|
|
66
|
+
property/probe bindings. It preserves existing samples and reports unmapped tokens;
|
|
67
|
+
it does not guess how a new value should look. Component/pattern constants can use
|
|
68
|
+
the colocated namespace contract in [ADS.md](ADS.md), with their own token scenario.
|
|
65
69
|
|
|
66
70
|
Create a component under `design-system/components/`, export it through `@ds`,
|
|
67
71
|
and colocate `Scenario.tsx` plus `fixture.ts` (or `<Owner>.scenario.tsx` and
|
|
@@ -79,6 +83,8 @@ stale retained output. Switching or rebuilding a scenario unmounts its previous
|
|
|
79
83
|
state. `showcase/mcp/main.tsx` exports `mountScenario(Scenario, container)` and
|
|
80
84
|
returns an unmount callback; it is not the shell. Keep the saved `framework`,
|
|
81
85
|
compiler and mount adapter consistent.
|
|
86
|
+
Managed sessions own their graph output; standalone prebuilds cannot replace it.
|
|
87
|
+
Verified generated graph snapshots preserve warm-start reuse across sessions.
|
|
82
88
|
|
|
83
89
|
The application and previews use the same foundation CSS and Linaria pipeline.
|
|
84
90
|
The source barrel loads the foundation once. The private `build:lib` script uses
|
|
@@ -98,3 +104,7 @@ from a user-selected external repository, preserving revisions and licenses.
|
|
|
98
104
|
inspection builds it automatically, then loads selected entries. Browser review
|
|
99
105
|
still checks layout, accessibility, keyboard/focus, states, themes and motion. A clean
|
|
100
106
|
build or delivered HTML alone does not establish those behaviors.
|
|
107
|
+
Opt-in MCP editing uses owner Git patches. `ads_prepare_patch` creates a temporary
|
|
108
|
+
owner draft/diff; `ads_apply_transaction` validates bounded coupled owner patches
|
|
109
|
+
against one final candidate. Preparation changes no live source. Keep all guards
|
|
110
|
+
and review the rendered result after applying.
|
package/dist/boundaries.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import ts from "typescript";
|
|
|
3
3
|
import { importedUiName } from "./ui-framework.mjs";
|
|
4
4
|
import { isInside, isStateVariable, isTestFile, isDevelopmentFile } from "./config.mjs";
|
|
5
5
|
import { isSharedToken } from "./token-policy.mjs";
|
|
6
|
+
import { scopedTokenOwner } from "./scoped-tokens.mjs";
|
|
6
7
|
|
|
7
8
|
export function projectCompilerOptions({ root }) {
|
|
8
9
|
const file = ts.findConfigFile(root, ts.sys.fileExists, "tsconfig.json");
|
|
@@ -59,6 +60,8 @@ export function checkComponentVariable(name, filename, options) {
|
|
|
59
60
|
const components = !development && isInside(path.join(dsRoot, "components"), filename);
|
|
60
61
|
const patterns = !development && isInside(path.join(dsRoot, "patterns"), filename);
|
|
61
62
|
const showcase = development;
|
|
63
|
+
const owned = scopedTokenOwner(options, name);
|
|
64
|
+
if (owned) return path.resolve(options.root, owned.file) === filename ? null : { rule: "token-ownership", message: `Define ${name} only in ${owned.file}, owned by ${owned.unit}. Consume it with var(); runtime geometry remains a separate styleWrites boundary.` };
|
|
62
65
|
if (isSharedToken(name)) return tokens ? null : { rule: "token-ownership", message: `Define ${name} in ADS tokens, not component, pattern, showcase, or app styles.` };
|
|
63
66
|
if (name.startsWith("--ux-")) return patterns || showcase ? null : { rule: "variable-ownership", message: "--ux-* variables belong to ADS patterns and showcase composition." };
|
|
64
67
|
if (name.startsWith("--showcase-")) return showcase ? null : { rule: "variable-ownership", message: "--showcase-* variables belong to the ADS showcase." };
|
package/dist/check.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import { inspectStyleBoundaries, pointerCaptureAdvisories } from "./style-bounda
|
|
|
18
18
|
import { inspectBehaviors, inspectControllers } from "./behaviors.mjs";
|
|
19
19
|
import { numericCssUnit, tokenLengthLiteral } from "./css-values.mjs";
|
|
20
20
|
import { foundationDeclaration, foundationSelector } from "./foundation.mjs";
|
|
21
|
+
import { scopedTokens, scopedTokenOwner } from "./scoped-tokens.mjs";
|
|
21
22
|
|
|
22
23
|
const scenarioLayoutGuidance = "Put demo-only sizing and framing in a public review/layout pattern. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
|
|
23
24
|
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
|
|
@@ -40,6 +41,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
40
41
|
diagnostics.push(...tokenInventory.diagnostics);
|
|
41
42
|
diagnostics.push(...inspectAssets(options));
|
|
42
43
|
const resolveImport = importResolver(options);
|
|
44
|
+
const scoped = scopedTokens(options);
|
|
45
|
+
const scopedFiles = new Set(scoped.definitions.map(entry => path.resolve(root, entry.file)));
|
|
43
46
|
const rootHtml = path.join(root, "index.html");
|
|
44
47
|
const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...(existsSync(rootHtml) ? [rootHtml] : [])])];
|
|
45
48
|
const boundaryFiles = [...config.inlineStyleFiles, ...config.boundaries.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
|
|
@@ -110,6 +113,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
110
113
|
const variable = checkComponentVariable(decl.prop, file, options);
|
|
111
114
|
if (variable) report(file, variable.rule, variable.message, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
112
115
|
for (const ref of references(decl.value)) {
|
|
116
|
+
const owned = scopedTokenOwner(options, ref.name);
|
|
117
|
+
if (owned) {
|
|
118
|
+
if (scoped.inventory.owner(scoped.inventory.relative(path.relative(root, file))) !== owned.unit || !declaredTokens.has(ref.name)) report(file, "token-reference", `${ref.name} belongs to ${owned.unit}. Use shared tokens across owners; owner-local tokens must be defined and consumed by their owner.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
113
121
|
const local = /^(?:--ds-|--ux-|--showcase-)/.test(ref.name);
|
|
114
122
|
if (foundation && local) report(file, "foundation-role", "Foundation defaults consume shared tokens, not component, pattern or scenario-local variables.", offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
115
123
|
if (!local && !isSharedToken(ref.name)) report(file, "token-name", `${ref.name} does not follow ADS's fixed token naming contract.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
@@ -130,6 +138,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
130
138
|
});
|
|
131
139
|
}
|
|
132
140
|
for (const file of files) {
|
|
141
|
+
if (scopedFiles.has(file)) continue; // Closed definition-only contract checked by inspectTokens.
|
|
133
142
|
if (file.endsWith(".css") && isInside(path.join(dsRoot, config.tokenDir), file) && !isDevelopmentFile(file, options)) { checkCss(file, readFileSync(file, "utf8"), undefined, true); continue; }
|
|
134
143
|
if (file.endsWith(".html")) { inspectHtml(readFileSync(file, "utf8"), (rule, message, line) => report(file, rule, message, line)); continue; }
|
|
135
144
|
if (file.endsWith(".css")) {
|
|
@@ -223,6 +232,10 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
223
232
|
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifier = node.moduleSpecifier.text;
|
|
224
233
|
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) specifier = node.arguments[0].text;
|
|
225
234
|
if (specifier && importViolation(specifier, file, options, resolveImport)) nodeReport(node, "public-import", `Import through ${config.publicAlias}, not ADS implementation paths.`);
|
|
235
|
+
if (specifier) for (const target of resolveImport(specifier, file)) {
|
|
236
|
+
const tokenOwner = scoped.definitions.find(entry => path.resolve(root, entry.file) === target);
|
|
237
|
+
if (tokenOwner && scoped.inventory.owner(scoped.inventory.relative(path.relative(root, file))) !== tokenOwner.unit) nodeReport(node, "token-ownership", `Only ${tokenOwner.unit} imports its token sheet. Import the public component/pattern to consume its design.`);
|
|
238
|
+
}
|
|
226
239
|
if (specifier && resolveImport(specifier, file).some((target) => (specifier.startsWith(".") || existsSync(target)) && target.endsWith(".css") && isInside(root, target) && !isInside(dsRoot, target) && target !== path.join(sourceRoot, "app-mount.css") && !isInside(path.join(root, "node_modules"), target))) nodeReport(node, "style-ownership", "Imported project CSS belongs to ADS components, patterns, or the foundation. Only structural app-mount.css is allowed outside the ADS.");
|
|
227
240
|
if (specifier && appImportViolation(specifier, file, options, resolveImport)) nodeReport(node, "no-app-import", "ADS implementations and showcase fixtures must not import app code. Use public ADS APIs with local fixture data; keep application integration harnesses in application tests.");
|
|
228
241
|
if (specifier && showcaseImportViolation(specifier, file, options, resolveImport)) nodeReport(node, "showcase-import", "Showcase code and styles are development fixtures; runtime code must not import them.");
|
package/dist/config.mjs
CHANGED
|
@@ -152,10 +152,14 @@ export function isBehaviorFile(file) {
|
|
|
152
152
|
return /(?:^|[\\/])behavior\.json$|\.behavior\.json$/.test(file);
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
+
export function isTokenManifestFile(file) {
|
|
156
|
+
return /(?:^|[\\/])tokens\.json$|\.tokens\.json$/.test(file);
|
|
157
|
+
}
|
|
158
|
+
|
|
155
159
|
export function isDevelopmentFile(file, { dsRoot }) {
|
|
156
160
|
if (!isInside(dsRoot, file)) return isTestFile(file);
|
|
157
161
|
const relative = path.relative(dsRoot, file).replaceAll("\\", "/");
|
|
158
|
-
return isTestFile(file) || isScenarioFile(file) || isFixtureFile(file) || isBehaviorFile(file)
|
|
162
|
+
return isTestFile(file) || isScenarioFile(file) || isFixtureFile(file) || isBehaviorFile(file) || isTokenManifestFile(file)
|
|
159
163
|
|| /^(?:showcase|composition)\//.test(relative)
|
|
160
164
|
|| /(?:^|\/)(?:scenario|fixtures)(?:\/|$)/.test(relative)
|
|
161
165
|
|| /\.scenario(?:-adapter)?\.[cm]?[jt]sx?$/.test(relative);
|
|
@@ -170,7 +174,7 @@ export function sourceFiles(root) {
|
|
|
170
174
|
if (ignored.has(entry.name) || entry.isSymbolicLink()) continue;
|
|
171
175
|
const file = path.join(root, entry.name);
|
|
172
176
|
if (entry.isDirectory()) files.push(...sourceFiles(file));
|
|
173
|
-
else if (entry.isFile() && (/\.(css|html|[cm]?[jt]sx?)$/.test(entry.name) || isBehaviorFile(entry.name))) files.push(file);
|
|
177
|
+
else if (entry.isFile() && (/\.(css|html|[cm]?[jt]sx?)$/.test(entry.name) || isBehaviorFile(entry.name) || isTokenManifestFile(entry.name))) files.push(file);
|
|
174
178
|
}
|
|
175
179
|
return files.sort();
|
|
176
180
|
}
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { isInside, projectPath } from "../config.mjs";
|
|
6
6
|
import { readPreviewManifest } from "../preview-resources.mjs";
|
|
7
|
+
import { previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
7
8
|
|
|
8
9
|
export const BUILD_URI = "ads://project/build";
|
|
9
10
|
export const buildStatusFile = (root) => path.join(root, ".ds/build-status.json");
|
|
@@ -123,7 +124,8 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
|
|
|
123
124
|
}
|
|
124
125
|
|
|
125
126
|
/** Read durable build events; a running process alone never means a fresh build. */
|
|
126
|
-
export function inspectBuildStatus(root, config, { session, processState, file = buildStatusFile(root) } = {}) {
|
|
127
|
+
export function inspectBuildStatus(root, config, { session, previewSession, processState, file = buildStatusFile(root) } = {}) {
|
|
128
|
+
const options = withPreviewSession({ root, config: { mcp: config } }, previewSession);
|
|
127
129
|
let report;
|
|
128
130
|
let reportError;
|
|
129
131
|
try {
|
|
@@ -137,7 +139,7 @@ export function inspectBuildStatus(root, config, { session, processState, file =
|
|
|
137
139
|
let graphError;
|
|
138
140
|
if (config.previewManifest && report?.previews.some(entry => entry.state === "ready")) {
|
|
139
141
|
try {
|
|
140
|
-
if (!readPreviewManifest(
|
|
142
|
+
if (!readPreviewManifest(options, { verify: true })) throw new Error("Preview resource manifest is missing.");
|
|
141
143
|
} catch (error) { graphError = `Invalid preview resource graph: ${error.message}`; }
|
|
142
144
|
}
|
|
143
145
|
const previews = config.apps.map((app) => {
|
|
@@ -145,12 +147,13 @@ export function inspectBuildStatus(root, config, { session, processState, file =
|
|
|
145
147
|
let state = value?.state ?? "unreported";
|
|
146
148
|
let diagnostics = value?.diagnosticSet !== undefined ? report.diagnosticSets[value.diagnosticSet] : value?.diagnostics ?? [];
|
|
147
149
|
if (report?.diagnostics?.length) { state = "error"; diagnostics = [...report.diagnostics, ...diagnostics].slice(0, 20); }
|
|
148
|
-
const
|
|
150
|
+
const artifact = path.resolve(root, previewArtifactPath(options, app.file));
|
|
151
|
+
const available = existsSync(artifact);
|
|
149
152
|
if (reportError) { state = "error"; diagnostics = [{ message: reportError }]; }
|
|
150
153
|
if (graphError && app.id.includes("/")) { state = "error"; diagnostics = [{ message: graphError }]; }
|
|
151
154
|
if (state === "ready") {
|
|
152
155
|
try {
|
|
153
|
-
if (value.lastSuccessfulRevision !== value.revision || artifactDigest(
|
|
156
|
+
if (value.lastSuccessfulRevision !== value.revision || artifactDigest(artifact) !== value.artifactDigest) throw new Error("Preview output does not match its successful build. Rebuild before reviewing it.");
|
|
154
157
|
} catch (error) { state = "error"; diagnostics = [{ message: error.message }]; }
|
|
155
158
|
}
|
|
156
159
|
if (processState?.state === "failed") { state = "error"; diagnostics = [{ message: processState.error ?? "Preview watcher exited." }, ...diagnostics].slice(0, 20); }
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { projectGuideFiles } from "../project-documents.mjs";
|
|
|
5
5
|
|
|
6
6
|
export const GUIDE_URI = "ads://project/guide";
|
|
7
7
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
8
|
-
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
|
|
8
|
+
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 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 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
9
|
|
|
10
10
|
function manager(root, pkg) {
|
|
11
11
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
|
@@ -56,7 +56,7 @@ Use this server for UI components/patterns, tokens/themes/branding, layout, inte
|
|
|
56
56
|
3. Select one workflow with ads_skills, then ads_read_skill. ${route.skills.map((skill) => `${skill.task}: ${skill.name}`).join("; ")}. Native skill activation is host-controlled. Relative skill references resolve from its SKILL.md URI. Read support files only when relevant.
|
|
57
57
|
4. ${route.preview} Token samples: ads_scenarios(kind: tokens), then ads_show_scenario or ads_show_tokens(category: id). Token source inspection: ads_tokens with a focused query. Registered previews: ${previews.map((preview) => `${preview.id}: ${preview.tool ?? "ads_show_scenario"}`).join(", ") || "none"}. Showcase URL: ${context.showcase.url ?? "not configured; use the project's showcase command"}.
|
|
58
58
|
Inspection connects a public export to its owning source, available guides, token values and discovered preview IDs. Bounded tools keep discovery focused; explicit resource reads supply detail. Source metadata does not prove layout, interaction or motion. A scenario renders the real public implementation and its fixture context in either review surface.
|
|
59
|
-
5. Check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements
|
|
59
|
+
5. Check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements; a real selected-owner re-export can remove its redundant export {};. Dry-run to inspect validation; apply only a passing patch. Fix rejected patches in the owning unit; use ads_apply_transaction for coupled owners instead of bypassing rejection with direct writes. ads_prepare_patch creates a local owner draft/diff; ads_prepare_token_samples reconciles explicit project bindings without guessing visual meaning. Intentional project setup, registered guard/compiler code and exceptions use configuration; shared globals use foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Binary/large Git diffs may use patchFile under .ds/patches/ to avoid model-context bytes. In read-only mode, source edits use the client editor/filesystem tools. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
|
|
60
60
|
6. ${route.validation} Registered commands: ${context.commands.map((command) => command.args?.join(" ") ?? `choose the project package manager for ${command.script}`).join("; ") || "none discovered; inspect the project's build setup"}. Run them from ${context.projectRoot}.
|
|
61
61
|
7. After edits, inspect ads_status.build or ads://project/build explicitly. Running/unreported/old output is not a current successful preview. Fix diagnostics in owned source, wait for rebuilding and invoke the preview tool again. Notifications may not start an agent turn.
|
|
62
62
|
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { isInside } from "../config.mjs";
|
|
6
|
+
import { checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
|
|
7
|
+
import { textDiff } from "./text-diff.mjs";
|
|
8
|
+
|
|
9
|
+
const hash = value => createHash("sha256").update(value).digest("hex");
|
|
10
|
+
const binary = bytes => bytes?.includes(0) || bytes && !Buffer.from(bytes.toString("utf8")).equals(bytes);
|
|
11
|
+
function generated(options, relative) {
|
|
12
|
+
const target = path.join(options.root, ".ds", relative);
|
|
13
|
+
mkdirSync(path.dirname(target), {recursive:true});
|
|
14
|
+
if (realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error("Patch preparation output cannot resolve through symlinks.");
|
|
15
|
+
return target;
|
|
16
|
+
}
|
|
17
|
+
export function storePreparedPatch(options, patch) {
|
|
18
|
+
if (Buffer.byteLength(patch) > 16 * 1024 * 1024) throw new Error("Prepared Git patch exceeds 16 MiB.");
|
|
19
|
+
if (!patch) return {patch:null,patchFile:null};
|
|
20
|
+
const file = `.ds/patches/${randomUUID()}.patch`;
|
|
21
|
+
writeFileSync(generated(options,file.slice(4)),patch);
|
|
22
|
+
return {patchFile:file,bytes:Buffer.byteLength(patch)};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A temporary copy of just one owner and its declared companions, not a project mirror. */
|
|
26
|
+
export function prepareUnitPatch(options, {unit, action = "create", draft}) {
|
|
27
|
+
validateUnitId(unit);
|
|
28
|
+
const inventory = inspectUnits(options);
|
|
29
|
+
if (action === "create") {
|
|
30
|
+
const owner = inventory.units.find(entry => entry.id === unit);
|
|
31
|
+
const files = [...new Set([...(owner?.files ?? []), ...(owner?.companionFiles ?? []).map(entry => entry.path),
|
|
32
|
+
...(!owner ? ["ds.config.json"] : []),
|
|
33
|
+
...(/^(?:components|patterns|controllers)\//.test(unit) ? [path.relative(options.root,path.join(options.dsRoot,options.config.publicEntry)).replaceAll("\\","/")] : [])])];
|
|
34
|
+
if (!owner && !/^(?:components|patterns|controllers|composition)\/.+/.test(unit)) throw new Error("Discover an existing unit or choose a new unoccupied component/pattern/controller/composition owner.");
|
|
35
|
+
if (/^(?:components|patterns|controllers|composition)\//.test(unit)) for (let directory=unit;directory!==".";directory=path.posix.dirname(directory)) {
|
|
36
|
+
const marker=path.join(options.dsRoot,directory,".gitkeep");
|
|
37
|
+
if (existsSync(marker) && realpathSync(marker)===marker && lstatSync(marker).isFile() && lstatSync(marker).size===0) {
|
|
38
|
+
const relative=path.relative(options.root,marker).replaceAll("\\","/");
|
|
39
|
+
if (!files.includes(relative)) files.push(relative);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
draft = randomUUID();
|
|
43
|
+
const base = generated(options,`patch-drafts/${draft}/manifest.json`), folder = path.join(path.dirname(base),"work");
|
|
44
|
+
const entries = [];
|
|
45
|
+
let bytes = 0;
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
const absolute = path.resolve(options.root,file);
|
|
48
|
+
if (!isInside(options.root,absolute) || realpathSync(absolute) !== absolute || !lstatSync(absolute).isFile()) throw new Error("Draft inputs must be ordinary project source files.");
|
|
49
|
+
if (lstatSync(absolute).size > 16 * 1024 * 1024) throw new Error("Draft input exceeds 16 MiB.");
|
|
50
|
+
const content = readFileSync(absolute);
|
|
51
|
+
bytes += content.length;
|
|
52
|
+
if (entries.length >= 256 || bytes > 32 * 1024 * 1024) throw new Error("Owner draft exceeds 256 files/32 MiB. Prepare a targeted Git patch instead.");
|
|
53
|
+
for (const name of ["work","base"]) {
|
|
54
|
+
const target = path.join(path.dirname(base),name,file);
|
|
55
|
+
mkdirSync(path.dirname(target),{recursive:true}); writeFileSync(target,content);
|
|
56
|
+
}
|
|
57
|
+
entries.push({file,digest:hash(content)});
|
|
58
|
+
}
|
|
59
|
+
mkdirSync(folder,{recursive:true});
|
|
60
|
+
writeFileSync(base,JSON.stringify({schemaVersion:1,unit,entries}));
|
|
61
|
+
return {draft,unit,directory:folder,files, next:"Edit only this draft, then call ads_prepare_patch with action: diff and this draft ID. Live source is unchanged; the resulting Git patch still requires ads_apply_patch and all its gates."};
|
|
62
|
+
}
|
|
63
|
+
if (!/^[a-f0-9-]{36}$/.test(draft ?? "")) throw new Error("Use the draft ID returned by ads_prepare_patch.");
|
|
64
|
+
const base = path.join(options.root,".ds/patch-drafts",draft);
|
|
65
|
+
if (realpathSync(base) !== base) throw new Error("Draft paths cannot resolve through symlinks.");
|
|
66
|
+
const metadata = JSON.parse(readFileSync(path.join(base,"manifest.json"),"utf8"));
|
|
67
|
+
if (metadata.schemaVersion !== 1 || metadata.unit !== unit) throw new Error("Draft and selected unit do not match.");
|
|
68
|
+
if (action === "discard") {rmSync(base,{recursive:true});return {discarded:true,draft,unit};}
|
|
69
|
+
if (action !== "diff") throw new Error("Choose create, diff or discard.");
|
|
70
|
+
const files = new Set(metadata.entries.map(entry => entry.file));
|
|
71
|
+
function walk(directory) {
|
|
72
|
+
if (realpathSync(directory) !== directory) throw new Error("Draft directories cannot resolve through symlinks.");
|
|
73
|
+
for (const entry of readdirSync(directory,{withFileTypes:true})) {
|
|
74
|
+
const file = path.join(directory,entry.name);
|
|
75
|
+
if (entry.isDirectory()) walk(file);
|
|
76
|
+
else if (!entry.isFile() || lstatSync(file).nlink !== 1) throw new Error("Drafts contain ordinary unlinked source files only.");
|
|
77
|
+
else files.add(path.relative(path.join(base,"work"),file).replaceAll("\\","/"));
|
|
78
|
+
if (files.size > 256) throw new Error("Draft exceeds 256 files.");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
walk(path.join(base,"work"));
|
|
82
|
+
const changes = [];
|
|
83
|
+
let patch = "", bytes = 0;
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
if (!file || path.isAbsolute(file) || file.includes("\\") || file.split("/").some(part => !part || part === "." || part === ".." || part.startsWith(".") && part !== ".gitkeep" && !/^\.(?:oxlintrc|linariarc|babelrc)(?:\.json)?$/.test(part))) throw new Error("Drafts use ordinary project-relative source paths.");
|
|
86
|
+
const original = path.join(base,"base",file), next = path.join(base,"work",file), live = path.join(options.root,file);
|
|
87
|
+
const read = file => {
|
|
88
|
+
if (!existsSync(file)) return null;
|
|
89
|
+
const stat = lstatSync(file);
|
|
90
|
+
if (realpathSync(file) !== file || !stat.isFile() || stat.nlink !== 1 || stat.size > 16 * 1024 * 1024) throw new Error("Draft inputs must be ordinary unlinked files no larger than 16 MiB.");
|
|
91
|
+
return readFileSync(file);
|
|
92
|
+
};
|
|
93
|
+
const expected = metadata.entries.find(entry => entry.file === file)?.digest ?? null;
|
|
94
|
+
const left = read(original), right = read(next), source = read(live);
|
|
95
|
+
if ((left && hash(left)) !== expected || (source && hash(source)) !== expected) throw new Error(`Source/baseline changed for ${file}; create a fresh owner draft.`);
|
|
96
|
+
if (left !== null && right !== null && left.equals(right) || left === null && right === null) continue;
|
|
97
|
+
bytes += (left?.length ?? 0) + (right?.length ?? 0);
|
|
98
|
+
if (bytes > 32 * 1024 * 1024) throw new Error("Draft changes exceed 32 MiB.");
|
|
99
|
+
const change = {path:file,originalContent:left === null ? null : binary(left) ? left : left.toString(),content:right === null ? null : binary(right) ? right : right.toString()};
|
|
100
|
+
changes.push(change);
|
|
101
|
+
if (!binary(left) && !binary(right)) patch += textDiff(file,change.originalContent,change.content);
|
|
102
|
+
else {
|
|
103
|
+
let diff;
|
|
104
|
+
try { diff = execFileSync("git",["diff","--no-index","--binary","--no-ext-diff","--no-textconv","--",left === null ? "/dev/null" : original,right === null ? "/dev/null" : next],{encoding:"utf8",maxBuffer:16*1024*1024}); }
|
|
105
|
+
catch (error) { if (error.status !== 1) throw error; diff=error.stdout; }
|
|
106
|
+
patch += diff.replace(/^diff --git .+$/m,`diff --git a/${file} b/${file}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (changes.length) checkUnitFiles(options,unit,changes,inventory,true);
|
|
110
|
+
return {unit,draft,changes:changes.map(entry=>entry.path),...storePreparedPatch(options,patch),next:"Apply with ads_apply_patch using this unit and patchFile. Preparation is not validation or publication."};
|
|
111
|
+
}
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import { projectContext } from "./context.mjs";
|
|
|
13
13
|
import { applyFilePatch, parseUnifiedPatch } from "./patch.mjs";
|
|
14
14
|
import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
|
|
15
15
|
|
|
16
|
-
export const mutationLimits = { files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 20000, snapshotBytes: 128 * 1024 * 1024 };
|
|
16
|
+
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 };
|
|
17
17
|
const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
18
18
|
const ignored = new Set([".git", ".ds", "node_modules", ".vite", "coverage", ".playwright-cli", "test-results", "output"]);
|
|
19
19
|
const textFile = file => /\.(?:[cm]?[jt]sx?|css|html|jsonc?|md|txt|svg)$/.test(file);
|
|
@@ -29,7 +29,7 @@ function address(options, file) {
|
|
|
29
29
|
if (!isInside(options.root, target) || target === options.root) throw fail("mutation-path", "Mutation paths must stay inside the project.", file);
|
|
30
30
|
for (let current = options.root; ; ) {
|
|
31
31
|
const relative = path.relative(current, target).split(path.sep);
|
|
32
|
-
if (relative.some(part => ignored.has(part) || part.startsWith(".") && !setupDotfile(part))) throw fail("mutation-path", "Hidden, dependency and generated paths are not editable.", file);
|
|
32
|
+
if (relative.some(part => ignored.has(part) || part.startsWith(".") && !setupDotfile(part) && !(part === ".gitkeep" && path.basename(target) === part && isInside(options.dsRoot, target)))) throw fail("mutation-path", "Hidden, dependency and generated paths are not editable.", file);
|
|
33
33
|
current = path.join(current, relative[0]);
|
|
34
34
|
const stat = lstatSync(current, { throwIfNoEntry: false });
|
|
35
35
|
if (stat?.isSymbolicLink() || stat && current !== target && !stat.isDirectory() || stat && current === target && (!stat.isFile() || stat.nlink !== 1)) throw fail("mutation-path", "Mutation paths must contain ordinary directories and unlinked regular files.", file);
|
|
@@ -154,7 +154,7 @@ export function createMutationController(directory) {
|
|
|
154
154
|
let commands = [], diagnostics = [];
|
|
155
155
|
try { commands = checks(options).map(check => [check.command, ...check.args].join(" ")); }
|
|
156
156
|
catch (error) { diagnostics = [error.diagnostic ?? { rule: "mutation-check", message: error.message }]; }
|
|
157
|
-
return { enabled: true, scope: "one-ds-unit", format: "git-unified-diff", dsDir: options.config.dsDir, limits: mutationLimits, checks: ["ads check", "registered Oxlint rules", ...commands], diagnostics, busy, lastResult };
|
|
157
|
+
return { enabled: true, scope: "one-ds-unit", format: "git-unified-diff", transactions:{tool:"ads_apply_transaction",maxUnits:mutationLimits.units,finalCandidateChecks:true}, preparation:{owner:"ads_prepare_patch",tokenSamples:"ads_prepare_token_samples"}, dsDir: options.config.dsDir, limits: mutationLimits, checks: ["ads check", "registered Oxlint rules", ...commands], diagnostics, busy, lastResult };
|
|
158
158
|
},
|
|
159
159
|
cancel() { active?.abort(); },
|
|
160
160
|
units() { return inspectUnits(loadConfig(root)).units; },
|
|
@@ -170,7 +170,7 @@ export function createMutationController(directory) {
|
|
|
170
170
|
return { ...source, unit, content, offset, nextOffset: end < source.content.length ? end : null, totalChars: source.content.length,
|
|
171
171
|
startLine: source.content.slice(0, offset).split("\n").length };
|
|
172
172
|
},
|
|
173
|
-
async apply({ unit, patch, patchFile, dryRun = false }, signal) {
|
|
173
|
+
async apply({ unit, patch, patchFile, patches, dryRun = false }, signal) {
|
|
174
174
|
if (busy) return { ok: false, applied: false, diagnostics: [{ rule: "mutation-busy", message: "Another mutation is validating; retry after it finishes." }] };
|
|
175
175
|
busy = true;
|
|
176
176
|
active = new AbortController();
|
|
@@ -179,26 +179,22 @@ export function createMutationController(directory) {
|
|
|
179
179
|
const verified = [];
|
|
180
180
|
try {
|
|
181
181
|
const options = loadConfig(root);
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
if (
|
|
193
|
-
|
|
194
|
-
if (entry.binary) change.binaryPatch = entry.patch;
|
|
195
|
-
change.expectedDigest = before.digest;
|
|
196
|
-
change.originalContent = before.content;
|
|
197
|
-
if (!entry.binary) validateContent(change, unit);
|
|
198
|
-
changes.push(change);
|
|
199
|
-
return { ...before, mode: before.exists ? lstatSync(target).mode : undefined };
|
|
182
|
+
if (patches !== undefined && (unit !== undefined || patch !== undefined || patchFile !== undefined || !Array.isArray(patches) || patches.length < 2 || patches.length > mutationLimits.units)) throw fail("mutation-batch", "A transaction requires 2–8 distinct owner patches, without a top-level unit/patch.");
|
|
183
|
+
const groups = patches ?? [{unit,patch,patchFile}];
|
|
184
|
+
if (new Set(groups.map(group => group.unit)).size !== groups.length) throw fail("mutation-batch", "Use one patch per distinct unit in a transaction.");
|
|
185
|
+
let patchBytes = 0;
|
|
186
|
+
const plans = groups.map(group => {
|
|
187
|
+
validateUnitId(group.unit);
|
|
188
|
+
if ((typeof group.patch === "string") === (typeof group.patchFile === "string")) throw fail("mutation-patch", "Provide exactly one of patch or patchFile for each owner.");
|
|
189
|
+
const value = group.patchFile === undefined ? group.patch : readPatchFile(options,group.patchFile);
|
|
190
|
+
const maxPatch = group.patchFile === undefined ? mutationLimits.patchBytes : mutationLimits.patchFileBytes;
|
|
191
|
+
patchBytes += Buffer.byteLength(value ?? "");
|
|
192
|
+
if (typeof value !== "string" || value.includes("\0") || Buffer.from(value).toString("utf8") !== value || Buffer.byteLength(value) > maxPatch || patchBytes > mutationLimits.patchFileBytes) throw fail("mutation-patch", "Patch exceeds its UTF-8 Git diff size limit.");
|
|
193
|
+
return {unit:group.unit,entries:parseUnifiedPatch(value,mutationLimits.files)};
|
|
200
194
|
});
|
|
201
|
-
const
|
|
195
|
+
const units = groups.map(group => group.unit), configuration = units.includes("configuration"), assets = units.some(unit => unit.startsWith("assets"));
|
|
196
|
+
for (const plan of plans) for (const entry of plan.entries) address(options,entry.path);
|
|
197
|
+
const changes = [], originals = [], byPath = new Map();
|
|
202
198
|
const cache = path.join(root, ".ds");
|
|
203
199
|
mkdirSync(cache, { recursive: true });
|
|
204
200
|
if (realpathSync(cache) !== path.join(realpathSync(root), ".ds")) throw fail("mutation-path", "The .ds directory cannot resolve through a symlink.");
|
|
@@ -206,7 +202,6 @@ export function createMutationController(directory) {
|
|
|
206
202
|
const candidate = path.join(temporary, "project");
|
|
207
203
|
mkdirSync(candidate);
|
|
208
204
|
const before = snapshot(options, candidate);
|
|
209
|
-
for (const original of originals) if (read(options, original.path).digest !== original.digest) throw fail("mutation-conflict", "Source changed while preparing the validation copy. Read the affected range and regenerate the patch.", original.path);
|
|
210
205
|
const dependencies = path.join(root, "node_modules");
|
|
211
206
|
if (!existsSync(dependencies)) throw fail("mutation-check", "Install project dependencies before using guarded mutations.");
|
|
212
207
|
symlinkSync(realpathSync(dependencies), path.join(candidate, "node_modules"), process.platform === "win32" ? "junction" : "dir");
|
|
@@ -222,24 +217,45 @@ export function createMutationController(directory) {
|
|
|
222
217
|
return true;
|
|
223
218
|
} });
|
|
224
219
|
}
|
|
220
|
+
const entries = plans.flatMap(plan => plan.entries);
|
|
225
221
|
if (entries.some(entry => entry.binary)) {
|
|
226
222
|
const formats = new Set(entries.filter(entry=>entry.binary).map(entry=>entry.objectFormat));
|
|
227
223
|
if (formats.size !== 1) throw fail("mutation-patch", "Binary blocks in one Git diff must use the same object format.");
|
|
228
224
|
await checkCommand("git", ["init", "--quiet", `--object-format=${[...formats][0]}`, candidate], root, signal);
|
|
229
225
|
}
|
|
230
|
-
for (const
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
change.content
|
|
236
|
-
validateContent(change,
|
|
226
|
+
for (const plan of plans) {
|
|
227
|
+
const current = loadConfig(candidate), selected = plan.entries.map(entry => {
|
|
228
|
+
address(options,entry.path);
|
|
229
|
+
const before = read(current,entry.path);
|
|
230
|
+
if (!entry.binary && before.binary) throw fail("mutation-patch", "Binary assets require a git diff --binary patch.", entry.path);
|
|
231
|
+
const change = {path:entry.path, originalContent:before.content, content:entry.binary ? entry.operation === "delete" ? null : before.content ?? Buffer.alloc(0) : applyFilePatch(entry,before.content), ...(entry.binary ? {binaryPatch:entry.patch} : {})};
|
|
232
|
+
if (!entry.binary) validateContent(change,plan.unit);
|
|
233
|
+
if (!byPath.has(entry.path)) {
|
|
234
|
+
const original = read(options,entry.path);
|
|
235
|
+
// The candidate copy and live inputs must agree before any changes.
|
|
236
|
+
if (original.digest !== before.digest) throw fail("mutation-conflict", "Source changed while preparing validation; regenerate the patch.", entry.path);
|
|
237
|
+
originals.push({...original,mode:original.exists ? lstatSync(address(options,entry.path)).mode : undefined});
|
|
238
|
+
byPath.set(entry.path,changes.length);
|
|
239
|
+
changes.push({...change,expectedDigest:original.digest});
|
|
240
|
+
if (changes.length > mutationLimits.files) throw fail("mutation-batch", "A transaction may change at most 32 distinct files.");
|
|
241
|
+
}
|
|
242
|
+
return change;
|
|
243
|
+
});
|
|
244
|
+
const inventory = checkUnitFiles(current,plan.unit,selected,inspectUnits(current),true);
|
|
245
|
+
for (const change of selected) {
|
|
246
|
+
const file = path.join(candidate,change.path);
|
|
247
|
+
if (change.binaryPatch) {
|
|
248
|
+
for (const match of change.binaryPatch.matchAll(/^(?:literal|delta) (\d+)$/gm)) if (Number(match[1]) > mutationLimits.fileBytes) throw fail("mutation-content", "Binary patch blocks exceed 16 MiB.", change.path);
|
|
249
|
+
await checkCommand("git",["apply","--binary","--whitespace=nowarn","-"],candidate,signal,change.binaryPatch);
|
|
250
|
+
change.content = existsSync(file) ? readFileSync(file) : null;
|
|
251
|
+
validateContent(change,plan.unit);
|
|
252
|
+
} else if (change.content === null) rmSync(file);
|
|
253
|
+
else {mkdirSync(path.dirname(file),{recursive:true});writeFileSync(file,change.content);}
|
|
254
|
+
changes[byPath.get(change.path)].content = change.content;
|
|
237
255
|
}
|
|
238
|
-
|
|
239
|
-
else { mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, change.content); }
|
|
256
|
+
checkUnitCandidate(loadConfig(candidate),plan.unit,selected,inventory);
|
|
240
257
|
}
|
|
241
258
|
const candidateOptions = loadConfig(candidate);
|
|
242
|
-
checkUnitCandidate(candidateOptions, unit, changes, inventory);
|
|
243
259
|
const extraChecks = checks(candidateOptions);
|
|
244
260
|
const expected = snapshot(candidateOptions);
|
|
245
261
|
const result = checkProject(candidate, { trackingRoot: root });
|
|
@@ -251,12 +267,12 @@ export function createMutationController(directory) {
|
|
|
251
267
|
const bin = JSON.parse(readFileSync(oxlintPackage, "utf8")).bin;
|
|
252
268
|
const executable = path.resolve(path.dirname(oxlintPackage), typeof bin === "string" ? bin : bin.oxlint);
|
|
253
269
|
const lintPaths = [candidateOptions.config.sourceDir, candidateOptions.config.dsDir].filter(file => existsSync(path.join(candidate, file)));
|
|
254
|
-
if (
|
|
270
|
+
if (configuration) for (const file of inspectUnits(candidateOptions).units.find(item => item.id === "configuration").files) {
|
|
255
271
|
if (/\.[cm]?[jt]sx?$/.test(file) && !lintPaths.some(directory => isInside(path.resolve(candidate, directory), path.resolve(candidate, file)))) lintPaths.push(file);
|
|
256
272
|
}
|
|
257
273
|
await checkCommand(process.execPath, [executable, "--deny-warnings", "--config", lintConfig, ...lintPaths], candidate, signal);
|
|
258
274
|
verified.push({ name: "registered Oxlint rules", passed: true });
|
|
259
|
-
if (
|
|
275
|
+
if (assets || configuration) {
|
|
260
276
|
const brand = await generateBrandAssets(candidate);
|
|
261
277
|
verified.push({ name: "brand assets", passed: true, skipped: !!brand.skipped });
|
|
262
278
|
}
|
|
@@ -300,8 +316,8 @@ export function createMutationController(directory) {
|
|
|
300
316
|
}
|
|
301
317
|
}
|
|
302
318
|
const warnings = [];
|
|
303
|
-
if (!dryRun && (
|
|
304
|
-
return lastResult = { ok: 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.slice(0, 50), advisoryCount: result.advisories.length } : {}), ...(warnings.length ? { warnings } : {}),
|
|
319
|
+
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}` }); } }
|
|
320
|
+
return lastResult = { 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.slice(0, 50), advisoryCount: result.advisories.length } : {}), ...(warnings.length ? { warnings } : {}),
|
|
305
321
|
preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." };
|
|
306
322
|
} catch (error) {
|
|
307
323
|
return lastResult = { ok: false, applied: false, diagnostics: [error.diagnostic ?? { rule: "mutation-error", message: error.message }], checks: verified };
|
|
@@ -4,6 +4,7 @@ import { statSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync }
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
|
|
7
|
+
import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
|
|
7
8
|
|
|
8
9
|
function stamp(file) {
|
|
9
10
|
try { const stat = statSync(file); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`; }
|
|
@@ -160,23 +161,27 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
160
161
|
}
|
|
161
162
|
|
|
162
163
|
const status = () => ({ state, ...(stalled ? { stalled: true } : {}), ...(child?.pid ? { pid: child.pid } : {}), ...(ownerGuard?.pid ? { guardPid: ownerGuard.pid } : {}), ...(error ? { error } : {}) });
|
|
163
|
-
const
|
|
164
|
+
const resourceSession = () => command && config.previewManifest ? session : undefined;
|
|
165
|
+
const buildStatus = () => inspectBuildStatus(root, config, command ? { session, previewSession: resourceSession(), file: reportFile, processState: status() } : {});
|
|
166
|
+
function clearOutput() {
|
|
167
|
+
for (const directory of previewSessionDirectories(withPreviewSession({ root, config: { mcp: config } }, resourceSession()))) rmSync(directory, { recursive: true, force: true });
|
|
168
|
+
}
|
|
164
169
|
|
|
165
170
|
async function stopChild() {
|
|
166
171
|
rmSync(requestFile, { force: true });
|
|
167
172
|
if (stopping) return stopping;
|
|
168
|
-
if (!child || childClosed) { if (command) state = "stopped"; rmSync(reportFile, { force: true }); return; }
|
|
173
|
+
if (!child || childClosed) { if (command) state = "stopped"; rmSync(reportFile, { force: true }); clearOutput(); return; }
|
|
169
174
|
if (state === "stopped") return;
|
|
170
175
|
state = "stopping";
|
|
171
176
|
stopping = (async () => {
|
|
172
177
|
kill("SIGTERM");
|
|
173
178
|
clearTimeout(killTimer);
|
|
174
179
|
const timer = setTimeout(() => kill("SIGKILL"), 1500);
|
|
175
|
-
try { await closed; } finally { clearTimeout(timer); rmSync(reportFile, { force: true }); }
|
|
180
|
+
try { await closed; } finally { clearTimeout(timer); rmSync(reportFile, { force: true }); clearOutput(); }
|
|
176
181
|
})();
|
|
177
182
|
return stopping;
|
|
178
183
|
}
|
|
179
|
-
return { start, ensure, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, buildStatus, setApps(apps) {
|
|
184
|
+
return { start, ensure, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
|
|
180
185
|
for (const app of apps) {
|
|
181
186
|
const file = path.resolve(root, app.file);
|
|
182
187
|
if (!baselines.has(file)) baselines.set(file, stamp(file));
|
|
@@ -195,6 +200,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
195
200
|
start() { if (!stopped && !replacing) current.start(); },
|
|
196
201
|
async ensure(file, signal) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal); },
|
|
197
202
|
status() { return replacing ? { state: "reconfiguring" } : current.status(); },
|
|
203
|
+
resourceSession() { return current.resourceSession(); },
|
|
198
204
|
buildStatus() { return current.buildStatus(); },
|
|
199
205
|
setApps(next) { apps = next; current.setApps(next); },
|
|
200
206
|
kill() { current.kill(); },
|