@reqvire-org/ads 0.3.41 → 0.3.42

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 CHANGED
@@ -22,6 +22,7 @@ inside your project.
22
22
  ADS requires Linaria for component and pattern styling; your project chooses its
23
23
  UI framework and visual design. The [architecture](docs/ARCHITECTURE.md) explains
24
24
  Data, UX, Skin, and the performance reasons behind that choice.
25
+ ADS manages its batch-task cache internally; see [cache controls and CI wiring](docs/CACHING.md).
25
26
 
26
27
  ADS supports **React and native Preact** with the same architecture guards and
27
28
  MCP preview flow. The empty starter uses React; this repository’s working example
@@ -1,13 +1,17 @@
1
1
  import path from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- import { runScenarioCompiler } from "./scenarios-compiler.mjs";
3
+ import { restoreCompiledPreviews, runScenarioCompiler } from "./scenarios-compiler.mjs";
4
+ import { loadConfig } from "./config.mjs";
5
+ import { withPreviewSession } from "./preview-scope.mjs";
4
6
  import { createBunPreviewBuilder } from "./preview-bun.mjs";
5
7
  import { checkCandidate } from "./validation-checks.mjs";
6
8
 
7
9
  /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
8
- export function compilePreviews(directory=process.cwd(),{watched=false}={}) {
10
+ export async function compilePreviews(directory=process.cwd(),{watched=false}={}) {
9
11
  const root=path.resolve(directory);
10
- return runScenarioCompiler(root,{watched,compilerFiles:[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))],
11
- async validate(){const result=await checkCandidate(root);if(!result.ok)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:result.diagnostics});},buildGraph:createBunPreviewBuilder()});
12
+ const compilerFiles=[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))];
13
+ async function validate(){const result=await checkCandidate(root);if(!result.ok)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:result.diagnostics});}
14
+ if(!watched){const restored=await restoreCompiledPreviews(withPreviewSession(loadConfig(root),process.env.ADS_MCP_BUILD_SESSION),compilerFiles);if(restored)return restored;}
15
+ return runScenarioCompiler(root,{watched,compilerFiles,validate,buildGraph:createBunPreviewBuilder()});
12
16
  }
13
17
  if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))await compilePreviews(process.cwd(),{watched:process.argv.includes("--watch")});
package/dist/cli.mjs CHANGED
@@ -35,6 +35,7 @@ Usage: ads init [options] Run inside your project
35
35
  --unit id Verify only: select one discovered behavior contract owner
36
36
  --check id Verify only: select a registered check (repeatable)
37
37
  --changed Validate only: select affected checks since the last full audit
38
+ --fresh Check/validate: execute batch checks without task-cache reads
38
39
 
39
40
  External components and examples are imported using the ADS skills.
40
41
  No component library or example catalogue is bundled.
@@ -53,13 +54,14 @@ async function main(args) {
53
54
  const selectedChecks = [];
54
55
  let showcase = true;
55
56
  let mutations = false;
56
- let changed = false, watched = false, policy;
57
+ let changed = false, watched = false, policy, fresh = false;
57
58
  const positional = [];
58
59
  for (let index = 0; index < args.length; index++) {
59
60
  const argument = args[index];
60
61
  if (argument === "--json") json = true;
61
62
  else if(argument === "--watch") watched = true;
62
63
  else if (argument === "--changed") changed = true;
64
+ else if (argument === "--fresh") fresh = true;
63
65
  else if (argument === "--policy") {if(policy!==undefined || !["acceptance","validation"].includes(args[index+1]))throw new Error("--policy requires acceptance or validation.");policy=args[++index];}
64
66
  else if (argument === "--no-showcase") showcase = false;
65
67
  else if (argument === "--mutations") mutations = true;
@@ -92,8 +94,9 @@ async function main(args) {
92
94
  const exitCode=await enterMemoryBudget(loadConfig(path.resolve(directory??process.cwd())).config,args);
93
95
  if(exitCode!==null){process.exitCode=exitCode;return;}
94
96
  }
95
- const { checkProject, generateBrandAssets, generateLintConfig, initProject, inspectTokens } = await import("./index.mjs");
97
+ const { generateBrandAssets, generateLintConfig, initProject, inspectTokens } = await import("./index.mjs");
96
98
  if(watched&&command!=="compile")throw new Error("--watch is supported only by compile.");
99
+ if(fresh && !["check","validate"].includes(command))throw new Error("--fresh is supported only by check/validate.");
97
100
  if(command==="compile"){const {compilePreviews}=await import("./bun-compiler.mjs");await compilePreviews(path.resolve(directory??process.cwd()),{watched});return;}
98
101
  if (policy!==undefined && command!=="validate")throw new Error("--policy is supported only by validate.");
99
102
  if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
@@ -114,12 +117,12 @@ async function main(args) {
114
117
  }
115
118
  let result;
116
119
  if (command === "init") result = initProject(target, { toolPackage, packageManager, framework });
117
- else if (command === "check") result = checkProject(target);
120
+ else if (command === "check") {const {checkCandidate}=await import("./validation-checks.mjs");result=await checkCandidate(target,undefined,target,{fresh});}
118
121
  else if (command === "validate") {
119
122
  const {createValidationController}=await import("./validation.mjs");
120
123
  const validation=createValidationController(target);
121
124
  const abort=()=>{void validation.close();};process.once("SIGINT",abort);process.once("SIGTERM",abort);
122
- try {result=await validation.run({scope:changed?"changed":"all",policy});}
125
+ try {result=await validation.run({scope:changed?"changed":"all",policy,fresh});}
123
126
  finally {process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort);await validation.close();}
124
127
  }
125
128
  else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
@@ -51,6 +51,7 @@ function summary(value, storageWarning) {
51
51
  ...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
52
52
  ...(value.draft?{draft:value.draft,draftRevision:value.draftRevision,draftEvent:value.draftEvent,updatedDependentCount:value.updatedDependents.length}:{}),
53
53
  acceptance: compactAcceptance(value.acceptance), failures: value.failurePreview ?? failureRows.slice(0, 3).map(item => compactRow({recordIndex:item.recordIndex,unit:item.unit,check:item.check,status:item.status,rule:item.rule,file:item.file,failure:item.failure,message:item.message},640)),
54
+ ...(value.sections.checks.some(item=>item.cache)?{taskCache:value.sections.checks.filter(item=>item.cache).map(item=>({task:item.cache.task,status:item.cache.status}))}:{}),
54
55
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
55
56
  ...(value.execution?{execution:compactRow(value.execution,1100)}:{}),
56
57
  next: value.detailsUnavailable ? null : { tool: "ads_results", arguments: { resultId, section, ...(section === "outcomes" && failedOutcomes.length ? { status: "not_passed" } : {}) } },
@@ -281,8 +281,8 @@ export function createMutationController(directory, { captures = createCaptureCo
281
281
  candidateRevision=digest(Buffer.from(expected));
282
282
  if (previewWork) releasePreview = await previewWork.acquire(signal);
283
283
  const result = await checkCandidate(candidate, signal, root);
284
+ verified.push({name:"ads check",passed:result.ok,cache:result.cache});
284
285
  if (!result.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: result.diagnostics, total: result.diagnostics.length, checks: verified },candidateRevision);
285
- verified.push({ name: "ads check", passed: true });
286
286
  if (assets || configuration) {
287
287
  boundary=evidenceFailure("build","brand-assets","ADS_ASSET_BUILD");
288
288
  const brand = await generateBrandAssets(candidate);
@@ -7,6 +7,7 @@ import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@m
7
7
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
8
8
  import { z } from "zod";
9
9
  import { checkCandidate } from "../validation-checks.mjs";
10
+ import { taskCacheSettings } from "../task-cache.mjs";
10
11
  import { createValidationController } from "../validation.mjs";
11
12
  import { loadConfig, sourceFiles } from "../config.mjs";
12
13
  import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
@@ -98,11 +99,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
98
99
  cache.registry = cache.catalog = cache.documents = undefined;
99
100
  }
100
101
  const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
101
- async function architecture(signal) {
102
+ async function architecture(signal, fresh=false) {
102
103
  let release;
103
104
  try {
104
105
  if (cache.previewWork) release = await cache.previewWork.acquire(signal);
105
- return await checkCandidate(root, signal);
106
+ return await checkCandidate(root, signal, root, {fresh});
106
107
  } finally { release?.(); }
107
108
  }
108
109
  function scenarioUrl(id) {
@@ -290,7 +291,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
290
291
  async function status() {
291
292
  const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
292
293
  const catalog = await getCatalog(), registry = cache.registry;
293
- return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
294
+ return { projectRoot: root, taskCache:taskCacheSettings(root), workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
294
295
  package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
295
296
  components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
296
297
  patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
@@ -432,7 +433,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
432
433
  { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
433
434
  { name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
434
435
  { name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
435
- { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
436
+ { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
436
437
  const result=await drafts.accept(args,signal,progress);
437
438
  if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
438
439
  return finishExecution("mutation",result);
@@ -480,9 +481,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
480
481
  const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
481
482
  return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
482
483
  } },
483
- { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: async ({ limit }, signal) => {
484
- const result = await architecture(signal);
485
- return json({ ok: result.ok, acceptance:result.acceptance, total: result.diagnostics.length, diagnostics: result.diagnostics.slice(0, limit), advisoryCount: result.advisories?.length ?? 0, advisories: (result.advisories ?? []).slice(0, limit), resourceUri: `${PROJECT_URI}/checks` });
484
+ { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20), fresh:z.boolean().default(false) }).strict(), call: async ({ limit, fresh }, signal) => {
485
+ const result = await architecture(signal,fresh);
486
+ return json({ ok: result.ok, acceptance:result.acceptance, cache:result.cache, total: result.diagnostics.length, diagnostics: result.diagnostics.slice(0, limit), advisoryCount: result.advisories?.length ?? 0, advisories: (result.advisories ?? []).slice(0, limit), resourceUri: `${PROJECT_URI}/checks` });
486
487
  } },
487
488
  { name: "ads_skills", description: "Select one ADS workflow after ads_status: ads-designer for building/refining/debugging UI; ads-port for a library reference; ads-import for another project's ADS; ads-motion for animation; ads-break-ui for stress testing. Then read that workflow with ads_read_skill. Listing does not activate a native skill.", schema: empty, call: () => json({ skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, ...frontmatter })) }) },
488
489
  { name: "ads_read_skill", description: "Read a selected skill or relative supporting text file in bounded chunks. This is explicit instruction access, not automatic native skill activation/install.", schema: z.object({ name: z.string().max(64), file: z.string().max(300).default("SKILL.md"), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(8000).default(6000) }).strict(), call: ({ name, file, offset, limit }) => {
@@ -516,7 +517,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
516
517
  { name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
517
518
  { name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
518
519
  { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
519
- { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
520
+ { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
520
521
  return finishExecution("validation",await validation.run(args,signal,progress));
521
522
  } },
522
523
  { name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
@@ -573,6 +574,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
573
574
  const args=input.data;
574
575
  const selection={...(args.policy?{policy:args.policy}:{}),...(args.scope?{requestedScope:args.scope,scope:args.scope}:{}),units:args.units??args.patches?.map(row=>row.unit)??(args.unit?[args.unit]:[]),...(args.id?{draft:args.id}:{}),...(args.checks?{checks:args.checks}:{})};
575
576
  const summary=await coordinator.execute({operation:name,kind,owner,selection,watchSource:kind!=="mutation"},context.mcpReq.signal,notify,(signal,progress)=>{
577
+ executionContext.getStore().fresh=args.fresh??false;
576
578
  if(name==="ads_accept")progress({stage:"selection",policy:"acceptance",scope:"changed",units:drafts.inspect(args.id).manifest.units});
577
579
  return tool.call(args,signal,progress);
578
580
  });
@@ -14,6 +14,7 @@ import { createScenarioInspector } from "./scenario-inspector.mjs";
14
14
  import { configurationFiles } from "./units.mjs";
15
15
  import { validationInputFiles } from "./validation-inputs.mjs";
16
16
  import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
17
+ import { architectureExternalInputs } from "./task-cache.mjs";
17
18
 
18
19
  const digest = value => createHash("sha256").update(value).digest("hex");
19
20
  const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
@@ -23,6 +24,9 @@ const cacheVersion = 3, maxCacheBytes = 8 * 1024 * 1024;
23
24
  * Cache state is development output, never proof that a failed build is current. */
24
25
  export function createPreviewCache(options, compilerFiles = []) {
25
26
  const { root } = options;
27
+ // Build adapters such as Vite set NODE_ENV while configuring a build. Capture
28
+ // the launch environment once; internal compiler setup is not an external edit.
29
+ const launchEnvironment=architectureExternalInputs(root).environment;
26
30
  const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
27
31
  const adapterFiles = [import.meta.filename, ...["runtime-requirements.mjs", "preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
28
32
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
@@ -40,7 +44,7 @@ export function createPreviewCache(options, compilerFiles = []) {
40
44
  }
41
45
  reload();
42
46
  function inputs() {
43
- const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()]];
47
+ const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()],["architecture-environment",{...architectureExternalInputs(root),environment:launchEnvironment}]];
44
48
  for (const file of compilerFiles) rows.push([key(file), fileDigest(file)]);
45
49
  // Tool upgrades invalidate validation even when the project's lockfile is unchanged.
46
50
  for (const name of readdirSync(import.meta.dirname).filter(name => name.endsWith(".mjs"))) {
@@ -183,6 +187,29 @@ export function preparePreviewCache(candidate, target) {
183
187
 
184
188
  export function promotePreviewCache(candidate,target) { const publish=preparePreviewCache(candidate,target);return publish?publish():false; }
185
189
 
190
+ /** Restore a complete verified graph without rediscovering semantic scenarios or
191
+ * starting a compiler. Live build evidence always belongs to this new session. */
192
+ export async function restoreCompiledPreviews(options, compilerFiles) {
193
+ const cache=createPreviewCache(options,compilerFiles),stamp=cache.inputs();
194
+ if(!cache.production(stamp))return false;
195
+ const entries=cache.registry(stamp);
196
+ if(!entries?.length)return false;
197
+ const publication=cachedPreviewPublication(options,entries,cache.graphRevision());
198
+ if(!publication)return false;
199
+ // The native graph stamp includes the successful gate's source, tool, runtime,
200
+ // Git tracking and installed-package environment. Do not invoke a second batch
201
+ // runner to revalidate identical evidence already attached to this graph.
202
+ const sourceRevision=previewSourceRevision(options);
203
+ if(cache.inputs()!==stamp)return false;
204
+ const reporter=createBuildReporter(options.root,{apps:entries.map(entry=>({id:entry.id,file:previewArtifactPath(options,entry.artifact)}))});
205
+ publication.publish(reporter.session);
206
+ mkdirSync(path.join(options.root,".ds/scenarios"),{recursive:true});
207
+ writeFileSync(path.join(options.root,".ds/scenarios/manifest.json"),JSON.stringify({schemaVersion:1,scenarios:entries}));
208
+ if(cache.inputs()!==stamp)return false;
209
+ reporter.batch(()=>{for(const entry of entries){const revision=reporter.begin(entry.id,{sourceRevision});reporter.ready(entry.id,revision);}reporter.progress("idle");});
210
+ return {restored:true,revision:publication.revision,scenarios:entries.length};
211
+ }
212
+
186
213
  /** Shared scheduling and cache; the project supplies its own React/Preact build. */
187
214
  export async function runScenarioCompiler(directory, { watched = false, validate, build, buildGraph, compilerFiles = [] }) {
188
215
  const root = path.resolve(directory);
@@ -1,5 +1,18 @@
1
1
  # Validation scope
2
2
 
3
+ ADS runs architecture batch checks through its internal pinned Turbo dependency.
4
+ Local task caching is on by default; projects need no Turbo config. Source/tool,
5
+ dependency, Git-tracking and runtime changes invalidate reports. A hit reuses only
6
+ the source analysis, never policy success, browser results, a baseline or a run ID.
7
+ Project scripts and registered behavior tests still follow the selected policy.
8
+ Use CLI `check/validate --fresh`, or MCP `ads_check`, `ads_validate`, `ads_accept`
9
+ with `fresh:true`, to bypass task-cache reads. `ADS_CACHE=off` disables reads and
10
+ writes; `ADS_CACHE_DIR` relocates the local store. Remote caching is opt-in with
11
+ `ADS_REMOTE_CACHE=1` and standard Turbo provider variables. For CI, persist only
12
+ `.ds/task-cache` with the CI cache action or configure that remote provider; no
13
+ ADS cache service/API is needed. Inspect task-cache status in source reports,
14
+ execution summaries and `ads_results`; it is not a new test execution claim.
15
+
3
16
  These checks apply to both [direct editing and MCP-only editing](workflows.md).
4
17
  Direct source edits need current checks and rendered review; ordinary edits do
5
18
  not require a draft or acceptance call. Tracked proposals validate on acceptance.
@@ -8,7 +8,12 @@ Install Bun 1.4.1+ for ADS tooling and previews. The application keeps its own
8
8
  Node/npm or Bun build pipeline. Use these commands alongside this skill's research,
9
9
  implementation, documentation, and verification workflow. ADS must be a project
10
10
  development dependency, and its checks must run before the project's build.
11
- Routine builds use the local CLI.
11
+ Routine builds use the local CLI. ADS manages its internal Turbo dependency and
12
+ local task cache automatically; no project Turbo configuration is required.
13
+ In Hermit-managed projects, pin supported Bun (>=1.4.1); Turbo arrives through
14
+ ADS in devDependencies, so do not add a separate Hermit/global Turbo installation.
15
+ `ads check --fresh` and `ads validate --fresh` bypass task-cache reads. See
16
+ [validation](validation.md) for cache controls and CI wiring.
12
17
 
13
18
  Select an actual published package/version or a real local tarball supplied by
14
19
  the user or built from the tool checkout. Respect the project's installed
@@ -1,5 +1,18 @@
1
1
  # Validation scope
2
2
 
3
+ ADS runs architecture batch checks through its internal pinned Turbo dependency.
4
+ Local task caching is on by default; projects need no Turbo config. Source/tool,
5
+ dependency, Git-tracking and runtime changes invalidate reports. A hit reuses only
6
+ the source analysis, never policy success, browser results, a baseline or a run ID.
7
+ Project scripts and registered behavior tests still follow the selected policy.
8
+ Use CLI `check/validate --fresh`, or MCP `ads_check`, `ads_validate`, `ads_accept`
9
+ with `fresh:true`, to bypass task-cache reads. `ADS_CACHE=off` disables reads and
10
+ writes; `ADS_CACHE_DIR` relocates the local store. Remote caching is opt-in with
11
+ `ADS_REMOTE_CACHE=1` and standard Turbo provider variables. For CI, persist only
12
+ `.ds/task-cache` with the CI cache action or configure that remote provider; no
13
+ ADS cache service/API is needed. Inspect task-cache status in source reports,
14
+ execution summaries and `ads_results`; it is not a new test execution claim.
15
+
3
16
  These checks apply to both [direct editing and MCP-only editing](workflows.md).
4
17
  Direct source edits need current checks and rendered review; ordinary edits do
5
18
  not require a draft or acceptance call. Tracked proposals validate on acceptance.
@@ -8,7 +8,12 @@ Install Bun 1.4.1+ for ADS tooling and previews. The application keeps its own
8
8
  Node/npm or Bun build pipeline. Use these commands alongside this skill's research,
9
9
  implementation, documentation, and verification workflow. ADS must be a project
10
10
  development dependency, and its checks must run before the project's build.
11
- Routine builds use the local CLI.
11
+ Routine builds use the local CLI. ADS manages its internal Turbo dependency and
12
+ local task cache automatically; no project Turbo configuration is required.
13
+ In Hermit-managed projects, pin supported Bun (>=1.4.1); Turbo arrives through
14
+ ADS in devDependencies, so do not add a separate Hermit/global Turbo installation.
15
+ `ads check --fresh` and `ads validate --fresh` bypass task-cache reads. See
16
+ [validation](validation.md) for cache controls and CI wiring.
12
17
 
13
18
  Select an actual published package/version or a real local tarball supplied by
14
19
  the user or built from the tool checkout. Respect the project's installed
@@ -1,5 +1,18 @@
1
1
  # Validation scope
2
2
 
3
+ ADS runs architecture batch checks through its internal pinned Turbo dependency.
4
+ Local task caching is on by default; projects need no Turbo config. Source/tool,
5
+ dependency, Git-tracking and runtime changes invalidate reports. A hit reuses only
6
+ the source analysis, never policy success, browser results, a baseline or a run ID.
7
+ Project scripts and registered behavior tests still follow the selected policy.
8
+ Use CLI `check/validate --fresh`, or MCP `ads_check`, `ads_validate`, `ads_accept`
9
+ with `fresh:true`, to bypass task-cache reads. `ADS_CACHE=off` disables reads and
10
+ writes; `ADS_CACHE_DIR` relocates the local store. Remote caching is opt-in with
11
+ `ADS_REMOTE_CACHE=1` and standard Turbo provider variables. For CI, persist only
12
+ `.ds/task-cache` with the CI cache action or configure that remote provider; no
13
+ ADS cache service/API is needed. Inspect task-cache status in source reports,
14
+ execution summaries and `ads_results`; it is not a new test execution claim.
15
+
3
16
  These checks apply to both [direct editing and MCP-only editing](workflows.md).
4
17
  Direct source edits need current checks and rendered review; ordinary edits do
5
18
  not require a draft or acceptance call. Tracked proposals validate on acceptance.
@@ -1,5 +1,18 @@
1
1
  # Validation scope
2
2
 
3
+ ADS runs architecture batch checks through its internal pinned Turbo dependency.
4
+ Local task caching is on by default; projects need no Turbo config. Source/tool,
5
+ dependency, Git-tracking and runtime changes invalidate reports. A hit reuses only
6
+ the source analysis, never policy success, browser results, a baseline or a run ID.
7
+ Project scripts and registered behavior tests still follow the selected policy.
8
+ Use CLI `check/validate --fresh`, or MCP `ads_check`, `ads_validate`, `ads_accept`
9
+ with `fresh:true`, to bypass task-cache reads. `ADS_CACHE=off` disables reads and
10
+ writes; `ADS_CACHE_DIR` relocates the local store. Remote caching is opt-in with
11
+ `ADS_REMOTE_CACHE=1` and standard Turbo provider variables. For CI, persist only
12
+ `.ds/task-cache` with the CI cache action or configure that remote provider; no
13
+ ADS cache service/API is needed. Inspect task-cache status in source reports,
14
+ execution summaries and `ads_results`; it is not a new test execution claim.
15
+
3
16
  These checks apply to both [direct editing and MCP-only editing](workflows.md).
4
17
  Direct source edits need current checks and rendered review; ordinary edits do
5
18
  not require a draft or acceptance call. Tracked proposals validate on acceptance.
@@ -8,7 +8,12 @@ Install Bun 1.4.1+ for ADS tooling and previews. The application keeps its own
8
8
  Node/npm or Bun build pipeline. Use these commands alongside this skill's research,
9
9
  implementation, documentation, and verification workflow. ADS must be a project
10
10
  development dependency, and its checks must run before the project's build.
11
- Routine builds use the local CLI.
11
+ Routine builds use the local CLI. ADS manages its internal Turbo dependency and
12
+ local task cache automatically; no project Turbo configuration is required.
13
+ In Hermit-managed projects, pin supported Bun (>=1.4.1); Turbo arrives through
14
+ ADS in devDependencies, so do not add a separate Hermit/global Turbo installation.
15
+ `ads check --fresh` and `ads validate --fresh` bypass task-cache reads. See
16
+ [validation](validation.md) for cache controls and CI wiring.
12
17
 
13
18
  Select an actual published package/version or a real local tarball supplied by
14
19
  the user or built from the tool checkout. Respect the project's installed
@@ -1,5 +1,18 @@
1
1
  # Validation scope
2
2
 
3
+ ADS runs architecture batch checks through its internal pinned Turbo dependency.
4
+ Local task caching is on by default; projects need no Turbo config. Source/tool,
5
+ dependency, Git-tracking and runtime changes invalidate reports. A hit reuses only
6
+ the source analysis, never policy success, browser results, a baseline or a run ID.
7
+ Project scripts and registered behavior tests still follow the selected policy.
8
+ Use CLI `check/validate --fresh`, or MCP `ads_check`, `ads_validate`, `ads_accept`
9
+ with `fresh:true`, to bypass task-cache reads. `ADS_CACHE=off` disables reads and
10
+ writes; `ADS_CACHE_DIR` relocates the local store. Remote caching is opt-in with
11
+ `ADS_REMOTE_CACHE=1` and standard Turbo provider variables. For CI, persist only
12
+ `.ds/task-cache` with the CI cache action or configure that remote provider; no
13
+ ADS cache service/API is needed. Inspect task-cache status in source reports,
14
+ execution summaries and `ads_results`; it is not a new test execution claim.
15
+
3
16
  These checks apply to both [direct editing and MCP-only editing](workflows.md).
4
17
  Direct source edits need current checks and rendered review; ordinary edits do
5
18
  not require a draft or acceptance call. Tracked proposals validate on acceptance.
@@ -0,0 +1,122 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import { spawnSync } from "node:child_process";
4
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { isInside, loadConfig } from "./config.mjs";
8
+ import { validationInputFiles } from "./validation-inputs.mjs";
9
+ import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
10
+ import { checkCommand } from "./validation-checks.mjs";
11
+
12
+ const hash = value => createHash("sha256").update(value).digest("hex");
13
+ const toolRoot = path.dirname(fileURLToPath(import.meta.url));
14
+ const semanticEnv = ["NODE_ENV", "NODE_OPTIONS", "BUN_OPTIONS", "TZ", "LANG", "LC_ALL"];
15
+ function turboBinary() {
16
+ const platform=process.platform==="win32"?"windows":process.platform==="android"?"linux":process.platform,arch=process.arch==="x64"?"64":process.arch;
17
+ try {
18
+ const resolve=createRequire(createRequire(import.meta.url).resolve("turbo/package.json"));
19
+ return resolve.resolve(`@turbo/${platform}-${arch}/bin/turbo${platform==="windows"?".exe":""}`);
20
+ } catch(cause) {
21
+ // Turbo's convenience JS launcher repairs missing binaries with npm install.
22
+ // Managed ADS operations must only run already-installed project dependencies.
23
+ throw Object.assign(new Error(`ADS needs its installed Turbo binary for ${platform}-${arch}. Reinstall ADS dependencies with platform optional dependencies enabled.`,{cause}),{code:"ADS_TASK_RUNTIME_MISSING"});
24
+ }
25
+ }
26
+ function toolInputs() {
27
+ const rows=[];
28
+ function visit(directory) {
29
+ for (const entry of readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))) {
30
+ const file=path.join(directory,entry.name);
31
+ if (entry.isDirectory() && !["skills","bootstrap-ds","showcase"].includes(entry.name)) visit(file);
32
+ else if(entry.isFile() && /\.(?:mjs|js|cjs|json)$/.test(entry.name)) rows.push([path.relative(toolRoot,file),hash(readFileSync(file))]);
33
+ }
34
+ }
35
+ visit(toolRoot);
36
+ // Include the tool's dependency lock when running from a source checkout.
37
+ const lock=path.join(toolRoot,"../package-lock.json");
38
+ if(existsSync(lock))rows.push(["tool-lock",hash(readFileSync(lock))]);
39
+ return rows;
40
+ }
41
+ // Recompute source digests per request: editing a running checkout must invalidate.
42
+ export function architectureExternalInputs(root, trackingRoot=root) {
43
+ const options=loadConfig(root),manifest=path.join(root,"package.json"),pkg=existsSync(manifest)?JSON.parse(readFileSync(manifest,"utf8")):{};
44
+ const dependencies=Object.keys({...pkg.dependencies,...pkg.devDependencies,...pkg.peerDependencies}).sort().map(name=>{
45
+ for(let directory=root;;directory=path.dirname(directory)) {
46
+ const file=path.join(directory,"node_modules",name,"package.json");
47
+ if(existsSync(file))return [name,hash(readFileSync(file))];
48
+ if(path.dirname(directory)===directory)return [name,null];
49
+ }
50
+ });
51
+ const tracked=spawnSync("git",["ls-files","-z","--","."],{cwd:trackingRoot,encoding:"utf8",maxBuffer:16*1024*1024});
52
+ const generated=[...options.config.assets.generatedPaths.map(file=>path.resolve(root,file)),path.join(root,".ds"),path.join(options.dsRoot,"dist-kit"),path.join(options.dsRoot,"dist-showcase")];
53
+ const noRepository=tracked.status===128 && /not a git repository/i.test(tracked.stderr??"");
54
+ const git={status:noRepository?0:tracked.status,error:tracked.error?.code??null,stderr:noRepository?"":tracked.stderr??"",files:(tracked.stdout??"").split("\0").filter(file=>file && generated.some(directory=>isInside(directory,path.resolve(root,file)))).sort().map(file=>[file,existsSync(path.resolve(root,file))||existsSync(path.resolve(trackingRoot,file))])};
55
+ return {dependencies,git,
56
+ environment:Object.fromEntries(semanticEnv.map(name=>[name,process.env[name]??null]))};
57
+ }
58
+ export function architectureTaskInputs(root, trackingRoot=root) {
59
+ return {schemaVersion:1,kind:"architecture",runtime:previewRuntimeFingerprint(),tool:toolInputs(),files:validationInputFiles(loadConfig(root)),...architectureExternalInputs(root,trackingRoot)};
60
+ }
61
+
62
+ export function taskCacheSettings(root) {
63
+ const directory=path.resolve(root,process.env.ADS_CACHE_DIR??".ds/task-cache");
64
+ return {backend:"turbo",enabled:process.env.ADS_CACHE!=="off",remote:process.env.ADS_REMOTE_CACHE==="1",directory};
65
+ }
66
+ function cacheDirectory(root, workspace) {
67
+ const settings=taskCacheSettings(root);
68
+ if(!settings.enabled)return {...settings,directory:path.join(workspace,"cache")};
69
+ try {
70
+ mkdirSync(settings.directory,{recursive:true});
71
+ if(realpathSync(settings.directory)!==settings.directory)throw new Error("ADS cache directory cannot resolve through a symlink.");
72
+ accessSync(settings.directory,constants.W_OK);
73
+ } catch(error) {
74
+ if(!["EACCES","EPERM","EROFS","ENOSPC","EDQUOT"].includes(error.code))throw error;
75
+ return {...settings,enabled:false,remote:false,directory:path.join(workspace,"cache"),reason:"cache-directory-unwritable"};
76
+ }
77
+ return settings;
78
+ }
79
+ function collect(directory) {
80
+ // Turbo owns serialization and atomic publication. Only prune finished, old
81
+ // artifacts, never current workspaces or live ADS evidence.
82
+ const entries=readdirSync(directory).filter(name=>/^[a-f0-9]+\.tar\.zst$/.test(name)).map(name=>{
83
+ const file=path.join(directory,name),stat=statSync(file),companions=["-meta.json","-manifest.json"].map(suffix=>file.replace(/\.tar\.zst$/,suffix));
84
+ return {file,companions,size:stat.size+companions.reduce((sum,file)=>sum+(existsSync(file)?statSync(file).size:0),0),mtime:stat.mtimeMs};
85
+ }).sort((a,b)=>b.mtime-a.mtime);
86
+ let bytes=0;
87
+ for(const entry of entries){bytes+=entry.size;if((bytes>256*1024*1024 || Date.now()-entry.mtime>7*86400000) && Date.now()-entry.mtime>60000){rmSync(entry.file,{force:true});for(const file of entry.companions)rmSync(file,{force:true});}}
88
+ }
89
+
90
+ /** One backend for deterministic ADS batch checks. Cache hits are still fenced
91
+ * against current source; they never restore locks, policy results or baselines. */
92
+ export async function runArchitectureTask(root, trackingRoot, directory, signal, {fresh=false}={}) {
93
+ // A nonexistent target is a structural diagnostic, not a task workspace to
94
+ // create as a side effect. The analysis primitive exits before source work.
95
+ if(!existsSync(root)){const {checkProject}=await import("./check.mjs");return checkProject(root);}
96
+ const settings=cacheDirectory(trackingRoot,directory),inputs=architectureTaskInputs(root,trackingRoot),key=hash(JSON.stringify(inputs));
97
+ writeFileSync(path.join(directory,"inputs.json"),JSON.stringify(inputs));
98
+ writeFileSync(path.join(directory,"worker.mjs"),readFileSync(new URL("./task-worker.mjs",import.meta.url)));
99
+ writeFileSync(path.join(directory,"package.json"),JSON.stringify({name:"ads-internal-task",version:"1.0.0",private:true,packageManager:"bun@1.4.1",scripts:{architecture:`${process.versions.bun?"bun":"node"} worker.mjs`}}));
100
+ const passThrough=["ADS_TASK_ROOT","ADS_TASK_TRACKING_ROOT","ADS_TASK_TOOL","ADS_TASK_KEY"];
101
+ writeFileSync(path.join(directory,"turbo.json"),JSON.stringify({tasks:{architecture:{inputs:["inputs.json","worker.mjs"],outputs:["out/report.json"],passThroughEnv:passThrough}},globalPassThroughEnv:semanticEnv}));
102
+ const modes=settings.enabled?`local:${fresh?"w":"rw"}${settings.remote?`,remote:${fresh?"w":"rw"}`:""}`:"local:";
103
+ const args=["run","architecture","--single-package",`--cache=${modes}`,`--cache-dir=${settings.directory}`,"--concurrency=1","--summarize","--output-logs=errors-only","--ui=stream"];
104
+ const started=Date.now();let failure;
105
+ try { await checkCommand(turboBinary(),args,directory,signal,undefined,{category:"architecture",phase:"ads-check"},60000,
106
+ {ADS_TASK_ROOT:root,ADS_TASK_TRACKING_ROOT:trackingRoot,ADS_TASK_TOOL:toolRoot,ADS_TASK_KEY:key,TURBO_TELEMETRY_DISABLED:"1"}); }
107
+ catch(error){failure=error;}
108
+ if(signal?.aborted)throw failure??Object.assign(new Error("Mutation cancelled during validation."),{diagnostic:{rule:"mutation-cancelled",message:"Mutation cancelled during validation."}});
109
+ if(hash(JSON.stringify(architectureTaskInputs(root,trackingRoot)))!==key)throw Object.assign(new Error("Source, dependencies or Git tracking changed during the ADS task; retry against the current inputs."),{code:"ADS_SOURCE_CHANGED"});
110
+ const report=path.join(directory,"out/report.json");
111
+ if(!existsSync(report))throw failure??new Error("ADS task did not produce an architecture report.");
112
+ if(statSync(report).size>16*1024*1024)throw new Error("Architecture report exceeds 16 MiB.");
113
+ const result=JSON.parse(readFileSync(report,"utf8"));
114
+ // Failing source guards return actionable diagnostics but never a cacheable
115
+ // successful task. Infrastructure failures cannot masquerade as source errors.
116
+ if(failure && result.ok!==false)throw failure;
117
+ let hit=false;
118
+ const summaries=path.join(directory,".turbo/runs");
119
+ if(existsSync(summaries))for(const file of readdirSync(summaries).filter(name=>name.endsWith(".json"))){const summary=JSON.parse(readFileSync(path.join(summaries,file),"utf8"));hit=summary.tasks?.some(task=>task.cache?.status==="HIT")??false;}
120
+ try{collect(settings.directory);}catch{/* Cache maintenance never changes gate results. */}
121
+ return {...result,cache:{backend:"turbo",task:"architecture",key,status:!settings.enabled?"disabled":fresh?"fresh":hit?"hit":"miss",...(settings.reason?{reason:settings.reason}:{}),elapsedMs:Date.now()-started}};
122
+ }
@@ -0,0 +1,19 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // Copied to an isolated Turbo task workspace. Physical source/tool locations are
7
+ // passed at execution time, not embedded into portable cached task inputs.
8
+ const {ADS_TASK_ROOT:root,ADS_TASK_TRACKING_ROOT:trackingRoot,ADS_TASK_TOOL:tool,ADS_TASK_KEY:key}=process.env;
9
+ if(!root || !trackingRoot || !tool || !key)throw new Error("Missing ADS task execution context.");
10
+ const {architectureTaskInputs}=await import(pathToFileURL(path.join(tool,"task-cache.mjs")));
11
+ const current=()=>createHash("sha256").update(JSON.stringify(architectureTaskInputs(root,trackingRoot))).digest("hex");
12
+ if(current()!==key)throw new Error("ADS task inputs changed before execution.");
13
+ const {checkProject}=await import(pathToFileURL(path.join(tool,"check.mjs")));
14
+ const result=checkProject(root,{trackingRoot});
15
+ if(current()!==key)throw new Error("ADS task inputs changed during execution.");
16
+ // The descriptor is part of Turbo's key; also reject an inconsistent caller.
17
+ if(createHash("sha256").update(readFileSync("inputs.json")).digest("hex")!==key)throw new Error("ADS task input descriptor mismatch.");
18
+ mkdirSync("out",{recursive:true});writeFileSync("out/report.json",JSON.stringify(result));
19
+ if(!result.ok)process.exitCode=1;
@@ -1,6 +1,6 @@
1
- import { finishExecutionGuard, trackExecutionChild, trackExecutionWorkspace } from "./mcp/execution-context.mjs";
1
+ import { executionContext, finishExecutionGuard, trackExecutionChild, trackExecutionWorkspace } from "./mcp/execution-context.mjs";
2
2
  import { spawn } from "node:child_process";
3
- import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import path from "node:path";
@@ -9,22 +9,20 @@ import { packageScriptCommand } from "./development-runtime.mjs";
9
9
  import { failure as evidenceFailure } from "./evidence.mjs";
10
10
  const fail = (rule, message, file, failure) => Object.assign(new Error(message), { diagnostic: {rule, message, ...(file ? {file} : {}), ...(failure ? {failure} : {})} });
11
11
 
12
- export async function checkCandidate(root, signal, trackingRoot = root) {
12
+ export async function checkCandidate(root, signal, trackingRoot = root, options = {}) {
13
13
  const directory = mkdtempSync(path.join(tmpdir(), "ads-architecture-"));
14
14
  trackExecutionWorkspace(directory);
15
- const report = path.join(directory, "report.json");
16
15
  try {
17
- await checkCommand(process.execPath, [fileURLToPath(new URL("./check-runner.mjs", import.meta.url)), root, report, trackingRoot], root, signal, undefined, {category:"architecture",phase:"ads-check"});
18
- if (statSync(report).size > 16 * 1024 * 1024) throw new Error("Architecture report exceeds 16 MiB.");
19
- return JSON.parse(readFileSync(report, "utf8"));
16
+ const {runArchitectureTask}=await import("./task-cache.mjs");
17
+ return await runArchitectureTask(root,trackingRoot,directory,signal,{fresh:executionContext.getStore()?.fresh,...options});
20
18
  } finally { rmSync(directory, { recursive:true, force:true }); }
21
19
  }
22
20
 
23
- export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
21
+ export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000, environment = {}) {
24
22
  return new Promise((resolve, reject) => {
25
23
  if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
26
24
  const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
27
- env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
25
+ env: { ...process.env, ...environment, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
28
26
  let output = "", failure, guard, done = false;
29
27
  const startedAt=Date.now();
30
28
  if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
@@ -39,7 +39,7 @@ export function createValidationController(directory, { previewWork } = {}) {
39
39
  return {
40
40
  status() { return { busy: !!active, ...(progress ? {progress} : {}) }; },
41
41
  async close() { const pending = active; pending?.abort(); await pending?.completion; },
42
- async run({scope = "all", policy = "validation"} = {}, signal, onProgress) {
42
+ async run({scope = "all", policy = "validation", fresh = false} = {}, signal, onProgress) {
43
43
  if (!["all","changed"].includes(scope)) throw new Error("Validation scope must be all or changed.");
44
44
  if (!["acceptance","validation"].includes(policy)) throw new Error("Policy must be acceptance or validation.");
45
45
  if (active) throw new Error("Validation is already running.");
@@ -77,9 +77,9 @@ export function createValidationController(directory, { previewWork } = {}) {
77
77
  }
78
78
  onProgress?.({stage:"selection",scope,requestedScope,units,elapsedMs:Date.now()-startedAt});
79
79
  stage("architecture");
80
- const core = await checkCandidate(root, signal);
80
+ const core = await checkCandidate(root, signal, root, {fresh});
81
81
  diagnostics.push(...core.diagnostics); advisories.push(...(core.advisories ?? []));
82
- checks.push({name:"architecture",passed:core.ok});
82
+ checks.push({name:"architecture",passed:core.ok,cache:core.cache});
83
83
  if (!core.ok) return complete();
84
84
  const scripts = projectChecks(options,policy);
85
85
  for (const launch of scripts) await command(`project:${launch.args.at(-1)}`,launch,options);
@@ -800,6 +800,15 @@ for 100,000 files / 2 GiB. Unrelated native artifacts are not copied. Declared e
800
800
  inputs support project commands that read data outside the UI graph. When
801
801
  `acceptance.behaviorChecks` is true, affected registered behavior checks, including
802
802
  consumers of a changed shared controller, run in the isolated candidate project.
803
+ Architecture batch checks use the internal pinned Turbo runner and its installed
804
+ platform binary; no global Turbo or runtime dependency installer is invoked. Local artifact
805
+ reuse is enabled by default and fenced by current input/tool/runtime/Git state;
806
+ policy results, browser evidence, locks and baselines are never task outputs.
807
+ Project scripts remain uncached without a known deterministic contract. The warm
808
+ Bun preview compiler retains its module cache; complete verified graph restoration
809
+ publishes fresh build-session evidence without semantic rediscovery. See
810
+ [cache controls and CI wiring](CACHING.md).
811
+
803
812
  `acceptance.checks` and `validation.checks` explicitly select project scripts; no
804
813
  names are inferred. Validation selects its own `behaviorChecks` flag. Direct
805
814
  edits can invoke `ads validate --policy acceptance`; separate baselines prevent
@@ -0,0 +1,99 @@
1
+ # Batch task caching
2
+
3
+ ADS uses its pinned Turborepo dependency internally for architecture batch tasks.
4
+ Projects do not install Turbo, create `turbo.json`, or choose between backends.
5
+ Local caching is enabled out of the box for `ads check` and the source-check
6
+ stages of validation, acceptance, guarded mutations and preview compilation.
7
+ The synchronous exported `checkProject` function remains the analysis primitive;
8
+ the CLI and managed execution paths use the internal task runner. ADS invokes
9
+ the already-installed platform binary directly. It never runs Turbo's automatic
10
+ repair installer; a missing binary reports `ADS_TASK_RUNTIME_MISSING` and asks
11
+ for dependency reinstallation with optional platform packages enabled.
12
+
13
+ Keys include relevant ADS/application source, local dependency inputs,
14
+ configuration, lockfiles, declared installed package manifests, Git tracking,
15
+ ADS implementation and runtime/platform, and the check's semantic environment.
16
+ Inputs are fenced around execution and when a hit is consumed. Install from the
17
+ lockfile; request a fresh check after manually modifying installed package
18
+ contents without changing a lockfile.
19
+
20
+ Only successful deterministic source reports are cached. Project policy scripts
21
+ and registered browser/behavior checks still execute according to their policy;
22
+ ADS cannot infer cache contracts for arbitrary scripts. A hit never restores a
23
+ successful acceptance, baseline, run ID, lock or live build status. Each policy
24
+ invocation establishes its own freshness and result. The existing coordinator
25
+ retains execution ownership, cancellation and cleanup.
26
+
27
+ ## Controls
28
+
29
+ | Control | Behavior |
30
+ | --- | --- |
31
+ | Default | Local `.ds/task-cache`; remote cache disabled |
32
+ | `ads check --fresh`, `ads validate --fresh` | Bypass task-cache reads; refresh successful cached outputs |
33
+ | MCP `ads_check`, `ads_validate`, `ads_accept`: `fresh:true` | Same override for the operation's source checks |
34
+ | `ADS_CACHE=off` | Disable task-cache reads/writes; keep the same runner |
35
+ | `ADS_CACHE_DIR=/absolute/path` | Relocate or share the local artifact store |
36
+ | `ADS_REMOTE_CACHE=1` | Opt into remote caching with standard Turbo provider settings |
37
+
38
+ Read-only projects and unwritable/full cache stores run through the same Turbo
39
+ runner uncached in an isolated temporary workspace, reporting the fallback reason.
40
+ `ADS_CACHE=off` also avoids creating a project cache directory.
41
+
42
+ Fresh concerns batch task reuse; it does not force unchanged Bun modules to
43
+ recompile or change the selected test policy. `ads_status.taskCache` reports
44
+ settings. Source reports include key, hit/miss/fresh/disabled status and elapsed
45
+ time. Execution replies include compact cache status; `ads_results` check records
46
+ retain details.
47
+
48
+ Collection targets 256 MiB and seven days, pruning old archives while protecting
49
+ files written within the last minute. Concurrent activity can temporarily exceed
50
+ the target. Isolated temporary workspaces are removed on completion or recovery.
51
+ Only immutable archives share storage; live outputs and evidence stay isolated.
52
+
53
+ ## Preview restoration
54
+
55
+ The interactive Bun compiler keeps its incremental module/graph cache. Turbo is
56
+ not launched on every edit. ADS reopens a matching complete graph without semantic
57
+ scenario discovery or compiler startup: check cached registry/dependencies, verify
58
+ immutable assets, match the successful guard evidence already attached to the
59
+ graph against current source/tool/runtime/Git/dependency state, fence inputs, and
60
+ publish new session metadata. This native handoff does not invoke Turbo again. Missing, changed or corrupt artifacts fall back to compiling.
61
+ Guard failures remain failures. Old live build evidence is never restored.
62
+
63
+ ## CI wiring
64
+
65
+ Use the existing CLI and persist the artifact directory. No additional ADS cache
66
+ server, network API or MCP endpoint is needed. For example, after installing the
67
+ project's dependencies and supported Bun:
68
+
69
+ ```yaml
70
+ - uses: actions/cache@v4
71
+ with:
72
+ path: explorer/.ds/task-cache
73
+ key: ads-${{ runner.os }}-${{ runner.arch }}-${{ github.sha }}
74
+ restore-keys: |
75
+ ads-${{ runner.os }}-${{ runner.arch }}-
76
+ - run: bunx --no-install ads validate . --json
77
+ working-directory: explorer
78
+ ```
79
+
80
+ Change `explorer/` to the project directory. ADS task keys determine input matches;
81
+ the outer archive key only finds candidate artifacts. Cache this directory,
82
+ not the entire `.ds` directory and its run-specific state. Alternatively set
83
+ `ADS_REMOTE_CACHE=1` with the provider's `TURBO_TOKEN`, `TURBO_TEAM` and optionally
84
+ `TURBO_API`. Managed or self-hosted storage is a project choice. Tasks execute on
85
+ the caller's machine or CI runner on a miss.
86
+
87
+ See [measurements and proofs](benchmarks/turbo-poc.md), Turbo's
88
+ [GitHub Actions guide](https://turborepo.dev/docs/guides/ci-vendors/github-actions)
89
+ and [cache controls](https://turborepo.dev/docs/reference/run#--cache-options).
90
+
91
+ ## Hermit-managed projects
92
+
93
+ Turbo is a normal dependency of the ADS tool package, which a project installs as
94
+ `@reqvire-org/ads` in `devDependencies`. Hermit should pin Bun >=1.4.1 for ADS;
95
+ it should not install a second global Turbo executable or manage a project
96
+ `turbo.json`. Keep the project's other Rust/native/Node tools as its build requires.
97
+ This ADS repository and the local shadcn example have no Hermit environment.
98
+ Reqvire pins Bun 1.4.2. Neezler's native-client Hermit environment also supplies
99
+ Bun 1.4.2 for the root ADS/frontend commands invoked by its Makefile.
package/docs/CHANGELOG.md CHANGED
@@ -1,34 +1,47 @@
1
1
  # Changelog
2
2
 
3
- ## 0.3.41
3
+ ## 0.3.42
4
4
 
5
5
  <!-- ads-local-tests:start -->
6
- Local verification: **618/618 passed** with `ADS_TEST_BUN=1 npm test`.
7
- Tested commit: `05760c51a94bd84b2d298837b9dbba09edb875f2`; Node v24.13.0, Bun 1.4.1.
8
- Completed 2026-10-26T13:40:29.074Z (793 seconds).
6
+ Local verification: **624/624 passed** with `ADS_TEST_BUN=1 npm test`.
7
+ Tested commit: `b85bcac055ff420b612b94961b177377c5f0dd16`; Node v24.13.0, Bun 1.4.1.
8
+ Completed 2026-10-26T17:07:50.019Z (754 seconds).
9
9
 
10
10
  <!-- ads-local-test-proof
11
11
  {
12
12
  "schema": 1,
13
- "version": "0.3.41",
14
- "commit": "05760c51a94bd84b2d298837b9dbba09edb875f2",
15
- "sourceSha256": "d890df59a6cdcd1b7e3082a7801fc4dcf2e37e417d2194c0142d4ea778851ecc",
13
+ "version": "0.3.42",
14
+ "commit": "b85bcac055ff420b612b94961b177377c5f0dd16",
15
+ "sourceSha256": "a3ac8b5ef580cb6793968b91c6a68a33f286194e39ab7def682b4642a71cde74",
16
16
  "command": "ADS_TEST_BUN=1 npm test",
17
17
  "result": "pass",
18
- "tests": 618,
19
- "pass": 618,
18
+ "tests": 624,
19
+ "pass": 624,
20
20
  "fail": 0,
21
21
  "cancelled": 0,
22
22
  "skipped": 0,
23
23
  "node": "v24.13.0",
24
24
  "bun": "1.4.1",
25
- "completedAt": "2026-10-26T13:40:29.074Z",
26
- "durationMs": 792714,
27
- "logSha256": "cdb07ccccde9de440b321252e99252bc69c8cedd64b63d52eb36670d8d19b912"
25
+ "completedAt": "2026-10-26T17:07:50.019Z",
26
+ "durationMs": 754350,
27
+ "logSha256": "18afde78bb91bacea61cc80ff8e15cd49b66f775a2f3998c91cf3b1522388600"
28
28
  }
29
29
  -->
30
30
  <!-- ads-local-tests:end -->
31
31
 
32
+ - Use pinned internal Turbo for deterministic architecture batch tasks, with
33
+ local caching enabled by default, fresh/off/shared-directory controls and
34
+ opt-in remote caching. Preserve policy script/test execution, source fences,
35
+ process ownership, cancellation and fresh run evidence. Report cache provenance.
36
+ - Keep read-only source inspection available: disabled or unavailable cache storage
37
+ runs uncached in a temporary workspace through the same runner. Invoke only the
38
+ installed Turbo platform binary; managed operations never run its repair installer.
39
+ - Restore complete verified preview graphs without repeating semantic scenario
40
+ discovery or starting a compiler; publish fresh live-session evidence. Document
41
+ CI cache wiring and keep the interactive Bun compiler's incremental graph.
42
+
43
+ ## 0.3.41
44
+
32
45
  - Coordinate validation, verification, draft acceptance and guarded edits across all
33
46
  clients of one ADS process. Return structured lock/holder/progress responses;
34
47
  keep Explorer and preview serving available.
@@ -0,0 +1,266 @@
1
+ # Turborepo POC: immutable batch tasks
2
+
3
+ Measured locally on 26 October 2026 with ADS 0.3.41, Turbo 2.11.10,
4
+ Bun 1.4.1 and Node 24.13.0 on Linux x64. This is an isolated experiment;
5
+ production ADS, project dependencies, policies, MCP locks and CI were not changed.
6
+
7
+ ## Workload and controls
8
+
9
+ The input is a frozen Neezler snapshot: 885 inventoried validation files,
10
+ 5,622,703 bytes, plus copied workspace/generated inputs. Inventoried source digest:
11
+ `4666c8a12353d4f60e1cd7828f8ce44a414b802b5dfdde9c18394429346ad9d6`.
12
+ Local workspace imports resolve to the snapshot, not the live terminal-renderer
13
+ checkout. Installed third-party dependencies are shared read-only. The live
14
+ project was used only for reading/preparing this snapshot.
15
+
16
+ Each pipeline executes the same three commands through a small report wrapper:
17
+
18
+ - ADS architecture/source check, capturing its JSON report.
19
+ - The project's complete `tsc --noEmit` typecheck.
20
+ - ADS native Bun preview compilation: **129 scenarios, 318 immutable assets**.
21
+
22
+ Preview compilation still performs its own mandatory ADS checks. This POC does
23
+ not remove that existing duplication. Both direct and Turbo variants perform the
24
+ same work. Direct warm compilation uses ADS's existing persisted preview cache;
25
+ it is not forced to compile again for an artificial comparison.
26
+
27
+ Turbo runs in single-package mode with local caching only and a two-task limit.
28
+ Inputs conservatively include the entire frozen source, lockfile, configuration,
29
+ task wrapper and recorded toolchain. Task outputs contain reports and the compiled
30
+ preview graph/cache. Live build-status files, locks, run journals, acceptance
31
+ baselines and verification outcomes are excluded. No remote service or CI is used.
32
+
33
+ Cold means empty ADS/Turbo build caches, not an empty operating-system disk cache.
34
+ Cold/edit comparisons have one trial per mode; unchanged warm comparisons have
35
+ three. Tests are local observations, not service limits or statistical guarantees.
36
+
37
+ ## Results
38
+
39
+ | Workload | Direct sequential | Turbo, two tasks |
40
+ | --- | ---: | ---: |
41
+ | Cold complete pipeline | 18.737 s | 11.645 s |
42
+ | Unchanged pipeline, median of three | 11.059 s | 0.070 s |
43
+ | Component source edit | 17.773 s | 11.228 s |
44
+ | Shared token edit | 17.671 s | 11.257 s |
45
+
46
+ The three unchanged Turbo runs took 81, 70 and 69 ms, executing **zero tasks**.
47
+ Direct unchanged preview compilation alone took 1.585, 1.710 and 1.541 seconds;
48
+ the remaining direct time was the source check and typecheck. Warm runs are much
49
+ faster because Turbo skips matching task execution, not because it compiles faster.
50
+
51
+ A scheduling control separates that cache benefit from ordinary parallelism:
52
+
53
+ | Cold scheduling control | Time | Sampled peak process-tree PSS |
54
+ | --- | ---: | ---: |
55
+ | Direct, sequential | 18.737 s | 1,937 MiB |
56
+ | Turbo, sequential | 18.512 s | 1,790 MiB |
57
+ | Direct, simple two-worker queue | 11.428 s | 2,815 MiB |
58
+ | Turbo, two tasks | 11.645 s | 2,842 MiB |
59
+
60
+ Cold timing differences between equivalent scheduling modes are small and within
61
+ normal local variation. A simple two-worker queue provides essentially the same
62
+ cold improvement. Turbo's demonstrated additional value is the task artifact
63
+ cache, not uniquely faster scheduling.
64
+
65
+ Memory is sampled through `/proc/*/smaps_rollup` every 150 ms; fast cache hits can
66
+ end between samples, so their memory values should not be interpreted as precise
67
+ peaks. Every benchmark phase ran inside a 6 GiB process-tree cgroup with swap
68
+ disabled. The first run's whole cgroup peaked around 3 GiB, including monitoring,
69
+ file-backed memory and other overhead beyond summed process PSS.
70
+
71
+ ## Correctness and concurrency checks
72
+
73
+ - Deleted all Turbo-variant report outputs and its entire `.ds/` directory.
74
+ Turbo restored the artifacts in **82 ms**, with zero tasks executed. ADS's
75
+ manifest/asset integrity reader verified all graph links, sizes and byte digests;
76
+ the preview revision matched the pre-deletion revision.
77
+ - Changed Badge's real default tone, then a shared `--accent` token. Each change
78
+ caused all three conservative whole-snapshot tasks to miss cache and execute.
79
+ The preview graph revision changed. Repeating each edited pipeline hit cache.
80
+ - Introduced an actual TypeScript assignment error. Both attempts failed and
81
+ executed the typechecker; a failed task was not reused as a successful result.
82
+ - Started two separate Turbo invocations for the same cold source-check key.
83
+ Both missed cache and **two source checks executed**, taking about 7.5 seconds
84
+ each. Turbo did not combine the requests into one in-flight computation.
85
+ Concurrent-run telemetry shares an observation log; use the aggregate count
86
+ in `concurrency.json`, rather than summing each invocation's overlapping window.
87
+
88
+ These checks establish task invalidation and restored artifact integrity for this
89
+ snapshot. They do not establish browser behavior, fresh per-run verification
90
+ reports, source isolation during concurrent edits, or acceptance correctness.
91
+ The existing ADS coordinator was neither replaced nor bypassed in production.
92
+
93
+ ## Assessment
94
+
95
+ There is a clear win for repeated identical batch work: approximately **158 times
96
+ faster** for this unchanged pipeline. Cold or edited work benefits from parallel
97
+ execution, which ADS could also obtain with a small bounded scheduler. Two-task
98
+ execution increases the memory requirement; task count alone is not a memory
99
+ budget.
100
+
101
+ The follow-up integration adopts Turbo as the mandatory internal backend for
102
+ controlled architecture batch tasks, with local caching enabled by default. Keep
103
+ ADS's source/freshness checks, result ownership, cancellation,
104
+ resource budgets and acceptance publication. Keep the live preview compiler warm;
105
+ this experiment does not justify launching Turbo on every edit or replacing the
106
+ interactive compiler's internal graph cache. Restored assets must be republished
107
+ into a current ADS session, distinguishing reused evidence from a new execution.
108
+ The follow-up proofs below exercise cross-checkout restoration and browser use.
109
+
110
+ This POC intentionally uses broad task inputs. It does not yet demonstrate
111
+ component-granular cache reuse or safe parallel MCP acceptance/verification. Those
112
+ require ADS dependency selection, isolated outputs and shared in-flight work.
113
+
114
+ ## Reproduction and artifacts
115
+
116
+ From the ADS checkout, use a fresh output directory and the same frozen-source
117
+ input to reproduce exactly. The default input is `../csc`; another project needs
118
+ its edit targets adjusted because this small POC targets Neezler's Badge/tokens.
119
+ The runner installs pinned Turbo only inside its output directory. A new snapshot
120
+ of an actively edited checkout can differ; preparation rejects detected races.
121
+
122
+ ```sh
123
+ export ADS_TURBO_POC_OUTPUT=output/turbo-poc-new
124
+ systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0 \
125
+ env ADS_TURBO_POC_OUTPUT="$ADS_TURBO_POC_OUTPUT" \
126
+ node scripts/benchmarks/turbo-poc/run.mjs /path/to/neezler
127
+ systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0 \
128
+ env ADS_TURBO_POC_OUTPUT="$ADS_TURBO_POC_OUTPUT" \
129
+ node scripts/benchmarks/turbo-poc/run.mjs /path/to/neezler --extras
130
+ ```
131
+
132
+ Bun and Node must be on PATH. The second command adds the equivalent cold serial
133
+ and direct parallel controls to the first command's report. The measured run is
134
+ retained under `output/turbo-poc/`:
135
+
136
+ - `summary.json`: aggregated results and snapshot/toolchain provenance.
137
+ - `measurements.json`: individual commands, timing, sampled PSS/RSS and Turbo hashes.
138
+ - `concurrency.json`: both cold invocations and actual task-start records.
139
+ - `logs/` and each snapshot's `.turbo/runs/`: original task logs/run summaries.
140
+ - `seed/`: frozen benchmark source and exact executed task wrapper.
141
+
142
+ The Turbo variant's cache occupies approximately 3.0 MB after these revisions.
143
+ Generated snapshots, installed Turbo and cache artifacts are ignored by Git.
144
+ The initial POC changed only these drivers and this report. The subsequent
145
+ integration adds the internal source-task backend and verified preview handoff.
146
+
147
+ Turbo's input/output model and local-cache behavior follow its official
148
+ [caching guide](https://turborepo.dev/docs/crafting-your-repository/caching).
149
+ Single-package scheduling and run summaries use its
150
+ [run command](https://turborepo.dev/docs/reference/run).
151
+
152
+ ## Follow-up integration proof
153
+
154
+ `output/turbo-proof-2/proofs.json` records three successful integration proofs
155
+ against ADS 0.3.41: a different checkout restored the complete graph, the original
156
+ checkout path was removed, and an actual MCP resource browser mounted Popover and
157
+ opened it. Restoring took 78 ms; invoking the existing full compiler to reestablish
158
+ current-session readiness took 2,340 ms. File restoration alone was not readiness.
159
+
160
+ The unreleased implementation separates that handoff from semantic discovery and
161
+ compiler startup. `output/turbo-proof-3/proofs.json` repeats all three proofs with
162
+ the local implementation: 129 scenarios, 318 assets, 73 ms restoration and
163
+ **1,148 ms handoff**, with the same graph revision before and after and successful
164
+ browser interaction. These are one-trial observations with changed implementation,
165
+ not a controlled statistical estimate; further warm samples are recorded separately.
166
+ The artifact set includes native graph metadata and the successful architecture
167
+ artifact store, but excludes live build status and policy results. Restored evidence
168
+ is republished for the destination session. Missing/corrupt input falls back safely.
169
+
170
+ Two real MCP clients also proved contention, own-request cancellation, descendant
171
+ cleanup (including a detached child), retry without using incomplete cache output,
172
+ warm reuse, reuse after server restart, and reading the previous result by ID.
173
+ A separate process was killed during validation: its detached child exited, restart
174
+ recorded an interrupted result without a baseline, and a fresh retry passed. Both
175
+ lifecycle proofs passed before and after the internal backend was introduced.
176
+
177
+ The production change deliberately caches ADS's controlled source-analysis task.
178
+ Opaque project scripts and live browser checks continue to execute under project
179
+ policy; this experiment does not establish their cache contracts. Bun's warm
180
+ interactive compiler and module cache remain in place. Local caching defaults on;
181
+ fresh/off/location controls and opt-in remote caching are documented in
182
+ [Batch task caching](../CACHING.md). GitHub CI needs CLI/cache-provider wiring,
183
+ not a new ADS server/API. These proofs ran on Linux x64; other platforms have not
184
+ been benchmarked here.
185
+
186
+ ### Separating native restoration from batch analysis
187
+
188
+ The final `output/turbo-proof-4/proofs.json` repeats all three integration proofs
189
+ successfully after removing the redundant Turbo lookup from native graph restore:
190
+ **72 ms** artifact restoration and **1,021 ms** separate CLI handoff/startup. The
191
+ existing graph's successful validation stamp now also includes relevant Git
192
+ tracking, declared installed-package manifests and semantic environment. A mismatch
193
+ falls back to the guarded compile path, rather than reusing prior gate evidence.
194
+
195
+ `output/turbo-proof-4/handoff.json` contains a primed, rotating-order comparison,
196
+ three measured samples per arm, in one Bun process against that exact frozen graph:
197
+
198
+ | Same graph and new handoff | Median | Samples |
199
+ | --- | ---: | --- |
200
+ | Native graph restoration, no Turbo call | **401 ms** | 410, 401, 382 ms |
201
+ | Additional Turbo-cached source check, then restoration | **564 ms** | 546, 599, 564 ms |
202
+ | Additional direct source analysis, then restoration | **5,329 ms** | 5,329, 5,333, 5,291 ms |
203
+
204
+ The first arm is the production warm path. The other arms deliberately add a
205
+ batch source check; direct analysis executes the same synchronous analysis
206
+ primitive without a child-process startup. These timings isolate task-result
207
+ reuse from the handoff refactor. **Turbo is not the cause of the preview-handoff
208
+ speedup**: an unnecessary task lookup adds overhead to an already verified graph.
209
+ Its value is skipping matching batch analysis when a validation/check operation
210
+ would otherwise execute it. The complete standalone CLI includes startup costs
211
+ that this within-process comparison excludes. No compilation speedup is claimed.
212
+
213
+ After the initial POC has populated `output/turbo-poc/seed` and `tools`, build the
214
+ current tool and run the proofs with a new output directory (Bun/Node on PATH):
215
+
216
+ ```sh
217
+ npm run build
218
+ export ADS_TURBO_PROOF_OUTPUT=output/turbo-proof-new
219
+ systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0 \
220
+ env ADS_TURBO_PROOF_OUTPUT="$ADS_TURBO_PROOF_OUTPUT" \
221
+ node scripts/benchmarks/turbo-poc/proofs.mjs
222
+ systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0 \
223
+ env ADS_TURBO_PROOF_OUTPUT="$ADS_TURBO_PROOF_OUTPUT" \
224
+ bun scripts/benchmarks/turbo-poc/handoff.mjs
225
+ ```
226
+
227
+ The proof driver intentionally refuses existing snapshot directories. It uses the
228
+ installed third-party dependencies and frozen workspace sources from the initial
229
+ Neezler POC; it never edits the live application. Failed attempts remain available
230
+ under earlier output directories instead of being overwritten.
231
+
232
+ ### Final implementation proof
233
+
234
+ `output/turbo-proof-final/proofs.json` records all three successful integration
235
+ proofs against the final internal runner, which invokes the installed Rust binary
236
+ without Turbo's convenience installer. The browser proof restored 129 scenarios
237
+ and 318 assets in **65 ms**, then established fresh destination readiness through a
238
+ separate CLI invocation in **978 ms**. The original checkout path was unavailable.
239
+ Cancellation, restart, detached-child cleanup, retained results and crash recovery
240
+ all passed again. Hermit-managed Bun **1.4.2** also passed the source check on the
241
+ same frozen project (`hermit-bun-1.4.2.json`).
242
+
243
+ The final `handoff.json` repeats the primed, rotating comparison with three samples:
244
+
245
+ | Path | Median | Samples |
246
+ | --- | ---: | --- |
247
+ | Native graph restoration; no Turbo call | **375 ms** | 360, 382, 375 ms |
248
+ | Additional Turbo source-cache hit, then restoration | **536 ms** | 538, 536, 529 ms |
249
+ | Additional executed source analysis, then restoration | **5,013 ms** | 5,075, 4,978, 5,013 ms |
250
+
251
+ These measurements confirm the division: native graph restoration is the warm
252
+ preview path; Turbo reuses deterministic batch analysis. It does not accelerate
253
+ compilation or make the already validated graph's native handoff faster.
254
+
255
+ The broad regression run exposed two compatibility defects, fixed before adoption:
256
+ Vite changes `NODE_ENV` during setup, so graph stamps now capture launch environment
257
+ rather than invalidating their own build; read-only inspection must work without a
258
+ project output directory, so unavailable/disabled cache storage uses the same runner
259
+ uncached in a temporary workspace. Dedicated regressions cover both behaviors.
260
+
261
+ The final full regression run passed **624/624 tests, zero skips or failures**,
262
+ with `ADS_TEST_BUN=1 npm test` in **764.8 seconds**, under an 8 GiB process-tree
263
+ limit with swap disabled. `output/turbo-proof-final/validation.json` records the
264
+ working-tree source fingerprint, runtime proof outcomes, timings and full-log
265
+ digest; `full-tests.log` retains the original output. This is unreleased working
266
+ code, not an npm release or a proof attached to a committed release tag.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reqvire-org/ads",
3
- "version": "0.3.41",
3
+ "version": "0.3.42",
4
4
  "type": "module",
5
5
  "description": "A design system your agent can see and shape. Your components. Your look. Your code.",
6
6
  "repository": {
@@ -54,15 +54,16 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@modelcontextprotocol/server": "2.3.1",
57
+ "@wyw-in-js/transform": "2.1.3",
57
58
  "css-tree": "3.2.1",
58
59
  "postcss": "^8.5.30",
59
60
  "postcss-selector-parser": "^7.1.6",
60
61
  "postcss-value-parser": "^4.2.0",
61
62
  "sharp": "^0.35.5",
63
+ "turbo": "2.11.10",
62
64
  "typescript": "^5.9.3",
63
65
  "yaml": "2.9.1",
64
- "zod": "4.4.3",
65
- "@wyw-in-js/transform": "2.1.3"
66
+ "zod": "4.4.3"
66
67
  },
67
68
  "devDependencies": {
68
69
  "@babel/core": "^7.29.7",
@@ -1,7 +0,0 @@
1
- import { writeFileSync } from "node:fs";
2
- import { checkProject } from "./check.mjs";
3
-
4
- // Candidate architecture analysis can retain a large TypeScript heap. Give it
5
- // a process lifetime instead of growing the long-running MCP process's heap.
6
- const [root, report, trackingRoot] = process.argv.slice(2);
7
- writeFileSync(report, JSON.stringify(checkProject(root, { trackingRoot })));