@reqvire-org/ads 0.3.35 → 0.3.37
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 +10 -8
- package/dist/bootstrap-ds/README.md +8 -9
- package/dist/bootstrap-ds/ds.config.json +1 -8
- package/dist/bootstrap-ds/package.json +4 -3
- package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/bun-compiler.mjs +13 -0
- package/dist/bun-worker.mjs +9 -0
- package/dist/check.mjs +7 -4
- package/dist/cli.mjs +11 -7
- package/dist/config.mjs +22 -4
- package/dist/development-runtime.mjs +3 -1
- package/dist/init.mjs +16 -18
- package/dist/mcp/build-status.mjs +6 -4
- package/dist/mcp/context.mjs +9 -4
- package/dist/mcp/drafts.mjs +9 -4
- package/dist/mcp/mutation-limits.mjs +2 -0
- package/dist/mcp/mutations.mjs +8 -17
- package/dist/mcp/patch.mjs +5 -3
- package/dist/mcp/preview-watch.mjs +21 -9
- package/dist/mcp/preview-widget.bundle.js +58 -63
- package/dist/mcp/preview-work.mjs +1 -15
- package/dist/mcp/project-widget.bundle.js +57 -62
- package/dist/mcp/prompts.mjs +2 -2
- package/dist/mcp/resource-loader.js +32 -10
- package/dist/mcp/server.mjs +90 -35
- package/dist/mcp/widget.bundle.js +59 -64
- package/dist/preview-builder.mjs +17 -5
- package/dist/preview-bun.mjs +266 -0
- package/dist/preview-imports.mjs +73 -0
- package/dist/preview-resources.mjs +26 -14
- package/dist/scenario-inspector.mjs +11 -4
- package/dist/scenarios-compiler.mjs +47 -6
- package/dist/showcase/client.bundle.js +68 -72
- package/dist/showcase/index.html +2 -2
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/showcase/style.css +4 -0
- package/dist/skills/ads-break-ui/SKILL.md +39 -40
- package/dist/skills/ads-break-ui/references/drafts.md +12 -3
- package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -5
- package/dist/skills/ads-break-ui/references/runtimes.md +91 -140
- package/dist/skills/ads-break-ui/references/validation.md +13 -3
- package/dist/skills/ads-break-ui/references/workflows.md +82 -0
- package/dist/skills/ads-designer/SKILL.md +38 -39
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
- package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
- package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/skills/ads-designer/references/cli.md +24 -20
- package/dist/skills/ads-designer/references/drafts.md +12 -3
- package/dist/skills/ads-designer/references/guarded-editing.md +6 -5
- package/dist/skills/ads-designer/references/runtimes.md +91 -140
- package/dist/skills/ads-designer/references/validation.md +13 -3
- package/dist/skills/ads-designer/references/workflows.md +82 -0
- package/dist/skills/ads-import/SKILL.md +40 -42
- package/dist/skills/ads-import/references/cli.md +24 -20
- package/dist/skills/ads-import/references/drafts.md +12 -3
- package/dist/skills/ads-import/references/guarded-editing.md +6 -5
- package/dist/skills/ads-import/references/runtimes.md +91 -140
- package/dist/skills/ads-import/references/validation.md +13 -3
- package/dist/skills/ads-import/references/workflows.md +82 -0
- package/dist/skills/ads-motion/SKILL.md +37 -38
- package/dist/skills/ads-motion/references/drafts.md +12 -3
- package/dist/skills/ads-motion/references/guarded-editing.md +6 -5
- package/dist/skills/ads-motion/references/runtimes.md +91 -140
- package/dist/skills/ads-motion/references/validation.md +13 -3
- package/dist/skills/ads-motion/references/workflows.md +82 -0
- package/dist/skills/ads-port/SKILL.md +37 -38
- package/dist/skills/ads-port/references/cli.md +24 -20
- package/dist/skills/ads-port/references/drafts.md +12 -3
- package/dist/skills/ads-port/references/guarded-editing.md +6 -5
- package/dist/skills/ads-port/references/runtimes.md +91 -140
- package/dist/skills/ads-port/references/validation.md +13 -3
- package/dist/skills/ads-port/references/workflows.md +82 -0
- package/dist/usage.mjs +84 -0
- package/dist/validation.mjs +0 -12
- package/dist/verification/browser.mjs +77 -48
- package/docs/ADS.md +17 -11
- package/docs/ARCHITECTURE.md +43 -29
- package/docs/BEHAVIORS.md +3 -3
- package/docs/CHANGELOG.md +67 -12
- package/docs/GUIDE.md +96 -53
- package/docs/MCP.md +97 -123
- package/docs/benchmarks/bun-previews.md +91 -0
- package/docs/benchmarks/gidi-preview-memory.md +4 -0
- package/package.json +15 -13
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.
|
|
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. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. 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];
|
|
@@ -35,6 +35,9 @@ export function projectContext(options) {
|
|
|
35
35
|
|
|
36
36
|
export function workflow(previews) {
|
|
37
37
|
return { guideUri: GUIDE_URI,
|
|
38
|
+
editing: {guideUri:"ads://guides/workflows",
|
|
39
|
+
direct:"Edit owned project files with the authorized editor/filesystem. Use MCP for preview, inspection and checks; ordinary source edits do not require drafts or ads_accept. Compiler ownership is independent: managed by default, externally published resources with mcp.previewWatch:false.",
|
|
40
|
+
mcpOnly:"Use enabled MCP source/draft mutation tools, rendered review and exact-revision acceptance. Without mutation tools or another source channel, editing is unavailable. mutations.enabled reports capability, not a mandatory editing route."},
|
|
38
41
|
next: "Find the requested public UI with ads_catalog (query + kind + small limit), then read its source/guide and one selected ADS skill. For a broad UI request, inspect the public barrel and targeted application entry files in sourceRoot.",
|
|
39
42
|
skills: [
|
|
40
43
|
{ task: "Build, refine or debug UI using the project ADS", name: "ads-designer" },
|
|
@@ -43,7 +46,7 @@ export function workflow(previews) {
|
|
|
43
46
|
{ task: "Implement or review motion", name: "ads-motion" },
|
|
44
47
|
{ task: "Stress-test layout, states and interactions", name: "ads-break-ui" },
|
|
45
48
|
],
|
|
46
|
-
preview: previews.length ? "Use ads_scenarios to select an exact path-derived id, then ads_show_scenario. Public UI and related parts share addressable scenarios; composition/ holds larger scenarios. Showcase and MCP mount the same source with colocated fixtures. The showcase is the tool's minimal MCP client and Apps host; it discovers these entries and invokes the same preview tools. Both transports share the managed
|
|
49
|
+
preview: previews.length ? "Use ads_scenarios to select an exact path-derived id, then ads_show_scenario. Public UI and related parts share addressable scenarios; composition/ holds larger scenarios. Showcase and MCP mount the same source with colocated fixtures. The showcase is the tool's minimal MCP client and Apps host; it discovers these entries and invokes the same preview tools. Both transports share the published preview graph and the managed compiler when enabled. A reusable sandboxed App loads selected modules and shared runtime/CSS/fonts through MCP resources; no project code or styling belongs in the outer host. Check build freshness after changes."
|
|
47
50
|
: "No component scenarios or legacy Apps are registered. Token inspection is available in the built-in showcase. Existing components need colocated independently mountable scenarios/fixtures and a project compiler before MCP can render them. Do not create a replica or separate browser app to get a preview.",
|
|
48
51
|
validation: "Use ads_check for core architecture diagnostics, then run the project's registered lint/typecheck/build and relevant tests from projectRoot. Core checks do not replace those commands. Review real UI in both themes; HTML delivery and compilation do not prove visual/behavioral correctness." };
|
|
49
52
|
}
|
|
@@ -59,7 +62,9 @@ Use this server for UI components/patterns, tokens/themes/branding, layout, inte
|
|
|
59
62
|
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.
|
|
60
63
|
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"}.
|
|
61
64
|
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.
|
|
62
|
-
5.
|
|
65
|
+
5. Choose an editing route using ads://guides/workflows and the user's instructions. With direct design-system code access, edit owned files in the normal editor and use MCP for discovery, preview, captures and checks. Ordinary source edits do not require drafts or ads_accept, even if mutations are enabled. The default managed compiler rebuilds them automatically. For an external builder, mcp.previewWatch:false disables MCP-started compilation; the editor/builder must publish the ADS resource graph and build evidence (for example with ads compile .). Existing views can stay visible while changed-source evidence is stale, until verified updated output is published.
|
|
66
|
+
With MCP-only access and enabled mutation tools, read ads://guides/drafts. Discover owners with ads_units, create a coherent proposal with ads_create_draft, read/edit marked source through ads_read_file/ads_update_draft, inspect ads_show_draft in the browser, then ads_accept with its exact reviewed revision. Direct editors can choose this isolated workflow too. Complete tracked changes by accepting required drafts; accept dependencies first and review dependents again. Retain a proposal only when requested. No extra human approval step is implied. Without an editor or mutation tools, source editing is unavailable.
|
|
67
|
+
For MCP-only focused repairs/migrations, use ads_units and guarded ads_apply_patch({unit,patch,dryRun}); include the owner's scenarios, fixtures and required public re-exports while preserving unrelated source. Use ads_apply_transaction for coupled owners. Token/runtime companionFiles allow only required foundation imports or selected-owner style-boundary changes. ads_prepare_patch stages an owner diff; ads_prepare_token_samples reconciles explicit bindings. Configuration/guard/compiler changes use configuration, shared globals foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Never bypass rejected patches or acceptance by switching to direct writes. Binary/large patches can use patchFile under .ds/patches/. 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/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Shared foundation Data is the only design-value catalogue. Components/patterns map shared roles; independent owner token namespaces and value sheets are rejected. Existing project font, text and spacing roles take precedence over divergent upstream constants. Read ads://guides/tokens for the source contract and overlap review. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
|
|
63
68
|
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}.
|
|
64
69
|
Execution replies from ads_verify and guarded edits contain counts, acceptance and resultId, not full reports. Read only needed outcomes/diagnostics/captures with ads_results, following nextCursor with identical filters. A truncated row has recordIndex for bounded text ranges. For one failure, use ads_investigate with its unit/check/runId; read request/error/artifact sections only when needed. Only the latest verification and mutation results, and latest investigation per check, are available. Notifications do not establish freshness.
|
|
65
70
|
|
|
@@ -69,6 +74,6 @@ Project guide resources: ${context.guides.map((guide) => `${guide.file}: ${guide
|
|
|
69
74
|
|
|
70
75
|
Development runtime: ${context.runtime.name} ${context.runtime.version}. Executable: ${context.runtime.executable}. Bin directory: ${context.runtime.binDir}. ${context.runtime.shellHint}
|
|
71
76
|
|
|
72
|
-
If the client exposes resources but no ADS tools, this guide and the project status/public-barrel/guide resources provide the entry path.
|
|
77
|
+
If the client exposes resources but no ADS tools, this guide and the project status/public-barrel/guide resources provide the entry path. Direct editors can use the returned local paths for scoped source inspection and project commands; MCP-only clients must not assume those server-local paths are accessible. Do not claim a resource-only connection offers ADS tool calls, native Skills activation or a rendered App. Configure/enable the tools in the client when required; project edits require a separate authorized editor/filesystem channel or enabled mutation tools.
|
|
73
78
|
`;
|
|
74
79
|
}
|
package/dist/mcp/drafts.mjs
CHANGED
|
@@ -12,13 +12,15 @@ import { mergeDraftExports, isDraftExportEntry } from "./draft-exports.mjs";
|
|
|
12
12
|
import { inspectTokens } from "../tokens.mjs";
|
|
13
13
|
import { previewFileIgnored, previewWatchDirectories } from "../preview-files.mjs";
|
|
14
14
|
import { createDraftDiscovery } from "./draft-discovery.mjs";
|
|
15
|
+
import { mutationLimits } from "./mutation-limits.mjs";
|
|
15
16
|
|
|
16
17
|
export const DRAFTS_URI = "ads://project/drafts";
|
|
17
18
|
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
18
19
|
const idSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/);
|
|
19
20
|
const relative = z.string().min(1).max(500).refine(value => !path.isAbsolute(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").some(part => !part || part === "." || part === ".."), "Use a canonical project-relative path.");
|
|
20
21
|
const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), unit: z.string().max(256) }).strict();
|
|
21
|
-
const
|
|
22
|
+
const draftUnits = z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units).refine(values=>new Set(values).size===values.length,"Draft owners must be unique.");
|
|
23
|
+
const manifestSchema = z.object({ schemaVersion: z.literal(1), id: idSchema, title: z.string().min(1).max(160), units: draftUnits, dependencies: z.array(idSchema).max(8).refine(values=>new Set(values).size===values.length,"Draft dependencies must be unique.").default([]), tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([]), files: z.array(fileSchema).max(mutationLimits.files) }).strict();
|
|
22
24
|
export const draftIdSchema = idSchema;
|
|
23
25
|
export const draftRevisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
24
26
|
|
|
@@ -154,6 +156,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
154
156
|
}
|
|
155
157
|
function create({ units, title, id = randomUUID(), dependencies = [], tokenGroups: selectedGroups = [] }) {
|
|
156
158
|
if (closed) throw new Error("Draft controller is closed.");
|
|
159
|
+
units = draftUnits.parse(units);
|
|
157
160
|
idSchema.parse(id);
|
|
158
161
|
if (existsSync(manifestFile(id))) throw new Error("Draft already exists.");
|
|
159
162
|
const options = loadConfig(root), inventory = inspectUnits(options), files = new Map();
|
|
@@ -174,7 +177,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
174
177
|
files.set(target, { target, source, baseline: hash(content), unit });
|
|
175
178
|
}
|
|
176
179
|
}
|
|
177
|
-
const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", "), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
|
|
180
|
+
const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", ").slice(0,160), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
|
|
178
181
|
for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);}
|
|
179
182
|
for (const file of manifest.files) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
|
|
180
183
|
save(manifest);
|
|
@@ -264,7 +267,8 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
264
267
|
session.watchFiles=[...watched];session.observed=watchStamp(session)+draftStamp();
|
|
265
268
|
return { ...value, session };
|
|
266
269
|
}
|
|
267
|
-
async function show({ id, scenario }) {
|
|
270
|
+
async function show({ id, scenario }, signal) {
|
|
271
|
+
if (signal?.aborted) throw new Error("Draft preview request cancelled.");
|
|
268
272
|
if (closed) throw new Error("Draft controller is closed.");
|
|
269
273
|
if(!previews.has(id)&&[...previews.values()].filter(session=>session.starting).length>=4){const oldest=[...previews].find(([,session])=>session.starting);if(oldest)await retire(oldest[0]);}
|
|
270
274
|
const value = prepare(id), { session } = value;
|
|
@@ -283,11 +287,12 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
283
287
|
session.selected = selected;
|
|
284
288
|
if (scenario && !registry.scenarios.some(item => item.id === scenario)) throw new Error("Unknown draft scenario. Read ads_show_draft without scenario to discover it.");
|
|
285
289
|
await startSession(id, session);
|
|
290
|
+
if (signal?.aborted) throw new Error("Draft preview request cancelled.");
|
|
286
291
|
if (metadata.revision === value.revision) session.runtime.primeRegistry?.(registry);
|
|
287
292
|
const url = new URL(session.runtime.url); if (selected) url.searchParams.set("scenario", selected);
|
|
288
293
|
const accepted = await discovery.current(root, session.projectRevision);
|
|
289
294
|
const acceptedExists = accepted.scenarios.some(item => item.id === selected);
|
|
290
|
-
const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"}):undefined;
|
|
295
|
+
const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"},signal):undefined;
|
|
291
296
|
if (session.runtime.buildStatus) recordBuild(id, session, session.runtime.buildStatus());
|
|
292
297
|
return { ...summary(value), scenario: selected, scenarios, diagnostics: registry.diagnostics, discovery: discovery.status(metadata, metadataRevision), build: previewResult?.structuredContent?.build ?? previewStatus(id), showcaseUrl: url.href, acceptedExists, previewOnly: true, previewResult,draftScope:`ads://drafts/${id}/resource?uri=`, next: "Inspect the actual rendered draft and its build freshness. Catalogue metadata may refresh in the background. Subscribe to ads://project/build and ads://project/drafts for updates. Reopen after edits; accept only the revision you reviewed. Full acceptance checks have not run." };
|
|
293
298
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Shared budgets for tracked drafts and guarded publication. */
|
|
2
|
+
export const mutationLimits = Object.freeze({ units: 64, files: 256, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 100000, snapshotBytes: 2 * 1024 * 1024 * 1024 });
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { createRequire } from "node:module";
|
|
3
2
|
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
4
3
|
import path from "node:path";
|
|
5
4
|
import ts from "typescript";
|
|
6
5
|
import { isInside, loadConfig } from "../config.mjs";
|
|
7
6
|
import { affectedBehaviorUnits, createVerificationController } from "../verification.mjs";
|
|
8
|
-
import { generateLintConfig } from "../lint-config.mjs";
|
|
9
7
|
import { generateBrandAssets } from "../brand-assets.mjs";
|
|
10
8
|
import { applyFilePatch, parseUnifiedPatch } from "./patch.mjs";
|
|
11
9
|
import { createCaptureController, captureSelections } from "../capture.mjs";
|
|
@@ -16,8 +14,9 @@ import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
|
|
|
16
14
|
import { checkCandidate, checkCommand, projectChecks as checks } from "../validation-checks.mjs";
|
|
17
15
|
import { preparePreviewCache } from "../scenarios-compiler.mjs";
|
|
18
16
|
import { validationInputFiles } from "../validation-inputs.mjs";
|
|
17
|
+
import { mutationLimits } from "./mutation-limits.mjs";
|
|
19
18
|
|
|
20
|
-
export
|
|
19
|
+
export { mutationLimits } from "./mutation-limits.mjs";
|
|
21
20
|
const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
22
21
|
const ignored = new Set([".git", ".ds", "node_modules", ".vite", "coverage", ".playwright-cli", "test-results", "output"]);
|
|
23
22
|
const textFile = file => /\.(?:[cm]?[jt]sx?|css|html|jsonc?|md|txt|svg)$/.test(file);
|
|
@@ -152,7 +151,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
152
151
|
let commands = [], diagnostics = [];
|
|
153
152
|
try { commands = checks(options).map(check => [check.command, ...check.args].join(" ")); }
|
|
154
153
|
catch (error) { diagnostics = [error.diagnostic ?? { rule: "mutation-check", message: error.message }]; }
|
|
155
|
-
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",
|
|
154
|
+
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", ...commands, ...options.config.mcp.previewManifest && options.config.mcp.previewWatch ? ["managed production previews"] : []], diagnostics, busy, ...(progress ? { progress } : {}), lastResult };
|
|
156
155
|
},
|
|
157
156
|
cancel() { active?.abort(); },
|
|
158
157
|
units() { return inspectUnits(loadConfig(root)).units; },
|
|
@@ -180,7 +179,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
180
179
|
const options = loadConfig(root);
|
|
181
180
|
if (screenshot && !dryRun || selections !== undefined && !screenshot) throw fail("mutation-capture", "Use screenshot:true only with dryRun:true and an explicit captures:[{scenario,target?,theme?,viewport?}] selection. Ordinary patches create no screenshots.");
|
|
182
181
|
if (screenshot) selections = captureSelections(selections);
|
|
183
|
-
if (patches !== undefined && (unit !== undefined || patch !== undefined || patchFile !== undefined || !Array.isArray(patches) || patches.length < 2 || patches.length > mutationLimits.units)) throw fail("mutation-batch",
|
|
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–${mutationLimits.units} distinct owner patches, without a top-level unit/patch.`);
|
|
184
183
|
const groups = patches ?? [{unit,patch,patchFile}];
|
|
185
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.");
|
|
186
185
|
let patchBytes = 0;
|
|
@@ -240,7 +239,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
240
239
|
originals.push({...original,mode:original.exists ? lstatSync(address(options,entry.path)).mode : undefined});
|
|
241
240
|
byPath.set(entry.path,changes.length);
|
|
242
241
|
changes.push({...change,expectedDigest:original.digest});
|
|
243
|
-
if (changes.length > mutationLimits.files) throw fail("mutation-batch",
|
|
242
|
+
if (changes.length > mutationLimits.files) throw fail("mutation-batch", `A transaction may change at most ${mutationLimits.files} distinct files.`);
|
|
244
243
|
}
|
|
245
244
|
return change;
|
|
246
245
|
});
|
|
@@ -282,17 +281,6 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
282
281
|
const result = await checkCandidate(candidate, signal, root);
|
|
283
282
|
if (!result.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: result.diagnostics, total: result.diagnostics.length, checks: verified },candidateRevision);
|
|
284
283
|
verified.push({ name: "ads check", passed: true });
|
|
285
|
-
const lintConfig = generateLintConfig(candidate).file;
|
|
286
|
-
const require = createRequire(path.join(candidate, "package.json"));
|
|
287
|
-
const oxlintPackage = require.resolve("oxlint/package.json");
|
|
288
|
-
const bin = JSON.parse(readFileSync(oxlintPackage, "utf8")).bin;
|
|
289
|
-
const executable = path.resolve(path.dirname(oxlintPackage), typeof bin === "string" ? bin : bin.oxlint);
|
|
290
|
-
const lintPaths = [candidateOptions.config.sourceDir, candidateOptions.config.dsDir].filter(file => existsSync(path.join(candidate, file)));
|
|
291
|
-
if (configuration) for (const file of inspectUnits(candidateOptions).units.find(item => item.id === "configuration").files) {
|
|
292
|
-
if (/\.[cm]?[jt]sx?$/.test(file) && !lintPaths.some(directory => isInside(path.resolve(candidate, directory), path.resolve(candidate, file)))) lintPaths.push(file);
|
|
293
|
-
}
|
|
294
|
-
await checkCommand(process.execPath, [executable, "--deny-warnings", "--config", lintConfig, ...lintPaths], candidate, signal, undefined, {category:"architecture",phase:"registered-oxlint"});
|
|
295
|
-
verified.push({ name: "registered Oxlint rules", passed: true });
|
|
296
284
|
if (assets || configuration) {
|
|
297
285
|
boundary=evidenceFailure("build","brand-assets","ADS_ASSET_BUILD");
|
|
298
286
|
const brand = await generateBrandAssets(candidate);
|
|
@@ -308,6 +296,9 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
308
296
|
const { startAdsMcp } = await import("./server.mjs");
|
|
309
297
|
previewHost = await startAdsMcp(candidate, { stdio:false });
|
|
310
298
|
await previewHost.buildAll(signal, {timeoutMs:candidateOptions.config.mcp.mutationCheckTimeoutMs});
|
|
299
|
+
// Browser checks consume this immutable production graph. Keep its
|
|
300
|
+
// resources hosted, release its compiler, and leave Explorer live.
|
|
301
|
+
await previewHost.parkCompiler();
|
|
311
302
|
verified.push({ name:"managed production previews", passed:true });
|
|
312
303
|
}
|
|
313
304
|
boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
|
package/dist/mcp/patch.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { mutationLimits } from "./mutation-limits.mjs";
|
|
2
|
+
|
|
1
3
|
function error(message, file, rule = "mutation-patch") {
|
|
2
4
|
return Object.assign(new Error(message), { diagnostic: { rule, message, ...(file ? { file } : {}) } });
|
|
3
5
|
}
|
|
@@ -10,7 +12,7 @@ function fileName(header, prefix) {
|
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
/** Text hunks are exact; Git binary blocks are applied by Git in the candidate. */
|
|
13
|
-
export function parseUnifiedPatch(patch, maxFiles =
|
|
15
|
+
export function parseUnifiedPatch(patch, maxFiles = mutationLimits.files) {
|
|
14
16
|
const lines = patch.split("\n");
|
|
15
17
|
if (lines.at(-1) === "") lines.pop();
|
|
16
18
|
const files = [], paths = new Set();
|
|
@@ -32,7 +34,7 @@ export function parseUnifiedPatch(patch, maxFiles = 32) {
|
|
|
32
34
|
if (lines[index] === "GIT binary patch") {
|
|
33
35
|
if (!gitPath || !binaryIndex) throw error("Binary patches need a Git file header and full blob hashes. Generate with git diff --binary.");
|
|
34
36
|
const file = gitPath;
|
|
35
|
-
if (paths.has(file) || files.length >= maxFiles) throw error(
|
|
37
|
+
if (paths.has(file) || files.length >= maxFiles) throw error(`Provide 1–${maxFiles} distinct file patches.`, file, "mutation-batch");
|
|
36
38
|
paths.add(file);
|
|
37
39
|
while (index < lines.length && !lines[index].startsWith("diff --git ")) index++;
|
|
38
40
|
const block = lines.slice(start, index).join("\n") + "\n";
|
|
@@ -44,7 +46,7 @@ export function parseUnifiedPatch(patch, maxFiles = 32) {
|
|
|
44
46
|
const file = after ?? before;
|
|
45
47
|
if (gitPath && gitPath !== file) throw error("Git metadata and file headers must identify the same path.", file);
|
|
46
48
|
if (!file || before && after && before !== after) throw error("Use separate delete and create entries to rename a file.", file);
|
|
47
|
-
if (paths.has(file) || files.length >= maxFiles) throw error(
|
|
49
|
+
if (paths.has(file) || files.length >= maxFiles) throw error(`Provide 1–${maxFiles} distinct file patches.`, file, "mutation-batch");
|
|
48
50
|
paths.add(file);
|
|
49
51
|
const entry = { path: file, operation: before === null ? "create" : after === null ? "delete" : "update", hunks: [] };
|
|
50
52
|
while (lines[index]?.startsWith("@@")) {
|
|
@@ -15,7 +15,7 @@ function stamp(file) {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
/** One project-owned compiler process, shared by all protocol instances. */
|
|
18
|
-
export function createPreviewWatch(root, config, { log = process.stderr, buildTimeout = 30000 } = {}) {
|
|
18
|
+
export function createPreviewWatch(root, config, { log = process.stderr, buildTimeout = 30000, prewarm = false } = {}) {
|
|
19
19
|
config = { ...config, apps: [...config.apps] };
|
|
20
20
|
const command = config.previewWatch;
|
|
21
21
|
let session = randomUUID();
|
|
@@ -30,7 +30,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
30
30
|
let restarting;
|
|
31
31
|
let disposed = false;
|
|
32
32
|
let stalled = false;
|
|
33
|
-
let suspended = false, resuming, suspending;
|
|
33
|
+
let suspended = false, immutablePark = false, resuming, suspending;
|
|
34
34
|
const baselines = new Map();
|
|
35
35
|
const ready = new Set();
|
|
36
36
|
const requests = new Set();
|
|
@@ -76,7 +76,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
76
76
|
// No shell: configured arguments remain literal. Child stdin cannot consume
|
|
77
77
|
// the MCP channel, and both output streams go exclusively to diagnostics.
|
|
78
78
|
const executable = developmentExecutable(command.command);
|
|
79
|
-
const env = { ...process.env, ADS_MCP_BUILD_SESSION: session, ADS_MCP_BUILD_STATUS: reportFile, ADS_MCP_REQUEST_FILE: requestFile, PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) };
|
|
79
|
+
const env = { ...process.env, ADS_MCP_BUILD_SESSION: session, ADS_MCP_BUILD_STATUS: reportFile, ADS_MCP_REQUEST_FILE: requestFile, ADS_MCP_PREWARM_VIEWS: prewarm ? "1" : "0", PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) };
|
|
80
80
|
try {
|
|
81
81
|
child = spawn(executable, command.args, { cwd: root, env, shell: false, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
82
82
|
} catch (failure) {
|
|
@@ -155,11 +155,20 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
155
155
|
if (manifest?.scenarios.some(entry => entry.id === app?.id)) return buildStatus().previews.find(entry => entry.id === app.id);
|
|
156
156
|
} catch { /* No retained preview: queue this request until validation ends. */ }
|
|
157
157
|
}
|
|
158
|
+
if(immutablePark)throw Object.assign(new Error("Candidate inputs changed after the production build; rerun validation."),{build:{code:"ADS_CANDIDATE_PREVIEW_STALE"}});
|
|
158
159
|
await waitForResume(signal);
|
|
159
160
|
}
|
|
160
161
|
if (state === "failed" || restarting || stalled) await restart();
|
|
161
162
|
if (disposed) throw new Error("Preview watcher is stopped.");
|
|
162
163
|
start();
|
|
164
|
+
if (prewarm) {
|
|
165
|
+
const selected=config.apps.find(app=>path.resolve(root,app.file)===file);
|
|
166
|
+
if(selected)try{
|
|
167
|
+
const directory=path.join(root,".ds"),target=path.join(directory,"last-preview.json"),temporary=target+".tmp";
|
|
168
|
+
mkdirSync(directory,{recursive:true});
|
|
169
|
+
if(realpathSync(directory)===directory){writeFileSync(temporary,JSON.stringify({scenario:selected.id}));renameSync(temporary,target);}
|
|
170
|
+
}catch{/* Remembering navigation must not prevent read-only previews. */}
|
|
171
|
+
}
|
|
163
172
|
request(file,buildStatus().previews.some(entry=>entry.diagnostics.some(item=>item.code==="ADS_PREVIEW_STALE_SOURCE")));
|
|
164
173
|
if (signal?.aborted) throw new Error("Preview request cancelled.");
|
|
165
174
|
const app = config.apps.find((entry) => path.resolve(root, entry.file) === file);
|
|
@@ -200,7 +209,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
200
209
|
throw Object.assign(new Error(`Preview build is still pending${report.progress ? ` in ${report.progress.phase} for ${Math.round((Date.now() - Date.parse(report.progress.updatedAt)) / 1000)}s` : ""}. Inspect ads://project/build and builder logs. Invoke the preview again to restart the timed-out builder within this MCP session.`), { build: { ...report, watcher: status(), code: "ADS_PREVIEW_PENDING" } });
|
|
201
210
|
}
|
|
202
211
|
|
|
203
|
-
const status = () => ({ state, ...(stalled ? { stalled: true } : {}), ...(child?.pid ? { pid: child.pid } : {}), ...(ownerGuard?.pid ? { guardPid: ownerGuard.pid } : {}), ...(error ? { error } : {}) });
|
|
212
|
+
const status = () => ({ state, buildTimeoutMs: buildTimeout, ...(stalled ? { stalled: true } : {}), ...(child?.pid ? { pid: child.pid } : {}), ...(ownerGuard?.pid ? { guardPid: ownerGuard.pid } : {}), ...(error ? { error } : {}) });
|
|
204
213
|
const resourceSession = () => command && config.previewManifest ? session : undefined;
|
|
205
214
|
const buildStatus = () => inspectBuildStatus(root, config, command ? { session, previewSession: resourceSession(), file: reportFile, processState: status() } : {});
|
|
206
215
|
function clearOutput() {
|
|
@@ -234,7 +243,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
234
243
|
function resume() {
|
|
235
244
|
if (suspending) { void suspending.then(resume); return; }
|
|
236
245
|
if (!suspended) return;
|
|
237
|
-
suspended = false;
|
|
246
|
+
suspended = false; immutablePark = false;
|
|
238
247
|
state = command ? "idle" : "disabled";
|
|
239
248
|
error = undefined; child = closed = stopping = undefined; childClosed = false;
|
|
240
249
|
ready.clear(); baselines.clear();
|
|
@@ -265,6 +274,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
265
274
|
throw new Error("Full preview build exceeded its command budget.");
|
|
266
275
|
}, async initialize() {
|
|
267
276
|
if (disposed || !command) return;
|
|
277
|
+
if(immutablePark)return;
|
|
268
278
|
await waitForResume();
|
|
269
279
|
if (disposed) return;
|
|
270
280
|
if (state === "failed" || restarting || stalled) await restart();
|
|
@@ -277,6 +287,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
277
287
|
if (!disposed) throw new Error(error ?? "Preview compiler initialization timed out.");
|
|
278
288
|
}, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
|
|
279
289
|
if (disposed || !command || !files.length) return;
|
|
290
|
+
if(immutablePark)throw Object.assign(new Error("Candidate inputs changed after the production build; rerun validation."),{build:{code:"ADS_CANDIDATE_PREVIEW_STALE"}});
|
|
280
291
|
await waitForResume();
|
|
281
292
|
const selected=active;
|
|
282
293
|
if (state === "failed" || restarting || stalled) await restart();
|
|
@@ -285,8 +296,9 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
285
296
|
for (const file of files) requests.add(file);
|
|
286
297
|
// Preparing a graph must not replace the user's active selection.
|
|
287
298
|
request(active ?? selected ?? files[0],true);
|
|
288
|
-
}, async suspend() {
|
|
299
|
+
}, async suspend({immutable=false} = {}) {
|
|
289
300
|
if (disposed || !command) return;
|
|
301
|
+
immutablePark=immutable;
|
|
290
302
|
if (suspended) return suspending;
|
|
291
303
|
suspended = true;
|
|
292
304
|
let finish; resuming = { promise: new Promise(resolve => { finish = resolve; }), finish: () => finish() };
|
|
@@ -306,7 +318,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
306
318
|
let current = createPreviewWatch(root, config, options);
|
|
307
319
|
let signature = JSON.stringify(config);
|
|
308
320
|
let apps = config.apps;
|
|
309
|
-
let pending = Promise.resolve(), replacing = false, stopped = false, parked = false;
|
|
321
|
+
let pending = Promise.resolve(), replacing = false, stopped = false, parked = false, parkOptions;
|
|
310
322
|
return {
|
|
311
323
|
start() { if (!stopped && !replacing && !parked) current.start(); },
|
|
312
324
|
async initialize() { await pending; if (!stopped) return current.initialize(); },
|
|
@@ -317,7 +329,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
317
329
|
async invalidate() { await pending; if (!stopped) current.invalidate(); },
|
|
318
330
|
async warm(files) { await pending; if (!stopped) return current.warm(files); },
|
|
319
331
|
async buildAll(signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.buildAll(signal, options); },
|
|
320
|
-
async suspend() { parked = true; await pending; if (!stopped && parked) return current.suspend(); },
|
|
332
|
+
async suspend(options) { parked = true; parkOptions=options; await pending; if (!stopped && parked) return current.suspend(options); },
|
|
321
333
|
resume() { parked = false; current.resume(); },
|
|
322
334
|
setApps(next) { apps = next; current.setApps(next); },
|
|
323
335
|
kill() { current.kill(); },
|
|
@@ -330,7 +342,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
330
342
|
await current.stop();
|
|
331
343
|
if (stopped) return;
|
|
332
344
|
current = createPreviewWatch(root, { ...next, apps }, options);
|
|
333
|
-
if (parked) await current.suspend(); else current.start();
|
|
345
|
+
if (parked) await current.suspend(parkOptions); else current.start();
|
|
334
346
|
}).finally(() => { replacing = false; });
|
|
335
347
|
return pending;
|
|
336
348
|
},
|