@reqvire-org/ads 0.3.24 → 0.3.25

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.
@@ -15,7 +15,7 @@ const id = z.string().regex(/^[a-zA-Z0-9][\w.-]{0,99}$/);
15
15
  const reference = z.string().min(1).max(500);
16
16
  const subject = z.union([
17
17
  z.object({ api: reference }).strict(),
18
- z.object({ source: reference, symbol: reference.optional() }).strict(),
18
+ z.object({ source: reference, symbol: reference.optional(), role:z.enum(["controller","implementation"]).optional() }).strict(),
19
19
  ]);
20
20
  export const behaviorSchema = z.object({
21
21
  schemaVersion: z.literal(1),
@@ -92,7 +92,9 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
92
92
  for(const entry of [...Object.values(declaration?.bindings??{}),...(declaration?.declarativeParts??[])])for(const name of entry.checks) {
93
93
  const check=value.checks[name],scenario=check&&scenarios.find(scenario=>scenario.id===check.scenario);
94
94
  const parent=entry.parentName??entry.scope.apiName;
95
- if(!check||config.mcp.behaviorProfiles[check.profile]?.mode!=="browser"||!scenario?.covers.includes(parent)||entry.parentName&&!scenario.exercises?.includes(entry.apiName))report(`Required contract check ${name} must use a browser profile and a scenario covering ${parent}${entry.parentName?` and exercising ${entry.apiName}`:""}. Source registration does not establish rendered behavior.`);
95
+ const roots=entry.rootNames??[parent];
96
+ const nested=declaration?.declarativeParts?.some(part=>part.apiName===parent);
97
+ if(!check||config.mcp.behaviorProfiles[check.profile]?.mode!=="browser"||!roots.some(root=>scenario?.covers.includes(root))||entry.parentName&&(!scenario?.exercises?.includes(entry.apiName)||nested&&!scenario?.exercises?.includes(parent)))report(`Required contract check ${name} must use a browser profile and a scenario covering a rendering root (${roots.join(", ")||parent})${entry.parentName?` and exercising ${entry.apiName}${nested?` through ${parent}`:""}`:""}. Source registration does not establish rendered behavior.`);
96
98
  if(!value.guarantees.some(guarantee=>guarantee.checks.includes(name)))report(`Required contract check ${name} must back a named guarantee, not remain an unclaimed execution.`);
97
99
  }
98
100
  contracts.push({ ...value, unit, file: relative(file), demonstrations: Object.fromEntries(Object.entries(value.subjects).filter(([, item]) => item.api).map(([name, item]) => [name, scenarios.filter(scenario => scenario.exercises?.includes(item.api)).map(scenario => scenario.id)])) });
@@ -107,7 +109,7 @@ export function inspectControllers(options, program, report, contracts = []) {
107
109
  const pkg = existsSync(path.join(root, "package.json")) ? JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) : {};
108
110
  const declared = new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies, ...pkg.optionalDependencies }));
109
111
  const privateFiles = new Map();
110
- for (const contract of contracts) for (const subject of Object.values(contract.subjects).filter(item => item.source)) {
112
+ for (const contract of contracts) for (const subject of Object.values(contract.subjects).filter(item => item.source&&item.role!=="implementation")) {
111
113
  const file = path.resolve(root, path.dirname(contract.file), subject.source);
112
114
  if (!privateFiles.has(file)) privateFiles.set(file, new Set());
113
115
  privateFiles.get(file).add(subject.symbol ?? null);
@@ -119,7 +121,7 @@ export function inspectControllers(options, program, report, contracts = []) {
119
121
  const wholeFile = isInside(path.join(dsRoot, "controllers"), file) || privateFiles.get(file)?.has(null);
120
122
  const subjects = wholeFile ? [] : checker.getSymbolsInScope(source, ts.SymbolFlags.Value).filter(symbol => privateFiles.get(file)?.has(symbol.name)).flatMap(symbol => symbol.declarations ?? []);
121
123
  const headless = node => wholeFile || subjects.some(subject => subject.getSourceFile() === source && node.pos >= subject.pos && node.end <= subject.end);
122
- function emit(node, rule, message) { const p = source.getLineAndCharacterOfPosition(node.getStart()); report(file, rule, message, p.line + 1, p.character + 1); }
124
+ function emit(node, rule, message) { const p = source.getLineAndCharacterOfPosition(node.getStart()); report(file, rule, message+(rule==="controller-skin"&&!isInside(path.join(dsRoot,"controllers"),file)?' An intentional visual behavior subject can declare role: "implementation"; controller subjects remain headless.':""), p.line + 1, p.character + 1); }
123
125
  function visit(node) {
124
126
  let specifier;
125
127
  if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) specifier = node.moduleSpecifier.text;
@@ -75,7 +75,7 @@ export function migrateContractDraft(options, prepared) {
75
75
  const subjects={};
76
76
  for(const [id,subject]of Object.entries(value.subjects??{})) {
77
77
  if(subject.api) {const api=apis.find(api=>api.name===subject.api);if(!api)throw new Error(`Unknown API ${subject.api}`);subjects[id]={api:importReference(slash(path.relative(options.root,api.file)),api.declaration.name?.text??subject.api)};}
78
- else if(subject.symbol)subjects[id]={implementation:importReference(slash(path.normalize(path.join(path.dirname(file),subject.source))),subject.symbol)};
78
+ else if(subject.symbol)subjects[id]={implementation:importReference(slash(path.normalize(path.join(path.dirname(file),subject.source))),subject.symbol),...(subject.role!==undefined?{role:subject.role}:{})};
79
79
  else throw new Error(`Subject ${id} names a whole file. Select an actual implementation symbol before migrating this behavior section.`);
80
80
  }
81
81
  const {schemaVersion:_version,...behavior}=value;contract.behavior={...behavior,subjects};remove.push(file);
@@ -8,14 +8,14 @@ export interface UnitContract {
8
8
  bindings?: Readonly<Record<string, {
9
9
  input: { api: Implementation; property: string };
10
10
  producer: Implementation;
11
- valueFrom: string;
11
+ valueFrom: string | readonly string[];
12
12
  variable: string;
13
13
  scope: { api: Implementation; selector: string };
14
14
  checks: readonly string[];
15
15
  }>>;
16
16
  declarativeParts?: readonly { api: Implementation; parent: Implementation; consumer: Implementation; checks: readonly string[] }[];
17
17
  behavior?: {
18
- subjects: Readonly<Record<string, { api: Implementation } | { implementation: Implementation }>>;
18
+ subjects: Readonly<Record<string, { api: Implementation } | { implementation: Implementation; role?: "controller" | "implementation" }>>;
19
19
  guarantees: readonly { id: string; description: string; subjects: readonly string[]; checks: readonly string[] }[];
20
20
  checks: Readonly<Record<string, BehaviorCheck>>;
21
21
  };
@@ -0,0 +1,144 @@
1
+ import ts from "typescript";
2
+ import { unwrap } from "./source-values.mjs";
3
+ import { uiOperation } from "./ui-framework.mjs";
4
+
5
+ /** Bounded source provenance for children, selections and projected child props.
6
+ * Unknown transforms and escaped mutable arrays provide no consumption credit. */
7
+ export function createChildFlow({ consumer, calls, bodies, canonical, key, checker }) {
8
+ const merge=sets=>new Set(sets.flatMap(set=>[...set]));
9
+ const empty=()=>new Set();
10
+ function nodes(node,predicate) {const found=[];function visit(item){if(predicate(item))found.push(item);ts.forEachChild(item,visit);}if(node)visit(node);return found;}
11
+ function functionNode(node) {return ts.isVariableDeclaration(node??{})?unwrap(node.initializer):node;}
12
+ function outputs(callback) {
13
+ if(!callback?.body||callback.asteriskToken||callback.modifiers?.some(item=>item.kind===ts.SyntaxKind.AsyncKeyword))return [];
14
+ if(!ts.isBlock(callback.body))return [callback.body];
15
+ return nodes(callback.body,ts.isReturnStatement).filter(node=>{for(let parent=node.parent;parent&&parent!==callback;parent=parent.parent)if(ts.isFunctionLike(parent))return false;return true;}).map(node=>node.expression).filter(Boolean);
16
+ }
17
+ const fn=expression=>functionNode(unwrap(expression)&&canonical(unwrap(expression)))??unwrap(expression);
18
+ const uses=new Map(),cache=new Map();
19
+ const changed=new Set(),aliases=[];
20
+ function rootOf(expression) {
21
+ expression=unwrap(expression);const fields=[];
22
+ while(expression&&(ts.isPropertyAccessExpression(expression)||ts.isElementAccessExpression(expression))){fields.unshift(ts.isPropertyAccessExpression(expression)?expression.name.text:"*");expression=unwrap(expression.expression);}
23
+ return {declaration:expression&&canonical(expression),fields};
24
+ }
25
+ for(const body of bodies)for(const node of nodes(body,node=>ts.isBinaryExpression(node)||ts.isVariableDeclaration(node)||ts.isDeleteExpression(node))) {
26
+ if(ts.isVariableDeclaration(node)&&node.initializer){const root=rootOf(node.initializer);if(root.declaration)aliases.push([node,root.declaration]);}
27
+ else if(ts.isDeleteExpression(node)||ts.isBinaryExpression(node)) {
28
+ const target=ts.isDeleteExpression(node)?node.expression:node.operatorToken.kind>=ts.SyntaxKind.FirstAssignment&&node.operatorToken.kind<=ts.SyntaxKind.LastAssignment?node.left:null;
29
+ if(target){const root=rootOf(target);if(root.declaration&&(!root.fields.length||["*","type","props","map","filter","find","forEach"].includes(root.fields[0])))changed.add(root.declaration);}
30
+ }
31
+ }
32
+ for(const call of calls)if(ts.isPropertyAccessExpression(call.expression)&&["push","unshift","splice","fill","copyWithin"].includes(call.expression.name.text)) {
33
+ const root=rootOf(call.expression.expression),declaration=root.declaration;
34
+ const initial=declaration&&ts.isVariableDeclaration(declaration)&&unwrap(declaration.initializer);
35
+ if(declaration&&!(initial&&ts.isArrayLiteralExpression(initial)&&!initial.elements.length))changed.add(declaration);
36
+ }
37
+ for(let pass=0;pass<=aliases.length;pass++){const count=changed.size;for(const[alias,target]of aliases)if(changed.has(alias))changed.add(target);if(changed.size===count)break;}
38
+ const add=(target,entry)=>{if(!target?.parameters)return;if(!uses.has(target))uses.set(target,[]);uses.get(target).push(entry);};
39
+ for(const call of calls) {
40
+ add(fn(call.expression),{call,direct:true});
41
+ const operation=uiOperation(call.expression,checker);
42
+ if(["Children.map","Children.forEach"].includes(operation))add(fn(call.arguments[1]),{call,input:call.arguments[0]});
43
+ else if(ts.isPropertyAccessExpression(call.expression)&&["map","forEach","flatMap","filter","find"].includes(call.expression.name.text))add(fn(call.arguments[0]),{call,input:call.expression.expression});
44
+ }
45
+ let budget;
46
+ function selectedInput(expression,seen=new Set()) {
47
+ expression=unwrap(expression);if(!expression||seen.has(expression)||seen.size>32)return false;
48
+ seen=new Set([...seen,expression]);
49
+ if(ts.isCallExpression(expression)&&ts.isPropertyAccessExpression(expression.expression)&&["filter","find"].includes(expression.expression.name.text))return true;
50
+ const declaration=canonical(expression);
51
+ if(changed.has(declaration))return false;
52
+ return !!(declaration&&ts.isVariableDeclaration(declaration)&&declaration.initializer&&selectedInput(declaration.initializer,seen));
53
+ }
54
+ function projected(origins,fields) {
55
+ if(!fields.length||fields.length===1&&fields[0]==="props")return origins;
56
+ if(fields[0]==="props"&&fields[1]==="children")return projected(new Set([...origins].map(origin=>origin+"/children")),fields.slice(2));
57
+ return empty();
58
+ }
59
+ function trace(expression,fields=[],seen=new Set(),active=new Set()) {
60
+ expression=unwrap(expression);
61
+ if(!expression||seen.size>80)return empty();
62
+ if(++budget.steps>12000){budget.exhausted=true;return empty();}
63
+ const marker=key(expression)+":"+expression.kind+":"+expression.end+":"+fields.join(".");if(seen.has(marker))return empty();
64
+ seen=new Set([...seen,marker]);
65
+ if(ts.isPropertyAccessExpression(expression))return trace(expression.expression,[expression.name.text,...fields],seen,active);
66
+ if(ts.isElementAccessExpression(expression)) {
67
+ if(ts.isStringLiteralLike(expression.argumentExpression))return trace(expression.expression,[expression.argumentExpression.text,...fields],seen,active);
68
+ if(expression.argumentExpression&&checker.getTypeAtLocation(expression.argumentExpression).flags&ts.TypeFlags.NumberLike)return trace(expression.expression,fields,seen,active);
69
+ return empty(); // Only numeric array selection retains element provenance.
70
+ }
71
+ if(ts.isObjectLiteralExpression(expression)&&fields.length) {
72
+ const property=expression.properties.findLast(property=>!ts.isSpreadAssignment(property)&&(property.name?.text??property.name?.getText())===fields[0]);
73
+ if(!property||expression.properties.some(ts.isSpreadAssignment))return empty();
74
+ return trace(ts.isShorthandPropertyAssignment(property)?property.name:property.initializer,fields.slice(1),seen,active);
75
+ }
76
+ if(ts.isConditionalExpression(expression))return merge([trace(expression.whenTrue,fields,seen,active),trace(expression.whenFalse,fields,seen,active)]);
77
+ if(ts.isBinaryExpression(expression)&&[ts.SyntaxKind.QuestionQuestionToken,ts.SyntaxKind.BarBarToken,ts.SyntaxKind.AmpersandAmpersandToken].includes(expression.operatorToken.kind))return merge([trace(expression.left,fields,seen,active),trace(expression.right,fields,seen,active)]);
78
+ const declaration=canonical(expression);
79
+ if(changed.has(declaration))return empty();
80
+ if(declaration===consumer?.parameters?.[0]&&fields[0]==="children")return projected(new Set(["children-input"]),fields.slice(1));
81
+ if(declaration&&ts.isBindingElement(declaration)&&ts.isObjectBindingPattern(declaration.parent)&&declaration.parent.parent===consumer?.parameters?.[0]&&(declaration.propertyName??declaration.name).getText()==="children")return projected(new Set(["children-input"]),fields);
82
+ if(declaration&&ts.isVariableDeclaration(declaration)) {
83
+ if(declaration.initializer) {
84
+ const initial=unwrap(declaration.initializer);
85
+ if(ts.isArrayLiteralExpression(initial)&&!initial.elements.length) {
86
+ let owner=declaration.parent;while(owner&&!ts.isFunctionLike(owner))owner=owner.parent;
87
+ const pushes=nodes(owner,ts.isCallExpression).filter(call=>ts.isPropertyAccessExpression(call.expression)&&call.expression.name.text==="push"&&canonical(call.expression.expression)===declaration);
88
+ const escaped=nodes(owner,ts.isIdentifier).some(node=>canonical(node)===declaration&&node!==declaration.name&&!ts.isReturnStatement(node.parent)&&!(ts.isPropertyAccessExpression(node.parent)&&node.parent.expression===node&&pushes.some(call=>call.expression===node.parent)));
89
+ if(escaped||!pushes.length)return empty();
90
+ const values=pushes.flatMap(call=>call.arguments.map(argument=>trace(ts.isSpreadElement(argument)?argument.expression:argument,fields,seen,active)));
91
+ return values.every(value=>value.size)?merge(values):empty();
92
+ }
93
+ return trace(initial,fields,seen,active);
94
+ }
95
+ if(ts.isVariableDeclarationList(declaration.parent)&&ts.isForOfStatement(declaration.parent.parent))return trace(declaration.parent.parent.expression,fields,seen,active);
96
+ }
97
+ if(declaration&&ts.isParameter(declaration)) {
98
+ const callback=declaration.parent,index=callback.parameters.indexOf(declaration),origins=[];
99
+ for(const {call,input,direct}of uses.get(callback)??[]) {
100
+ if(direct){
101
+ let recursive=false;for(let parent=call.parent;parent;parent=parent.parent)if(parent===callback){recursive=true;break;}
102
+ if(!recursive&&call.arguments[index])origins.push(trace(call.arguments[index],fields,seen,active));continue;
103
+ }
104
+ if(index!==0)continue;
105
+ const arrayCall=ts.isPropertyAccessExpression(call.expression)&&["map","forEach","flatMap","filter","find"].includes(call.expression.name.text);
106
+ const source=trace(input,[],seen,active);
107
+ if(source.size) {
108
+ const selected=arrayCall&&["filter","find"].includes(call.expression.name.text);
109
+ const inherited=selectedInput(input);
110
+ const elements=selected||!inherited?new Set([...source].map(origin=>origin+"/"+key(call))):source;
111
+ origins.push(projected(elements,fields));
112
+ }else origins.push(trace(input,fields,seen,active));
113
+ }
114
+ return merge(origins);
115
+ }
116
+ if(ts.isCallExpression(expression)) {
117
+ const operation=uiOperation(expression.expression,checker);
118
+ if(["Children.toArray","toChildArray"].includes(operation))return trace(expression.arguments[0],fields,seen,active);
119
+ if(operation==="useMemo")return merge(outputs(fn(expression.arguments[0])).map(output=>trace(output,fields,seen,active)));
120
+ if(ts.isPropertyAccessExpression(expression.expression)) {
121
+ const method=expression.expression.name.text,input=expression.expression.expression,callback=fn(expression.arguments[0]);
122
+ if(["filter","find"].includes(method)) {
123
+ const source=trace(input,[],seen,active);
124
+ return source.size?projected(new Set([...source].map(origin=>origin+"/"+key(expression))),fields):trace(input,fields,seen,active);
125
+ }
126
+ if(method==="slice")return trace(input,fields,seen,active);
127
+ if(["map","flatMap"].includes(method))return merge(outputs(callback).map(output=>trace(output,fields,seen,active)));
128
+ }
129
+ const helper=fn(expression.expression);
130
+ if(helper?.body) {
131
+ // A recursive flattening call only receives descendants of its input.
132
+ // The outer returned-array proof still validates every push and escape.
133
+ if(active.has(helper))return trace(expression.arguments[0],fields,seen,active);
134
+ return merge(outputs(helper).map(output=>trace(output,fields,seen,new Set([...active,helper]))));
135
+ }
136
+ }
137
+ return empty();
138
+ }
139
+ return expression=>{
140
+ if(cache.has(expression))return cache.get(expression);
141
+ budget={steps:0,exhausted:false};const result=trace(expression);
142
+ const proven=budget.exhausted?empty():result;cache.set(expression,proven);return proven;
143
+ };
144
+ }
@@ -57,10 +57,12 @@ export function inspectCatalog(options, scenarios = []) {
57
57
  const line = declaration.getSourceFile().getLineAndCharacterOfPosition(declaration.getStart()).line + 1;
58
58
  const guides = documents.filter((doc) => doc.file.endsWith(".md") && path.dirname(doc.file) === path.dirname(file)).map((doc) => doc.uri);
59
59
  const contract=contracts.find(contract=>[...(contract.paintInputs??[]),...(contract.declarativeParts??[])].some(input=>input.apiName===exported.name)||Object.values(contract.bindings??{}).some(binding=>binding.apiName===exported.name));
60
- const declarative=contract?.declarativeParts?.find(part=>part.apiName===exported.name);
60
+ const relationships=contract?.declarativeParts?.filter(part=>part.apiName===exported.name)??[];
61
+ const declarative=relationships[0];
62
+ const relationship=part=>({parent:part.parentName,roots:(part.rootNames??[part.parentName]).slice(0,8),rootCount:part.rootNames?.length??1,sourceUri:sourceUri(part.consumer.source),symbol:part.consumer.symbol,checks:part.checks.slice(0,8),checkCount:part.checks.length});
61
63
  const bindings=Object.entries(contract?.bindings??{}).filter(([,binding])=>binding.apiName===exported.name);
62
64
  items.push({ name: exported.name, kind, apiKind: declarative ? "declarative" : ui ? "ui" : "behavior", importFrom: config.publicAlias, file: relative, line, sourceUri: sourceUri(relative), guides,
63
- ...(contract?{contractUri:sourceUri(contract.file),paintInputCount:contract.paintInputs?.filter(input=>input.apiName===exported.name).length??0,paintInputs:contract.paintInputs?.filter(input=>input.apiName===exported.name).slice(0,8).map(input=>({property:input.property,kind:input.kind,bindings:input.bindings??[]})),...(declarative?{consumer:{parent:declarative.parentName,sourceUri:sourceUri(declarative.consumer.source),symbol:declarative.consumer.symbol,checks:declarative.checks.slice(0,8),checkCount:declarative.checks.length},evidence:"registered relationship; source and browser verification are separate"}:{})}:{}),
65
+ ...(contract?{contractUri:sourceUri(contract.file),paintInputCount:contract.paintInputs?.filter(input=>input.apiName===exported.name).length??0,paintInputs:contract.paintInputs?.filter(input=>input.apiName===exported.name).slice(0,8).map(input=>({property:input.property,kind:input.kind,bindings:input.bindings??[]})),...(declarative?{consumer:relationship(declarative),consumerCount:relationships.length,consumers:relationships.slice(0,4).map(relationship),evidence:"registered relationships; source and browser verification are separate"}:{})}:{}),
64
66
  ...(bindings.length?{bindingCount:bindings.length,bindings:bindings.slice(0,4).map(([id,binding])=>({id,variable:binding.variable,scope:binding.scope.selector,producer:{sourceUri:sourceUri(binding.producer.source),symbol:binding.producer.symbol},checks:binding.checks.slice(0,8),checkCount:binding.checks.length})),bindingEvidence:"registered; verify source diagnostics and current browser checks"}:{}),
65
67
  previews: scenarios.filter(item => item.covers.includes(exported.name) || item.exercises?.includes(exported.name)).map(item => item.id) });
66
68
  }
@@ -5,15 +5,21 @@ import { isDevelopmentFile, isReviewFile } from "./config.mjs";
5
5
  import { inspectUnitContracts, implementationIdentity, implementationNode } from "./unit-contracts.mjs";
6
6
  import { tokenContract } from "./token-policy.mjs";
7
7
  import { uiOperation } from "./ui-framework.mjs";
8
+ import { createChildFlow } from "./declarative-flow.mjs";
8
9
  import { unwrap, createSourceValues, reference } from "./source-values.mjs";
9
10
 
10
11
  function fn(node) { return node && ts.isVariableDeclaration(node) ? unwrap(node.initializer) : node; }
11
12
  function all(node, predicate) { const result=[];function visit(item){if(predicate(item))result.push(item);ts.forEachChild(item,visit);}if(node)visit(node);return result; }
12
13
 
13
14
  export function inspectRuntimeContracts(options, program) {
15
+ // Contract discovery already owns a fully resolved program. Reuse it for
16
+ // typed array selections; the lightweight source guard program has no libs.
17
+ const declarations=inspectUnitContracts(options);
18
+ program=declarations.program??program;
14
19
  if(options.runtimeContracts?.program===program)return options.runtimeContracts;
15
- const checker=program.getTypeChecker(), declarations=inspectUnitContracts(options);
20
+ const checker=program.getTypeChecker();
16
21
  const result={program,diagnostics:[],bindings:[],parts:[],allowedStyles:new Set(),allowedStyleTypes:new Set()};
22
+ const partProofs=new Map();
17
23
  options.runtimeContracts=result;
18
24
  const key=node=>`${node.getSourceFile().fileName}:${node.pos}`;
19
25
  const values=createSourceValues(program,options,{strict:true});
@@ -36,39 +42,14 @@ export function inspectRuntimeContracts(options, program) {
36
42
  }
37
43
  for(const contract of declarations.contracts) {
38
44
  for(const part of contract.declarativeParts??[]) {
39
- const consumer=fn(implementationNode(program,part.consumer,options.root));
40
- const bodies=localCalls(consumer),calls=bodies.flatMap(body=>all(body,ts.isCallExpression));
41
- function childOrigins(expression,seen=new Set()) {
42
- expression=unwrap(expression);if(!expression||seen.has(expression)||seen.size>40)return new Set();
43
- seen=new Set([...seen,expression]);
44
- const merge=sets=>new Set(sets.flatMap(set=>[...set]));
45
- if(ts.isPropertyAccessExpression(expression)&&expression.name.text==="children") {
46
- if(canonical(expression.expression)===consumer?.parameters?.[0])return new Set(["children-input"]);
47
- if(ts.isPropertyAccessExpression(expression.expression)&&expression.expression.name.text==="props"&&childOrigins(expression.expression.expression,seen).size)return new Set([key(expression)]);
48
- }
49
- const declaration=canonical(expression);
50
- if(declaration&&ts.isBindingElement(declaration)&&ts.isObjectBindingPattern(declaration.parent)&&declaration.parent.parent===consumer?.parameters?.[0]&&(declaration.propertyName??declaration.name).getText()==="children")return new Set(["children-input"]);
51
- if(declaration&&ts.isVariableDeclaration(declaration)) {
52
- if(declaration.initializer)return childOrigins(declaration.initializer,seen);
53
- if(ts.isVariableDeclarationList(declaration.parent)&&ts.isForOfStatement(declaration.parent.parent)&&childOrigins(declaration.parent.parent.expression,seen).size)return new Set([key(declaration)]);
54
- }
55
- if(declaration&&ts.isParameter(declaration)) {
56
- const callback=declaration.parent,index=callback.parameters.indexOf(declaration),origins=[];
57
- for(const call of calls) {
58
- if(fn(canonical(call.expression))===callback&&call.arguments[index])origins.push(childOrigins(call.arguments[index],seen));
59
- const operation=uiOperation(call.expression,checker);
60
- const childrenCall=["Children.map","Children.forEach"].includes(operation)&&call.arguments[1]&&(call.arguments[1]===callback||fn(canonical(call.arguments[1]))===callback);
61
- const arrayCall=ts.isPropertyAccessExpression(call.expression)&&["map","forEach","flatMap"].includes(call.expression.name.text)&&call.arguments[0]&&(call.arguments[0]===callback||fn(canonical(call.arguments[0]))===callback);
62
- if(index===0&&(childrenCall&&childOrigins(call.arguments[0],seen).size||arrayCall&&childOrigins(call.expression.expression,seen).size))origins.push(new Set([key(declaration)]));
63
- }
64
- return merge(origins);
65
- }
66
- if(ts.isCallExpression(expression)) {
67
- if(["Children.toArray","toChildArray"].includes(uiOperation(expression.expression,checker)))return childOrigins(expression.arguments[0],seen);
68
- if(ts.isPropertyAccessExpression(expression.expression)&&["filter","slice"].includes(expression.expression.name.text))return childOrigins(expression.expression.expression,seen);
69
- }
70
- return new Set();
45
+ const proofId=`${part.api.identity}@${part.consumer.identity}`;
46
+ if(partProofs.has(proofId)) {
47
+ if(partProofs.get(proofId))result.parts.push({...part,unit:contract.unit,file:contract.file});
48
+ continue;
71
49
  }
50
+ const consumer=fn(implementationNode(program,part.consumer,options.root));
51
+ const bodies=[...new Set(localCalls(consumer))],calls=[...new Set(bodies.flatMap(body=>all(body,ts.isCallExpression)))];
52
+ const childOrigins=createChildFlow({consumer,calls,bodies,canonical,key,checker});
72
53
  const propOrigins=new Set(bodies.flatMap(body=>all(body,ts.isPropertyAccessExpression).filter(node=>node.name.text==="props").flatMap(node=>[...childOrigins(node.expression)])));
73
54
  const readsProps=expression=>[...childOrigins(expression)].some(origin=>propOrigins.has(origin));
74
55
  let consumed=false;
@@ -88,13 +69,15 @@ export function inspectRuntimeContracts(options, program) {
88
69
  }
89
70
  }
90
71
  }
72
+ partProofs.set(proofId,!!consumer&&consumed);
91
73
  if(!consumer||!consumed)report(contract,`${part.apiName}: cannot establish that ${part.consumer.symbol} identifies this declarative child from its children input by resolved symbol and reads that same child's props. A registration, decoy object, import or unused reference is not consumption.`,"declarative-consumer");
92
74
  else result.parts.push({...part,unit:contract.unit,file:contract.file});
93
75
  }
94
76
  for(const [name,binding]of Object.entries(contract.bindings??{})) {
95
77
  const producer=fn(implementationNode(program,binding.producer,options.root));
96
78
  const [prefix,suffix]=binding.variable.split("${key}");
97
- if(!(contract.paintInputs??[]).some(input=>input.api.identity===binding.input.api.identity&&input.property===`${binding.input.property}.*.${binding.valueFrom}`)) {report(contract,`${name}: register the actual config-entry value path as a constrained paint input. A producer does not authorize untyped config colours.`,"binding-input");continue;}
79
+ const valuePaths=typeof binding.valueFrom==="string"?[binding.valueFrom]:binding.valueFrom;
80
+ if(valuePaths.some(field=>!(contract.paintInputs??[]).some(input=>input.api.identity===binding.input.api.identity&&input.property===`${binding.input.property}.*.${field}`))) {report(contract,`${name}: register every valueFrom config-entry path as a constrained paint input. A producer does not authorize untyped config colours.`,"binding-input");continue;}
98
81
  if([...tokenContract.naming.prefixes,"--ds-","--ux-","--showcase-"].some(value=>value.startsWith(prefix)||prefix.startsWith(value))||[...tokenContract.naming.names,...Object.keys(tokenContract.tokens)].some(value=>value.startsWith(prefix)&&value.endsWith(suffix))) {
99
82
  report(contract,`${name}: runtime family ${binding.variable} overlaps the shared token vocabulary. Use a nonconflicting private runtime family; registration cannot grant shared-token overrides.`,"binding-collision");continue;
100
83
  }
@@ -122,8 +105,14 @@ export function inspectRuntimeContracts(options, program) {
122
105
  function pairMatches(template,value,keySymbol,valueSymbol) {
123
106
  template=unwrap(template);value=unwrap(value);
124
107
  if(!template||!ts.isTemplateExpression(template)||template.templateSpans.length!==1||template.head.text!==prefix||template.templateSpans[0].literal.text!==suffix||checker.getSymbolAtLocation(template.templateSpans[0].expression)!==keySymbol)return false;
125
- let valueRoot=value;const fields=[];while(ts.isPropertyAccessExpression(valueRoot)){fields.unshift(valueRoot.name.text);valueRoot=valueRoot.expression;}
126
- return checker.getSymbolAtLocation(valueRoot)===valueSymbol&&fields.join(".")===binding.valueFrom;
108
+ function entryValue(expression) {
109
+ expression=unwrap(expression);const fields=[];while(expression&&ts.isPropertyAccessExpression(expression)){fields.unshift(expression.name.text);expression=unwrap(expression.expression);}
110
+ return expression&&checker.getSymbolAtLocation(expression)===valueSymbol&&valuePaths.includes(fields.join("."));
111
+ }
112
+ if(entryValue(value))return true;
113
+ return ts.isTemplateExpression(value)&&value.head.text==="light-dark("&&value.templateSpans.length===2
114
+ &&/^\s*,\s*$/.test(value.templateSpans[0].literal.text)&&value.templateSpans[1].literal.text===")"
115
+ &&value.templateSpans.every(span=>entryValue(span.expression));
127
116
  }
128
117
  function proveMap(body,seen=new Set()) {
129
118
  if(!body?.parameters?.[0]||!ts.isIdentifier(body.parameters[0].name)||seen.has(body)||seen.size>8)return null;
@@ -163,7 +152,7 @@ export function inspectRuntimeContracts(options, program) {
163
152
  return mapSymbol&&!escapes&&checker.getSymbolAtLocation(returned)===mapSymbol?[body]:null;
164
153
  }
165
154
  const proof=proveMap(producer);
166
- if(!proof){report(contract,`${name}: producer must return only the declared config-entry paint map. Use Object.entries with a loop or Object.fromEntries/map, guard keys with /^[A-Za-z0-9_-]+$/ before writing (throw or continue), and the exact computed family. Owner-local helper returns are supported; escaped maps, extra writes and unknown returns grant no permission.`,"binding-producer");continue;}
155
+ if(!proof){report(contract,`${name}: producer must return only the declared config-entry paint map. Declare every source path in valueFrom (one path or an array), with matching paintInputs; theme pairs may use an exact light-dark() template over two declared paths. Use Object.entries with a loop or Object.fromEntries/map, guard keys with /^[A-Za-z0-9_-]+$/ before writing (throw or continue), and the exact computed family. Owner-local helper returns are supported; escaped maps, extra writes and unknown returns grant no permission.`,"binding-producer");continue;}
167
156
  const scope=fn(implementationNode(program,binding.scope.api,options.root));
168
157
  let attached=false;
169
158
  const returnedElements=new Set();
@@ -27,10 +27,12 @@ export function createScenarioTrace(program, options) {
27
27
  return false;
28
28
  }
29
29
  const isCx = expression => linaria(expression, "cx");
30
- const { state, next, at, resolve, get, arrays, returns, props } = createSourceValues(program, options, { preserveCall: expression => isCx(expression) || uiOperation(expression, checker) === "createElement", strict: true });
30
+ const { state, next, at, resolve, get, arrays, returns, props } = createSourceValues(program, options, { preserveCall: expression => isCx(expression) || uiOperation(expression, checker) === "createElement" || ts.isPropertyAccessExpression(expression)&&["map","flatMap"].includes(expression.name.text), strict: true });
31
31
  const publicNodes = new Map(), helpers = new Map(), inventory = inspectUnits(options);
32
32
  const parts = inspectRuntimeContracts(options, program).parts.map(part => ({ ...part,
33
+ edge: `${part.api.identity}>${part.parent.identity}@${part.consumer.identity}`,
33
34
  apiNode: resolve(reference(implementationNode(program, part.api, options.root)?.name), state()).node,
35
+ parentNode: resolve(reference(implementationNode(program, part.parent, options.root)?.name), state()).node,
34
36
  consumerNode: resolve(reference(implementationNode(program, part.consumer, options.root)?.name), state()).node,
35
37
  }));
36
38
  const locationKey = value => JSON.stringify([value.file, value.line, value.column]);
@@ -66,19 +68,35 @@ export function createScenarioTrace(program, options) {
66
68
  return null;
67
69
  }
68
70
 
69
- function traceRenders(site, { entry = false } = {}) {
71
+ function traceRenders(site, { entry = false, exercise = false } = {}) {
70
72
  const limits = new Set();
71
- function childParts(input, context) {
73
+ const alternatives=exercise?combine:common;
74
+ const initial={...state(),...(exercise?{maxDepth:128,maxSteps:16000}:{})};
75
+ function mapped(value,context,visit) {
76
+ const call=value.node;
77
+ if(!call||!ts.isCallExpression(call)||!ts.isPropertyAccessExpression(call.expression)||!["map","flatMap"].includes(call.expression.name.text))return null;
78
+ const items=arrays(reference(call.expression.expression,value.env,value.via),next(context));
79
+ if(!items?.length)return new Set();
80
+ const callback=resolve(reference(call.arguments[0],value.env,value.via),next(context));
81
+ if(callback.kind!=="node"||!isFunction(callback.node))return new Set();
82
+ return combine(items.slice(0,maxBranches).map((item,index)=>combine(returns(callback,[item,{kind:"literal",value:index}],next(context)).map(output=>visit(output,next(context))))));
83
+ }
84
+ function childParts(input, context, parent = null) {
72
85
  const value = resolve(input, next(context));
73
- if (value.kind === "union") return common(value.values.slice(0, maxBranches).map(item => childParts(item, next(context))));
74
- if (value.kind === "array") return combine(value.values.map(item => childParts(item, next(context))));
86
+ if (value.kind === "union") return alternatives(value.values.slice(0, maxBranches).map(item => childParts(item, next(context),parent)));
87
+ if (value.kind === "array") return combine(value.values.map(item => childParts(item, next(context),parent)));
75
88
  if (value.kind !== "node") return new Set();
76
- if (ts.isJsxExpression(value.node)) return childParts(reference(value.node.expression, value.env, value.via), next(context));
77
- if (ts.isJsxFragment(value.node)) return combine(value.node.children.map(item => childParts(reference(item, value.env, value.via), next(context))));
89
+ const mappedChildren=mapped(value,context,(output,context)=>childParts(output,context,parent));
90
+ if(mappedChildren)return mappedChildren;
91
+ if (ts.isJsxExpression(value.node)) return childParts(reference(value.node.expression, value.env, value.via), next(context),parent);
92
+ if (ts.isJsxFragment(value.node)) return combine(value.node.children.map(item => childParts(reference(item, value.env, value.via), next(context),parent)));
78
93
  const view = element(value.node, value.env, value.via);
79
94
  if (!view) return new Set();
80
95
  const target = resolve(view.tag, next(context));
81
- return new Set([...parts.filter(part => part.apiNode && part.apiNode === target.node).map(part => part.apiName), ...childParts(get(view.attributes, "children", next(context)), next(context))]);
96
+ if(["provider","context"].includes(target.kind))return childParts(get(view.attributes,"children",next(context)),next(context),parent);
97
+ const matched=parts.filter(part=>part.apiNode&&part.apiNode===target.node);
98
+ const edges=matched.filter(part=>parent?part.parentNode===parent:!parts.some(other=>other.apiNode===part.parentNode)).map(part=>part.edge);
99
+ return new Set([...edges,...(matched.length?childParts(get(view.attributes,"children",next(context)),next(context),target.node):[])]);
82
100
  }
83
101
  function render(input, context) {
84
102
  const value = resolve(input, next(context));
@@ -86,10 +104,11 @@ export function createScenarioTrace(program, options) {
86
104
  if (value.kind === "unknown") { if (value.reason) limits.add(value.reason); return new Set(); }
87
105
  if (value.kind === "union") {
88
106
  if (value.values.length > maxBranches) { limits.add("Scenario render tracing reached its alternative limit."); return new Set(); }
89
- return common(value.values.map(item => render(item, next(context))));
107
+ return alternatives(value.values.map(item => render(item, next(context))));
90
108
  }
91
109
  if (value.kind === "array") return combine(value.values.map(item => render(item, next(context))));
92
110
  if (value.kind !== "node") return new Set();
111
+ if(exercise){const mappedChildren=mapped(value,context,render);if(mappedChildren)return mappedChildren;}
93
112
  const { node, env, via } = value;
94
113
  if (ts.isJsxExpression(node)) return render(reference(node.expression, env, via), next(context));
95
114
  if (ts.isJsxFragment(node)) return combine(node.children.map(child => render(reference(child, env, via), next(context))));
@@ -100,21 +119,31 @@ export function createScenarioTrace(program, options) {
100
119
  function component(input) {
101
120
  const target = resolve(input, next(context));
102
121
  if (["provider", "context"].includes(target.kind)) return render(get(view.attributes, "children", next(context)), next(context));
103
- if (target.kind === "union") return target.values.length <= maxBranches ? common(target.values.map(component)) : new Set();
122
+ if (target.kind === "union") return target.values.length <= maxBranches ? alternatives(target.values.map(component)) : new Set();
104
123
  if (target.kind !== "node") return new Set();
105
124
  const names = new Set(publicNodes.get(target.node) ?? []);
106
- for (const part of parts) if (target.node === part.consumerNode && childParts(get(view.attributes, "children", next(context)), next(context)).has(part.apiName)) names.add(`@consumed:${part.apiName}`);
125
+ const children=parts.some(part=>target.node===part.consumerNode)?childParts(get(view.attributes,"children",next(context)),next(context)):new Set();
126
+ for (const part of parts) if (target.node === part.consumerNode && children.has(part.edge)) names.add(`@consumed:${part.edge}`);
107
127
  if (isFunction(target.node) && (entry || !isDevelopmentFile(target.node.getSourceFile().fileName, options) || isReviewFile(target.node.getSourceFile().fileName, options))) {
108
- const outputs = returns(target, [view.attributes], next(context), "component");
109
- for (const name of render(union(outputs), next(context))) names.add(name);
128
+ const sites=context.componentSites??new Set();
129
+ if(sites.has(node))limits.add("Recursive component source site could not be fully traced.");
130
+ else {
131
+ const nested={...next(context),componentSites:new Set([...sites,node])};
132
+ const outputs = returns(target, [view.attributes], nested, "component");
133
+ for (const name of render(union(outputs), nested)) names.add(name);
134
+ }
135
+ }
136
+ for(let pass=0;pass<parts.length;pass++) {
137
+ const count=names.size;
138
+ for (const part of parts) if ((names.has(part.parentName)||names.has(`@exercised:${part.parentName}`)) && names.has(`@consumed:${part.edge}`)) names.add(`@exercised:${part.apiName}`);
139
+ if(names.size===count)break;
110
140
  }
111
- for (const part of parts) if (names.has(part.parentName) && names.has(`@consumed:${part.apiName}`)) names.add(`@exercised:${part.apiName}`);
112
141
  return names;
113
142
  }
114
143
  return component(view.tag);
115
144
  }
116
- const target=entry&&resolve(reference(site),state());
117
- const evidence = target?.kind==="node"&&isFunction(target.node) ? render(union(returns(target,[{kind:"object",layers:[]}],state(),"component")),state()) : render(reference(site), state());
145
+ const target=entry&&resolve(reference(site),initial);
146
+ const evidence = target?.kind==="node"&&isFunction(target.node) ? render(union(returns(target,[{kind:"object",layers:[]}],initial,"component")),initial) : render(reference(site), initial);
118
147
  return { rendered: new Set([...evidence].filter(name => !name.startsWith("@"))), declarative: new Set([...evidence].filter(name => name.startsWith("@exercised:")).map(name => name.slice(11))), limits: [...limits].slice(0, 3) };
119
148
  }
120
149
 
@@ -167,11 +196,11 @@ export function createScenarioTrace(program, options) {
167
196
  if (!ok && !reasons.size) reasons.add("Each nonempty return path needs owned Linaria styles; stable hooks alone are not styling evidence.");
168
197
  return { present: !property || value.kind !== "unknown", ok, reasons: [...reasons].slice(0, 3) };
169
198
  }
170
- function traceEntry(source) {
199
+ function traceEntry(source, {exercise=false}={}) {
171
200
  const module=checker.getSymbolAtLocation(source),symbol=module&&checker.getExportsOfModule(module).find(symbol=>symbol.name==="default");
172
201
  const resolved=symbol?.flags&ts.SymbolFlags.Alias?checker.getAliasedSymbol(symbol):symbol;
173
202
  const declaration=resolved?.valueDeclaration;
174
- return traceRenders(declaration&&(ts.isExportAssignment(declaration)?declaration.expression:declaration.name??declaration),{entry:true});
203
+ return traceRenders(declaration&&(ts.isExportAssignment(declaration)?declaration.expression:declaration.name??declaration),{entry:true,exercise});
175
204
  }
176
205
  return { traceRenders, traceEntry, classValue };
177
206
  }
@@ -282,7 +282,7 @@ export function inspectScenarioCoverage(options, program, report, advise = () =>
282
282
  ts.forEachChild(node, child => visit(child, reached && (ts.isExportAssignment(node) || ts.isVariableDeclaration(node))));
283
283
  }
284
284
  for (const node of source.statements) if (ts.isExportAssignment(node) || node.modifiers?.some(item => item.kind === ts.SyntaxKind.DefaultKeyword)) visit(node, true);
285
- if(parts.some(part=>scenario.exercises?.includes(part.apiName)))for(const name of trace.traceEntry(source).declarative)declarative.add(name);
285
+ if(parts.some(part=>scenario.exercises?.includes(part.apiName)))for(const name of trace.traceEntry(source,{exercise:true}).declarative)declarative.add(name);
286
286
  for (const name of scenario.covers) {
287
287
  if (!rendered.has(name)) report(source.fileName, "scenario-render", `${name} is declared in covers but has no reachable public render reference. Render it directly or through a traced parent with fixture props/defaults selecting that child. Imports, unused JSX and unknown conditional paths do not establish coverage.${renderLimits.size ? ` Source tracing could not establish: ${[...renderLimits].slice(0, 2).join(" ")}` : ""} Review the real scenario in a browser; do not hide a valid public part just to avoid coverage. See ads://guides/scenarios.`);
288
288
  else covered.add(name);
@@ -357,5 +357,6 @@ Source credits and retained MIT terms: [README.md](README.md) and
357
357
  [LICENSE.upstream](LICENSE.upstream).
358
358
 
359
359
  For static owner contracts, `.ads.` development roles, typed paint/binding APIs,
360
- declarative evidence, token privacy and guarded migration, read
360
+ declarative parent graphs, constrained theme bindings, private visual subject roles,
361
+ token privacy and guarded migration, read
361
362
  [contracts.md](references/contracts.md) when the task touches those contracts.
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -184,9 +203,30 @@ export const scenario = {
184
203
  };
185
204
  ```
186
205
 
187
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
188
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
189
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
190
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
191
231
  child or metadata claim gives no consumption credit. Unknown render branches are
192
232
  conservative. Browser checks must verify that adding/removing/changing the part
@@ -524,5 +524,6 @@ A screenshot alone does not prove behavior or animation. Validate public imports
524
524
  CSS/asset resolution, required setup, and local documentation links.
525
525
 
526
526
  For static owner contracts, `.ads.` development roles, typed paint/binding APIs,
527
- declarative evidence, token privacy and guarded migration, read
527
+ declarative parent graphs, constrained theme bindings, private visual subject roles,
528
+ token privacy and guarded migration, read
528
529
  [contracts.md](references/contracts.md) when the task touches those contracts.
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -184,9 +203,30 @@ export const scenario = {
184
203
  };
185
204
  ```
186
205
 
187
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
188
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
189
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
190
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
191
231
  child or metadata claim gives no consumption credit. Unknown render branches are
192
232
  conservative. Browser checks must verify that adding/removing/changing the part
@@ -457,5 +457,6 @@ demo URLs only when running; clean up
457
457
  temporary comparison servers when finished unless the user requested they remain.
458
458
 
459
459
  For static owner contracts, `.ads.` development roles, typed paint/binding APIs,
460
- declarative evidence, token privacy and guarded migration, read
460
+ declarative parent graphs, constrained theme bindings, private visual subject roles,
461
+ token privacy and guarded migration, read
461
462
  [contracts.md](references/contracts.md) when the task touches those contracts.
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -184,9 +203,30 @@ export const scenario = {
184
203
  };
185
204
  ```
186
205
 
187
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
188
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
189
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
190
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
191
231
  child or metadata claim gives no consumption credit. Unknown render branches are
192
232
  conservative. Browser checks must verify that adding/removing/changing the part
@@ -414,5 +414,6 @@ upstream reference. Keep comparison dependencies and downloaded source outside
414
414
  the production dependency graph unless the user chose otherwise.
415
415
 
416
416
  For static owner contracts, `.ads.` development roles, typed paint/binding APIs,
417
- declarative evidence, token privacy and guarded migration, read
417
+ declarative parent graphs, constrained theme bindings, private visual subject roles,
418
+ token privacy and guarded migration, read
418
419
  [contracts.md](references/contracts.md) when the task touches those contracts.
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -184,9 +203,30 @@ export const scenario = {
184
203
  };
185
204
  ```
186
205
 
187
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
188
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
189
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
190
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
191
231
  child or metadata claim gives no consumption credit. Unknown render branches are
192
232
  conservative. Browser checks must verify that adding/removing/changing the part
@@ -339,5 +339,6 @@ This workflow adapts Emil Kowalski's animation skills. See
339
339
  [README.md](README.md) and [LICENSE.upstream](LICENSE.upstream) for provenance.
340
340
 
341
341
  For static owner contracts, `.ads.` development roles, typed paint/binding APIs,
342
- declarative evidence, token privacy and guarded migration, read
342
+ declarative parent graphs, constrained theme bindings, private visual subject roles,
343
+ token privacy and guarded migration, read
343
344
  [contracts.md](references/contracts.md) when the task touches those contracts.
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -184,9 +203,30 @@ export const scenario = {
184
203
  };
185
204
  ```
186
205
 
187
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
188
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
189
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
190
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
191
231
  child or metadata claim gives no consumption credit. Unknown render branches are
192
232
  conservative. Browser checks must verify that adding/removing/changing the part
@@ -53,7 +53,7 @@ export function createSourceValues(program, options, { preserveCall = () => fals
53
53
  }
54
54
  const state = () => ({ budget: { steps: 0 }, depth: 0, calls: new Set() });
55
55
  function next(context) { return { ...context, depth: context.depth + 1 }; }
56
- function exhausted(context) { return ++context.budget.steps > 4000 || context.depth > 48; }
56
+ function exhausted(context) { return ++context.budget.steps > (context.maxSteps??4000) || context.depth > (context.maxDepth??48); }
57
57
  function at(node, kind, name) {
58
58
  const source = node.getSourceFile(), position = source.getLineAndCharacterOfPosition(node.getStart(source));
59
59
  return { file: source.fileName, line: position.line + 1, column: position.character + 1, kind, name: name.slice(0, 100) };
@@ -137,10 +137,10 @@ export function createSourceValues(program, options, { preserveCall = () => fals
137
137
  return [];
138
138
  }
139
139
  function returns(fn, args, context, kind = "helper") {
140
- if (context.calls.has(fn.node)) return [unknown("Recursive local call could not be fully traced.")];
140
+ if (kind!=="component"&&context.calls.has(fn.node)) return [unknown("Recursive local call could not be fully traced.")];
141
141
  if (!fn.node.body || fn.node.asteriskToken || fn.node.modifiers?.some(item => item.kind === ts.SyntaxKind.AsyncKeyword)) return [unknown("Async, generator or declaration-only calls are outside atomic source tracing.")];
142
142
  const env = new Map(fn.env), via = [...fn.via, at(fn.node, kind, fn.node.name?.getText() ?? "local function")];
143
- const inner = { ...next(context), calls: new Set([...context.calls, fn.node]) };
143
+ const inner = { ...next(context), calls: new Set(kind==="component"?[fn.node]:[...context.calls, fn.node]) };
144
144
  for (const [index, parameter] of fn.node.parameters.entries()) {
145
145
  if (parameter.dotDotDotToken) { bind(parameter.name, { kind: "array", values: args.slice(index) }, env, via, inner); break; }
146
146
  bind(parameter.name, withDefault(resolve(args[index] ?? literal(undefined), inner), parameter.initializer && reference(parameter.initializer, env, via), inner), env, via, inner);
@@ -13,7 +13,7 @@ const id = z.string().regex(/^[A-Za-z0-9][\w.-]{0,99}$/);
13
13
  const checks = z.array(id).min(1).max(100);
14
14
  const field = z.string().regex(/^[A-Za-z_$][\w$]*(?:\.(?:[A-Za-z_$][\w$]*|\*))*$/).max(200);
15
15
  const paint = z.object({ api: ref, property: field, kind: z.literal("paint-reference"), bindings: z.array(id).max(20).optional() }).strict();
16
- const binding = z.object({ input: z.object({ api: ref, property: field }).strict(), producer: ref, valueFrom: field,
16
+ const binding = z.object({ input: z.object({ api: ref, property: field }).strict(), producer: ref, valueFrom: z.union([field,z.array(field).min(1).max(12).refine(paths=>new Set(paths).size===paths.length,"Value paths must be distinct.")]),
17
17
  variable: z.string().regex(/^--[a-z][\w-]*\$\{key\}[\w-]*$/), scope: z.object({ api: ref, selector: z.string().min(1).max(200) }).strict(), checks }).strict();
18
18
  const part = z.object({ api: ref, parent: ref, consumer: ref, checks }).strict();
19
19
  const schema = z.object({ schemaVersion: z.literal(1),
@@ -165,12 +165,31 @@ export function inspectUnitContracts(options) {
165
165
  if (entry.apiName !== entry.scope.apiName) report("The binding input and attachment scope must belong to the same public API.", `bindings.${name}`);
166
166
  }
167
167
  for (const [index, entry] of (data.declarativeParts ?? []).entries()) {
168
- if(data.declarativeParts.slice(0,index).some(prior=>prior.api.identity===entry.api.identity))report("A declarative API needs one unambiguous parent/consumer relationship.",`declarativeParts.${index}`);
168
+ if(data.declarativeParts.slice(0,index).some(prior=>prior.api.identity===entry.api.identity&&prior.parent.identity===entry.parent.identity))report("Duplicate declarative parent relationship: each API/parent pair has one consumer and check registration.",`declarativeParts.${index}`);
169
169
  entry.apiName = apiName(entry.api, `declarativeParts.${index}.api`);
170
170
  entry.parentName = apiName(entry.parent, `declarativeParts.${index}.parent`);
171
- if(!publicByIdentity.get(entry.parent.identity)?.renderable)report("Declarative parents require a real public rendering API.",`declarativeParts.${index}.parent`);
172
171
  implementation(entry.consumer, `declarativeParts.${index}.consumer`);
173
172
  }
173
+ const parts=data.declarativeParts??[];
174
+ const rootCache=new Map(),cycleCache=new Map();
175
+ function roots(reference,seen=new Set()) {
176
+ if(seen.has(reference.identity))return [];
177
+ if(rootCache.has(reference.identity))return rootCache.get(reference.identity);
178
+ const parents=parts.filter(part=>part.api.identity===reference.identity);
179
+ if(!parents.length)return publicByIdentity.get(reference.identity)?.renderable?[publicByIdentity.get(reference.identity).name]:[];
180
+ const names=[...new Set(parents.flatMap(part=>roots(part.parent,new Set([...seen,reference.identity]))))];rootCache.set(reference.identity,names);return names;
181
+ }
182
+ function cyclic(reference,seen=new Set()) {
183
+ if(seen.has(reference.identity))return true;
184
+ if(cycleCache.has(reference.identity))return cycleCache.get(reference.identity);
185
+ const found=parts.filter(part=>part.api.identity===reference.identity).some(part=>cyclic(part.parent,new Set([...seen,reference.identity])));
186
+ cycleCache.set(reference.identity,found);return found;
187
+ }
188
+ for(const [index,entry]of parts.entries()) {
189
+ entry.rootNames=roots(entry.parent);
190
+ if(cyclic(entry.parent))report("Declarative parent relationships must be acyclic.",`declarativeParts.${index}.parent`);
191
+ if(!entry.rootNames.length)report("A declarative parent must reach a real public rendering API through registered parent relationships.",`declarativeParts.${index}.parent`);
192
+ }
174
193
  let behavior;
175
194
  if (data.behavior) {
176
195
  if(Object.hasOwn(data.behavior,"schemaVersion"))report("Behavior inherits the owner contract's schemaVersion; remove the competing nested version.","behavior.schemaVersion");
@@ -179,7 +198,7 @@ export function inspectUnitContracts(options) {
179
198
  if (subject?.api && identities.has(subject.api)) return [name, { api: apiName(subject.api, `behavior.subjects.${name}.api`) ?? "" }];
180
199
  if (subject?.implementation && identities.has(subject.implementation)) {
181
200
  implementation(subject.implementation, `behavior.subjects.${name}.implementation`);
182
- return [name, { source: `./${slash(path.relative(path.dirname(file), path.resolve(options.root, subject.implementation.source)))}`, symbol: subject.implementation.symbol }];
201
+ return [name, { source: `./${slash(path.relative(path.dirname(file), path.resolve(options.root, subject.implementation.source)))}`, symbol: subject.implementation.symbol, ...(subject.role!==undefined?{role:subject.role}:{}) }];
183
202
  }
184
203
  report("Behavior subjects must use an actual public api or owner-local implementation symbol.", `behavior.subjects.${name}`);
185
204
  return [name, subject];
@@ -591,6 +591,11 @@ Owner-local tooling declarations use optional `<Owner>.ads.contract.ts` modules.
591
591
  ADS resolves their data and implementation symbols statically without executing
592
592
  project imports. Tokens and behavior share this contract with constrained paint
593
593
  inputs, instance binding families and declarative parent/consumer relationships.
594
+ Declarative relationships form an acyclic graph: parts may have several parents
595
+ and contain nested parts, with every chain anchored at a rendering root. Exercise
596
+ metadata records reachable use; registered browser checks establish its effects.
597
+ Binding producers declare each direct/derived paint path explicitly. Private
598
+ visual implementation subjects are distinct from headless controller subjects.
594
599
  Legacy JSON sections remain supported; duplicate policies fail. The
595
600
  [contract reference](CONTRACTS.md) specifies the authoring and analysis limits.
596
601
 
package/docs/BEHAVIORS.md CHANGED
@@ -80,6 +80,14 @@ subjects and checks. Each check names an owner-local test/spec file, stable case
80
80
  ID, registered profile and optional discovered scenario. Several guarantees may
81
81
  reference one check. Repeated execution identities use the same check ID.
82
82
 
83
+ Private subjects default to the headless controller role. For an intentionally
84
+ visual internal renderer or binding producer, declare `role: "implementation"`
85
+ alongside its `implementation` reference in the TypeScript contract (or its
86
+ `source`/`symbol` in legacy JSON). Its source ownership and normal runtime gates
87
+ still apply; registration does not make it public API. Shared `controllers/`
88
+ source remains headless regardless of subject metadata. See the
89
+ [owner contract](CONTRACTS.md#a-contract-uses-actual-implementation-references).
90
+
83
91
  Static validation establishes registration and ownership, not that the guarantee
84
92
  is true. README prose is not automatically certified. Link specific guarantees
85
93
  when describing the evidence available for a behavior.
package/docs/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.3.25
6
+
7
+ - Support source-proven shared/nested declarative parts, with acyclic parent
8
+ graphs anchored to rendering roots and bounded multi-relationship discovery.
9
+ - Trace recursive child flattening, selections, props records, mapped fixtures
10
+ and repeated review layout instances without changing render coverage.
11
+ - Prove derived theme binding maps from explicit constrained `valueFrom` paths;
12
+ retain key/map/scope checks and current browser paint audits.
13
+ - Distinguish private visual behavior subjects with explicit implementation roles
14
+ while preserving headless defaults, shared-controller gates and migration.
15
+
5
16
  ## 0.3.24
6
17
 
7
18
  - Audit derived `light-dark()` bindings when both branches are accessible
package/docs/CONTRACTS.md CHANGED
@@ -75,7 +75,7 @@ export default {
75
75
  { api: Series, parent: Plot, consumer: Renderer, checks: ["isolation"] },
76
76
  ],
77
77
  behavior: {
78
- subjects: { plot: { api: Plot }, renderer: { implementation: Renderer } },
78
+ subjects: { plot: { api: Plot }, renderer: { implementation: Renderer, role: "implementation" } },
79
79
  guarantees: [{
80
80
  id: "scoped-output",
81
81
  description: "Changing either instance updates only its own output.",
@@ -97,7 +97,13 @@ Symbol references resolve through normal imports, aliases and re-exports.
97
97
  Calls, getters, methods, computed metadata and environment-dependent expressions
98
98
  are rejected. Function references are opaque identities, never executed.
99
99
  Private implementation subjects may be internal module exports without becoming
100
- public barrel exports. Producers/consumers must belong to the same owner. Required
100
+ public barrel exports. Private subjects default to the existing headless controller
101
+ contract. Use `role: "controller"` explicitly for behavior-only code, or
102
+ `role: "implementation"` for a private visual renderer or binding producer whose
103
+ guarantees should be tracked without classifying it as a controller. Shared
104
+ `controllers/` source always remains headless. An implementation role retains
105
+ normal ownership, dependency, styling and development boundaries; it is not a
106
+ style exception. Producers/consumers must belong to the same owner. Required
101
107
  checks must exist, back named guarantees and use a browser profile with the
102
108
  corresponding scenario. A relationship is registration, not a passing guarantee.
103
109
 
@@ -145,6 +151,19 @@ it does not authorize arbitrary inline styling, CSSProperties APIs or bulk write
145
151
  Unsupported dynamic producers/attachment paths fail with an analysis diagnostic.
146
152
  Keep the implementation project-owned; there is no required ADS binding helper.
147
153
 
154
+ A producer with alternative/derived sources declares each entry path, for example:
155
+
156
+ ```ts
157
+ valueFrom: ["paint", "scheme.day", "scheme.night"],
158
+ ```
159
+
160
+ Register each matching `config.*.<path>` in `paintInputs`. The producer may write
161
+ one declared field, or an exact `light-dark(${entry.scheme.day}, ${entry.scheme.night})`
162
+ template over two declared fields. The normal key/map/root proof still applies.
163
+ Raw constants, undeclared fields, extra writes and unknown transforms are rejected.
164
+ The browser audit checks actual accessible color references in both branches;
165
+ a local SVG URL or `none` is not a CSS color inside `light-dark()`.
166
+
148
167
  Families cannot overlap shared tokens, owner-token namespaces, private runtime
149
168
  prefixes or other bindings. A broad family such as `--color-${key}` grants no
150
169
  shared-token exception. Use a distinct private family where collision freedom
@@ -152,6 +171,13 @@ cannot be established. Registered paint consumers list their allowed binding IDs
152
171
  borrowing a peer's family or private token remains invalid. Bindings are scoped
153
172
  to their actual root; portals outside it need deliberate project integration.
154
173
 
174
+ A registered binding producer may combine two accessible color references as
175
+ `light-dark(var(--light-token), var(--dark-token))`. The App paint audit checks
176
+ both branches and their observed effect in the active color scheme. Raw colors,
177
+ unknown/private tokens and SVG URLs inside this color function remain invalid.
178
+ This derived binding form does not widen public paint-input types; use constrained
179
+ references for each theme input and verify both color schemes in browser checks.
180
+
155
181
  The App audit checks current mounted instances, accessible values, local SVG
156
182
  resources and computed paint-property responses. Visibility and complete rendered
157
183
  output still need assertions in the registered browser checks. It rejects missing/duplicate IDs and reports unobserved written values separately. It is bounded to 100 families, 20 instances per family, 100 keys
@@ -177,9 +203,30 @@ export const scenario = {
177
203
  };
178
204
  ```
179
205
 
180
- The real part must reach its registered consumer through a rendered parent.
206
+ A part may register several distinct parents; each API/parent pair has one
207
+ consumer/check declaration. A parent may itself be a registered declarative part.
208
+ The graph must be acyclic and every parent chain must reach a public rendering
209
+ root. Duplicate pairs, cycles and detached part graphs fail.
210
+
211
+ For example, `Entry` can belong to `FirstView` and `SecondView`, while `Detail`
212
+ belongs to `Entry`. The scenario covers the rendering roots and exercises both
213
+ `Entry` and `Detail`. A nested `Detail` outside its registered parent does not count.
214
+
215
+ The real part must reach its registered consumer through a rendering parent.
181
216
  ADS resolves source identity comparisons (`child.type === Series`, including a
182
217
  traceable comparison helper) and reads of that same child’s props traced from the consumer’s children input.
218
+ Traceable paths include local recursive fragment flattening, `find`/`filter`,
219
+ callback aliases and props carried through local records. Reusing a review layout
220
+ inside another instance of itself is ordinary component composition, not a
221
+ recursive helper call. Source sites/work limits still bound analysis.
222
+
223
+ `exercises` establishes reachable behavioral use, including a conditional state
224
+ and mapped literal fixture data; it does not promise unconditional initial DOM.
225
+ Always-false branches, unused adapters, empty/unknown fixture maps and broken
226
+ parent chains grant no credit. `covers` retains its rendering contract. Required
227
+ browser checks cover a rendering root and exercise the relevant parent/child
228
+ chain, then verify adding/removing/updating the part changes actual output.
229
+
183
230
  A comparison against a decoy object gives no evidence. An import, unrelated parent, unused
184
231
  child or metadata claim gives no consumption credit. Unknown render branches are
185
232
  conservative. Browser checks must verify that adding/removing/changing the part
package/docs/MCP.md CHANGED
@@ -1077,7 +1077,9 @@ Tool updates do not overwrite existing project-owned scenarios or renderers.
1077
1077
 
1078
1078
  `ads_units` includes `contractFile` for a single `<Owner>.ads.contract.ts`.
1079
1079
  `ads_catalog` identifies declarative APIs and their parent/consumer/check links,
1080
- and registered constrained paint-input paths. Read the relevant source range;
1080
+ and registered constrained paint-input paths. Declarative summaries include
1081
+ `consumerCount` and up to four `consumers`, with their rendering roots; read the
1082
+ contract source for additional relationships. Read the relevant source range;
1081
1083
  these summaries establish registration, not completed verification. Detailed
1082
1084
  results remain bounded and paged.
1083
1085
 
@@ -1094,3 +1096,10 @@ both branches and their observed effect in the active color scheme. Raw colors,
1094
1096
  unknown/private tokens and SVG URLs inside this color function remain invalid.
1095
1097
  This derived binding form does not widen public paint-input types; use constrained
1096
1098
  references for each theme input and verify both color schemes in browser checks.
1099
+
1100
+ Binding `valueFrom` accepts one path or an explicit array of registered entry
1101
+ paths for alternative/theme paints. Parts can have multiple distinct parents and
1102
+ registered nested parents, anchored at rendering roots. `exercises` records
1103
+ reachable use; registered browser checks establish the effects. Private visual
1104
+ behavior subjects use explicit `role: "implementation"`; headless defaults and
1105
+ shared-controller gates remain enabled. See [CONTRACTS.md](CONTRACTS.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reqvire-org/ads",
3
- "version": "0.3.24",
3
+ "version": "0.3.25",
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": {