@reqvire-org/ads 0.3.24 → 0.3.26
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 +7 -5
- package/dist/behaviors.mjs +6 -4
- package/dist/bootstrap-ds/ADS.md +28 -30
- package/dist/bootstrap-ds/README.md +6 -6
- package/dist/bootstrap-ds/design-system/assets/brand/README.md +3 -2
- package/dist/boundaries.mjs +0 -3
- package/dist/check.mjs +15 -22
- package/dist/config.mjs +3 -7
- package/dist/contract-migration.mjs +3 -3
- package/dist/contracts.d.mts +2 -3
- package/dist/declarative-flow.mjs +144 -0
- package/dist/design-values.mjs +81 -0
- package/dist/evidence.mjs +1 -1
- package/dist/mcp/catalog.mjs +4 -2
- package/dist/mcp/context.mjs +3 -3
- package/dist/mcp/prompts.mjs +4 -4
- package/dist/mcp/reports.mjs +101 -0
- package/dist/mcp/server.mjs +38 -3
- package/dist/paint-contracts.mjs +4 -5
- package/dist/preview-resources.mjs +1 -2
- package/dist/runtime-contracts.mjs +26 -37
- package/dist/scenario-trace.mjs +47 -18
- package/dist/scenarios.mjs +15 -15
- package/dist/skills/README.md +7 -3
- package/dist/skills/ads-break-ui/SKILL.md +24 -13
- package/dist/skills/ads-break-ui/references/atomic-styles.md +9 -2
- package/dist/skills/ads-break-ui/references/behaviors.md +393 -0
- package/dist/skills/ads-break-ui/references/captures.md +1 -1
- package/dist/skills/ads-break-ui/references/contracts.md +61 -40
- package/dist/skills/ads-break-ui/references/design-data.md +91 -0
- package/dist/skills/ads-break-ui/references/evidence.md +4 -0
- package/dist/skills/ads-break-ui/references/guarded-editing.md +7 -11
- package/dist/skills/ads-break-ui/references/reporting.md +101 -0
- package/dist/skills/ads-break-ui/references/scenarios.md +9 -15
- package/dist/skills/ads-designer/SKILL.md +26 -15
- package/dist/skills/ads-designer/assets/bootstrap-ds/ADS.md +28 -30
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +6 -6
- package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/README.md +3 -2
- package/dist/skills/ads-designer/references/atomic-styles.md +9 -2
- package/dist/skills/ads-designer/references/behaviors.md +393 -0
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/contracts.md +61 -40
- package/dist/skills/ads-designer/references/design-craft.md +1 -1
- package/dist/skills/ads-designer/references/design-data.md +91 -0
- package/dist/skills/ads-designer/references/evidence.md +4 -0
- package/dist/skills/ads-designer/references/guarded-editing.md +7 -11
- package/dist/skills/ads-designer/references/mobile.md +1 -1
- package/dist/skills/ads-designer/references/reporting.md +101 -0
- package/dist/skills/ads-designer/references/scenarios.md +9 -15
- package/dist/skills/ads-import/SKILL.md +29 -17
- package/dist/skills/ads-import/references/atomic-styles.md +9 -2
- package/dist/skills/ads-import/references/behaviors.md +393 -0
- package/dist/skills/ads-import/references/branding.md +1 -1
- package/dist/skills/ads-import/references/captures.md +1 -1
- package/dist/skills/ads-import/references/contracts.md +61 -40
- package/dist/skills/ads-import/references/design-data.md +91 -0
- package/dist/skills/ads-import/references/evidence.md +4 -0
- package/dist/skills/ads-import/references/guarded-editing.md +7 -11
- package/dist/skills/ads-import/references/implementation.md +3 -2
- package/dist/skills/ads-import/references/reporting.md +101 -0
- package/dist/skills/ads-import/references/scenarios.md +9 -15
- package/dist/skills/ads-import/references/tokens.md +11 -9
- package/dist/skills/ads-motion/SKILL.md +23 -12
- package/dist/skills/ads-motion/references/atomic-styles.md +9 -2
- package/dist/skills/ads-motion/references/behaviors.md +393 -0
- package/dist/skills/ads-motion/references/captures.md +1 -1
- package/dist/skills/ads-motion/references/contracts.md +61 -40
- package/dist/skills/ads-motion/references/design-data.md +91 -0
- package/dist/skills/ads-motion/references/evidence.md +4 -0
- package/dist/skills/ads-motion/references/guarded-editing.md +7 -11
- package/dist/skills/ads-motion/references/reporting.md +101 -0
- package/dist/skills/ads-motion/references/scenarios.md +9 -15
- package/dist/skills/{ads-migrate → ads-port}/SKILL.md +59 -31
- package/dist/skills/ads-port/agents/openai.yaml +4 -0
- package/dist/skills/{ads-migrate → ads-port}/references/atomic-styles.md +9 -2
- package/dist/skills/ads-port/references/behaviors.md +393 -0
- package/dist/skills/{ads-migrate → ads-port}/references/captures.md +1 -1
- package/dist/skills/{ads-migrate → ads-port}/references/contracts.md +61 -40
- package/dist/skills/ads-port/references/design-data.md +91 -0
- package/dist/skills/{ads-migrate → ads-port}/references/evidence.md +4 -0
- package/dist/skills/{ads-migrate → ads-port}/references/guarded-editing.md +7 -11
- package/dist/skills/{ads-migrate → ads-port}/references/lint-and-docs.md +5 -0
- package/dist/skills/{ads-migrate → ads-port}/references/native-implementation.md +49 -15
- package/dist/skills/ads-port/references/reporting.md +101 -0
- package/dist/skills/{ads-migrate → ads-port}/references/scenarios.md +9 -15
- package/dist/skills/{ads-migrate → ads-port}/references/testing.md +11 -1
- package/dist/source-values.mjs +3 -3
- package/dist/tokens.mjs +5 -8
- package/dist/unit-contracts.mjs +24 -12
- package/docs/ADS.md +42 -73
- package/docs/ARCHITECTURE.md +54 -20
- package/docs/BEHAVIORS.md +46 -36
- package/docs/CHANGELOG.md +34 -0
- package/docs/CONTRACTS.md +67 -39
- package/docs/GUIDE.md +21 -13
- package/docs/MCP.md +67 -11
- package/package.json +1 -1
- package/dist/scoped-tokens.mjs +0 -68
- package/dist/skills/ads-migrate/agents/openai.yaml +0 -4
- /package/dist/skills/{ads-migrate → ads-port}/references/cli.md +0 -0
- /package/dist/skills/{ads-migrate → ads-port}/references/layers.md +0 -0
- /package/dist/skills/{ads-migrate → ads-port}/references/review.md +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { lexer, parse, generate } from "css-tree";
|
|
3
|
+
import valueParser from "postcss-value-parser";
|
|
4
|
+
import { isInside } from "./config.mjs";
|
|
5
|
+
import { createSourceValues, reference } from "./source-values.mjs";
|
|
6
|
+
|
|
7
|
+
const colorCache = new Map();
|
|
8
|
+
export function isColorKeyword(value) {
|
|
9
|
+
if (!/^[a-z]+$/i.test(value) || /^(?:currentcolor|transparent|none|inherit|initial|unset|revert)$/i.test(value)) return false;
|
|
10
|
+
const key=value.toLowerCase();
|
|
11
|
+
if(!colorCache.has(key))colorCache.set(key,!!lexer.matchType("color",key).matched);
|
|
12
|
+
return colorCache.get(key);
|
|
13
|
+
}
|
|
14
|
+
const refs = value => {
|
|
15
|
+
const names=[];
|
|
16
|
+
valueParser(value).walk(node=>{if(node.type==="function"&&node.value==="var"){const name=node.nodes.find(child=>child.type==="word")?.value;if(name?.startsWith("--"))names.push(name);}});
|
|
17
|
+
return names;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Resolve static interpolations through imports/local helpers; never execute project code. */
|
|
21
|
+
export function createDesignValues(program, options) {
|
|
22
|
+
const values=createSourceValues(program,options);
|
|
23
|
+
function strings(input, context=values.state()) {
|
|
24
|
+
const value=values.resolve(input,context);
|
|
25
|
+
if(value.kind==="literal")return ["string","number"].includes(typeof value.value)?[String(value.value)]:[];
|
|
26
|
+
if(value.kind==="union")return value.values.slice(0,16).flatMap(item=>strings(item,values.next(context)));
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
return expression => [...new Set(strings(reference(expression)))];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Variable names cannot conceal the typography/layering role of their consumer. */
|
|
33
|
+
export function inspectDesignAliases(styles, options, report) {
|
|
34
|
+
const declarations=[], roles=new Map(), protectedProperties=new Set(["font-family","font-weight","z-index"]);
|
|
35
|
+
const add=(name,role)=>{if(!roles.has(name))roles.set(name,new Set());const before=roles.get(name).size;roles.get(name).add(role);return roles.get(name).size!==before;};
|
|
36
|
+
for(const entry of styles) {
|
|
37
|
+
if(isInside(path.join(options.dsRoot,options.config.tokenDir),entry.file))continue;
|
|
38
|
+
entry.css.walkDecls(decl=>{
|
|
39
|
+
if(decl.parent.type==="atrule"&&decl.parent.name.toLowerCase()==="property")return;
|
|
40
|
+
declarations.push({...entry,decl});
|
|
41
|
+
if(protectedProperties.has(decl.prop))for(const name of refs(decl.value))add(name,decl.prop);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
// A finite fixed point includes all alias/fallback branches and imported helper styles.
|
|
45
|
+
let changed=true;
|
|
46
|
+
while(changed){changed=false;for(const {decl} of declarations)for(const role of roles.get(decl.prop)??[])for(const name of refs(decl.value))changed=add(name,role)||changed;}
|
|
47
|
+
for(const {file,offset,decl} of declarations) {
|
|
48
|
+
const selected=protectedProperties.has(decl.prop)?new Set([decl.prop]):roles.get(decl.prop);
|
|
49
|
+
if(!selected)continue;
|
|
50
|
+
const nodes=valueParser(decl.value).nodes.filter(node=>!["space","comment"].includes(node.type));
|
|
51
|
+
function allowed(nodes){
|
|
52
|
+
nodes=nodes.filter(node=>!["space","comment"].includes(node.type));
|
|
53
|
+
if(nodes.length!==1)return false;
|
|
54
|
+
const [node]=nodes;
|
|
55
|
+
if(node.type==="word")return /^(?:inherit|initial|unset|revert(?:-layer)?|auto)$/.test(node.value);
|
|
56
|
+
if(node.type!=="function"||node.value!=="var"||node.unclosed)return false;
|
|
57
|
+
const parts=node.nodes.filter(node=>!["space","comment"].includes(node.type));
|
|
58
|
+
return parts[0]?.type==="word"&&/^--[\w-]+$/.test(parts[0].value)&&(parts.length===1||parts[1]?.type==="div"&&parts[1].value===","&&allowed(parts.slice(2)));
|
|
59
|
+
}
|
|
60
|
+
const valid=allowed(nodes);
|
|
61
|
+
if(!valid)report(file,"design-value-source",`${decl.prop} reaches ${[...selected].sort().join("/")}. Map it to shared Data with a token reference; a private variable or raw fallback cannot introduce independent typography/layering values.`,offset.line+decl.source.start.line-1,decl.source.start.column,{guidanceUri:"ads://guides/tokens"});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const canonical=value=>{try{return generate(parse(value,{context:"value"}));}catch{return value.trim();}};
|
|
66
|
+
/** Equal definitions invite review, not an automatic merge of different semantic roles. */
|
|
67
|
+
export function tokenOverlapAdvisories(tokens) {
|
|
68
|
+
const groups=new Map();
|
|
69
|
+
for(const token of tokens) {
|
|
70
|
+
if(token.owner!=="tokens"||!token.definitions.length)continue;
|
|
71
|
+
const definitions=token.definitions.map(({scope,value})=>[scope,canonical(value)]).sort(([a],[b])=>a.localeCompare(b));
|
|
72
|
+
if(definitions.every(([,value])=>/^var\(--[\w-]+\)$/.test(value))||definitions.every(([,value])=>/^(?:0|1|none|auto|inherit|initial|unset|transparent)$/.test(value)))continue;
|
|
73
|
+
const signature=JSON.stringify(definitions);
|
|
74
|
+
if(!groups.has(signature))groups.set(signature,[]);
|
|
75
|
+
groups.get(signature).push(token);
|
|
76
|
+
}
|
|
77
|
+
return [...groups.values()].filter(group=>group.length>1).map(group=>{
|
|
78
|
+
const [first]=group, {file,line,column}=first.definitions[0],names=group.map(token=>token.name);
|
|
79
|
+
return {rule:"token-overlap-review",severity:"warning",file,line,column,tokens:names,guidanceUri:"ads://guides/tokens",message:`Shared Data tokens have identical definitions across their declared theme/condition scopes: ${names.slice(0,6).join(", ")}${names.length>6?` and ${names.length-6} more`:""}. Review semantic roles and consumers before consolidating. Equal values do not prove equivalent purpose; preserve distinct roles or use an explicit shared alias when appropriate.`};
|
|
80
|
+
});
|
|
81
|
+
}
|
package/dist/evidence.mjs
CHANGED
|
@@ -12,7 +12,7 @@ export function acceptance(scope, passed, established, unverified) {
|
|
|
12
12
|
|
|
13
13
|
export function architectureEvidence(result) {
|
|
14
14
|
return { ...result,
|
|
15
|
-
diagnostics: result.diagnostics.map(diagnostic => ({ ...diagnostic, ...(/^(?:unit-contract|paint-.+|binding-.+|declarative-.+|development-role)$/.test(diagnostic.rule)&&!diagnostic.guidanceUri?{guidanceUri:"ads://guides/contracts"}:{}), failure: diagnostic.failure ?? failure("architecture", "source-analysis", diagnostic.rule) })),
|
|
15
|
+
diagnostics: result.diagnostics.map(diagnostic => ({ ...diagnostic, ...(["style-token","design-value-source","token-name","token-ownership"].includes(diagnostic.rule)&&!diagnostic.guidanceUri?{guidanceUri:"ads://guides/tokens"}:{}), ...(/^(?:unit-contract|paint-.+|binding-.+|declarative-.+|development-role)$/.test(diagnostic.rule)&&!diagnostic.guidanceUri?{guidanceUri:"ads://guides/contracts"}:{}), ...(["declarative-consumer","binding-producer","scenario-render","scenario-exercise","showcase-control"].includes(diagnostic.rule)?{reportingGuidanceUri:"ads://guides/reporting"}:{}), failure: diagnostic.failure ?? failure("architecture", "source-analysis", diagnostic.rule) })),
|
|
16
16
|
acceptance: acceptance("core-architecture", result.ok, result.ok ? ["core-source-guards"] : [], ["project-checks", "compiled-preview", "browser-behavior", "visual-parity", "accessibility-audit"]),
|
|
17
17
|
};
|
|
18
18
|
}
|
package/dist/mcp/catalog.mjs
CHANGED
|
@@ -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
|
|
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:
|
|
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
|
}
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { projectGuideFiles } from "../project-documents.mjs";
|
|
|
5
5
|
|
|
6
6
|
export const GUIDE_URI = "ads://project/guide";
|
|
7
7
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
8
|
-
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
8
|
+
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
9
9
|
|
|
10
10
|
function manager(root, pkg) {
|
|
11
11
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
|
@@ -36,7 +36,7 @@ export function workflow(previews) {
|
|
|
36
36
|
next: "Find the requested public UI with ads_catalog (query + kind + small limit), then read its source/guide and one selected ADS skill. For a broad UI request, inspect the public barrel and targeted application entry files in sourceRoot.",
|
|
37
37
|
skills: [
|
|
38
38
|
{ task: "Build, refine or debug UI using the project ADS", name: "ads-designer" },
|
|
39
|
-
{ task: "Adapt a component-library reference", name: "ads-
|
|
39
|
+
{ task: "Adapt a component-library reference", name: "ads-port" },
|
|
40
40
|
{ task: "Import from another project's design-system", name: "ads-import" },
|
|
41
41
|
{ task: "Implement or review motion", name: "ads-motion" },
|
|
42
42
|
{ task: "Stress-test layout, states and interactions", name: "ads-break-ui" },
|
|
@@ -57,7 +57,7 @@ Use this server for UI components/patterns, tokens/themes/branding, layout, inte
|
|
|
57
57
|
3. Select one workflow with ads_skills, then ads_read_skill. ${route.skills.map((skill) => `${skill.task}: ${skill.name}`).join("; ")}. Native skill activation is host-controlled. Relative skill references resolve from its SKILL.md URI. Read support files only when relevant.
|
|
58
58
|
4. ${route.preview} Token samples: ads_scenarios(kind: tokens), then ads_show_scenario or ads_show_tokens(category: id). Token source inspection: ads_tokens with a focused query. Registered previews: ${previews.map((preview) => `${preview.id}: ${preview.tool ?? "ads_show_scenario"}`).join(", ") || "none"}. Showcase URL: ${context.showcase.url ?? "not configured; use the project's showcase command"}.
|
|
59
59
|
Inspection connects a public export to its owning source, available guides, token values and discovered preview IDs. Bounded tools keep discovery focused; explicit resource reads supply detail. Source metadata does not prove layout, interaction or motion. A scenario renders the real public implementation and its fixture context in either review surface.
|
|
60
|
-
5. Check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements; a real selected-owner re-export can remove its redundant export {};. Dry-run to inspect validation; apply only a passing patch. Fix rejected patches in the owning unit; use ads_apply_transaction for coupled owners instead of bypassing rejection with direct writes. ads_prepare_patch creates a local owner draft/diff; ads_prepare_token_samples reconciles explicit project bindings without guessing visual meaning. Intentional project setup, registered guard/compiler code and exceptions use configuration; shared globals use foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Binary/large Git diffs may use patchFile under .ds/patches/ to avoid model-context bytes. In read-only mode, source edits use the client editor/filesystem tools. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
|
|
60
|
+
5. Check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements; a real selected-owner re-export can remove its redundant export {};. Dry-run to inspect validation; apply only a passing patch. Fix rejected patches in the owning unit; use ads_apply_transaction for coupled owners instead of bypassing rejection with direct writes. ads_prepare_patch creates a local owner draft/diff; ads_prepare_token_samples reconciles explicit project bindings without guessing visual meaning. Intentional project setup, registered guard/compiler code and exceptions use configuration; shared globals use foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Binary/large Git diffs may use patchFile under .ds/patches/ to avoid model-context bytes. In read-only mode, source edits use the client editor/filesystem tools. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Shared foundation Data is the only design-value catalogue. Components/patterns map shared roles; independent owner token namespaces and value sheets are rejected. Existing project font, text and spacing roles take precedence over divergent upstream constants. Read ads://guides/tokens for the source contract and overlap review. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
|
|
61
61
|
6. ${route.validation} Registered commands: ${context.commands.map((command) => command.args?.join(" ") ?? `choose the project package manager for ${command.script}`).join("; ") || "none discovered; inspect the project's build setup"}. Run them from ${context.projectRoot}.
|
|
62
62
|
Execution replies from ads_verify and guarded edits contain counts, acceptance and resultId, not full reports. Read only needed outcomes/diagnostics/captures with ads_results, following nextCursor with identical filters. A truncated row has recordIndex for bounded text ranges. For one failure, use ads_investigate with its unit/check/runId; read request/error/artifact sections only when needed. Only the latest verification and mutation results, and latest investigation per check, are available. Notifications do not establish freshness.
|
|
63
63
|
|
package/dist/mcp/prompts.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
export const reasoning = `ADS is development tooling. The project owns its components, patterns, token values and branding.
|
|
2
|
-
Start with ads_status and use its projectRoot, workflow and project commands; the MCP workspace may be nested inside the client repository. If ADS tools are not exposed, read ads://project/guide then ads://project/status. Find existing public UI with ads_catalog and load one relevant ADS workflow via ads_skills/ads_read_skill. UI implementation/refinement uses ads-designer; library adaptation ads-
|
|
3
|
-
When ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements
|
|
4
|
-
Reason through Data (design-token values, semantic roles and relationships), UX (structure, behavior, accessibility, states and layout), and Skin (token-backed identity and visual states). Business data is a separate application-owned input, supplied through typed props or injected callbacks/services. The project uses Linaria extraction for owned styles; MCP adds no production runtime.
|
|
2
|
+
Start with ads_status and use its projectRoot, workflow and project commands; the MCP workspace may be nested inside the client repository. If ADS tools are not exposed, read ads://project/guide then ads://project/status. Find existing public UI with ads_catalog and load one relevant ADS workflow via ads_skills/ads_read_skill. UI implementation/refinement uses ads-designer; library adaptation ads-port; ADS transfer ads-import; motion ads-motion; stress testing ads-break-ui. Domain-model workflows are separate. Inspect the relevant public API, local guide, token definitions and real showcase fixture before proposing changes. Keep source/instruction discovery scoped to the target project, ancestry and selected external sources; broad scans of /mnt or home are not needed to discover this ADS.
|
|
3
|
+
When ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements. A real re-export may replace a redundant export {}; placeholder; do not add empty exports. Token manifests list companionFiles: include required foundation import changes only for canonical token files created/deleted in the same patch, preserving other imports/comments and canonical order. Use dryRun to review validation. Rejected patches leave source unchanged; fix diagnostics rather than bypassing checks with direct writes. Shared globals use foundation; guides use documentation; assets use discovered assets/* units. Intentional configuration, registered project guards/builders and rule exceptions use configuration, which validates the proposed settings and refreshes its compiler. Keep mandatory ADS gates. For large/binary diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; Git binary patches require installed Git. When editing is disabled, use local editing tools.
|
|
4
|
+
Reason through Data (design-token values, semantic roles and relationships), UX (structure, behavior, accessibility, states and layout), and Skin (token-backed identity and visual states). Business data is a separate application-owned input, supplied through typed props or injected callbacks/services. Shared foundation Data is the only design-value catalogue. Components map it with --ds-* and patterns/review with --ux-*; there are no independent owner token namespaces or value sheets. Reuse project font, text and spacing roles when upstream constants differ. Read ads://guides/tokens for source boundaries and duplication review. The project uses Linaria extraction for owned styles; MCP adds no production runtime.
|
|
5
5
|
Choose an existing public component or pattern first. Keep application data/routing/effects in the application and fixture data/state beside its scenario. Change presentation in its owning ADS implementation, then demonstrate the same public API in the showcase. Put demo-only sizing and framing in a development-only review/ helper, exported through the separate review entry rather than the production barrel; add component props for deliberate runtime API needs and preserve required behavior. Do not create a widget-only replica or override component internals.
|
|
6
6
|
For token source inspection, call ads_tokens with a focused query. For token samples, components, patterns and composition, use ads_scenarios to select a path-derived id and invoke ads_show_scenario. Showcase and MCP mount that exact entry and its colocated fixture; no page initialization is required. The showcase is a minimal tool-owned shell plus an MCP client and Apps host. Its menus come from tools; it invokes the same entry tools and refreshes the active scenario through notifications. The reusable App loads framework runtime, foundation CSS, fonts and selected modules via MCP resources inside its sandbox. Keep project execution and styles out of the outer host; preserve mount/unmount cleanup and lazy dependencies. Use the existing ads_status showcase URL, or ads showcase when no MCP runtime is connected. Projects supply scenarios/fixtures and the compiler, not browser page files or another shell. Tool metadata selects an MCP App; a resources/read of HTML alone is not proof of rendered UI. If the host has no Apps view, give the configured showcase URL and use text/resources.
|
|
7
7
|
Check ads_status.previewWatch before launching a separate preview builder. A configured watcher is managed by ads mcp. Check ads_status.build or ads://project/build after changes: running does not mean ready, and unreported freshness is not evidence of current source. Reported preview failures include structured diagnostics; fix the owning source and wait for a successful rebuild, then invoke the preview tool again. Notifications may not reach the agent, so read status explicitly. Build revisions identify reported compilation attempts, not proof of runtime/visual correctness. Do not invent replacement UI to bypass a failed preview.
|
|
8
8
|
Skills: use ads_skills to select a workflow and read its SKILL.md with ads_read_skill. Resolve relative supporting files from that skill URI. Reading instructions does not prove native skill activation or authorize unrelated actions.
|
|
9
|
-
Ask for missing intent only when it changes the outcome. State the proposed behavior, states and difficult content. Preserve lazy loading, workers, caches, cancellation, reduced motion, focus and keyboard behavior. For controllers and hooks, read ads://guides/behaviors. Discover guarantees/checks with ads_behaviors and run ads_verify; read current execution evidence. Keep
|
|
9
|
+
Ask for missing intent only when it changes the outcome. State the proposed behavior, states and difficult content. Preserve lazy loading, workers, caches, cancellation, reduced motion, focus and keyboard behavior. For controllers and hooks, read ads://guides/behaviors. Discover guarantees/checks with ads_behaviors and run ads_verify; read current execution evidence. Keep <Owner>.ads.contract.ts, marked scenarios/fixtures and checks development-only. Use the configured framework and declared dependencies, not MCP host globals. Preserve covers for rendered UI; exercises links behavioral APIs to demonstrations, not passing guarantees. Run ads_check plus the project's registered lint, typecheck, build and relevant tests; inspect the actual browser/rendered app at narrow and wide sizes in both themes. Static success does not establish visual or interaction parity.`;
|
|
10
10
|
|
|
11
11
|
export function promptDefinitions(skills) {
|
|
12
12
|
const prompts = [
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { compactRow, jsonBytes } from "./result-pages.mjs";
|
|
6
|
+
|
|
7
|
+
export const reportLimits = Object.freeze({ recordBytes: 32768 });
|
|
8
|
+
const text = max => z.string().trim().min(1).max(max);
|
|
9
|
+
const identifier = text(256).refine(value => !["\r","\n","\0"].some(character=>value.includes(character)), "Use a single project discovery ID.");
|
|
10
|
+
const evidence = z.union([
|
|
11
|
+
z.object({ resultId: z.string().uuid() }).strict(),
|
|
12
|
+
z.object({ unit: identifier, check: text(100), runId: text(100) }).strict(),
|
|
13
|
+
]);
|
|
14
|
+
const common = { title: text(160), unit: identifier.optional(), scenario: identifier.optional(), reporter: text(100).optional(), evidence: z.array(evidence).max(3).default([]) };
|
|
15
|
+
export const bugReportSchema = z.object({ ...common, expected: text(2000), observed: text(2000), steps: z.array(text(500)).min(1).max(12), frequency: z.enum(["always", "intermittent", "once", "unknown"]), suspectedCause: text(1000).optional() }).strict();
|
|
16
|
+
export const featureRequestSchema = z.object({ ...common, workflow: text(2000), capability: text(2000), impact: text(1000), proposal: text(1500).optional() }).strict();
|
|
17
|
+
const schemas = { bug: bugReportSchema, feature: featureRequestSchema };
|
|
18
|
+
const uuid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
19
|
+
const digest = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
20
|
+
function receipt(record) {
|
|
21
|
+
return { reportId: record.id, revision: record.revision, kind: record.kind, status: "untriaged", classification: "agent-supplied",
|
|
22
|
+
createdAt: record.createdAt, updatedAt: record.updatedAt, submissionCount: record.submissionCount,
|
|
23
|
+
storagePath: `.ds/reports/${record.id}.json`, delivery: "local-only" };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Durable project-local intake with bounded records and delivery. */
|
|
27
|
+
export function createReportStore(root, { context = () => ({}), resolveEvidence = () => { throw new Error("Evidence is unavailable."); } } = {}) {
|
|
28
|
+
root = path.resolve(root);
|
|
29
|
+
const folder = path.join(root, ".ds/reports"), lock = path.join(folder, "write.lock"), cached = new Map();
|
|
30
|
+
function directory(target, create = false) {
|
|
31
|
+
if (create && !existsSync(target)) { try { mkdirSync(target); } catch(error) { if(error.code!=="EEXIST")throw error; } }
|
|
32
|
+
if (realpathSync(target) !== target || !lstatSync(target).isDirectory()) throw new Error("Report storage must use ordinary project directories.");
|
|
33
|
+
}
|
|
34
|
+
function parents(create = false) { directory(root); directory(path.join(root, ".ds"), create); directory(folder, create); }
|
|
35
|
+
function regular(target, max) {
|
|
36
|
+
const stat = lstatSync(target);
|
|
37
|
+
if (realpathSync(target) !== target || !stat.isFile() || stat.nlink !== 1 || stat.size > max) throw new Error("Invalid or oversized report storage file.");
|
|
38
|
+
}
|
|
39
|
+
function files() {
|
|
40
|
+
if (!existsSync(path.join(root, ".ds"))) return [];
|
|
41
|
+
directory(path.join(root, ".ds"));
|
|
42
|
+
if (!existsSync(folder)) return [];
|
|
43
|
+
parents();
|
|
44
|
+
return readdirSync(folder).filter(name => name.endsWith(".json") && uuid(name.slice(0,-5))).sort().map(name => {
|
|
45
|
+
const file=path.join(folder,name),stat=lstatSync(file);
|
|
46
|
+
return {file,id:name.slice(0,-5),stamp:`${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`};
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function readFile(file,id) {
|
|
50
|
+
regular(file,reportLimits.recordBytes);
|
|
51
|
+
const record=JSON.parse(readFileSync(file,"utf8"));
|
|
52
|
+
if(record.schemaVersion!==1||record.id!==id||!uuid(record.revision)||!/^[a-f0-9]{64}$/.test(record.fingerprint)||!Object.hasOwn(schemas,record.kind)||!schemas[record.kind].safeParse(record.submission).success||!Number.isSafeInteger(record.submissionCount)||record.submissionCount<1||!Array.isArray(record.evidence)||!record.context||typeof record.context!=="object"||typeof record.createdAt!=="string"||typeof record.updatedAt!=="string")throw new Error("Invalid saved report; preserve it for recovery rather than overwriting it.");
|
|
53
|
+
return record;
|
|
54
|
+
}
|
|
55
|
+
function headers() {
|
|
56
|
+
const entries=files(),live=new Set(entries.map(entry=>entry.id));
|
|
57
|
+
for(const id of cached.keys())if(!live.has(id))cached.delete(id);
|
|
58
|
+
return entries.map(({file,id,stamp})=>{
|
|
59
|
+
if(cached.get(id)?.stamp!==stamp){const record=readFile(file,id);cached.set(id,{stamp,value:{id,fingerprint:record.fingerprint,createdAt:record.createdAt,submissionCount:record.submissionCount}});}
|
|
60
|
+
return cached.get(id).value;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function acquire() {
|
|
64
|
+
parents(true);
|
|
65
|
+
if (existsSync(lock)) try {
|
|
66
|
+
regular(lock, 512);
|
|
67
|
+
const previous = readFileSync(lock, "utf8"), owner = JSON.parse(previous);
|
|
68
|
+
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || !uuid(owner.nonce)) throw new Error("Invalid report lock; inspect the local store.");
|
|
69
|
+
let gone = false;
|
|
70
|
+
try { process.kill(owner.pid, 0); } catch (error) { if (error.code === "ESRCH") gone = true; }
|
|
71
|
+
if (gone && readFileSync(lock, "utf8") === previous) rmSync(lock);
|
|
72
|
+
}catch(error){if(error instanceof SyntaxError)throw new Error("Report storage is busy or its lock is incomplete. Retry the same submission; inspect a persistent lock.");if(error.code!=="ENOENT")throw error;}
|
|
73
|
+
const token = JSON.stringify({ pid: process.pid, nonce: randomUUID() });
|
|
74
|
+
let fd;
|
|
75
|
+
try { fd = openSync(lock, "wx", 0o600); writeFileSync(fd, token); }
|
|
76
|
+
catch (error) { if(fd!==undefined)rmSync(lock,{force:true}); if (error.code === "EEXIST") throw new Error("Report storage is busy. Retry the same submission; duplicates reuse their report ID."); throw error; }
|
|
77
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
78
|
+
return () => { if (readFileSync(lock, "utf8") === token) rmSync(lock); };
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
submit(kind, args) {
|
|
82
|
+
if (!Object.hasOwn(schemas,kind)) throw new Error("Unknown report kind.");
|
|
83
|
+
const submission = schemas[kind].parse(args);
|
|
84
|
+
// Resolve exact evidence before writing. Superseded or fabricated IDs fail.
|
|
85
|
+
const evidence = submission.evidence.map(reference => ({ reference, snapshot: compactRow(resolveEvidence(reference), 4096) }));
|
|
86
|
+
const captured = compactRow(context(submission), 4096);
|
|
87
|
+
const { title, unit, scenario, expected, observed, steps, workflow, capability } = submission;
|
|
88
|
+
const normalized = value => typeof value === "string" ? value.replace(/\s+/g, " ").trim() : value;
|
|
89
|
+
const identity = JSON.parse(JSON.stringify({ kind, version: captured.ads?.version, framework: captured.framework, title, unit, scenario, expected, observed, steps, workflow, capability }), (_key, value) => normalized(value));
|
|
90
|
+
const fingerprint = digest(identity), release = acquire();
|
|
91
|
+
try {
|
|
92
|
+
const prior = headers().find(record => record.fingerprint === fingerprint), now = new Date().toISOString();
|
|
93
|
+
const record = { schemaVersion:1,id: prior?.id ?? randomUUID(), revision: randomUUID(), fingerprint, kind, createdAt: prior?.createdAt ?? now, updatedAt: now, submissionCount: (prior?.submissionCount ?? 0) + 1, submission, context: captured, evidence };
|
|
94
|
+
if (jsonBytes(record) > reportLimits.recordBytes) throw new Error("Report exceeds 32 KiB. Shorten the narrative/reproduction; reference existing evidence instead of pasting logs or files.");
|
|
95
|
+
const file=path.join(folder,`${record.id}.json`),bytes = JSON.stringify(record), temporary = path.join(folder, `${randomUUID()}.tmp`);
|
|
96
|
+
try { writeFileSync(temporary, bytes, { flag: "wx", mode: 0o600 }); renameSync(temporary, file); } finally { rmSync(temporary, { force: true }); }
|
|
97
|
+
return { ok: true, ...receipt(record), deduplicated: !!prior, retention:"until-explicit-removal", guidanceUri: "ads://guides/reporting" };
|
|
98
|
+
} finally { release(); }
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { z } from "zod";
|
|
|
6
6
|
import { checkProject } from "../check.mjs";
|
|
7
7
|
import { loadConfig, sourceFiles } from "../config.mjs";
|
|
8
8
|
import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
|
|
9
|
-
import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigationResource } from "../investigations.mjs";
|
|
9
|
+
import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
|
|
10
10
|
import { failure } from "../evidence.mjs";
|
|
11
11
|
import { inspectTokens } from "../tokens.mjs";
|
|
12
12
|
import { inspectScenarios } from "../scenarios.mjs";
|
|
@@ -29,6 +29,8 @@ import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
|
29
29
|
import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
|
|
30
30
|
import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
|
|
31
31
|
import { compactProgress, resultBudgets } from "./result-pages.mjs";
|
|
32
|
+
import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
32
34
|
|
|
33
35
|
const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
34
36
|
class InvalidParamsError extends ProtocolError {
|
|
@@ -63,6 +65,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
63
65
|
const edits = cache.edits ??= createMutationController(root, { captures });
|
|
64
66
|
const verification = cache.verification ??= createVerificationController(root);
|
|
65
67
|
const executionResults = cache.executionResults ??= createExecutionResults(root);
|
|
68
|
+
const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
|
|
66
69
|
let options = loadConfig(root);
|
|
67
70
|
const signature = `${root}:${JSON.stringify(options.config)}`;
|
|
68
71
|
if (cache.signature !== signature) {
|
|
@@ -114,6 +117,31 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
114
117
|
};
|
|
115
118
|
const previews = () => options.config.mcp.apps.map((app) => ({ id: app.id, title: app.title, kind: app.kind, tool: `ads_show_${app.id.replaceAll("-", "_")}`, resourceUri: appUri(app.id), available: existsSync(path.resolve(root, app.file)), file: app.file }));
|
|
116
119
|
|
|
120
|
+
function reportContext(submission) {
|
|
121
|
+
const captured = { ads: { package: pkg.name, version: pkg.version }, capturedAt: new Date().toISOString(), framework: null,
|
|
122
|
+
runtime: { node: process.version, platform: process.platform, arch: process.arch }, warnings: [] };
|
|
123
|
+
try { const current=loadConfig(root);captured.framework=current.config.framework;captured.configurationRevision=createHash("sha256").update(JSON.stringify(current.config)).digest("hex");captured.sourceRevision=previewSourceRevision(current); }
|
|
124
|
+
catch { captured.warnings.push("Current configuration/source revision could not be captured."); }
|
|
125
|
+
try{const projectPackage=JSON.parse(readFileSync(path.join(root,"package.json"),"utf8"));if(typeof projectPackage.name==="string")captured.project={name:projectPackage.name.slice(0,160)};}catch{captured.warnings.push("Project package name could not be captured.");}
|
|
126
|
+
try { const build=builds(),preview=build.previews?.find(item=>item.id===submission.scenario);captured.build={state:build.state,updatedAt:build.updatedAt,session:build.session,sequence:build.sequence,...(preview?{preview:{id:preview.id,state:preview.state,revision:preview.revision,current:preview.current,stale:preview.stale}}:{})}; }
|
|
127
|
+
catch { captured.warnings.push("Current build metadata could not be captured."); }
|
|
128
|
+
// Target names can describe an unaccepted draft; they are agent claims, not registrations.
|
|
129
|
+
if(submission.scenario)try{captured.scenarioRegistered=getRegistry().scenarios.some(item=>item.id===submission.scenario);}catch{captured.scenarioRegistered=null;}
|
|
130
|
+
if(submission.unit)try{captured.unitRegistered=edits.units().some(item=>item.id===submission.unit);}catch{captured.unitRegistered=null;}
|
|
131
|
+
return captured;
|
|
132
|
+
}
|
|
133
|
+
function reportEvidence(reference) {
|
|
134
|
+
if(reference.resultId)return JSON.parse(executionResults.readResource(`ads://results/${reference.resultId}`).text);
|
|
135
|
+
const bundle=readInvestigation(root,reference);
|
|
136
|
+
if(bundle.runId!==reference.runId)throw new Error("Investigation was superseded. Reference the exact current unit/check/runId or describe earlier observations without attaching unrelated evidence.");
|
|
137
|
+
const {unit,check,runId,status,target,inputRevision,observedPreviewRevision,framework,profile,completedAt,failure,source,failingStep,viewport,acceptance}=bundle;
|
|
138
|
+
return {unit,check,runId,status,target,inputRevision,observedPreviewRevision,framework,profile,completedAt,failure,source,failingStep,viewport,acceptance,
|
|
139
|
+
artifacts:(bundle.artifacts??[]).slice(0,3).map(({resourceUri,digest,mimeType,available})=>({resourceUri,digest,mimeType,available})),artifactsAreReferences:true};
|
|
140
|
+
}
|
|
141
|
+
function submitReport(kind,args) {
|
|
142
|
+
return json(reports.submit(kind,args));
|
|
143
|
+
}
|
|
144
|
+
|
|
117
145
|
function resources() {
|
|
118
146
|
const context = project();
|
|
119
147
|
const documents = getDocuments();
|
|
@@ -142,6 +170,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
142
170
|
// Keep fallback workflow metadata discoverable in the bounded first page.
|
|
143
171
|
...skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description, mimeType: "text/markdown" })),
|
|
144
172
|
...documents.filter(document => promoted.has(document.uri)).sort((a, b) => Number(b.uri === context.publicEntryUri) - Number(a.uri === context.publicEntryUri)).map(({ file: _file, ...document }) => document),
|
|
173
|
+
{ uri: "ads://guides/tokens", name: "Shared Data and component variable boundaries", mimeType: "text/markdown" },
|
|
174
|
+
{ uri: "ads://guides/reporting", name: "Report suspected ADS bugs and feature requests", mimeType: "text/markdown" },
|
|
145
175
|
{ uri: TOKENS_APP_URI, name: "Experimental token widget", mimeType: APP_MIME },
|
|
146
176
|
{ uri: SCENARIO_APP_URI, name: "Experimental scenario widget", mimeType: APP_MIME },
|
|
147
177
|
...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "Preview dependency graph", mimeType: "application/json" }] : []),
|
|
@@ -165,12 +195,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
165
195
|
scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
|
|
166
196
|
behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
|
|
167
197
|
captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
|
|
198
|
+
reports: { access:"submission-only", storageDirectory:".ds/reports", bugTool:"ads_report_bug", featureTool:"ads_request_feature", guidanceUri:"ads://guides/reporting", delivery:"local-only", retention:"until-explicit-removal" },
|
|
168
199
|
experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
|
|
169
200
|
}
|
|
170
201
|
async function read(uri, signal) {
|
|
171
202
|
if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
|
|
172
|
-
if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("
|
|
203
|
+
if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
|
|
173
204
|
if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
|
|
205
|
+
if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
|
|
206
|
+
if (uri === "ads://guides/reporting") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/reporting.md", import.meta.url), "utf8") }] };
|
|
174
207
|
if (uri === "ads://guides/atomic-styles") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/atomic-styles.md", import.meta.url), "utf8") }] };
|
|
175
208
|
if (uri === "ads://guides/scenarios") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/scenarios.md", import.meta.url), "utf8") }] };
|
|
176
209
|
if (uri === "ads://guides/layers") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/layers.md", import.meta.url), "utf8") }] };
|
|
@@ -282,7 +315,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
282
315
|
const result = checkProject(root);
|
|
283
316
|
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` });
|
|
284
317
|
} },
|
|
285
|
-
{ name: "ads_skills", description: "Select one ADS workflow after ads_status: ads-designer for building/refining/debugging UI; ads-
|
|
318
|
+
{ 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 })) }) },
|
|
286
319
|
{ 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 }) => {
|
|
287
320
|
const skill = skills.skills.find((entry) => entry.frontmatter.name === name);
|
|
288
321
|
if (!skill) throw new Error("Unknown ADS skill name.");
|
|
@@ -310,6 +343,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
310
343
|
} },
|
|
311
344
|
{ name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
|
|
312
345
|
{ name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
|
|
346
|
+
{ 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) },
|
|
347
|
+
{ 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) },
|
|
313
348
|
{ 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. Only the latest bundle per check is retained, 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)) },
|
|
314
349
|
{ 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) => {
|
|
315
350
|
const result = await verification.run(args, signal, progress);
|
package/dist/paint-contracts.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import ts from "typescript";
|
|
3
3
|
import valueParser from "postcss-value-parser";
|
|
4
|
+
import { isSharedToken } from "./token-policy.mjs";
|
|
4
5
|
import { isContractFile, isInside } from "./config.mjs";
|
|
5
6
|
import { inspectUnitContracts, implementationIdentity, runtimeBindingOwner } from "./unit-contracts.mjs";
|
|
6
7
|
import { createSourceValues, reference } from "./source-values.mjs";
|
|
@@ -61,8 +62,7 @@ export function inspectPaintContracts(options) {
|
|
|
61
62
|
const paintProp=/^(?:background(?:Color)?|color|fill|stroke|stopColor|stop-color|floodColor|flood-color|(?:\w+)?ColorToken)$/i;
|
|
62
63
|
|
|
63
64
|
/** Check resolved values at the consuming source, so exports cannot launder privacy. */
|
|
64
|
-
export function inspectTokenValueFlows(program, options, inventory,
|
|
65
|
-
if(!scoped.definitions.length && !inspectUnitContracts(options).contracts.some(contract=>contract.paintInputs?.length))return;
|
|
65
|
+
export function inspectTokenValueFlows(program, options, inventory, units, report) {
|
|
66
66
|
const values=createSourceValues(program,options), checker=program.getTypeChecker();
|
|
67
67
|
const declarations=inspectUnitContracts(options).contracts;
|
|
68
68
|
function strings(input, context=values.state()) {
|
|
@@ -82,14 +82,13 @@ export function inspectTokenValueFlows(program, options, inventory, scoped, repo
|
|
|
82
82
|
}
|
|
83
83
|
for(const source of program.getSourceFiles()) {
|
|
84
84
|
if(!isInside(options.root,source.fileName)||source.fileName.includes(`${path.sep}node_modules${path.sep}`)||isContractFile(source.fileName))continue;
|
|
85
|
-
const owner=
|
|
85
|
+
const owner=units.owner(units.relative(path.relative(options.root,source.fileName)));
|
|
86
86
|
const emitted=new Set();
|
|
87
87
|
function check(node,text,bare=false,requirePaint=false,allowedBindings=null) {
|
|
88
88
|
const names=bare&&/^--[\w-]+$/.test(text)?[text]:valueParser(text).nodes.flatMap(function walk(value){return value.type==="function"&&value.value==="var"?[value.nodes.find(item=>item.type==="word")?.value]:value.nodes?value.nodes.flatMap(walk):[];}).filter(Boolean);
|
|
89
89
|
for(const name of names) {
|
|
90
|
-
const tokenOwner=scoped.definitions.find(entry=>name.startsWith(entry.namespace));
|
|
91
90
|
const binding=runtimeBindingOwner(options,name);
|
|
92
|
-
const issue=
|
|
91
|
+
const issue=binding&&(binding.unit!==owner||allowedBindings&&!allowedBindings.includes(binding.id))?`${name} is an instance binding private to ${binding.unit} and is not permitted by this consuming paint input.`:!binding&&(!isSharedToken(name)&&!/^--(?:ds|ux|showcase)-/.test(name)||requirePaint&&!inventory.tokens.some(token=>token.name===name))?`Undefined paint reference ${name}. Declare a real accessible token or a scoped runtime binding.`:null;
|
|
93
92
|
if(issue&&!emitted.has(`${node.pos}:${name}`)) {emitted.add(`${node.pos}:${name}`);const p=source.getLineAndCharacterOfPosition(node.getStart());report(source.fileName,"token-reference",issue,p.line+1,p.character+1);}
|
|
94
93
|
}
|
|
95
94
|
if(requirePaint&&!paintReference(text)) {const p=source.getLineAndCharacterOfPosition(node.getStart());report(source.fileName,"paint-reference",`Invalid paint reference ${JSON.stringify(text)}. Use an accessible token, declared scoped binding, local SVG paint resource, none or currentColor.`,p.line+1,p.character+1);}
|