@h2loop/autosar 1.8.0 → 1.9.0
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/package.json +1 -1
- package/plugins/index.js +53 -52
- package/python/ecuc_engine/codegen/__init__.py +7 -1
- package/python/ecuc_engine/codegen/cwriter.py +15 -0
- package/python/ecuc_engine/codegen/emit.py +15 -0
- package/python/ecuc_engine/edit.py +170 -6
- package/python/ecuc_engine/rules/__init__.py +1 -1
- package/python/ecuc_engine/rules/mcal.py +219 -0
package/package.json
CHANGED
package/plugins/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{readFileSync as Fe}from"fs";import{isAbsolute as He,join as z,resolve as Be}from"path";import{tool as _}from"@kilocode/plugin";import{homedir as _e}from"os";import{join as O}from"path";var $e=()=>process.env.HYDRON_TEST_HOME||_e(),J=(i,t)=>process.env[i]||O($e(),t),Se=()=>O(J("XDG_CONFIG_HOME",".config"),"hydron-cli"),ke=()=>O(J("XDG_DATA_HOME",".local/share"),"hydron-cli"),Ae=()=>O(J("XDG_STATE_HOME",".local/state"),"hydron-cli");async function W(i){let t=Bun.file(i);if(!await t.exists())return;return t.json().catch(()=>{return})}async function B(){let i=process.env.KILO_API_URL?.trim();if(i)return i.replace(/\/+$/,"");let t=await W(O(Se(),"server-config.json")),s=typeof t?.apiBaseUrl==="string"?t.apiBaseUrl:void 0;if(!s)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return s.replace(/\/+$/,"")}function ve(i){let t=i?.split(".")[1];if(!t)return"";try{let s=JSON.parse(Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof s.sub==="string"?s.sub:""}catch{return""}}async function Oe(i){let t=ve(i.access);if(t)return t;if(!i.refresh)return"";return new Bun.CryptoHasher("sha256").update(i.refresh).digest("hex").slice(0,12)}async function ee(){let t=(await W(O(ke(),"auth.json")))?.hydron;if(!t||t.type!=="oauth"||!t.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return t}async function te(){let i=await ee();if(typeof i.expires==="number"&&i.expires>0&&Date.now()>=i.expires-30000)throw Error("The H2Loop session token has expired. Send any message in Hydron (the CLI refreshes it) or re-login with `hydron auth login`, then retry.");return i.access}async function Z(i){let t=await fetch(`${await B()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await te()}`},signal:i?AbortSignal.any([i,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(t.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!t.ok)throw Error(`could not list H2Loop projects: HTTP ${t.status}`);let s=await t.json();return Array.isArray(s)?s:s?.items??[]}var Q=()=>O(Ae(),"h2loop-project.json");async function D(i,t){let s=i===void 0||i===null?"":String(i).trim();if(/^\d+$/.test(s))return s;if(s){let n=await Z(t),r=n.filter((u)=>u.name===s),l=r.length?r:n.filter((u)=>u.name?.toLowerCase()===s.toLowerCase());if(l.length===1)return String(l[0].id);if(l.length>1)throw Error(`workspace "${s}" is ambiguous: ${l.map((u)=>`${u.name} (id ${u.id})`).join(", ")}; pass the numeric id`);let
|
|
3
|
-
`)[0]??"",r=/^NEW since/.test(n)?/"error":\s*[1-9]/.test(n):/"error":\s*[1-9]/.test(n)||/^\S+:\d+ error /m.test(c);if(
|
|
2
|
+
import{readFileSync as Fe}from"fs";import{isAbsolute as He,join as z,resolve as Be}from"path";import{tool as _}from"@kilocode/plugin";import{homedir as _e}from"os";import{join as O}from"path";var $e=()=>process.env.HYDRON_TEST_HOME||_e(),J=(i,t)=>process.env[i]||O($e(),t),Se=()=>O(J("XDG_CONFIG_HOME",".config"),"hydron-cli"),ke=()=>O(J("XDG_DATA_HOME",".local/share"),"hydron-cli"),Ae=()=>O(J("XDG_STATE_HOME",".local/state"),"hydron-cli");async function W(i){let t=Bun.file(i);if(!await t.exists())return;return t.json().catch(()=>{return})}async function B(){let i=process.env.KILO_API_URL?.trim();if(i)return i.replace(/\/+$/,"");let t=await W(O(Se(),"server-config.json")),s=typeof t?.apiBaseUrl==="string"?t.apiBaseUrl:void 0;if(!s)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return s.replace(/\/+$/,"")}function ve(i){let t=i?.split(".")[1];if(!t)return"";try{let s=JSON.parse(Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof s.sub==="string"?s.sub:""}catch{return""}}async function Oe(i){let t=ve(i.access);if(t)return t;if(!i.refresh)return"";return new Bun.CryptoHasher("sha256").update(i.refresh).digest("hex").slice(0,12)}async function ee(){let t=(await W(O(ke(),"auth.json")))?.hydron;if(!t||t.type!=="oauth"||!t.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return t}async function te(){let i=await ee();if(typeof i.expires==="number"&&i.expires>0&&Date.now()>=i.expires-30000)throw Error("The H2Loop session token has expired. Send any message in Hydron (the CLI refreshes it) or re-login with `hydron auth login`, then retry.");return i.access}async function Z(i){let t=await fetch(`${await B()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await te()}`},signal:i?AbortSignal.any([i,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(t.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!t.ok)throw Error(`could not list H2Loop projects: HTTP ${t.status}`);let s=await t.json();return Array.isArray(s)?s:s?.items??[]}var Q=()=>O(Ae(),"h2loop-project.json");async function D(i,t){let s=i===void 0||i===null?"":String(i).trim();if(/^\d+$/.test(s))return s;if(s){let n=await Z(t),r=n.filter((u)=>u.name===s),l=r.length?r:n.filter((u)=>u.name?.toLowerCase()===s.toLowerCase());if(l.length===1)return String(l[0].id);if(l.length>1)throw Error(`workspace "${s}" is ambiguous: ${l.map((u)=>`${u.name} (id ${u.id})`).join(", ")}; pass the numeric id`);let o=n.filter((u)=>u.name?.toLowerCase().includes(s.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${s}"`+(o.length?`; similar: ${o.map((u)=>`${u.name} (id ${u.id})`).join(", ")}`:`; you have ${n.length} project(s)`))}let c=await W(Q());if(!c)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let p=await ee();if(c.project&&typeof c.project==="object"){let n=c.project;if(typeof c.account==="string"&&c.account!==await Oe(p))throw Error("The selected H2Loop project belongs to another account; select one again or pass workspace_id.");if(n.id!==void 0)return String(n.id)}let e=c;if(e.id===void 0)throw Error(`${Q()} holds no project id; select a project again or pass workspace_id.`);if(!(await Z(t)).some((n)=>String(n.id)===String(e.id)))throw Error(`The selected project ${e.name??""} (id ${e.id}) is not accessible to the signed-in account; select another or pass workspace_id.`);return String(e.id)}async function L(i,t,s,c,p=120000){let e=`${await B()}${i}?workspace_id=${encodeURIComponent(t)}`,a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await te()}`},body:JSON.stringify(s),signal:c?AbortSignal.any([c,AbortSignal.timeout(p)]):AbortSignal.timeout(p)}),n=await a.text();if(a.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(a.status===404&&n.includes("Not Found"))throw Error(`${i} is not available on ${await B()} (backend predates the AUTOSAR endpoints).`);if(!a.ok)throw Error(`H2Loop ${i} failed: HTTP ${a.status} ${n.slice(0,800)}`);try{return JSON.parse(n)}catch(r){throw Error(`H2Loop ${i} returned non-JSON (${String(r)}): ${n.slice(0,300)}`)}}var G=/\.arxml\b/i,V="Blocked: .arxml files must not be edited by hand (it breaks DEFINITION-REF/DEST, UUIDs and the round trip). Use ecuc_edit for ECUC values, arxml_edit for System-extract/SWC elements (or autosar_add_signal for a new signal), then ecuc_validate. To start a NEW .arxml file, use arxml_edit with {op:'new_file', file, packages} followed by add ops.";function ne(i,t){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!t)return;let s=typeof t.filePath==="string"?t.filePath:typeof t.file_path==="string"?t.file_path:"";if(["edit","write","multiedit"].includes(i)){let c=Array.isArray(t.edits)?t.edits.some((p)=>typeof p?.filePath==="string"&&G.test(p.filePath)):!1;if(G.test(s)||c)return`${V} (${i} on ${s||"an .arxml file"})`;return}if(i==="apply_patch"||i==="patch"){let c=String(t.patchText??t.patch??""),p=c.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??c.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return p?`${V} (${i} on ${p[1].trim()})`:void 0}if(i==="bash"){let c=String(t.command??"");if(!G.test(c))return;let p=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(c)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(c),e=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(c)||/\btee\b[^|;&]*\.arxml\b/i.test(c),a=/\b(?:mv|cp|ln|install|rsync)\b[^|;&]*\.arxml['"]?\s*(?:$|[|;&])/im.test(c)||/\b(?:os\.(?:rename|replace)|shutil\.(?:move|copy\w*)|fs\.(?:rename|copyFile)\w*|Path\([^)]*\)\.rename)\([^)]*\.arxml/i.test(c)||/\.(?:rename|replace)\(\s*['"][^'"]*\.arxml/i.test(c),n=/open\([^)]*\.arxml[^)]*,\s*(?:mode\s*=\s*)?['"][wa+]/i.test(c)||/\.arxml['"]?\s*\)?\s*\.write_(?:text|bytes)\b/i.test(c)||/write_(?:text|bytes)\([^)]*\)[^;\n]*\.arxml/i.test(c)||/\bwriteFile(?:Sync)?\([^)]*\.arxml/i.test(c)||/\.write\(\s*['"][^'"]*\.arxml/i.test(c)||/\b(?:awk|gawk)\b[^|;&]*-i\s+inplace/.test(c)||/\bed\b\s+-s\s+[^|;&]*\.arxml/.test(c);if(p||e||n||a)return`${V} (bash: ${c.slice(0,120)})`}return}var Re=/(?:^|[;&|(]\s*|\bnode\s+\S*|\bnpx\s+)(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\b/m,Ee='Not a shell command: ecuc_*/arxml_*/autosar_* are TOOLS of this session. Call the tool directly (a tool call, not bash) with its arguments as JSON, e.g. arxml_edit with {"ops": [ ... ]}. If a tool call fails, read its error, fix the arguments and call the tool again.';function ie(i,t){if(i!=="bash"||!t)return;let s=String(t.command??""),c=/\s(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\s+(?:--|<|\{|\[|'|")/.test(s);if(Re.test(s)||c)return`${Ee} (bash: ${s.slice(0,100)})`;if(/\becuc_engine\b|hydron-cli[\\/]store[\\/]/.test(s))return`Blocked: do not run the AUTOSAR pack's engine or files from the plugin store by hand. Use its tools (ecuc_read/ecuc_edit/arxml_edit/ecuc_validate ...) as tool calls. (bash: ${s.slice(0,100)})`;if(/(?:^|[;&|]\s*)(?:\S*\/)?(?:hydron|kilo|opencode)\s+(?:run|serve)\b/m.test(s))return"Blocked: do not start another agent session from inside this one; do the work here with your tools.";return}var Ce=new Set(["autosar_build_context","ecuc_read","ecuc_find","ecuc_crosscheck","autosar_config_lookup","autosar_trace","autosar_audit","query_hydron_project","get_symbol_info"]),se=new Set(["ecuc_edit","arxml_edit","autosar_add_signal","autosar_add_like"]),oe=/\.(c|h)$/i,ae=/(^|[\\/])(Output|gen|Gen|GenData|generated)[\\/]/;var X=new Map;function U(i){let t=i??"-",s=X.get(t);if(!s)s={grounded:[],contextFor:[],changed:[],validation:"never",cFiles:[],rte:"n/a",docs:"n/a",blocks:0},X.set(t,s);return s}function ce(i){if(!i)return"";return String(i.filePath??i.file_path??"")}function de(i,t,s){if(process.env.AUTOSAR_LOOP_GATES==="0")return;let c=U(i);if(c.blocks>=2)return;if(se.has(t)&&!s?.dry_run&&c.grounded.length===0)return c.blocks++,"GROUND FIRST: no facts have been gathered in this session, so this change would be decided from memory. Before editing, get every fact the change depends on from the tools and list them with their source: autosar_build_context (target = the module/container/element, or swc+runnable) gives the project facts AND the facts from the ingested documents in one call; ecuc_read (schema=true) for what may be set; ecuc_find for what exists and references what. Then plan from those facts only and retry this edit.";let p=ce(s);if((t==="edit"||t==="write"||t==="multiedit")&&oe.test(p)&&!ae.test(p)){if(!c.grounded.includes("autosar_build_context")&&!c.grounded.includes("autosar_audit"))return c.blocks++,`GROUND FIRST: call autosar_build_context for the SW-C/runnable this C file implements (it lists the allowed RTE APIs with exact signatures, the related configuration and the relevant document facts) before changing ${p}. For C that is not runnable code, autosar_audit grounds BSW usage instead. Then retry.`}return}function q(i,t,s,c){let p=U(i),e=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(c)||c.includes("edit rejected");if(Ce.has(t)&&!e){if(!p.grounded.includes(t))p.grounded.push(t);if(t==="autosar_build_context"){let n=String(s?.target??s?.runnable??s?.swc??"");if(n&&!p.contextFor.includes(n))p.contextFor.push(n)}}if(se.has(t)&&!e&&!s?.dry_run&&!/^Dry run/.test(c)){p.validation=/AUTO-VALIDATE: clean/.test(c)?"clean":/AUTO-VALIDATE/.test(c)?"errors":"stale",p.docs="pending";for(let n of Te(t,s,c))if(!p.changed.includes(n))p.changed.push(n)}let a=ce(s);if((t==="edit"||t==="write"||t==="multiedit")&&oe.test(a)&&!ae.test(a)&&!e){if(!p.cFiles.includes(a))p.cFiles.push(a);p.rte="pending"}if(t==="ecuc_validate"&&!e){let n=c.split(`
|
|
3
|
+
`)[0]??"",r=/^NEW since/.test(n)?/"error":\s*[1-9]/.test(n):/"error":\s*[1-9]/.test(n)||/^\S+:\d+ error /m.test(c);if(p.validation=r?"errors":"clean",s?.docs&&p.docs==="pending"&&!/DOCUMENT CHECK UNAVAILABLE/.test(c))p.docs="done"}if(t==="autosar_verify_rte"&&!e)p.rte=/\u2014 FAILING/.test(c)?"fail":"pass"}function Te(i,t,s){let c=[];if(i==="ecuc_edit"){let p=re(t?.ops);for(let e of p){let a=String(e.path??""),n=e.param?`${a}/${e.param}`:e.container?`${a}/${e.container}`:a;c.push(e.value!==void 0?`${n} = ${JSON.stringify(e.value).slice(0,80)}`:`${n} (${e.op})`)}}else if(i==="arxml_edit"){let p=s.match(/created (\[[^\]]*\])/);if(p)try{c.push(...JSON.parse(p[1]))}catch{}for(let e of re(t?.ops))if(e.op==="set")c.push(`${e.path}/${e.element} = ${JSON.stringify(e.value)}`)}else if(i==="autosar_add_signal")c.push(`new Com signal ${t?.name} in ${t?.ipdu}`);else if(i==="autosar_add_like"){let p=s.match(/Created:\n((?: .*\n?)+)/);if(p)c.push(...p[1].split(`
|
|
4
4
|
`).map((e)=>e.trim()).filter(Boolean));else c.push(`${t?.name} like ${t?.like}`)}return c.filter(Boolean)}function re(i){let t=i;for(let s=0;s<3&&typeof t==="string";s++)try{t=JSON.parse(t)}catch{return[]}if(Array.isArray(t))return t.filter((s)=>s&&typeof s==="object");if(t&&typeof t==="object")return[t];return[]}function le(i){let t=X.get(i??"-");if(!t)return;let s=[];if(t.validation==="stale")s.push("Config/ARXML changed since the last ecuc_validate: run it (unfiltered) now.");if(t.validation==="errors")s.push("The last ecuc_validate reported errors: fix them and validate again.");if(t.rte==="pending")s.push(`C changed (${t.cFiles.slice(-5).join(", ")}): run autosar_verify_rte on it.`);if(t.rte==="fail")s.push("autosar_verify_rte is FAILING: fix the calls (or apply its arxml_edit ops) and verify again.");if(t.docs==="pending"&&t.validation==="clean")s.push(`Changed elements not yet checked against the ingested documents (${t.changed.slice(0,8).join("; ")}${t.changed.length>8?"; \u2026":""}): run ecuc_validate docs=true and answer its checklist item by item.`);if(!s.length)return;return["# AUTOSAR: open verification items (do not report the task as done until each is resolved)",...s.map((c)=>`- ${c}`)].join(`
|
|
5
|
-
`)}var Ne=/^(?:hi+|hello+|hey+|hiya|yo|hola|namaste|good\s+(?:morning|afternoon|evening|day)|thanks?|thank\s+you|thx|ty|ok(?:ay)?|cool|nice|great|bye|good\s*bye|see\s+you)(?:\s+(?:there|all|team|hydron|again|so\s+much|a\s+lot))*$/i,ue=new Map;function xe(i){let t=i.trim().replace(/[\p{Extended_Pictographic}\u200D\uFE0F]/gu,"").replace(/[!.?,:;~\-]+/g," ").replace(/\s+/g," ").trim();return t.length>0&&t.length<=40&&Ne.test(t)}function fe(i,t){ue.set(i??"-",xe(t))}function he(i,t){if(process.env.AUTOSAR_LOOP_GATES==="0")return;if(!ue.get(i??"-"))return;return`NO TOOLS: the user only greeted you (no task). Do not call ${t} or any other tool, and do not read or explore the project. Reply in one short line (e.g. what you can help with here) and stop.`}import{existsSync as je}from"fs";import{dirname as Ie,join as Y}from"path";import{fileURLToPath as De}from"url";var Le="autosar-data==0.17.0";function Ue(){let i=Ie(De(import.meta.url)),t=[Y(i,"..","python"),Y(i,"..","..","python")].find((s)=>je(Y(s,"ecuc_engine","__main__.py")));if(!t)throw Error(`ECUC engine not found next to ${i} (expected ../python/ecuc_engine)`);return t}async function Pe(i){try{return await Bun.spawn([...i,"-c","import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"],{stdout:"ignore",stderr:"ignore",stdin:"ignore"}).exited===0}catch{return!1}}var M={};async function Me(){if(M.cmd!==void 0)return M.cmd;let i=process.env.AUTOSAR_PYTHON?.trim(),s=i?[[i]]:[["uv","run","--no-project","--quiet","--with",Le,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let c of s)if(await Pe(c))return M.cmd=c,c;return M.cmd=null,null}async function b(i,t,s){let c=await Me();if(!c)return{ok:!1,error:"no Python >= 3.10 found. Install uv (https://docs.astral.sh/uv/) or Python 3.10+, or set AUTOSAR_PYTHON to an interpreter path."};let
|
|
5
|
+
`)}var Ne=/^(?:hi+|hello+|hey+|hiya|yo|hola|namaste|good\s+(?:morning|afternoon|evening|day)|thanks?|thank\s+you|thx|ty|ok(?:ay)?|cool|nice|great|bye|good\s*bye|see\s+you)(?:\s+(?:there|all|team|hydron|again|so\s+much|a\s+lot))*$/i,ue=new Map;function xe(i){let t=i.trim().replace(/[\p{Extended_Pictographic}\u200D\uFE0F]/gu,"").replace(/[!.?,:;~\-]+/g," ").replace(/\s+/g," ").trim();return t.length>0&&t.length<=40&&Ne.test(t)}function fe(i,t){ue.set(i??"-",xe(t))}function he(i,t){if(process.env.AUTOSAR_LOOP_GATES==="0")return;if(!ue.get(i??"-"))return;return`NO TOOLS: the user only greeted you (no task). Do not call ${t} or any other tool, and do not read or explore the project. Reply in one short line (e.g. what you can help with here) and stop.`}import{existsSync as je}from"fs";import{dirname as Ie,join as Y}from"path";import{fileURLToPath as De}from"url";var Le="autosar-data==0.17.0";function Ue(){let i=Ie(De(import.meta.url)),t=[Y(i,"..","python"),Y(i,"..","..","python")].find((s)=>je(Y(s,"ecuc_engine","__main__.py")));if(!t)throw Error(`ECUC engine not found next to ${i} (expected ../python/ecuc_engine)`);return t}async function Pe(i){try{return await Bun.spawn([...i,"-c","import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"],{stdout:"ignore",stderr:"ignore",stdin:"ignore"}).exited===0}catch{return!1}}var M={};async function Me(){if(M.cmd!==void 0)return M.cmd;let i=process.env.AUTOSAR_PYTHON?.trim(),s=i?[[i]]:[["uv","run","--no-project","--quiet","--with",Le,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let c of s)if(await Pe(c))return M.cmd=c,c;return M.cmd=null,null}async function b(i,t,s){let c=await Me();if(!c)return{ok:!1,error:"no Python >= 3.10 found. Install uv (https://docs.astral.sh/uv/) or Python 3.10+, or set AUTOSAR_PYTHON to an interpreter path."};let p=Ue(),e=Bun.spawn([...c,"-m","ecuc_engine","--root",i,...t,"--json"],{cwd:i,env:{...process.env,PYTHONPATH:[p,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:s}),[a,n]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text()]);await e.exited;let r=a.trim().split(`
|
|
6
6
|
`).filter(Boolean).at(-1);if(!r)return{ok:!1,error:`engine produced no output (exit ${e.exitCode}): ${n.trim().slice(-2000)}`};try{return JSON.parse(r)}catch(l){return{ok:!1,error:`engine output was not JSON (${String(l)}): ${r.slice(0,500)} ${n.slice(-500)}`}}}var d=_.schema,Je=["# AUTOSAR pack: only for AUTOSAR work","If the request is about this AUTOSAR project or its work (ARXML/ECUC config, BSW/RTE/MCAL code, AUTOSAR","specs): load the `autosar` skill and use its tools (ecuc_read/find, ecuc_edit/arxml_edit, ecuc_validate,","autosar_build_context). Otherwise (a greeting, an unrelated question) just answer: no tools, no exploring."].join(`
|
|
7
7
|
`);function T(i){if(typeof i!=="string")return i;let t=i.trim();if(!t.startsWith("[")&&!t.startsWith("{")&&!t.startsWith('"'))return i;try{return T(JSON.parse(t))}catch{return i}}var R=(i)=>d.preprocess(T,i);function C(i){let t=T(i);if(t===void 0||t===null||t==="")return;if(typeof t==="string")return[t];if(Array.isArray(t))return t.map(String).filter((s)=>s.trim());return[String(t)]}var x=()=>d.preprocess(C,d.array(d.string()).optional()),E=" In answers cite, for every element, its AUTOSAR path (the value's @path, e.g. /Pkg/Com/ComConfig/MySig), its"+" DEFINITION-REF (@def, e.g. /AUTOSAR/EcucDefs/Com/ComConfig/ComSignal) and file:line \u2014 never give the"+` DEFINITION-REF when the path is asked. A value's file:line is its "@at:<Param>" (the VALUE element; "@at" is`+' the container); integers come with "@hex:<Param>" \u2014 copy both, never compute a line or a base conversion'+" yourself. Cite a requirement ID only if it appears verbatim in a tool result or spec text read this session.";function j(i,t=200){let s=i.slice(0,t).map((c)=>`${c.file}:${c.line} ${c.severity.toUpperCase()} ${c.rule} ${c.path} \u2014 ${c.message}${c.defRef?` [def ${c.defRef}]`:""}`);if(i.length>t)s.push(`\u2026 ${i.length-t} more`);return s}function k(i){let t=i.didYouMean?`
|
|
8
8
|
Did you mean: ${i.didYouMean.join(", ")}`:"",s=i.schema?`
|
|
@@ -10,84 +10,85 @@ Schema errors: ${JSON.stringify(i.schema)}`:"";return`ERROR: ${i.error}${t}${s}`
|
|
|
10
10
|
`)+`
|
|
11
11
|
`:""}function w(i,t){if(!t)return i;return He(t)?t:Be(i,t)}async function We(i){let t=Bun.file(z(i,".hydron","autosar.json"));if(!await t.exists())return{};return t.json().catch((s)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(s)}`)})}async function Ge(i,t){let s=(await We(i))[t];if(typeof s==="string")return{command:s};if(s&&typeof s==="object"&&typeof s.command==="string")return s;return}function pe(i,t=150){let s=i.split(`
|
|
12
12
|
`);return s.length>t?[`\u2026 (${s.length-t} earlier lines omitted)`,...s.slice(-t)].join(`
|
|
13
|
-
`):i}async function Ve(i,t,s,c){let
|
|
13
|
+
`):i}async function Ve(i,t,s,c){let p=process.platform==="win32"?["cmd","/d","/s","/c",i]:["sh","-c",i],e=Date.now(),a=Bun.spawn(p,{cwd:t,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([c,AbortSignal.timeout(s*1000)])}),[n,r]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text()]);return{code:await a.exited,out:n,err:r,secs:Math.round((Date.now()-e)/1000)}}var Xe=(i)=>(i??[]).map((t)=>`CAN ID ${t.canIdHex??"?"} (${t.canId??"?"}) ${t.direction} via ${t.canIfPdu}, controller ${t.controller??"?"}, network ${(t.network??[]).join(", ")||"?"}`).join("; ");async function ge(i,t,s){let c=t.filter((n)=>n?.path&&/\/Com((Group)?Signal|IPdu)$/.test(String(n.definition_ref??""))&&n.ipdu===void 0&&n.direction===void 0);if(!c.length)return[];let p=await b(i,["signal-owners",...new Set(c.map((n)=>n.path))],s);if(!p.ok)return[`NOTE: owning I-PDU not computed locally (${p.error})`];let e=p.owners,a=[];for(let n of c){let r=e[n.path];if(r===null||r===void 0){a.push(`NOTE: ${n.path} is not in the local checkout (${i}); owning I-PDU/direction unknown`);continue}n.ipdu_local=r,a.push(r.length?`${n.path}: owning I-PDU ${r.map((l)=>`${l.ipdu} (ComIPduDirection=${l.direction??"?"}${l.can?.length?`; ${Xe(l.can)}`:""})`).join(", ")} [local ECUC]`:`${n.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return a}var qe=(i)=>{if(typeof i==="number"&&Number.isSafeInteger(i))return i;if(typeof i==="string"&&/^\s*-?(0x[0-9a-f]+|\d+)\s*$/i.test(i)){let t=i.trim(),s=t.startsWith("-")?-Number(t.slice(1)):Number(t);return Number.isSafeInteger(s)?s:null}return null},we=(i)=>i<0?`-0x${(-i).toString(16).toUpperCase()}`:`0x${i.toString(16).toUpperCase()}`;async function me(i,t,s){let c=t.filter((n)=>typeof n?.path==="string");if(!c.length)return[];let p=await b(i,["value-sites",...new Set(c.map((n)=>n.path))],s),e=p.ok?p.sites:{},a=[];if(!p.ok)a.push(`NOTE: value lines not computed locally (${p.error})`);for(let n of c){let r=e[n.path];if(r){n.values_local=r.values,a.push(`VALUES ${n.path} (container ${r.at}) [local ECUC; cite these lines]:`);for(let[u,h]of Object.entries(r.values))for(let g of Array.isArray(h)?h:[h])a.push(` ${u} = ${JSON.stringify(g.value)}${g.hex?` (dec ${g.dec}, hex ${g.hex})`:""} @ ${g.at}`);continue}let l=n.values&&typeof n.values==="object"?n.values:{},o={};for(let[u,h]of Object.entries(l)){let g=qe(h);if(g!==null)o[u]=`dec ${g}, hex ${we(g)}`}if(Object.keys(o).length)n.values_int=o;if(p.ok)a.push(`NOTE: ${n.path} is not in the local checkout (${i}): its file:line${n.file?` ${n.file}:${n.line??"?"}`:""} is where the ELEMENT starts, not a value line. To cite a value's line, read that file; never estimate one.`)}return a}var ye=(i)=>{let t=i.notes??[],s=i.errors??[];return[...t.map((c)=>`NOTE: ${typeof c==="string"?c:JSON.stringify(c)}`),...s.map((c)=>`BACKEND ERROR: ${typeof c==="string"?c:JSON.stringify(c)}`)]};async function Ye(i,t){try{let s=await t(),c=typeof s==="string"?s:s.output;if(c&&c.trim())return s;return`${i}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(s){return`ERROR (${i}): ${s instanceof Error?s.message:String(s)}`}}function Ke(i){for(let[t,s]of Object.entries(i)){let c=s.execute;s.execute=(p,e)=>Ye(t,()=>c(p,e))}return i}function ze(i,t=process.env){let s=new Set;for(let c of(t.AUTOSAR_DISABLE_TOOLS??"").split(/[\s,]+/))if(c)s.add(c);if(i)try{let c=JSON.parse(Fe(z(i,".hydron","autosar.json"),"utf8"));if(Array.isArray(c.disableTools)){for(let p of c.disableTools)if(typeof p==="string"&&p)s.add(p)}}catch{}return s}function Ze(i,t){if(t.size===0)return i;return Object.fromEntries(Object.entries(i).filter(([s])=>!t.has(s)))}function Qe(i,t){if(!t)return;if(i==="autosar_add_like")return typeof t.like==="string"?t.like:void 0;if(i==="autosar_add_signal")return typeof t.ipdu==="string"?t.ipdu:void 0;let s=T(t.ops);if(!Array.isArray(s))s=s&&typeof s==="object"?[s]:[];for(let c of s){let p=c?.path??c?.parent_path;if(typeof p==="string"&&p.trim())return p.trim()}return}var be=new Map;async function K(i,t,s,c){let p=`${t??"-"}|${s??""}|${i}`,e=be.get(p);if(e)return e;let a;try{let n=await D(s,c),r=await L("/api/v1/mcp/retriever/query",n,{query:i,workspace_id:Number(n)||n},c,300000),l=(r.citations??[]).slice(0,12).map((o,u)=>{let h=o.file?`${o.file}${o.start_line?`:${o.start_line}`:""}`:`${o.doc_name??"?"}${o.title?` > ${o.title}`:""}`;return` [D${u+1}] ${h}: "${(o.excerpt??"").replace(/\s+/g," ").slice(0,280)}"`});a=r.answer?`(project ${n}; retriever answer, ${l.length} citation(s). Trust a statement only where a citation supports it.)
|
|
14
14
|
${r.answer.trim()}
|
|
15
15
|
Citations:
|
|
16
16
|
${l.join(`
|
|
17
|
-
`)||" (none)"}`:`(project ${n}: no answer${r.error_message?`: ${r.error_message}`:""})`}catch(n){return`UNAVAILABLE: ${n instanceof Error?n.message:String(n)} -- select a Hydron project with the documents ingested (hydron projects select) or pass workspace_id.`}return be.set(
|
|
18
|
-
{"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let a
|
|
19
|
-
${pe(
|
|
20
|
-
${pe(
|
|
21
|
-
`),metadata:{exit:
|
|
17
|
+
`)||" (none)"}`:`(project ${n}: no answer${r.error_message?`: ${r.error_message}`:""})`}catch(n){return`UNAVAILABLE: ${n instanceof Error?n.message:String(n)} -- select a Hydron project with the documents ingested (hydron projects select) or pass workspace_id.`}return be.set(p,a),a}var et=async(i)=>{let t=ze(i?.directory),s=(e)=>_({description:e==="generate"?"Run the project's AUTOSAR code generator (e.g. the vendor's configurator CLI) as configured in .hydron/autosar.json `generate` ({command, cwd?, timeoutSec?} or a string; `{module}` and `{args}` placeholders are substituted). Run it only after ecuc_validate reports no errors. Asks the user for permission. Returns the exit code and the output tail; follow with arxml_diff/autosar_build.":"Run the project's build command as configured in .hydron/autosar.json `build` ({command, cwd?, timeoutSec?} or a string; `{module}`/`{args}` substituted). Asks the user for permission. Returns the exit code and the output tail (compiler/linker errors). Use after autosar_generate.",args:{module:d.string().optional().describe("module name substituted for {module} in the command, if used"),args:d.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(a,n){let r=w(n.directory,a.project_dir),l=await Ge(r,e);if(!l)return`No \`${e}\` command configured. Add it to ${z(r,".hydron","autosar.json")}, e.g.
|
|
18
|
+
{"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let o=a.args??"",u=l.command.replaceAll("{module}",a.module??""),h=u.includes("{args}")?u.replaceAll("{args}",o):`${u}${o?` ${o}`:""}`,g=w(r,l.cwd);await n.ask({permission:`autosar_${e}`,patterns:[h],always:[l.command],metadata:{command:h,cwd:g}}),n.metadata({title:`${e}: ${h}`});let f=await Ve(h,g,l.timeoutSec??3600,n.abort),m=f.code===0?"OK":`FAILED (exit ${f.code})`;return{title:`autosar_${e} ${m}`,output:[`$ ${h} (cwd ${g}, ${f.secs}s) -> ${m}`,f.out.trim()?`--- stdout (tail) ---
|
|
19
|
+
${pe(f.out)}`:"",f.err.trim()?`--- stderr (tail) ---
|
|
20
|
+
${pe(f.err,80)}`:""].filter(Boolean).join(`
|
|
21
|
+
`),metadata:{exit:f.code}}}}),c={},p=i?.directory;return{"chat.message":async(e,a)=>{let n=(a?.parts??[]).map((r)=>r.type==="text"?String(r.text??""):"").join(" ");fe(e.sessionID,n)},"tool.execute.before":async(e,a)=>{let n=he(e.sessionID,e.tool);if(n)throw Error(n);let r=ne(e.tool,a.args)??ie(e.tool,a.args);if(r)throw Error(r);let l=de(e.sessionID,e.tool,a.args);if(l){let o=Qe(e.tool,a.args),u="";if(o&&c.autosar_build_context)try{let h=await c.autosar_build_context.execute({target:o,task:`ground the ${e.tool} about to change ${o}`},{directory:p,worktree:p,sessionID:e.sessionID,abort:new AbortController().signal,metadata(){},async ask(){}});if(u=typeof h==="string"?h:String(h?.output??""),u&&!u.startsWith("ERROR"))q(e.sessionID,"autosar_build_context",{target:o},u);else u=""}catch{u=""}throw Error(u?`${l}
|
|
22
22
|
|
|
23
|
-
The context engine was run for you on ${
|
|
23
|
+
The context engine was run for you on ${o}; these are the facts to plan from:
|
|
24
24
|
${u.slice(0,14000)}
|
|
25
25
|
|
|
26
|
-
List the facts your edit relies on (F#/D#), adjust the edit to them, then retry it.`:l)}},"tool.execute.after":async(e,
|
|
26
|
+
List the facts your edit relies on (F#/D#), adjust the edit to them, then retry it.`:l)}},"tool.execute.after":async(e,a)=>{q(e.sessionID,e.tool,e.args,String(a?.output??""))},"experimental.chat.system.transform":async(e,a)=>{a.system.push(Je);let n=le(e?.sessionID);if(n)a.system.push(n)},tool:c=Ze(Ke({ecuc_read:_({description:`THE way to answer any question about configured ECUC values (use it instead of grep/read on .arxml). Read AUTOSAR ECUC configuration as compact ECUC JSON (keyed by def names: "<DefName>:<ShortName>" for containers, params by def short-name, references as "->/path"; every container carries @path = its AUTOSAR path, @def = its DEFINITION-REF and @at = its file:line; every value is followed by "@at:<Param>" = file:line of its VALUE element, and integers by "@hex:<Param>" ("@dec:<Param>" when the ARXML text is hex)). No path: lists modules and the param-def/config files found. path may be a full AUTOSAR path, a SHORT-NAME ('DoorLatch') or a partial path ('ComConfig/DoorLatch', 'DoorLatch/ComBitPosition'); ambiguous names return candidate paths. A module/container: its values to `+"`depth` levels (merged across split files). A param path (\u2026/Container/Param) or a def path "+"(/AUTOSAR/EcucDefs/\u2026): the value and/or the definition. schema=true adds the def summary (allowed "+"params with type/range/literals/multiplicity, allowed sub-containers) \u2014 read it before ecuc_edit. "+"Never read or edit ARXML by hand."+E,args:{path:d.string().optional().describe("AUTOSAR path, SHORT-NAME or partial path of a module/container/parameter, or a def path"),depth:d.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:d.boolean().optional().describe("include the param-def summary for the element"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=["read"];if(e.path)n.push(e.path);if(n.push("--depth",String(e.depth??2)),e.schema)n.push("--schema");let r=await b(w(a.directory,e.project_dir),n,a.abort);if(!r.ok)return A(r)+k(r);let{ok:l,engine:o,ms:u,warnings:h,...g}=r;return A(r)+JSON.stringify(g,null,1)}}),ecuc_edit:_({description:"Edit ECUC ARXML in place \u2014 the ONLY way to change configuration (edit/write/sed on .arxml are blocked). "+"Get exact paths and allowed params from ecuc_read (schema=true) first. Ops by AUTOSAR path: {op:'set', path, param, value} (value scalar, '->/ref/path', or a list for multi-valued "+"params), {op:'add', path:<parent>, container:'DefName:ShortName', values:{\u2026ECUC JSON\u2026}}, {op:'add', "+"path, param, value} (append a value), {op:'remove', path[, param[, value]]}. The engine picks the value element type, DEFINITION-REF/DEST and VALUE-REF DEST from the param defs, rejects out-of-range/non-literal values, patches only the changed bytes in the file each element lives in (UUIDs, order, comments preserved), applies all ops or none, and checks ARXML schema validity. Returns the unified diff and the validation of touched files. ALWAYS run ecuc_validate after editing and fix what it reports."+E,args:{ops:R(d.array(R(d.object({op:d.enum(["set","add","remove"]),path:d.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:d.string().optional().describe("parameter/reference def short-name"),value:d.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:d.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:R(d.record(d.string(),d.any()).optional()).describe("for add: ECUC JSON of the new container")}))).min(1)).describe("list of ops (a JSON array; a JSON-encoded string is also accepted)"),dry_run:d.boolean().optional().describe("compute and show the diff without writing"),force:d.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)n.push("--dry-run");if(e.force)n.push("--force");let r=await b(w(a.directory,e.project_dir),n,a.abort);if(!r.ok){let h=r.changes??[],g=(r.notes??[]).map((f)=>`
|
|
27
|
+
NOTE: ${f}`).join("");return A(r)+k(r)+g+(h.length?`
|
|
27
28
|
Rejected diff:
|
|
28
|
-
${
|
|
29
|
-
`)}`:"")}let l=r.changes??[],
|
|
30
|
-
`)}}}),ecuc_validate:_({description:"Validate ALL ARXML of the project. ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions, plus semantic rule packs (H2L-*: Com signals inside their I-PDU and non-overlapping incl. Motorola bit order, unique handle IDs) that run even without defs. System/ECU extract, SWC and interface files: strict AUTOSAR schema load and every *-REF resolves with the right DEST (H2L-ARXML-*). Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit / arxml_edit and before "+"autosar_generate. `files` takes files, directories or globs; omit it to validate everything (preferred). The output always lists which files/modules were loaded; a filter that matches nothing is an ERROR. If it reports nothing on a project you expect to have issues, rerun unfiltered and check the loaded-file list."+E,args:{files:x().describe("only report diagnostics in these: files, directories (recursive, trailing slash optional) or globs (`**/Com*.arxml`), relative to the project root or absolute. A filter that matches no loaded file is reported as an ERROR (H2L-FILTER-NOMATCH), never as clean"),module:d.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),new_only:d.boolean().optional().describe("report only findings that the last git commit did not have (what YOUR change introduced); counts of pre-existing ones are still given. Default: on once this session has edited something (the verify step), off before (an audit sees everything)"),docs:d.boolean().optional().describe("validation step 2: after the deterministic checks, check the elements changed in this session (or `about`) against the ingested specs/manuals of the selected Hydron project; returns a checklist to answer item by item"),about:d.string().optional().describe("with docs=true: the elements/values to check when nothing was changed in this session"),workspace_id:d.union([d.string(),d.number()]).optional().describe("Hydron project for docs=true (default: the selected one)"),max:d.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:d.boolean().optional().describe("regenerate in a scratch copy and report stale generated files (H2L-GEN-001). Default: on when a generate command is configured and the configuration is < 5 MB"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,
|
|
29
|
+
${h.map((f)=>f.diff).join(`
|
|
30
|
+
`)}`:"")}let l=r.changes??[],o=r.validation,u=[`${r.written?"Written":"Dry run (nothing written)"}: ${r.applied} op(s), ${l.length} file(s) changed.`,...(r.notes??[]).map((h)=>`NOTE: ${h}`),...l.map((h)=>h.diff)];if(o)u.push(o.validated?o.baseline==="git HEAD"?`Validation of touched files, NEW since git HEAD: ${JSON.stringify(o.summary)}`+(o.preexisting&&Object.keys(o.preexisting).length?` (pre-existing, not listed: ${JSON.stringify(o.preexisting)})`:""):`Validation of touched files: ${JSON.stringify(o.summary)}`:"Validation skipped: no param defs loaded.",...j(o.diagnostics,50));return{title:`ecuc_edit ${l.map((h)=>h.file).join(", ")}`,output:A(r)+u.join(`
|
|
31
|
+
`)}}}),ecuc_validate:_({description:"Validate ALL ARXML of the project. ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions, plus semantic rule packs (H2L-*: Com signals inside their I-PDU and non-overlapping incl. Motorola bit order, unique handle IDs) that run even without defs. System/ECU extract, SWC and interface files: strict AUTOSAR schema load and every *-REF resolves with the right DEST (H2L-ARXML-*). Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit / arxml_edit and before "+"autosar_generate. `files` takes files, directories or globs; omit it to validate everything (preferred). The output always lists which files/modules were loaded; a filter that matches nothing is an ERROR. If it reports nothing on a project you expect to have issues, rerun unfiltered and check the loaded-file list."+E,args:{files:x().describe("only report diagnostics in these: files, directories (recursive, trailing slash optional) or globs (`**/Com*.arxml`), relative to the project root or absolute. A filter that matches no loaded file is reported as an ERROR (H2L-FILTER-NOMATCH), never as clean"),module:d.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),new_only:d.boolean().optional().describe("report only findings that the last git commit did not have (what YOUR change introduced); counts of pre-existing ones are still given. Default: on once this session has edited something (the verify step), off before (an audit sees everything)"),docs:d.boolean().optional().describe("validation step 2: after the deterministic checks, check the elements changed in this session (or `about`) against the ingested specs/manuals of the selected Hydron project; returns a checklist to answer item by item"),about:d.string().optional().describe("with docs=true: the elements/values to check when nothing was changed in this session"),workspace_id:d.union([d.string(),d.number()]).optional().describe("Hydron project for docs=true (default: the selected one)"),max:d.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:d.boolean().optional().describe("regenerate in a scratch copy and report stale generated files (H2L-GEN-001). Default: on when a generate command is configured and the configuration is < 5 MB"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=["validate"];for(let v of C(e.files)??[])r.push("--file",v);if(e.module)r.push("--module",e.module);if(e.checkGenerated===!0)r.push("--check-generated");if(e.checkGenerated===!1)r.push("--no-check-generated");if(e.new_only??U(a.sessionID).changed.length>0)r.push("--new-only");let o=await b(n,r,a.abort);if(!o.ok)return A(o)+k(o);let{diagnostics:u,scope:h}=o,g=u.filter((v)=>v.rule!=="H2L-DISCOVERY"),{summaryNew:f,preexisting:m}=o,S=f?`NEW since ${o.baseline}: ${Object.keys(f).some((v)=>v!=="info")?JSON.stringify(f):"no new findings"}`+(m&&Object.keys(m).length?`; pre-existing, not listed: ${JSON.stringify(m)} (new_only=false lists them)`:""):"",P=h.configFiles===0&&o.scope.inputFiles?`Checked ${o.scope.inputFiles} extract/SWC file(s) (AUTOSAR schema + references): ${g.length?JSON.stringify(o.summary):"CLEAN, no findings"}`:o.validated?`Validated ${o.modules.join(", ")||"(no modules)"} against ${o.defsLoaded} module def(s): ${g.length?JSON.stringify(o.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${g.length?JSON.stringify(o.summary):"no findings"}`,N=[`Loaded ${h.configFiles} config file(s) and ${o.scope.inputFiles??0} extract/SWC file(s)`+(h.filter?`; files filter ${JSON.stringify(h.filter.files)} matched ${h.filter.matchedCount}`:"")+(h.module?`; module filter ${h.module}`:"")+":",...h.files.slice(0,30).map((v)=>` ${v.file} (${v.modules.join(", ")})`),...h.files.length>30||h.filesTruncated?[` \u2026 ${h.files.length-30+(h.filesTruncated??0)} more`]:[]],I="";if(e.docs){let v=U(a.sessionID).changed,F=e.about?.trim()||v.join("; ");if(!F)I="\n\nDOCUMENT CHECK UNAVAILABLE: nothing was changed in this session; pass `about` with the elements/values to check.";else{let H=await K(`Check these AUTOSAR configuration elements and values against the specifications and manuals in this knowledge base: ${F}. For each one, give every constraint that applies (allowed range or literals, multiplicity, dependencies on other parameters/modules, hardware limits of the target microcontroller) with the document name and section or requirement ID, and say whether the value satisfies it.`,a.sessionID,e.workspace_id,a.abort);I=H.startsWith("UNAVAILABLE")?`
|
|
31
32
|
|
|
32
33
|
DOCUMENT CHECK UNAVAILABLE: ${H}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${F}`,H,"","Answer this checklist before finishing, one line per element: `<element> = <value>: OK | VIOLATED | NOT COVERED \u2014 [D#]`.","VIOLATED \u2192 fix with ecuc_edit/arxml_edit and validate again. NOT COVERED \u2192 say so; never invent a constraint.","Check every requirement ID you cite with autosar_spec_id_check."].join(`
|
|
33
|
-
`)}}return{title:`ecuc_validate ${JSON.stringify(
|
|
34
|
-
`)+I}}}),arxml_diff:_({description:"Semantic ARXML diff by AUTOSAR path between two files or directories (e.g. a git checkout of the old Config/ vs the current one, or Output/ before/after generation inputs). Ignores UUIDs, whitespace, comments, element order and file splits; ECUC values are compared per parameter. Returns added/removed/changed elements with the changed parameter values. Use it to review edits and PRs instead of a textual diff.",args:{a:d.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:d.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,
|
|
35
|
-
`)}}}),autosar_config_lookup:_({description:"Look up one ARXML element in the H2Loop code graph by AUTOSAR path: the element (module, DEFINITION-REF, file:line, values), its direct children, references out and in (who points at it), and linked C symbols. Elements in the local checkout get a VALUES block with each value's VALUE-element file:line and integers in dec + hex. Use it to navigate config relations across the ingested repo (including files not in the local checkout); for local edits use ecuc_read/ecuc_edit."+E,args:{path:d.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:d.number().int().optional().describe("restrict to one code data source"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:d.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,
|
|
36
|
-
`)}}}),ecuc_find:_({description:"Structured query over the ECUC configuration \u2014 use it instead of grep/read on ARXML. Filter containers by "+`module, container_def (def short-name, e.g. PduRRoutingPath, ComSignal, NvMBlockDescriptor), where ("ComIPduDirection=SEND, ComBitSize>8"; =, !=, >, <, >=, <=, ~regex), ref_to (containers that reference this path directly or through up to 2 references, e.g. all routing paths whose destination is an EcuC Pdu), and referenced_by (e.g. all ComSignals referenced by I-PDU Y). Returns AUTOSAR paths, the container's file:line (at) and its values, each with "@at:<Param>" (file:line of the VALUE element) and, for integers, "@hex:<Param>".`+E,args:{module:d.string().optional(),container_def:d.string().optional().describe("container definition short-name"),where:d.union([d.string(),d.record(d.string(),d.any())]).optional().describe("conditions on parameter values"),ref_to:d.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:d.string().optional().describe("container whose references define the result set"),limit:d.number().int().min(1).max(500).optional(),project_dir:d.string().optional()},async execute(e,
|
|
37
|
-
${
|
|
38
|
-
`)}}}),ecuc_crosscheck:_({description:"Per-module cross-check table: runs the semantic rule packs for one module (Com, PduR, EcuC, NvM, Fee, Ea, "+"CanIf, Dem, ...) \u2014 config vs System/ECU extract (H2L-SYS), gateway routing vs extract (H2L-PDUR), NvM/Fee "+"length vs the C RAM object's sizeof (H2L-NVM), memory capacity (H2L-MEM), signal packing and handle IDs \u2014 "+"and returns, per element, the findings, plus notes on what could NOT be checked. Run it for every module present after ecuc_validate; a clean validate alone is not proof of a correct configuration."+E,args:{module:d.string().describe("module name, e.g. PduR"),project_dir:d.string().optional()},async execute(e,
|
|
39
|
-
${
|
|
40
|
-
`)}`),...j(l,50),...(n.notes??[]).map((
|
|
41
|
-
`)}}}),arxml_edit:_({description:"Structured edit of NON-ECUC ARXML (System/ECU extract, SWC, interfaces), including NEW files \u2014 never write "+"that XML by hand. Ops: {op:'new_file', file:'Input/SWC_X.arxml', packages:['/Swcs','/Interfaces']} (empty R25-11 file; later ops in the same call can fill it), {op:'add', parent_path, element:'I-SIGNAL', short_name, values:{TAG: value | '->/ref/path' | {nested} | [list]}}, {op:'set', path, element:'START-POSITION', value}, {op:'remove', path}. Missing packages along parent_path are created (top level needs `file` when the project has several ARXML files). Every *-REF gets its DEST from the referenced element's real tag (targets must exist or be added earlier in the same call), elements are placed and ordered per the AUTOSAR schema, references are re-checked and the file is strictly re-loaded; nothing is written if anything fails. For ECUC values use ecuc_edit; to add a whole signal use autosar_add_signal.",args:{ops:R(d.array(R(d.record(d.string(),d.any()))).min(1)).describe("list of ops"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,
|
|
34
|
+
`)}}return{title:`ecuc_validate ${JSON.stringify(f??o.summary)}`,output:A(o)+[S||P,...S?[P]:[],...j(u,e.max??200),...N].join(`
|
|
35
|
+
`)+I}}}),arxml_diff:_({description:"Semantic ARXML diff by AUTOSAR path between two files or directories (e.g. a git checkout of the old Config/ vs the current one, or Output/ before/after generation inputs). Ignores UUIDs, whitespace, comments, element order and file splits; ECUC values are compared per parameter. Returns added/removed/changed elements with the changed parameter values. Use it to review edits and PRs instead of a textual diff.",args:{a:d.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:d.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=await b(n,["diff",e.a,e.b],a.abort);if(!r.ok)return k(r);let{ok:l,engine:o,ms:u,...h}=r;return JSON.stringify(h,null,1)}}),autosar_trace:_({description:"Trace AUTOSAR configuration to code through the H2Loop code graph of the selected project: query with an AUTOSAR path, a SHORT-NAME, or a C symbol (reverse lookup). Returns the ARXML element (path, module, DEFINITION-REF, file:line, values), the C symbols it configures (generated macros/const tables via the symbolic-name rule or token/value matching, with method + score) and their callers in in-house code. For a ComSignal it also shows the owning I-PDU and its ComIPduDirection (direction lives on the I-PDU). Elements in the local checkout get a VALUES block: each value with the file:line of its VALUE element and integers in dec + hex (the graph's file:line is only where the element starts). Use for impact analysis ('what code changes if I change X?') and 'where does this symbol come from?'. Requires the project's code to be ingested."+E,args:{query:d.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:d.number().int().optional().describe("restrict to one code data source"),limit:d.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:d.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,a){let n=await D(e.workspace_id,a.abort),r={query:e.query};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;if(e.limit!==void 0)r.limit=e.limit;let l=await L("/api/v1/mcp/autosar/trace",n,r,a.abort),o=l.matches??[],u=w(a.directory,e.project_dir),h=o.map((S)=>S.arxml).filter((S)=>!!S),[g,f]=await Promise.all([ge(u,h,a.abort),me(u,h,a.abort)]),m=[`${o.length} match(es) for "${e.query}" in workspace ${n}`+(l.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(l.data_sources_queried)})`:""),...ye(l),...g,...f,JSON.stringify(o,null,1)];if(!o.length)m.push("No match: try a SHORT-NAME, a full AUTOSAR path from ecuc_read, or the C symbol.");return{title:`autosar_trace ${e.query}`,output:m.join(`
|
|
36
|
+
`)}}}),autosar_config_lookup:_({description:"Look up one ARXML element in the H2Loop code graph by AUTOSAR path: the element (module, DEFINITION-REF, file:line, values), its direct children, references out and in (who points at it), and linked C symbols. Elements in the local checkout get a VALUES block with each value's VALUE-element file:line and integers in dec + hex. Use it to navigate config relations across the ingested repo (including files not in the local checkout); for local edits use ecuc_read/ecuc_edit."+E,args:{path:d.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:d.number().int().optional().describe("restrict to one code data source"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:d.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,a){let n=await D(e.workspace_id,a.abort),r={path:e.path};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;let l=await L("/api/v1/mcp/autosar/config-lookup",n,r,a.abort),o=l.matches??[],u=w(a.directory,e.project_dir),h=o.map((m)=>m.element).filter((m)=>!!m),[g,f]=await Promise.all([ge(u,h,a.abort),me(u,h,a.abort)]);return{title:`autosar_config_lookup ${e.path}`,output:[`${o.length} match(es) for ${e.path} in workspace ${n}`,...ye(l),...g,...f,JSON.stringify(o,null,1)].join(`
|
|
37
|
+
`)}}}),ecuc_find:_({description:"Structured query over the ECUC configuration \u2014 use it instead of grep/read on ARXML. Filter containers by "+`module, container_def (def short-name, e.g. PduRRoutingPath, ComSignal, NvMBlockDescriptor), where ("ComIPduDirection=SEND, ComBitSize>8"; =, !=, >, <, >=, <=, ~regex), ref_to (containers that reference this path directly or through up to 2 references, e.g. all routing paths whose destination is an EcuC Pdu), and referenced_by (e.g. all ComSignals referenced by I-PDU Y). Returns AUTOSAR paths, the container's file:line (at) and its values, each with "@at:<Param>" (file:line of the VALUE element) and, for integers, "@hex:<Param>".`+E,args:{module:d.string().optional(),container_def:d.string().optional().describe("container definition short-name"),where:d.union([d.string(),d.record(d.string(),d.any())]).optional().describe("conditions on parameter values"),ref_to:d.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:d.string().optional().describe("container whose references define the result set"),limit:d.number().int().min(1).max(500).optional(),project_dir:d.string().optional()},async execute(e,a){let n=["find"];if(e.module)n.push("--module",e.module);if(e.container_def)n.push("--container-def",e.container_def);if(e.where)n.push("--where",typeof e.where==="string"?e.where:JSON.stringify(e.where));if(e.ref_to)n.push("--ref-to",e.ref_to);if(e.referenced_by)n.push("--referenced-by",e.referenced_by);n.push("--limit",String(e.limit??50));let r=await b(w(a.directory,e.project_dir),n,a.abort);if(!r.ok)return A(r)+k(r);let{ok:l,engine:o,ms:u,warnings:h,...g}=r;return A(r)+JSON.stringify(g,null,1)}}),autosar_spec_id_check:_({description:"Check AUTOSAR requirement IDs (SWS_/SRS_/TPS_/ECUC_/RS_ \u2026, e.g. SWS_Com_00197, 'SWS_NvM_00898/00899') "+"against the project's own AUTOSAR spec texts (.hydron/autosar.json `specDocs` globs of .txt/.md exports, or $AUTOSAR_SPEC_DOCS). Returns per ID: DEFINED (with document, line and the requirement text), MENTIONED-ONLY (occurs only in trace tables / running text), NOT-FOUND or MALFORMED. Run it BEFORE citing any ID that did not come verbatim from a tool result; never cite an ID it does not report DEFINED, and describe the rule with the returned text, not from memory.",args:{ids:x().describe("requirement IDs to check (a list, a JSON-encoded list, or one ID)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=C(e.ids)??[];if(!n.length)return'ERROR: pass ids, e.g. ["SWS_Com_00197"]';let r=await b(w(a.directory,e.project_dir),["spec-ids",...n],a.abort);if(!r.ok)return k(r);let l=r.results;return{title:`autosar_spec_id_check ${JSON.stringify(r.counts)}`,output:[`Checked ${l.length} ID(s) against ${r.docs} spec text file(s) (${r.docsOrigin}; ${r.indexedIds} IDs indexed): ${JSON.stringify(r.counts)}`,...l.map((o)=>`${o.id} ${o.status}`+(o.doc?` \u2014 ${o.doc}:${o.line}`:"")+(o.didYouMean?` (did you mean ${o.didYouMean}?)`:"")+(o.text?`
|
|
38
|
+
${o.text}`:"")),l.some((o)=>o.status!=="DEFINED")?"Do not cite IDs that are not DEFINED; state the rule without an ID instead.":""].filter(Boolean).join(`
|
|
39
|
+
`)}}}),ecuc_crosscheck:_({description:"Per-module cross-check table: runs the semantic rule packs for one module (Com, PduR, EcuC, NvM, Fee, Ea, "+"CanIf, Dem, ...) \u2014 config vs System/ECU extract (H2L-SYS), gateway routing vs extract (H2L-PDUR), NvM/Fee "+"length vs the C RAM object's sizeof (H2L-NVM), memory capacity (H2L-MEM), signal packing and handle IDs \u2014 "+"and returns, per element, the findings, plus notes on what could NOT be checked. Run it for every module present after ecuc_validate; a clean validate alone is not proof of a correct configuration."+E,args:{module:d.string().describe("module name, e.g. PduR"),project_dir:d.string().optional()},async execute(e,a){let n=await b(w(a.directory,e.project_dir),["crosscheck",e.module],a.abort);if(!n.ok)return A(n)+k(n);let r=n.rows,l=n.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${n.summary}`,output:[`${e.module}: ${n.summary} (element kinds: ${n.elementKinds.join(", ")||"none"})`,...r.map((o)=>`${o.element} (${o.at})
|
|
40
|
+
${o.findings.join(`
|
|
41
|
+
`)}`),...j(l,50),...(n.notes??[]).map((o)=>`NOTE: ${o}`)].join(`
|
|
42
|
+
`)}}}),arxml_edit:_({description:"Structured edit of NON-ECUC ARXML (System/ECU extract, SWC, interfaces), including NEW files \u2014 never write "+"that XML by hand. Ops: {op:'new_file', file:'Input/SWC_X.arxml', packages:['/Swcs','/Interfaces']} (empty R25-11 file; later ops in the same call can fill it), {op:'add', parent_path, element:'I-SIGNAL', short_name, values:{TAG: value | '->/ref/path' | {nested} | [list]}}, {op:'set', path, element:'START-POSITION', value}, {op:'remove', path}. Missing packages along parent_path are created (top level needs `file` when the project has several ARXML files). Every *-REF gets its DEST from the referenced element's real tag (targets must exist or be added earlier in the same call), elements are placed and ordered per the AUTOSAR schema, references are re-checked and the file is strictly re-loaded; nothing is written if anything fails. For ECUC values use ecuc_edit; to add a whole signal use autosar_add_signal.",args:{ops:R(d.array(R(d.record(d.string(),d.any()))).min(1)).describe("list of ops"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,a){let n=["arxml-edit","--ops",JSON.stringify(T(e.ops))];if(e.dry_run)n.push("--dry-run");let r=await b(w(a.directory,e.project_dir),n,a.abort),l=r.changes??[];if(!r.ok)return k(r)+(r.problems?.length?`
|
|
42
43
|
${r.problems.join(`
|
|
43
44
|
`)}`:"")+(l.length?`
|
|
44
45
|
Rejected diff:
|
|
45
|
-
${l.map((
|
|
46
|
-
`)}`:"");let
|
|
47
|
-
AUTO-VALIDATE (new since ${
|
|
48
|
-
${j(
|
|
46
|
+
${l.map((g)=>g.diff).join(`
|
|
47
|
+
`)}`:"");let o=r.notes??[],u=r.createdPackages??[],h="";if(r.written){let g=await b(w(a.directory,e.project_dir),["validate","--no-check-generated","--new-only","--max","40"],a.abort);if(g.ok!==!1&&g.diagnostics){let f=g.diagnostics.filter((m)=>m.severity==="error"||m.severity==="warning");h=f.length?`
|
|
48
|
+
AUTO-VALIDATE (new since ${g.baseline??"?"}): ${JSON.stringify(g.summaryNew??g.summary)} -- FIX these before going on:
|
|
49
|
+
${j(f,25).join(`
|
|
49
50
|
`)}`:`
|
|
50
|
-
AUTO-VALIDATE: clean (no errors or warnings)`}}return`${r.written?"Written":"Dry run"}; `+((r.newFiles??[]).length?`new file(s) ${r.newFiles.join(", ")}; `:"")+`created ${JSON.stringify(r.created)}`+(u.length?`; new packages ${u.join(", ")}`:"")+(
|
|
51
|
-
NOTE: ${
|
|
51
|
+
AUTO-VALIDATE: clean (no errors or warnings)`}}return`${r.written?"Written":"Dry run"}; `+((r.newFiles??[]).length?`new file(s) ${r.newFiles.join(", ")}; `:"")+`created ${JSON.stringify(r.created)}`+(u.length?`; new packages ${u.join(", ")}`:"")+(o.length?`
|
|
52
|
+
NOTE: ${o.join(`
|
|
52
53
|
NOTE: `)}`:"")+`
|
|
53
|
-
${l.map((
|
|
54
|
-
`)}`+(
|
|
55
|
-
Next: ecuc_validate (checks extract/SWC files too).`)}}),autosar_add_like:_({description:"Add a new X LIKE an existing Y, end to end, in one checked step: a new message (frame, I-PDU, triggerings, EcuC Pdu, CanIf PDU, PduR route, Com I-PDU), port, runnable with its event and task mapping, Dem event + DTC, NvM block + Fee block, interface... Projects name a thing's elements after it, so the engine clones every element whose SHORT-NAME contains `like` and that is linked to the others by references, across ECUC and System/SWC ARXML, renamed to `name`; lists that contain the template get the clone too; handle IDs get the lowest free value; the template's own members (a message's signals) are left out unless named in `also`. `set` then sets values on the clones by ECUC parameter name, XML tag, or 'Owner:key'. Schema + references are checked and validation runs before/after: any new finding rolls everything back. PREFER THIS over building a chain op by op with arxml_edit/ecuc_edit. Example: like='BCM_DoorStatus', name='BCM_SettingsAck', also={'DrvDoorOpenSts':'SettingsAckCounter'}, set={'IDENTIFIER':'0x4F8','CanIfTxPduCanId':'0x4F8','PduLength':2,'FRAME-LENGTH':2,'I-SIGNAL-I-PDU:LENGTH':2,'ComTxModeTimePeriod':1.0,'SettingsAckCounter:ComBitSize':8}. Pick as template the existing element most like the new one (same direction/bus/kind); dry_run first.",args:{like:d.string().describe("name stem of the template element, e.g. BCM_DoorStatus (an existing message), DoorLockActuatorFault (a Dem event)"),name:d.string().describe("the new stem, e.g. BCM_SettingsAck"),also:R(d.record(d.string(),d.string())).optional().describe("template members to clone and rename too: {template stem: new stem}"),set:R(d.record(d.string(),d.any())).optional().describe("values on the clones: {ParamDefName | XML-TAG | 'Owner:key': value}"),seed:d.string().optional().describe("one element of the template chain, when several separate chains carry the stem"),keep_members:d.boolean().optional().describe("also copy the template's own members (default false)"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,
|
|
56
|
-
`)}}),autosar_add_signal:_({description:"Add one Com signal end to end, consistently: ComSignal (ComHandleId = lowest unused; existing handles never move) + ComIPduSignalRef in the ECUC, SYSTEM-SIGNAL / I-SIGNAL / I-SIGNAL-TO-I-PDU-MAPPING and the rest of the signal chain (triggering, port, extract references) in the System extract, and the DBC SG_ line when a .dbc carries the frame. Everything is derived by following references from an existing signal of the same I-PDU. It refuses on overlap or out-of-bounds bits, picks the first free byte-aligned position when bit_position is omitted, runs ecuc_validate after writing and rolls back on any new finding. Then run autosar_generate, use ComConf_ComSignal_<name> in the C code, and autosar_build.",args:{name:d.string(),ipdu:d.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:d.number().int().min(1).max(64).optional(),type:d.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:d.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:d.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:d.union([d.number(),d.string()]).optional(),transfer_property:d.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,
|
|
54
|
+
${l.map((g)=>g.diff).join(`
|
|
55
|
+
`)}`+(h||`
|
|
56
|
+
Next: ecuc_validate (checks extract/SWC files too).`)}}),autosar_add_like:_({description:"Add a new X LIKE an existing Y, end to end, in one checked step: a new message (frame, I-PDU, triggerings, EcuC Pdu, CanIf PDU, PduR route, Com I-PDU), port, runnable with its event and task mapping, Dem event + DTC, NvM block + Fee block, interface... Projects name a thing's elements after it, so the engine clones every element whose SHORT-NAME contains `like` and that is linked to the others by references, across ECUC and System/SWC ARXML, renamed to `name`; lists that contain the template get the clone too; handle IDs get the lowest free value; the template's own members (a message's signals) are left out unless named in `also`. `set` then sets values on the clones by ECUC parameter name, XML tag, or 'Owner:key'. Schema + references are checked and validation runs before/after: any new finding rolls everything back. PREFER THIS over building a chain op by op with arxml_edit/ecuc_edit. Example: like='BCM_DoorStatus', name='BCM_SettingsAck', also={'DrvDoorOpenSts':'SettingsAckCounter'}, set={'IDENTIFIER':'0x4F8','CanIfTxPduCanId':'0x4F8','PduLength':2,'FRAME-LENGTH':2,'I-SIGNAL-I-PDU:LENGTH':2,'ComTxModeTimePeriod':1.0,'SettingsAckCounter:ComBitSize':8}. Pick as template the existing element most like the new one (same direction/bus/kind); dry_run first.",args:{like:d.string().describe("name stem of the template element, e.g. BCM_DoorStatus (an existing message), DoorLockActuatorFault (a Dem event)"),name:d.string().describe("the new stem, e.g. BCM_SettingsAck"),also:R(d.record(d.string(),d.string())).optional().describe("template members to clone and rename too: {template stem: new stem}"),set:R(d.record(d.string(),d.any())).optional().describe("values on the clones: {ParamDefName | XML-TAG | 'Owner:key': value}"),seed:d.string().optional().describe("one element of the template chain, when several separate chains carry the stem"),keep_members:d.boolean().optional().describe("also copy the template's own members (default false)"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,a){let n=["add-like","--like",e.like,"--name",e.name];if(e.also)n.push("--also",JSON.stringify(T(e.also)));if(e.set)n.push("--set",JSON.stringify(T(e.set)));if(e.seed)n.push("--seed",e.seed);if(e.keep_members)n.push("--keep-members");if(e.dry_run)n.push("--dry-run");let r=await b(w(a.directory,e.project_dir),n,a.abort),l=(u)=>r[u]??[],o=[r.ok?`${r.written?"Written":"Dry run OK"}: ${l("created").length} element(s) like ${e.like} as ${e.name}`:`NOT DONE: ${r.error}`,...l("created").length?["Created:",...l("created").map((u)=>` ${u}`)]:[],...l("set").length?["Set:",...l("set").map((u)=>` ${u}`)]:[],...l("ids").length?["Handle IDs:",...l("ids").map((u)=>` ${u}`)]:[],...l("linked").length?["Linked:",...l("linked").map((u)=>` ${u}`)]:[],...l("notCopied").length?[`Not copied (the template's own members): ${l("notCopied").length}`,...l("notCopied").slice(0,12).map((u)=>` ${u}`)]:[],...l("singleValuedNotLinked").length?["Single-valued references to the template NOT changed (add/point your own if the new element needs one):",...l("singleValuedNotLinked").map((u)=>` ${u}`)]:[],...l("notes").map((u)=>`NOTE: ${u}`),...l("todo").length?["STILL TO DO (completeness, not undone):",...l("todo").map((u)=>` ${u}`)]:[],...(r.problems??[]).map((u)=>`PROBLEM: ${u}`),...(r.diagnostics??[]).length?j(r.diagnostics,20):[]];if(r.ok&&!r.written)o.push("Next: run again without dry_run.");if(r.ok&&r.written)o.push(String(r.next??""));return o.join(`
|
|
57
|
+
`)}}),autosar_add_signal:_({description:"Add one Com signal end to end, consistently: ComSignal (ComHandleId = lowest unused; existing handles never move) + ComIPduSignalRef in the ECUC, SYSTEM-SIGNAL / I-SIGNAL / I-SIGNAL-TO-I-PDU-MAPPING and the rest of the signal chain (triggering, port, extract references) in the System extract, and the DBC SG_ line when a .dbc carries the frame. Everything is derived by following references from an existing signal of the same I-PDU. It refuses on overlap or out-of-bounds bits, picks the first free byte-aligned position when bit_position is omitted, runs ecuc_validate after writing and rolls back on any new finding. Then run autosar_generate, use ComConf_ComSignal_<name> in the C code, and autosar_build.",args:{name:d.string(),ipdu:d.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:d.number().int().min(1).max(64).optional(),type:d.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:d.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:d.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:d.union([d.number(),d.string()]).optional(),transfer_property:d.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,a){let n=["add-signal","--name",e.name,"--ipdu",e.ipdu,"--type",e.type??"UINT8"];if(e.bit_size!==void 0)n.push("--bit-size",String(e.bit_size));if(e.bit_position!==void 0)n.push("--bit-position",String(e.bit_position));if(e.endianness)n.push("--endianness",e.endianness);if(e.init!==void 0)n.push("--init",String(e.init));if(e.transfer_property)n.push("--transfer-property",e.transfer_property);if(e.dry_run)n.push("--dry-run");let r=await b(w(a.directory,e.project_dir),n,a.abort);if(!r.ok)return k(r)+(r.diagnostics?.length?`
|
|
57
58
|
${j(r.diagnostics,20).join(`
|
|
58
|
-
`)}`:"");let{ok:l,engine:
|
|
59
|
+
`)}`:"");let{ok:l,engine:o,ms:u,...h}=r;return JSON.stringify(h,null,1)}}),autosar_audit:_({description:"Integration review \u2014 run this FIRST when reviewing C code that uses BSW services. Deterministically scans "+"C files (default: .hydron/autosar.json `audit` paths, else every .c in the project except generated files, "+"recognised by banner or *_Cfg/*_PBcfg/Rte* names \u2014 folder names do not matter) for Com_Send/ReceiveSignal[Group], "+"NvM_Read/WriteBlock/RestoreBlockDefaults, Dem_SetEventStatus/ReportErrorStatus, PduR_*Transmit and Rte_Write_/Rte_Read_ (resolved through the generated Output/ RTE headers), resolves every handle through the ECUC (symbolic name or raw number), and reports: H2L-API-001 raw numeric handle, -002 unknown handle, -003 direction mismatch (send on a RECEIVE I-PDU signal or receive on SEND), -004 C object width vs ComSignalType, -005 NvM NULL_PTR without a permanent RAM block (NULL_PTR WITH one is valid, SWS_NvM_00900). Each finding has file:line, evidence (configured values + AUTOSAR paths) and a spec citation; calls it cannot check are listed as unchecked, never guessed. Confirm findings with ecuc_read / autosar_trace.",args:{paths:x().describe("C files, directories or globs to scan (default: .hydron/autosar.json audit paths, else every .c under the project except generator output); matching nothing is an ERROR"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=await b(n,["audit",...C(e.paths)??[]],a.abort);if(!r.ok)return A(r)+k(r);let l=(r.notes??[]).map((m)=>`NOTE: ${m}`),{findings:o,unchecked:u,scanned:h}=r,g=[`Scanned ${h.sources.length} C file(s), ${h.calls} BSW call(s): ${o.length?JSON.stringify(r.summary):"no findings"}`,...o.map((m)=>`${m.file}:${m.line} ${m.severity.toUpperCase()} ${m.rule} ${m.call}
|
|
59
60
|
${m.message}
|
|
60
61
|
evidence: ${JSON.stringify(m.evidence)}
|
|
61
62
|
spec: ${m.cite}${m.fix?`
|
|
62
|
-
fix: ${m.fix}`:""}`)];if(u.length)
|
|
63
|
-
`)}}}),autosar_verify_rte:_({description:"Verify Rte_* calls in C against the SW-C description (SWS_RTE naming, R25-11). Each call is mapped to its enclosing function, then to every runnable whose entry point (RUNNABLE-ENTITY SYMBOL) reaches it, and classified: OK (the runnable has the access point), NOT-ALLOWED (the API exists for the SW-C but this runnable has no dataSendPoint/dataReceivePoint/serverCallPoint/... for it), INVENTED (no such port, element, runnable, or wrong direction/semantics). For NOT-ALLOWED/INVENTED it returns ready-to-run arxml_edit ops (dry-run checked) that add the access point / port / data element. Run it after writing runnable code and never finish with a failing verify.",args:{paths:x().describe("C files, directories or globs (default: all in-house C)"),diff_against:d.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:d.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:d.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,
|
|
64
|
-
`),metadata:{counts:u}}}}),autosar_build_context:_({description:"GROUND step: call this FIRST for any change. Two modes. (1) target=<module, container or element> for a configuration change (e.g. an MCAL Can/Fls/Port change): the element's current values with file:line and its param-def schema (allowed params, types, ranges, literals, multiplicity), plus the constraints the ingested specs/manuals give for it. (2) swc(+runnable) for C: assemble the context for implementing or changing a runnable, deterministically (same inputs -> byte-identical text) in a fixed order: 1 task, 2 SW-C definition (ports, interfaces, types, runnables, events), 3 ALLOWED RTE API for the runnable with the exact declarations from Rte_<Swc>.h (else SWS_RTE signatures), 4 the runnable's current C body, 5 functions it calls, 6 related config (Com signals / NvM blocks behind its ports), 7 FUZZY similar functions in other SW-Cs, 8 FUZZY similar past git changes (ARXML delta + C hunks). Fits budget_tokens (~4 chars/token) by dropping 8, 7, then shortening bodies; never the allowed API. Returns the text plus a JSON manifest of every source included. Call it FIRST for any runnable task and use only the allowed APIs it lists. Both modes append DOC FACTS from the selected Hydron project's ingested documents (docs=false skips; the retriever can take minutes, results are cached per session). Plan only from these facts and cite them (F#/D#); a fact you could not ground is an open question, not a guess.",args:{swc:d.string().optional().describe("SW-C short name or AUTOSAR path (runnable/C mode)"),target:d.string().optional().describe("configuration mode: module, container or element (AUTOSAR path, SHORT-NAME or partial path), e.g. 'Can', 'CanController_0'"),docs:d.boolean().optional().describe("add DOC FACTS from the ingested documents (default true)"),runnable:d.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:d.string().describe("the task, verbatim"),budget_tokens:d.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:d.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,
|
|
65
|
-
`):[`(${e.target} is not an ECUC element this engine can read: ${String(
|
|
63
|
+
fix: ${m.fix}`:""}`)];if(u.length)g.push(`Unchecked (${u.length}):`,...u.slice(0,50).map((m)=>` ${m.file}:${m.line} ${m.call} \u2014 ${m.reason}`));let f=r.unreferenced??{};for(let[m,S]of Object.entries(f))g.push(`INFO configured but never referenced in the scanned code \u2014 ${m}: ${S.count} (e.g. ${S.sample.slice(0,5).join(", ")})`);return g.push(...l),{title:`autosar_audit ${JSON.stringify(r.summary)}`,output:A(r)+g.join(`
|
|
64
|
+
`)}}}),autosar_verify_rte:_({description:"Verify Rte_* calls in C against the SW-C description (SWS_RTE naming, R25-11). Each call is mapped to its enclosing function, then to every runnable whose entry point (RUNNABLE-ENTITY SYMBOL) reaches it, and classified: OK (the runnable has the access point), NOT-ALLOWED (the API exists for the SW-C but this runnable has no dataSendPoint/dataReceivePoint/serverCallPoint/... for it), INVENTED (no such port, element, runnable, or wrong direction/semantics). For NOT-ALLOWED/INVENTED it returns ready-to-run arxml_edit ops (dry-run checked) that add the access point / port / data element. Run it after writing runnable code and never finish with a failing verify.",args:{paths:x().describe("C files, directories or globs (default: all in-house C)"),diff_against:d.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:d.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:d.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=["verify-rte",...C(e.paths)??[]];if(e.diff_against)r.push("--diff-against",e.diff_against);if(e.swc)r.push("--swc",e.swc);if(e.runnable)r.push("--runnable",e.runnable);let l=await b(n,r,a.abort);if(!l.ok)return k(l);let{findings:o,counts:u}=l,h=o.filter((y)=>y.status!=="OK"),g=l.scanned,f=[`Verified ${g.calls} Rte_* call(s) in ${g.files.length} file(s) against SW-C(s) ${l.swcs.join(", ")}: OK ${u.OK}, NOT-ALLOWED ${u["NOT-ALLOWED"]}, INVENTED ${u.INVENTED}`+(h.length?" \u2014 FAILING":" \u2014 PASS")];for(let y of h){if(f.push(`${y.at} ${y.status} ${y.call} in ${y.function}() [${y.swc??"?"}${y.runnable?`/${y.runnable}`:""}]`,` ${y.why}`),y.expected)f.push(` expected: ${y.expected} [${y.cite}]`);if(y.hint)f.push(` hint: ${y.hint}`);if(y.arxml_edit?.length)f.push(` fix (arxml_edit ops${y.opsChecked===!0?", dry-run OK":y.opsChecked?`, dry-run FAILED: ${y.opsChecked}`:""}): ${JSON.stringify(y.arxml_edit)}`)}let m=l.notChecked??[];if(m.length)f.push(`Not checked (${m.length}): ${m.map((y)=>`${y.call} @ ${y.at}`).join(", ")}`);let S=l.runnablesWithoutCode??[];if(S.length)f.push(`Runnables without a C definition: ${S.map((y)=>`${y.swc}.${y.runnable} (${y.symbol})`).join(", ")}`);for(let y of l.notes??[])f.push(`NOTE: ${y}`);if(h.length)f.push("Next: rewrite the call with an allowed API (autosar_build_context lists them), or \u2014 only if the behaviour "+"truly needs new data \u2014 apply the ops with arxml_edit, run autosar_generate, then autosar_verify_rte again.");return{title:`autosar_verify_rte ${h.length?"FAIL":"PASS"} ${JSON.stringify(u)}`,output:f.join(`
|
|
65
|
+
`),metadata:{counts:u}}}}),autosar_build_context:_({description:"GROUND step: call this FIRST for any change. Two modes. (1) target=<module, container or element> for a configuration change (e.g. an MCAL Can/Fls/Port change): the element's current values with file:line and its param-def schema (allowed params, types, ranges, literals, multiplicity), plus the constraints the ingested specs/manuals give for it. (2) swc(+runnable) for C: assemble the context for implementing or changing a runnable, deterministically (same inputs -> byte-identical text) in a fixed order: 1 task, 2 SW-C definition (ports, interfaces, types, runnables, events), 3 ALLOWED RTE API for the runnable with the exact declarations from Rte_<Swc>.h (else SWS_RTE signatures), 4 the runnable's current C body, 5 functions it calls, 6 related config (Com signals / NvM blocks behind its ports), 7 FUZZY similar functions in other SW-Cs, 8 FUZZY similar past git changes (ARXML delta + C hunks). Fits budget_tokens (~4 chars/token) by dropping 8, 7, then shortening bodies; never the allowed API. Returns the text plus a JSON manifest of every source included. Call it FIRST for any runnable task and use only the allowed APIs it lists. Both modes append DOC FACTS from the selected Hydron project's ingested documents (docs=false skips; the retriever can take minutes, results are cached per session). Plan only from these facts and cite them (F#/D#); a fact you could not ground is an open question, not a guess.",args:{swc:d.string().optional().describe("SW-C short name or AUTOSAR path (runnable/C mode)"),target:d.string().optional().describe("configuration mode: module, container or element (AUTOSAR path, SHORT-NAME or partial path), e.g. 'Can', 'CanController_0'"),docs:d.boolean().optional().describe("add DOC FACTS from the ingested documents (default true)"),runnable:d.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:d.string().describe("the task, verbatim"),budget_tokens:d.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:d.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=e.docs!==!1;if(!e.swc){if(!e.target)return"ERROR: give target (configuration change) or swc (+runnable, for C code).";let f=await b(n,["read",e.target,"--depth","3","--schema"],a.abort),{ok:m,engine:S,ms:y,...P}=f,N=f.ok?JSON.stringify(P,null,1).split(`
|
|
66
|
+
`):[`(${e.target} is not an ECUC element this engine can read: ${String(f.error??"").slice(0,300)}; for System/SWC ARXML read the element or its file, and use autosar_config_lookup / ecuc_find)`],I=N.length>400?`${N.slice(0,400).join(`
|
|
66
67
|
`)}
|
|
67
68
|
\u2026 (${N.length-400} more lines: narrow the target)`:N.join(`
|
|
68
|
-
`),v=r?await K(`For this AUTOSAR configuration task: "${e.task}". The element concerned is ${e.target}. From the specifications and manuals in this knowledge base, list every constraint, default, allowed range or literal, multiplicity, dependency on other parameters or modules, and hardware limit of the target microcontroller that applies to it and to what the task changes, each with the document name and section or requirement ID.`,
|
|
69
|
+
`),v=r?await K(`For this AUTOSAR configuration task: "${e.task}". The element concerned is ${e.target}. From the specifications and manuals in this knowledge base, list every constraint, default, allowed range or literal, multiplicity, dependency on other parameters or modules, and hardware limit of the target microcontroller that applies to it and to what the task changes, each with the document name and section or requirement ID.`,a.sessionID,e.workspace_id,a.abort):"(skipped: docs=false)";return{title:`autosar_build_context target ${e.target}`,output:["# CONTEXT (configuration change)",`## 1. TASK
|
|
69
70
|
${e.task}`,`## 2. PROJECT FACTS [F]: current values with @at file:line, and the param-def schema (what may be set)
|
|
70
71
|
${I}`,`## 3. DOC FACTS [D]: from the ingested documents
|
|
71
72
|
${v}`,`## 4. NEXT
|
|
72
73
|
Write the facts you will rely on as a numbered list (F1.. from section 2 with their @at, D1.. from section 3 with their citation). Plan the change from those facts only, in dependency order, citing them. Anything you could not ground: look it up (ecuc_find, ecuc_read, autosar_config_lookup) or ask; never guess a value, id or reference target. Then edit (ecuc_edit / arxml_edit), ecuc_validate until clean, then ecuc_validate docs=true and answer its checklist.`].join(`
|
|
73
74
|
|
|
74
|
-
`)}}let l=["build-context","--swc",e.swc,"--task",e.task,"--budget-tokens",String(e.budget_tokens??24000)];if(e.runnable)l.push("--runnable",e.runnable);let
|
|
75
|
-
${JSON.stringify(y.matches??[],null,1).slice(0,6000)}`)}}catch(m){
|
|
75
|
+
`)}}let l=["build-context","--swc",e.swc,"--task",e.task,"--budget-tokens",String(e.budget_tokens??24000)];if(e.runnable)l.push("--runnable",e.runnable);let o=await b(n,l,a.abort);if(!o.ok)return k(o);let u=o.text,h=o.codeMissing??[];if(h.length&&e.use_backend){let f=[];try{let m=await D(e.workspace_id,a.abort);for(let S of h){let y=await L("/api/v1/mcp/autosar/trace",m,{query:S,limit:3},a.abort);f.push(`### backend trace for ${S} (workspace ${m})
|
|
76
|
+
${JSON.stringify(y.matches??[],null,1).slice(0,6000)}`)}}catch(m){f.push(`(backend lookup unavailable: ${m instanceof Error?m.message:String(m)})`)}u+=`
|
|
76
77
|
## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
|
|
77
|
-
${
|
|
78
|
+
${f.join(`
|
|
78
79
|
`)}
|
|
79
|
-
`}if(r){let
|
|
80
|
+
`}if(r){let f=await K(`For this AUTOSAR task: "${e.task}" in SW-C ${e.swc}${e.runnable?`, runnable ${e.runnable}`:""}. From the specifications and manuals in this knowledge base, list the requirements and constraints that apply (RTE API semantics, timing, data handling, BSW service usage), each with the document name and section or requirement ID.`,a.sessionID,e.workspace_id,a.abort);u+=`
|
|
80
81
|
## 9. DOC FACTS [D] from the ingested documents (not part of the deterministic context)
|
|
81
|
-
${
|
|
82
|
-
`}let
|
|
82
|
+
${f}
|
|
83
|
+
`}let g={swc:o.swc,runnables:o.runnables,estimatedTokens:o.estimatedTokens,budgetTokens:o.budgetTokens,reductions:o.reductions,overBudget:o.overBudget??!1,sha1:o.sha1,sections:o.sections,sources:o.manifest};return{title:`autosar_build_context ${o.swc}${o.runnables.length===1?`/${o.runnables[0]}`:""} ~${o.estimatedTokens} tok`,output:`${u}
|
|
83
84
|
---
|
|
84
|
-
MANIFEST ${JSON.stringify(
|
|
85
|
-
${
|
|
86
|
-
`)}`:"")}let{modules:
|
|
85
|
+
MANIFEST ${JSON.stringify(g)}`,metadata:{sha1:o.sha1,estimatedTokens:o.estimatedTokens}}}}),autosar_codegen:_({description:"Deterministic BSW configuration code generation from the ECUC ARXML + param defs (no LLM output: the same ARXML always gives the same C). Modules: NvM, MemIf, Fee, Ea, Dem, PduR, CanIf, Port, Dio, and every configured MCAL driver (Mcu, Gpt, Can, Adc, Pwm, Icu, Spi, Wdg, Lin, Fls, ...: generic def-driven tables with enum literal names and *Notification function pointers); any other configured module can be named. Emits <Mip>_Cfg.h (pre-compile #defines, STD_ON/STD_OFF, <MIP>_CFG_* version macros, TPS_ECUC_02108 symbols <Mip>Conf_<ContainerDef>_<Name>), <Mip>_Cfg.c / _Lcfg.c / _PBcfg.c by each parameter's config class, const tables for multiplicity-n containers, MemMap-wrapped, SchM_<Mip>.h and <Mip>_MemMap.h. Static-code struct layouts (the SIP's NvM_BlockDescriptorType, PduR_RoutingPathType, ...) come from a binding selected by the project's headers. Missing handle IDs are assigned deterministically and written back into the ECUC ARXML in place (TPS_ECUC_02107) unless write_back=false. Writes to the scratch dir .hydron/codegen/out unless out_dir is given: when the user wants the files in Output/ (or another folder), pass out_dir='Output'. Follow with autosar_codegen_diff against the existing Output/, then autosar_build.",args:{modules:x().describe("modules to generate (default: every supported module that is configured)"),out_dir:d.string().optional().describe("output dir, relative to the project or absolute; 'project' = codegen.outDir / Output. Default: scratch .hydron/codegen/out"),write_back:d.boolean().optional().describe("write assigned handle IDs into the ECUC ARXML (default true)"),binding:d.string().optional().describe("force a static-code binding (e.g. 'sip-standin'), or 'none' for generic tables only"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=["codegen"];for(let f of C(e.modules)??[])r.push("--module",f);if(e.out_dir)r.push("--out",e.out_dir);if(e.write_back===!1)r.push("--no-write-back");if(e.binding)r.push("--binding",e.binding);let l=await b(n,r,a.abort);if(!l.ok){let f=l.handleErrors??[];return A(l)+k(l)+(f.length?`
|
|
86
|
+
${f.map((m)=>` ${m}`).join(`
|
|
87
|
+
`)}`:"")}let{modules:o,handles:u,timings:h}=l,g=[`Generated ${Object.keys(o).length} module(s) into ${l.outDir} in ${h.total_ms} ms (AUTOSAR R${l.release}):`,...Object.entries(o).map(([f,m])=>` ${f} (${m.variant}${m.binding?`, binding ${m.binding}`:", generic tables"}): ${m.files.join(", ")}; ${m.symbols} symbol(s)`+m.notes.map((S)=>`
|
|
87
88
|
NOTE: ${S}`).join("")),u.assigned.length?`Assigned ${u.assigned.length} handle ID(s) (${u.writtenBack?"written back into the ECUC ARXML":"in memory only, NOT written back"}):
|
|
88
|
-
`+u.assigned.slice(0,40).map((
|
|
89
|
+
`+u.assigned.slice(0,40).map((f)=>` ${f.path}/${f.param} = ${f.value} (hex ${we(f.value)})`).join(`
|
|
89
90
|
`)+(u.changes.length?`
|
|
90
|
-
${u.changes.map((
|
|
91
|
-
`)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(l.notes??[]).map((
|
|
92
|
-
`)}}}),autosar_codegen_diff:_({description:"Semantic diff of generated C configuration code against a reference dir (e.g. the vendor-generated Output/): compares #define names and values and the contents of every initialised table/struct element by element, plus table ordering, after normalising numbers (0x2A0u == 672), casts, parentheses and macro references. Ignores formatting, comments, banners and include order. Reports per module: matching symbols, missing (in reference only), extra (generated only), value mismatches with both values.",args:{reference_dir:d.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:d.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:x().describe("only these modules"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,
|
|
91
|
+
${u.changes.map((f)=>f.diff).join(`
|
|
92
|
+
`)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(l.notes??[]).map((f)=>`NOTE: ${f}`)];return{title:`autosar_codegen ${Object.keys(o).join(", ")}`,output:A(l)+g.join(`
|
|
93
|
+
`)}}}),autosar_codegen_diff:_({description:"Semantic diff of generated C configuration code against a reference dir (e.g. the vendor-generated Output/): compares #define names and values and the contents of every initialised table/struct element by element, plus table ordering, after normalising numbers (0x2A0u == 672), casts, parentheses and macro references. Ignores formatting, comments, banners and include order. Reports per module: matching symbols, missing (in reference only), extra (generated only), value mismatches with both values.",args:{reference_dir:d.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:d.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:x().describe("only these modules"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,a){let n=w(a.directory,e.project_dir),r=["codegen-diff",e.reference_dir];if(e.generated_dir)r.push(e.generated_dir);for(let h of C(e.modules)??[])r.push("--module",h);let l=await b(n,r,a.abort);if(!l.ok)return k(l);let o=l.modules,u=[`Semantic diff ${l.reference} (reference) vs ${l.generated} (generated): ${JSON.stringify(l.total)}`,`Not generated (reference only): ${l.notGenerated.join(", ")||"-"}; not in reference: ${l.notInReference.join(", ")||"-"}`];for(let[h,g]of Object.entries(o)){if(u.push(`== ${h}: ${g.summary.matching} matching, ${g.summary.missing} missing, ${g.summary.extra} extra, ${g.summary.mismatches} mismatch(es); table elements ${g.elements.match} equal / ${g.elements.mismatch} different`),g.defines.missing.length)u.push(` missing #define: ${g.defines.missing.slice(0,30).join(", ")}`);for(let f of g.defines.mismatch.slice(0,30))u.push(` #define ${f.name}: reference ${f.reference} | generated ${f.generated}`);if(g.objects.missing.length)u.push(` missing object: ${g.objects.missing.join(", ")}`);if(g.objects.extra.length)u.push(` extra object: ${g.objects.extra.join(", ")}`);for(let f of g.objects.order)u.push(` order differs: ${f.name} (same rows)`);for(let f of g.objects.mismatch)u.push(` ${f.name}: ${f.count} element(s) differ`,...f.elements.slice(0,12).map((m)=>` ${m.element}: reference ${m.reference} | generated ${m.generated}`));if(g.defines.extra.length)u.push(` extra #define (${g.defines.extra.length}): ${g.defines.extra.slice(0,12).join(", ")}${g.defines.extra.length>12?", \u2026":""}`)}return{title:`autosar_codegen_diff ${JSON.stringify(l.total)}`,output:u.join(`
|
|
93
94
|
`)}}}),autosar_generate:s("generate"),autosar_build:s("build")}),t)}},tt=et;export{tt as Autosar};
|
|
@@ -62,6 +62,10 @@ def _scan_c(root: str, exclude: list) -> tuple:
|
|
|
62
62
|
return headers, sources
|
|
63
63
|
|
|
64
64
|
|
|
65
|
+
MCAL_LAYER = {"Mcu", "Port", "Dio", "Gpt", "Wdg", "Can", "CanXL", "Lin", "Fr", "Eth", "Spi", "Adc", "Pwm", "Icu", "Ocu",
|
|
66
|
+
"Fls", "Eep", "Mem", "Crypto", "Cdd"}
|
|
67
|
+
|
|
68
|
+
|
|
65
69
|
def resolve_out(root: str, out_dir: Optional[str], opts: dict) -> str:
|
|
66
70
|
if not out_dir:
|
|
67
71
|
return os.path.join(root, SCRATCH)
|
|
@@ -89,7 +93,9 @@ def generate(project: Project, modules: Optional[list] = None, out_dir: Optional
|
|
|
89
93
|
return {"ok": False, "error": f"module {m!r} is not configured (configured: {', '.join(configured)})"}
|
|
90
94
|
want.append(hit[0])
|
|
91
95
|
else:
|
|
92
|
-
|
|
96
|
+
# registered generators + the MCAL layer (SRS_BSW layered architecture: microcontroller drivers), whose
|
|
97
|
+
# generic tables come straight from the defs; other unregistered modules only when asked for by name
|
|
98
|
+
want = [m for m in configured if m in registered() or m in MCAL_LAYER]
|
|
93
99
|
if not project.defs:
|
|
94
100
|
return {"ok": False, "error": "code generation needs the ECUC param defs (paramDefs in .hydron/autosar.json "
|
|
95
101
|
"or $AUTOSAR_PARAMDEFS): config classes and types come from them"}
|
|
@@ -93,6 +93,16 @@ def int_ctype(lo: Optional[int], hi: Optional[int]) -> str:
|
|
|
93
93
|
return "uint64"
|
|
94
94
|
|
|
95
95
|
|
|
96
|
+
NOTIFY = "@notification" # placeholder ctype, resolved per module to <Mip>_CfgNotificationType
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def is_notification(d: D.DefNode) -> bool:
|
|
100
|
+
"""FUNCTION-NAME params named *Notification are the SWS 'void <name>(void)' callbacks (Gpt/Icu/Pwm/Adc/Spi/
|
|
101
|
+
Wdg/Fls/Com notifications); they get a function-pointer field. Other function names (callouts with
|
|
102
|
+
module-specific signatures) stay bound to static-code prototypes."""
|
|
103
|
+
return d.kind == "FUNCTION-NAME" and (d.name or "").endswith("Notification")
|
|
104
|
+
|
|
105
|
+
|
|
96
106
|
def param_ctype(d: D.DefNode) -> Optional[str]:
|
|
97
107
|
"""Platform type for a param def in a generated table, or None if it has no table representation."""
|
|
98
108
|
k = d.kind
|
|
@@ -104,6 +114,8 @@ def param_ctype(d: D.DefNode) -> Optional[str]:
|
|
|
104
114
|
return "float64"
|
|
105
115
|
if k == "ENUMERATION":
|
|
106
116
|
return "uint8" if len(d.literals) <= 256 else "uint16"
|
|
117
|
+
if k == "FUNCTION-NAME" and is_notification(d):
|
|
118
|
+
return NOTIFY
|
|
107
119
|
return None # STRING / FUNCTION-NAME / LINKER-SYMBOL / MULTILINE-STRING bind to static-code prototypes
|
|
108
120
|
|
|
109
121
|
|
|
@@ -126,6 +138,9 @@ def macro_value(d: Optional[D.DefNode], raw: str) -> str:
|
|
|
126
138
|
def table_value(d: Optional[D.DefNode], raw: Optional[str], hexa: bool = False) -> tuple:
|
|
127
139
|
"""(C initialiser, comment) of a param value in a generated table."""
|
|
128
140
|
k = d.kind if d is not None else None
|
|
141
|
+
if k == "FUNCTION-NAME":
|
|
142
|
+
fn = (raw or "").strip()
|
|
143
|
+
return (fn if fn and fn != "NULL_PTR" and C_EXPR.match(fn) else "NULL_PTR", "" if fn else "no notification")
|
|
129
144
|
if raw is None:
|
|
130
145
|
raw = d.default if d is not None and d.default is not None else None
|
|
131
146
|
if raw is None:
|
|
@@ -402,6 +402,11 @@ def _value(cg: CgModel, mo: ModuleOutput, row: Container, f: Field) -> tuple:
|
|
|
402
402
|
mask |= 1 << d.literals.index(x)
|
|
403
403
|
return (W.c_uint(mask, hexa=True), "|".join(lits))
|
|
404
404
|
raw = owner.text(d.name) if owner is not None else None
|
|
405
|
+
if d.kind == "ENUMERATION":
|
|
406
|
+
lit = (raw if raw is not None else d.default or "").strip()
|
|
407
|
+
if lit in d.literals and all(x.upper().startswith(mo.MIP + "_") for x in d.literals):
|
|
408
|
+
enum_literals(mo, d) # guarded #defines in the header; the table names the literal
|
|
409
|
+
return (lit, "")
|
|
405
410
|
return W.table_value(d, raw)
|
|
406
411
|
|
|
407
412
|
|
|
@@ -425,6 +430,12 @@ def generic_tables(cg: CgModel, mo: ModuleOutput, skip: set):
|
|
|
425
430
|
fields = [Field("Parent", "uint16", [], parent=True)] + fields
|
|
426
431
|
if not fields:
|
|
427
432
|
continue
|
|
433
|
+
for f in fields:
|
|
434
|
+
if f.ctype == W.NOTIFY:
|
|
435
|
+
f.ctype = f"{mo.mip}_CfgNotificationType"
|
|
436
|
+
td = f"typedef void (*{f.ctype})(void);"
|
|
437
|
+
if td not in mo.types:
|
|
438
|
+
mo.types.insert(0, td)
|
|
428
439
|
tname = f"{mo.mip}_Cfg{dname}Type"
|
|
429
440
|
oname = f"{mo.mip}_Cfg{dname}"
|
|
430
441
|
rank = max([cg.eff_class(mc, f.d) for f in fields if f.d is not None] + [cg.eff_class(mc, cdef), 1])
|
|
@@ -437,6 +448,10 @@ def generic_tables(cg: CgModel, mo: ModuleOutput, skip: set):
|
|
|
437
448
|
for f in fields:
|
|
438
449
|
v, n = _value(cg, mo, r, f)
|
|
439
450
|
vals.append(v)
|
|
451
|
+
for f, v in zip(fields, vals):
|
|
452
|
+
proto = f"extern void {v}(void);"
|
|
453
|
+
if f.d is not None and W.is_notification(f.d) and v != "NULL_PTR" and proto not in mo.hdecls:
|
|
454
|
+
mo.hdecls.append(proto)
|
|
440
455
|
sym = cg.symbol(r)
|
|
441
456
|
lines.append(W.initializer(vals, sym or r.name))
|
|
442
457
|
multi = cdef.upper != 1 or len(rows) > 1
|
|
@@ -37,12 +37,19 @@ class EditError(Exception):
|
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
class Editor:
|
|
40
|
+
notes: list
|
|
41
|
+
|
|
40
42
|
def __init__(self, project: Project):
|
|
41
43
|
self.p = project
|
|
42
44
|
self.original: dict[str, bytes] = {}
|
|
43
45
|
self.notes: list = []
|
|
44
46
|
|
|
45
47
|
# ---------- low-level byte patching ----------
|
|
48
|
+
def note(self, msg: str):
|
|
49
|
+
if not hasattr(self, "notes"):
|
|
50
|
+
self.notes = []
|
|
51
|
+
self.notes.append(msg)
|
|
52
|
+
|
|
46
53
|
def data(self, f: str) -> bytes:
|
|
47
54
|
return self.p.files[f].data
|
|
48
55
|
|
|
@@ -286,18 +293,52 @@ class Editor:
|
|
|
286
293
|
g = self.container(path)
|
|
287
294
|
pd = self.child_def(g[0], op["param"], "parameter")
|
|
288
295
|
have = sum(1 for e in g for pv in e.params if pv.name == pd.name)
|
|
296
|
+
if pd.upper == 1 and have == 1 and not isinstance(op.get("value"), list):
|
|
297
|
+
self.note(f"{pd.name} on {path} already has a value and allows one: set instead of add")
|
|
298
|
+
self.op_set({"op": "set", "path": path, "param": pd.name, "value": op.get("value")})
|
|
299
|
+
return
|
|
289
300
|
if pd.upper is not None and have >= pd.upper:
|
|
290
301
|
raise EditError(f"{pd.name} already has {have} value(s), def allows {pd.mult}; use set")
|
|
291
|
-
|
|
292
|
-
|
|
302
|
+
vals = op.get("value") if isinstance(op.get("value"), list) else [op.get("value")]
|
|
303
|
+
if pd.upper is not None and have + len(vals) > pd.upper:
|
|
304
|
+
raise EditError(f"{pd.name}: {len(vals)} value(s) would exceed the def's {pd.mult} (has {have}); use set")
|
|
305
|
+
for v in vals:
|
|
306
|
+
self.check(pd, v)
|
|
307
|
+
for v in vals:
|
|
308
|
+
self._add_value(path, pd, v)
|
|
293
309
|
return
|
|
294
310
|
key = op.get("container")
|
|
295
311
|
if not key:
|
|
296
312
|
raise EditError("add needs 'container' (\"DefName:ShortName\") or 'param' + 'value'")
|
|
297
313
|
dname, _, sname = key.partition(":")
|
|
314
|
+
unnamed = not sname
|
|
298
315
|
sname = sname or dname
|
|
299
316
|
g = self.container(path)
|
|
300
|
-
|
|
317
|
+
try:
|
|
318
|
+
cd = self.child_def(g[0], dname, "container")
|
|
319
|
+
except EditError as first:
|
|
320
|
+
# a ComSignal added under its ComIPdu belongs under ComConfig: use the nearest ancestor that takes it
|
|
321
|
+
anc = path
|
|
322
|
+
cd = None
|
|
323
|
+
while "/" in anc.strip("/"):
|
|
324
|
+
anc = anc.rsplit("/", 1)[0]
|
|
325
|
+
ga = self.p.find(anc)
|
|
326
|
+
if not ga:
|
|
327
|
+
continue
|
|
328
|
+
try:
|
|
329
|
+
cd = self.child_def(ga[0], dname, "container")
|
|
330
|
+
except EditError:
|
|
331
|
+
continue
|
|
332
|
+
self.note(f"{dname} cannot go under {path}; added under {anc} instead (where its def allows it)"
|
|
333
|
+
+ (" -- attach it to its owner with the owner's reference (e.g. ComIPduSignalRef), or use "
|
|
334
|
+
"autosar_add_signal which does both" if dname == "ComSignal" else ""))
|
|
335
|
+
path, g = anc, ga
|
|
336
|
+
break
|
|
337
|
+
if cd is None:
|
|
338
|
+
raise first
|
|
339
|
+
if unnamed and (cd.upper is None or cd.upper > 1):
|
|
340
|
+
raise EditError(f"container {cd.name} needs a SHORT-NAME: container \"{cd.name}:<Name>\" (only a single-instance "
|
|
341
|
+
"container may be named after its def)")
|
|
301
342
|
new_path = f"{path}/{sname}"
|
|
302
343
|
if self.p.find(new_path):
|
|
303
344
|
raise EditError(f"{new_path} already exists")
|
|
@@ -357,6 +398,120 @@ class Editor:
|
|
|
357
398
|
|
|
358
399
|
|
|
359
400
|
OP_KEYS = {"op", "path", "param", "value", "container", "values"}
|
|
401
|
+
_PATHISH = ("VALUE", "value", "ref", "$ref", "path", "REF", "VALUE-REF")
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _unwrap_ref(v):
|
|
405
|
+
"""{"VALUE": "/a/b", "VALUE-REF DEST": ...} / {"ref": ...} -> "/a/b" (lists element-wise)."""
|
|
406
|
+
if isinstance(v, list):
|
|
407
|
+
return [_unwrap_ref(x) for x in v]
|
|
408
|
+
if isinstance(v, dict):
|
|
409
|
+
for k in _PATHISH:
|
|
410
|
+
if isinstance(v.get(k), str) and v[k].lstrip("->").strip().startswith("/"):
|
|
411
|
+
return v[k]
|
|
412
|
+
return v
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def normalize_ops(project: Project, ops, notes: list):
|
|
416
|
+
"""Accept the shapes agents use for ECUC edits (arxml_edit's keys, SHORT-NAME given separately, refs as objects,
|
|
417
|
+
params added to a container that does not exist yet) and rewrite them into ecuc_edit's own; note each rewrite."""
|
|
418
|
+
if isinstance(ops, dict):
|
|
419
|
+
ops = [ops]
|
|
420
|
+
if not isinstance(ops, list):
|
|
421
|
+
return ops
|
|
422
|
+
out = []
|
|
423
|
+
for i, op in enumerate(ops):
|
|
424
|
+
if not isinstance(op, dict):
|
|
425
|
+
out.append(op)
|
|
426
|
+
continue
|
|
427
|
+
op = dict(op)
|
|
428
|
+
if "path" not in op and isinstance(op.get("parent_path"), str):
|
|
429
|
+
op["path"] = op.pop("parent_path")
|
|
430
|
+
notes.append(f"op {i}: 'parent_path' read as 'path'")
|
|
431
|
+
sn = None
|
|
432
|
+
for k in ("short_name", "name", "shortName"):
|
|
433
|
+
if isinstance(op.get(k), str):
|
|
434
|
+
sn = op.pop(k)
|
|
435
|
+
break
|
|
436
|
+
vals = op.get("values")
|
|
437
|
+
if sn is None and isinstance(vals, dict) and isinstance(vals.get("SHORT-NAME"), str):
|
|
438
|
+
vals = dict(vals)
|
|
439
|
+
sn = vals.pop("SHORT-NAME")
|
|
440
|
+
op["values"] = vals
|
|
441
|
+
if not op.get("container") and isinstance(op.get("element"), str) and op.get("op") == "add":
|
|
442
|
+
op["container"] = op.pop("element")
|
|
443
|
+
elif "element" in op and op.get("op") == "set" and not op.get("param"):
|
|
444
|
+
op["param"] = op.pop("element")
|
|
445
|
+
else:
|
|
446
|
+
op.pop("element", None)
|
|
447
|
+
if sn is not None:
|
|
448
|
+
if isinstance(op.get("container"), str) and ":" not in op["container"]:
|
|
449
|
+
op["container"] = f"{op['container']}:{sn}"
|
|
450
|
+
notes.append(f"op {i}: container + short_name read as container {op['container']!r}")
|
|
451
|
+
elif not op.get("container"):
|
|
452
|
+
notes.append(f"op {i}: short_name {sn!r} ignored (no container to name)")
|
|
453
|
+
if op.get("op") == "add" and isinstance(op.get("param"), str) and ":" in op["param"] and not op.get("container"):
|
|
454
|
+
op["container"] = op.pop("param")
|
|
455
|
+
notes.append(f"op {i}: param {op['container']!r} read as a container (DefName:ShortName)")
|
|
456
|
+
if op.get("op") == "add" and not op.get("param") and not op.get("container") and isinstance(op.get("path"), str) \
|
|
457
|
+
and not project.find(op["path"].rstrip("/")) and project.find(op["path"].rstrip("/").rpartition("/")[0]):
|
|
458
|
+
parent, _, last = op["path"].rstrip("/").rpartition("/")
|
|
459
|
+
op["path"], op["param"] = parent, last
|
|
460
|
+
notes.append(f"op {i}: the parameter name in the path read as param {last!r} of {parent}")
|
|
461
|
+
for k in ("value",):
|
|
462
|
+
if k in op:
|
|
463
|
+
nv = _unwrap_ref(op[k])
|
|
464
|
+
if nv is not op[k]:
|
|
465
|
+
notes.append(f"op {i}: reference object read as its path")
|
|
466
|
+
op[k] = nv
|
|
467
|
+
if isinstance(op.get("values"), dict):
|
|
468
|
+
op["values"] = {k: _unwrap_ref(v) for k, v in op["values"].items()}
|
|
469
|
+
out.append(op)
|
|
470
|
+
return _merge_params_into_new_container(project, out, notes)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _merge_params_into_new_container(project: Project, ops: list, notes: list) -> list:
|
|
474
|
+
"""add-param ops on a container that does not exist (its parent does) = create that container with those values,
|
|
475
|
+
when exactly one container def under the parent has every one of those params."""
|
|
476
|
+
from collections import OrderedDict
|
|
477
|
+
groups: "OrderedDict[str, list]" = OrderedDict()
|
|
478
|
+
for i, op in enumerate(ops):
|
|
479
|
+
if isinstance(op, dict) and op.get("op") == "add" and op.get("param") and isinstance(op.get("path"), str) \
|
|
480
|
+
and not project.find(op["path"].rstrip("/")):
|
|
481
|
+
groups.setdefault(op["path"].rstrip("/"), []).append(i)
|
|
482
|
+
if not groups:
|
|
483
|
+
return ops
|
|
484
|
+
drop, insert = set(), {}
|
|
485
|
+
for path, idx in groups.items():
|
|
486
|
+
parent, _, last = path.rpartition("/")
|
|
487
|
+
pg = project.find(parent)
|
|
488
|
+
if not pg:
|
|
489
|
+
continue
|
|
490
|
+
pdef = _resolve_def(project.defs, pg[0].def_ref)
|
|
491
|
+
if pdef is None:
|
|
492
|
+
continue
|
|
493
|
+
names = {ops[i]["param"] for i in idx}
|
|
494
|
+
cands = []
|
|
495
|
+
for c in pdef.containers:
|
|
496
|
+
cd = project.defs.by_path[c]
|
|
497
|
+
have = {project.defs.by_path[x].name for x in cd.params + cd.refs}
|
|
498
|
+
if names <= have:
|
|
499
|
+
cands.append(cd.name)
|
|
500
|
+
if len(cands) != 1:
|
|
501
|
+
continue
|
|
502
|
+
merged = {"op": "add", "path": parent, "container": f"{cands[0]}:{last}",
|
|
503
|
+
"values": {ops[i]["param"]: ops[i].get("value") for i in idx}}
|
|
504
|
+
notes.append(f"{len(idx)} add-param op(s) on the missing {path} read as: create {cands[0]} {last} under {parent} "
|
|
505
|
+
"with those values")
|
|
506
|
+
drop.update(idx)
|
|
507
|
+
insert[idx[0]] = merged
|
|
508
|
+
res = []
|
|
509
|
+
for i, op in enumerate(ops):
|
|
510
|
+
if i in insert:
|
|
511
|
+
res.append(insert[i])
|
|
512
|
+
if i not in drop:
|
|
513
|
+
res.append(op)
|
|
514
|
+
return res
|
|
360
515
|
|
|
361
516
|
|
|
362
517
|
def check_ops(ops) -> None:
|
|
@@ -401,12 +556,14 @@ def schema_check(path: str, data: bytes) -> Optional[str]:
|
|
|
401
556
|
|
|
402
557
|
def edit(project: Project, ops: list, dry_run: bool = False, force: bool = False, run_validate: bool = True) -> dict:
|
|
403
558
|
ed = Editor(project)
|
|
559
|
+
ed.notes = []
|
|
404
560
|
try:
|
|
561
|
+
ops = normalize_ops(project, ops, ed.notes)
|
|
405
562
|
ed.apply(ops, force=force)
|
|
406
563
|
except EditError as e:
|
|
407
|
-
return {"ok": False, "error": str(e), "written": False}
|
|
564
|
+
return {"ok": False, "error": str(e), "written": False, "notes": ed.notes}
|
|
408
565
|
changes = ed.diffs()
|
|
409
|
-
res: dict = {"ok": True, "applied": len(ops), "changes": changes, "written": False}
|
|
566
|
+
res: dict = {"ok": True, "applied": len(ops), "changes": changes, "written": False, "notes": ed.notes}
|
|
410
567
|
schema = []
|
|
411
568
|
for f, before in ed.original.items():
|
|
412
569
|
if schema_check(f, before) is None:
|
|
@@ -424,6 +581,13 @@ def edit(project: Project, ops: list, dry_run: bool = False, force: bool = False
|
|
|
424
581
|
if run_validate:
|
|
425
582
|
touched = list(ed.original)
|
|
426
583
|
v = validate(project, files=touched)
|
|
427
|
-
res
|
|
584
|
+
if res.get("written"):
|
|
585
|
+
# report what THIS edit introduced (vs git HEAD) when there is a baseline; legacy findings are only counted
|
|
586
|
+
from .validate import mark_new
|
|
587
|
+
v = mark_new(project, v)
|
|
588
|
+
if v.get("baseline") == "git HEAD":
|
|
589
|
+
v["diagnostics"] = [d for d in v["diagnostics"] if d.get("new")]
|
|
590
|
+
res["validation"] = {"validated": v["validated"], "summary": v["summaryNew"] if "summaryNew" in v else v["summary"],
|
|
591
|
+
"preexisting": v.get("preexisting"), "baseline": v.get("baseline"),
|
|
428
592
|
"diagnostics": v["diagnostics"][:50]}
|
|
429
593
|
return res
|
|
@@ -74,7 +74,7 @@ class RuleContext:
|
|
|
74
74
|
|
|
75
75
|
|
|
76
76
|
def run_rules(project: Project) -> Iterable[dict]:
|
|
77
|
-
from . import chain, com, handles, mem, nvm, pdur, system # noqa: F401 (registers the packs)
|
|
77
|
+
from . import chain, com, handles, mcal, mem, nvm, pdur, system # noqa: F401 (registers the packs)
|
|
78
78
|
ctx = RuleContext(project)
|
|
79
79
|
for r in RULES:
|
|
80
80
|
for item in r.fn(ctx):
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""H2L-MCAL-*: MCAL configuration consistency the param defs cannot express.
|
|
2
|
+
|
|
3
|
+
Each value can be in range and the configuration still unusable: a GPT tick the prescaler cannot produce, a CAN
|
|
4
|
+
bit timing whose time quanta do not divide the controller clock, duplicate or gapped handle ids, a notification
|
|
5
|
+
configured while its enable/disable service is compiled out. These are the checks an MCAL configurator runs
|
|
6
|
+
before it generates code. Clock frequencies are followed through the references (GptChannelClkSrcRef ->
|
|
7
|
+
GptClockReferencePoint.GptClockReference / CanCpuClockRef -> Mcu McuClockReferencePoint frequency).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
|
|
13
|
+
from . import rule
|
|
14
|
+
from ..values import parse_int
|
|
15
|
+
|
|
16
|
+
GPT = "Gpt/GptChannelConfigSet/GptChannelConfiguration"
|
|
17
|
+
CAN = "Can/CanConfigSet/CanController"
|
|
18
|
+
HOH = "Can/CanConfigSet/CanHardwareObject"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _num(s):
|
|
22
|
+
if s is None:
|
|
23
|
+
return None
|
|
24
|
+
s = str(s).strip()
|
|
25
|
+
try:
|
|
26
|
+
return Fraction(parse_int(s)) if parse_int(s) is not None else Fraction(s)
|
|
27
|
+
except (ValueError, ZeroDivisionError):
|
|
28
|
+
try:
|
|
29
|
+
return Fraction(float(s))
|
|
30
|
+
except ValueError:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _anchor(ctx, e, name):
|
|
35
|
+
v = ctx.value(e, name)
|
|
36
|
+
return (v.node.line if v is not None and getattr(v, "node", None) is not None else e.line), (v.def_ref if v else None)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _name(e):
|
|
40
|
+
return e.path.rsplit("/", 1)[-1]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _clock(ctx, ref_pv, seen=0):
|
|
44
|
+
"""(frequency in Hz, None) or (None, why) for a clock reference (direct or via a GptClockReferencePoint)."""
|
|
45
|
+
t = ctx.target(ref_pv)
|
|
46
|
+
if t is None:
|
|
47
|
+
return None, f"reference {ref_pv.value if ref_pv is not None else '(missing)'} does not resolve"
|
|
48
|
+
rel = ctx.rel(t.def_ref)
|
|
49
|
+
if rel.endswith("GptClockReferencePoint") and seen < 3:
|
|
50
|
+
return _clock(ctx, ctx.value(t, "GptClockReference"), seen + 1)
|
|
51
|
+
f = _num(ctx.text(t, "McuClockReferencePointFrequency"))
|
|
52
|
+
if not f:
|
|
53
|
+
return None, f"{_name(t)} has no McuClockReferencePointFrequency"
|
|
54
|
+
return f, None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _dense(items, param):
|
|
58
|
+
ids = [(parse_int(param(e) or ""), e) for e in items]
|
|
59
|
+
vals = [i for i, _ in ids]
|
|
60
|
+
if None in vals or len(set(vals)) != len(vals):
|
|
61
|
+
return None # missing / duplicate ids are H2L-HID-001's finding
|
|
62
|
+
if sorted(vals) != list(range(len(vals))):
|
|
63
|
+
return sorted(vals)
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _hz(f):
|
|
68
|
+
f = float(f)
|
|
69
|
+
return f"{f / 1e6:g} MHz" if f >= 1e6 else f"{f / 1e3:g} kHz" if f >= 1e3 else f"{f:g} Hz"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@rule("H2L-MCAL-001", "error", "SWS_Gpt / SWS_Can handle ids: unique, starting at 0, without gaps",
|
|
73
|
+
"GPT channel / CAN controller / CAN hardware object ids start at 0 without gaps")
|
|
74
|
+
def dense_ids(ctx):
|
|
75
|
+
for rel, p in ((GPT, "GptChannelId"), (CAN, "CanControllerId"), (HOH, "CanObjectId")):
|
|
76
|
+
items = ctx.containers(rel)
|
|
77
|
+
if not items:
|
|
78
|
+
continue
|
|
79
|
+
bad = _dense(items, lambda e, p=p: ctx.text(e, p))
|
|
80
|
+
if bad is not None:
|
|
81
|
+
ln, d = _anchor(ctx, items[-1], p)
|
|
82
|
+
yield items[-1], ln, (f"{p} values {bad} over {len(items)} {rel.rsplit('/', 1)[-1]} container(s): ids must be "
|
|
83
|
+
f"0..{len(items) - 1} without gaps"), d
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@rule("H2L-MCAL-002", "error", "SWS_Gpt GptChannelTickFrequency / GptChannelClkSrcRef; SWS_Mcu McuClockReferencePoint",
|
|
87
|
+
"GPT tick frequency is an integer division of its clock")
|
|
88
|
+
def gpt_tick(ctx):
|
|
89
|
+
for ch in ctx.containers(GPT):
|
|
90
|
+
src = ctx.value(ch, "GptChannelClkSrcRef")
|
|
91
|
+
f, why = _clock(ctx, src)
|
|
92
|
+
ln, d = _anchor(ctx, ch, "GptChannelTickFrequency")
|
|
93
|
+
if f is None:
|
|
94
|
+
yield ch, ln, f"{_name(ch)}: clock source: {why}", d
|
|
95
|
+
continue
|
|
96
|
+
tick = _num(ctx.text(ch, "GptChannelTickFrequency"))
|
|
97
|
+
if not tick:
|
|
98
|
+
continue
|
|
99
|
+
div = f / tick
|
|
100
|
+
if tick > f or div.denominator != 1:
|
|
101
|
+
lo = f / (div.numerator // div.denominator + 1) if tick <= f else f
|
|
102
|
+
ok = [f / n for n in range(max(1, int(div)), int(div) + 40) if (f / n).denominator == 1 and f / n <= tick][:1]
|
|
103
|
+
hint = f"; nearest at or below: {_hz(ok[0])} (/{int(f / ok[0])})" if ok else ""
|
|
104
|
+
yield ch, ln, (f"{_name(ch)}: tick {_hz(tick)} is not an integer division of its {_hz(f)} clock "
|
|
105
|
+
f"(prescaler {float(div):.4g}){hint}"), d
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@rule("H2L-MCAL-003", "error", "SWS_Gpt GptNotification / GptEnableDisableNotificationApi, GptEnableWakeup / "
|
|
109
|
+
"GptWakeupFunctionalityApi", "GPT notifications and wakeups have their services enabled")
|
|
110
|
+
def gpt_services(ctx):
|
|
111
|
+
opt = ctx.containers("Gpt/GptConfigurationOfOptApiServices")
|
|
112
|
+
api = {}
|
|
113
|
+
for o in opt:
|
|
114
|
+
for k in ("GptEnableDisableNotificationApi", "GptWakeupFunctionalityApi"):
|
|
115
|
+
api[k] = (ctx.text(o, k) or "").strip().lower() in ("true", "1")
|
|
116
|
+
for ch in ctx.containers(GPT):
|
|
117
|
+
n = (ctx.text(ch, "GptNotification") or "").strip()
|
|
118
|
+
if n and n != "NULL_PTR" and opt and not api.get("GptEnableDisableNotificationApi"):
|
|
119
|
+
ln, d = _anchor(ctx, ch, "GptNotification")
|
|
120
|
+
yield ch, ln, (f"{_name(ch)} has GptNotification {n} but GptEnableDisableNotificationApi is off: "
|
|
121
|
+
"Gpt_EnableNotification is compiled out, the notification can never be enabled"), d
|
|
122
|
+
if (ctx.text(ch, "GptEnableWakeup") or "").strip().lower() in ("true", "1"):
|
|
123
|
+
ln, d = _anchor(ctx, ch, "GptEnableWakeup")
|
|
124
|
+
if opt and not api.get("GptWakeupFunctionalityApi"):
|
|
125
|
+
yield ch, ln, f"{_name(ch)}: GptEnableWakeup is set but GptWakeupFunctionalityApi is off", d
|
|
126
|
+
has_src = any(pv.name == "GptWakeupSourceRef" and pv.value for g in ctx.p.find(ch.path)
|
|
127
|
+
for c in g.children for gg in ctx.p.find(c.path) for pv in gg.params)
|
|
128
|
+
if not has_src:
|
|
129
|
+
yield ch, ln, f"{_name(ch)}: GptEnableWakeup is set but no GptWakeupSourceRef (EcuM wakeup source)", d
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _timing(ctx, b, fclk, rate_p, lo, hi, label):
|
|
133
|
+
rate = _num(ctx.text(b, rate_p))
|
|
134
|
+
seg = {k: parse_int(ctx.text(b, k) or "") for k in
|
|
135
|
+
("CanControllerPropSeg", "CanControllerSeg1", "CanControllerSeg2", "CanControllerSyncJumpWidth")}
|
|
136
|
+
ln, d = _anchor(ctx, b, rate_p)
|
|
137
|
+
if None in seg.values() or not rate:
|
|
138
|
+
return
|
|
139
|
+
ntq = 1 + seg["CanControllerPropSeg"] + seg["CanControllerSeg1"] + seg["CanControllerSeg2"]
|
|
140
|
+
if not lo <= ntq <= hi:
|
|
141
|
+
yield b, ln, f"{_name(b)}: {label} bit = 1+prop+seg1+seg2 = {ntq} time quanta, expected {lo}..{hi}", d
|
|
142
|
+
if not 1 <= seg["CanControllerSyncJumpWidth"] <= seg["CanControllerSeg2"]:
|
|
143
|
+
yield b, ln, (f"{_name(b)}: {label} sync jump width {seg['CanControllerSyncJumpWidth']} must be 1..seg2 "
|
|
144
|
+
f"({seg['CanControllerSeg2']})"), d
|
|
145
|
+
if fclk:
|
|
146
|
+
q = fclk / (rate * 1000 * ntq)
|
|
147
|
+
if q.denominator != 1 or q < 1:
|
|
148
|
+
fits = [n for n in range(lo, hi + 1) if (fclk / (rate * 1000 * n)).denominator == 1]
|
|
149
|
+
hint = (f"; with this clock {float(rate):g} kbit/s works with {', '.join(map(str, fits[:6]))} tq per bit"
|
|
150
|
+
if fits else f"; {float(rate):g} kbit/s is not reachable from {_hz(fclk)}")
|
|
151
|
+
yield b, ln, (f"{_name(b)}: {label} {float(rate):g} kbit/s x {ntq} tq does not divide the {_hz(fclk)} CAN clock "
|
|
152
|
+
f"(prescaler {float(q):.4g}, actual {float(fclk / ntq / max(1, round(q)) / 1000):.4g} kbit/s){hint}"), d
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@rule("H2L-MCAL-004", "error", "SWS_Can CanControllerBaudrateConfig (PropSeg/Seg1/Seg2/SyncJumpWidth), CanCpuClockRef; "
|
|
156
|
+
"ISO 11898-1 bit timing", "CAN bit timing is exactly achievable from the controller clock")
|
|
157
|
+
def can_timing(ctx):
|
|
158
|
+
for c in ctx.containers(CAN):
|
|
159
|
+
fclk, why = _clock(ctx, ctx.value(c, "CanCpuClockRef"))
|
|
160
|
+
if fclk is None:
|
|
161
|
+
ln, d = _anchor(ctx, c, "CanCpuClockRef")
|
|
162
|
+
yield c, ln, f"{_name(c)}: CanCpuClockRef: {why}", d
|
|
163
|
+
bauds = [k for g in ctx.p.find(c.path) for k in g.children
|
|
164
|
+
if ctx.rel(k.def_ref).endswith("CanControllerBaudrateConfig")]
|
|
165
|
+
dflt = ctx.value(c, "CanControllerDefaultBaudrate")
|
|
166
|
+
if bauds and (dflt is None or dflt.value.strip() not in {b.path for b in bauds}):
|
|
167
|
+
ln, d = _anchor(ctx, c, "CanControllerDefaultBaudrate")
|
|
168
|
+
yield c, ln, (f"{_name(c)}: CanControllerDefaultBaudrate must reference one of its own baud rate configs "
|
|
169
|
+
f"({', '.join(_name(b) for b in bauds)})"), d
|
|
170
|
+
ids = [ctx.text(b, "CanControllerBaudRateConfigID") for b in bauds]
|
|
171
|
+
if len(set(ids)) != len(ids):
|
|
172
|
+
yield c, c.line, f"{_name(c)}: CanControllerBaudRateConfigID values {ids} are not unique", None
|
|
173
|
+
for b in bauds:
|
|
174
|
+
yield from _timing(ctx, b, fclk, "CanControllerBaudRate", 8, 25, "nominal")
|
|
175
|
+
for g in ctx.p.find(b.path):
|
|
176
|
+
for fd in g.children:
|
|
177
|
+
if ctx.rel(fd.def_ref).endswith("CanControllerFdBaudrateConfig"):
|
|
178
|
+
yield from _timing(ctx, fd, fclk, "CanControllerFdBaudRate", 5, 49, "data phase")
|
|
179
|
+
nb, fb = _num(ctx.text(b, "CanControllerBaudRate")), _num(ctx.text(fd, "CanControllerFdBaudRate"))
|
|
180
|
+
if nb and fb and fb < nb:
|
|
181
|
+
ln, d = _anchor(ctx, fd, "CanControllerFdBaudRate")
|
|
182
|
+
yield fd, ln, f"{_name(fd)}: data phase {float(fb):g} kbit/s is below nominal {float(nb):g}", d
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@rule("H2L-MCAL-005", "error", "SWS_Port PortPinId / PortNumberOfPortPins / PortPinInitialMode",
|
|
186
|
+
"Port pins: unique ids, pin count matches, initial mode is an allowed mode")
|
|
187
|
+
def port(ctx):
|
|
188
|
+
seen = {}
|
|
189
|
+
for p in ctx.containers("Port/PortConfigSet/PortContainer/PortPin"):
|
|
190
|
+
pid = ctx.text(p, "PortPinId")
|
|
191
|
+
ln, d = _anchor(ctx, p, "PortPinId")
|
|
192
|
+
if pid is not None and pid in seen:
|
|
193
|
+
yield p, ln, f"{_name(p)}: PortPinId {pid} already used by {seen[pid]}", d
|
|
194
|
+
seen.setdefault(pid, _name(p))
|
|
195
|
+
modes = [pv.value for pv in ctx.values(p, "PortPinMode")]
|
|
196
|
+
init = ctx.text(p, "PortPinInitialMode")
|
|
197
|
+
if init and modes and init not in modes:
|
|
198
|
+
ln, d = _anchor(ctx, p, "PortPinInitialMode")
|
|
199
|
+
yield p, ln, f"{_name(p)}: PortPinInitialMode {init} is not one of its PortPinMode values {modes}", d
|
|
200
|
+
for pc in ctx.containers("Port/PortConfigSet/PortContainer"):
|
|
201
|
+
n = sum(1 for g in ctx.p.find(pc.path) for k in g.children if ctx.rel(k.def_ref).endswith("PortPin"))
|
|
202
|
+
want = parse_int(ctx.text(pc, "PortNumberOfPortPins") or "")
|
|
203
|
+
if want is not None and want != n:
|
|
204
|
+
ln, d = _anchor(ctx, pc, "PortNumberOfPortPins")
|
|
205
|
+
yield pc, ln, f"{_name(pc)}: PortNumberOfPortPins = {want} but it has {n} PortPin container(s)", d
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@rule("H2L-MCAL-006", "warning", "SWS_Dio channel group: adjoining channels of one port, DioPortMask / DioPortOffset",
|
|
209
|
+
"Dio channel group mask is contiguous and starts at its offset")
|
|
210
|
+
def dio_group(ctx):
|
|
211
|
+
for g in ctx.containers("Dio/DioConfig/DioPort/DioChannelGroup"):
|
|
212
|
+
mask = parse_int(ctx.text(g, "DioPortMask") or "")
|
|
213
|
+
off = parse_int(ctx.text(g, "DioPortOffset") or "")
|
|
214
|
+
if mask is None or off is None:
|
|
215
|
+
continue
|
|
216
|
+
low = (mask & -mask).bit_length() - 1 if mask else -1
|
|
217
|
+
if not mask or ((mask >> low) & ((mask >> low) + 1)) != 0 or low != off:
|
|
218
|
+
ln, d = _anchor(ctx, g, "DioPortMask")
|
|
219
|
+
yield g, ln, (f"{_name(g)}: DioPortMask {mask:#x} must be adjoining bits starting at DioPortOffset {off}"), d
|