@h2loop/autosar 1.9.1 → 1.11.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h2loop/autosar",
3
- "version": "1.9.1",
3
+ "version": "1.11.0",
4
4
  "description": "AUTOSAR Classic pack for Hydron: ECUC read/edit-in-place/validate/diff on ARXML, config-to-code trace, generator and build runners",
5
5
  "type": "module",
6
6
  "private": false,
package/plugins/index.js CHANGED
@@ -1,94 +1,104 @@
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 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
- `).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 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
- `).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
- `);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
- Did you mean: ${i.didYouMean.join(", ")}`:"",s=i.schema?`
9
- Schema errors: ${JSON.stringify(i.schema)}`:"";return`ERROR: ${i.error}${t}${s}`}function A(i){let t=i.warnings??[];return t.length?t.map((s)=>`WARNING: ${s}`).join(`
2
+ import{readFileSync as ze}from"fs";import{isAbsolute as Ke,join as te,resolve as Ze}from"path";import{tool as S}from"@kilocode/plugin";import{homedir as Oe}from"os";import{join as E}from"path";var Ee=()=>process.env.HYDRON_TEST_HOME||Oe(),J=(n,t)=>process.env[n]||E(Ee(),t),Re=()=>E(J("XDG_CONFIG_HOME",".config"),"hydron-cli"),Ce=()=>E(J("XDG_DATA_HOME",".local/share"),"hydron-cli"),Te=()=>E(J("XDG_STATE_HOME",".local/state"),"hydron-cli");async function G(n){let t=Bun.file(n);if(!await t.exists())return;return t.json().catch(()=>{return})}async function W(){let n=process.env.KILO_API_URL?.trim();if(n)return n.replace(/\/+$/,"");let t=await G(E(Re(),"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 Ne(n){let t=n?.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 xe(n){let t=Ne(n.access);if(t)return t;if(!n.refresh)return"";return new Bun.CryptoHasher("sha256").update(n.refresh).digest("hex").slice(0,12)}async function ce(){let t=(await G(E(Ce(),"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 de(){let n=await ce();if(typeof n.expires==="number"&&n.expires>0&&Date.now()>=n.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 n.access}async function oe(n){let t=await fetch(`${await W()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await de()}`},signal:n?AbortSignal.any([n,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 ae=()=>E(Te(),"h2loop-project.json");async function P(n,t){let s=n===void 0||n===null?"":String(n).trim();if(/^\d+$/.test(s))return s;if(s){let i=await oe(t),r=i.filter((u)=>u.name===s),d=r.length?r:i.filter((u)=>u.name?.toLowerCase()===s.toLowerCase());if(d.length===1)return String(d[0].id);if(d.length>1)throw Error(`workspace "${s}" is ambiguous: ${d.map((u)=>`${u.name} (id ${u.id})`).join(", ")}; pass the numeric id`);let c=i.filter((u)=>u.name?.toLowerCase().includes(s.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${s}"`+(c.length?`; similar: ${c.map((u)=>`${u.name} (id ${u.id})`).join(", ")}`:`; you have ${i.length} project(s)`))}let a=await G(ae());if(!a)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let f=await ce();if(a.project&&typeof a.project==="object"){let i=a.project;if(typeof a.account==="string"&&a.account!==await xe(f))throw Error("The selected H2Loop project belongs to another account; select one again or pass workspace_id.");if(i.id!==void 0)return String(i.id)}let e=a;if(e.id===void 0)throw Error(`${ae()} holds no project id; select a project again or pass workspace_id.`);if(!(await oe(t)).some((i)=>String(i.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 M(n,t,s,a,f=120000){let e=`${await W()}${n}?workspace_id=${encodeURIComponent(t)}`,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await de()}`},body:JSON.stringify(s),signal:a?AbortSignal.any([a,AbortSignal.timeout(f)]):AbortSignal.timeout(f)}),i=await o.text();if(o.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(o.status===404&&i.includes("Not Found"))throw Error(`${n} is not available on ${await W()} (backend predates the AUTOSAR endpoints).`);if(!o.ok)throw Error(`H2Loop ${n} failed: HTTP ${o.status} ${i.slice(0,800)}`);try{return JSON.parse(i)}catch(r){throw Error(`H2Loop ${n} returned non-JSON (${String(r)}): ${i.slice(0,300)}`)}}var V=/\.arxml\b/i,X="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 le(n,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(n)){let a=Array.isArray(t.edits)?t.edits.some((f)=>typeof f?.filePath==="string"&&V.test(f.filePath)):!1;if(V.test(s)||a)return`${X} (${n} on ${s||"an .arxml file"})`;return}if(n==="apply_patch"||n==="patch"){let a=String(t.patchText??t.patch??""),f=a.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??a.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return f?`${X} (${n} on ${f[1].trim()})`:void 0}if(n==="bash"){let a=String(t.command??"");if(!V.test(a))return;let f=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(a)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(a),e=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(a)||/\btee\b[^|;&]*\.arxml\b/i.test(a),o=/\b(?:mv|cp|ln|install|rsync)\b[^|;&]*\.arxml['"]?\s*(?:$|[|;&])/im.test(a)||/\b(?:os\.(?:rename|replace)|shutil\.(?:move|copy\w*)|fs\.(?:rename|copyFile)\w*|Path\([^)]*\)\.rename)\([^)]*\.arxml/i.test(a)||/\.(?:rename|replace)\(\s*['"][^'"]*\.arxml/i.test(a),i=/open\([^)]*\.arxml[^)]*,\s*(?:mode\s*=\s*)?['"][wa+]/i.test(a)||/\.arxml['"]?\s*\)?\s*\.write_(?:text|bytes)\b/i.test(a)||/write_(?:text|bytes)\([^)]*\)[^;\n]*\.arxml/i.test(a)||/\bwriteFile(?:Sync)?\([^)]*\.arxml/i.test(a)||/\.write\(\s*['"][^'"]*\.arxml/i.test(a)||/\b(?:awk|gawk)\b[^|;&]*-i\s+inplace/.test(a)||/\bed\b\s+-s\s+[^|;&]*\.arxml/.test(a);if(f||e||i||o)return`${X} (bash: ${a.slice(0,120)})`}return}var je=/(?:^|[;&|(]\s*|\bnode\s+\S*|\bnpx\s+)(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\b/m,Ie='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 ue(n,t){if(n!=="bash"||!t)return;let s=String(t.command??""),a=/\s(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\s+(?:--|<|\{|\[|'|")/.test(s);if(je.test(s)||a)return`${Ie} (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 De=new Set(["autosar_build_context","ecuc_read","ecuc_find","ecuc_crosscheck","autosar_config_lookup","autosar_trace","autosar_audit","query_hydron_project","get_symbol_info"]),q=new Set(["ecuc_edit","arxml_edit","autosar_add_signal","autosar_add_like"]),he=/\.(c|h)$/i,ge=/(^|[\\/])(Output|gen|Gen|GenData|generated)[\\/]/;var fe=/(^|[\\/])[A-Z][A-Za-z0-9]*_(?:Cfg|PBcfg|PBCfg|Lcfg|LCfg)\.[ch]$/,Le=/\b[A-Z][A-Za-z0-9]*_(?:Cfg|PBcfg|PBCfg|Lcfg|LCfg)\.[ch]\b/,Y=new Map;function F(n){let t=n??"-",s=Y.get(t);if(!s)s={grounded:[],contextFor:[],changed:[],validation:"never",cFiles:[],rte:"n/a",docs:"n/a",blocks:0,modules:[],moduleBlocks:{},codegen:!1,cfgBlocks:0,firstBlocks:0},Y.set(t,s);return s}function K(n){if(!n)return"";return String(n.filePath??n.file_path??"")}function O(n){if(!n||!n.startsWith("/"))return;let t=n.split("/").filter(Boolean);return t.length>=2?t[1]:void 0}function Ue(n){return z(n?.ops)}function Pe(n,t){if(n!=="ecuc_edit")return[];let s=[];for(let a of Ue(t)){let f=O(String(a.path??a.parent_path??""));if(f&&!s.includes(f))s.push(f)}return s}function Me(n,t){if(!t)return;if(n==="edit"||n==="write"||n==="multiedit"){let s=K(t);return fe.test(s)?s:void 0}if(n==="apply_patch"||n==="patch"){let s=String(t.patchText??t.patch??"").match(/^\*\*\* (?:Add|Update) File: (.+)$/m);return s&&fe.test(s[1].trim())?s[1].trim():void 0}if(n==="bash"){let s=String(t.command??""),a=s.match(Le);if(!a)return;return/>\s*['"]?[^\s'"|;&]*_(?:Cfg|PBcfg|PBCfg|Lcfg|LCfg)\.[ch]\b/.test(s)||/\btee\b/.test(s)||/open\([^)]*,\s*['"][wa]/.test(s)||/write_text|writeFile|\.write\(/.test(s)||/\bsed\b[^|;&]*\s-i/.test(s)?a[0]:void 0}return}function pe(n,t,s){if(process.env.AUTOSAR_LOOP_GATES==="0")return;let a=F(n);if(a.blocks>=6)return;let f=Me(t,s);if(f&&!a.codegen&&a.cfgBlocks<2)return a.blocks++,a.cfgBlocks++,`GENERATE, DO NOT HAND-WRITE: ${f} is generated configuration code. It is derived from the ECUC ARXML, so (1) make the ARXML right (ecuc_read / ecuc_edit / ecuc_validate until clean), then (2) call autosar_codegen with modules=[<the module>] and out_dir='Output' (or the folder the user named): it writes <Mip>_Cfg.h, <Mip>_Cfg.c/_Lcfg.c/_PBcfg.c deterministically from the configuration. Only if the generator cannot produce what is needed, edit its output afterwards and say why.`;if(q.has(t)&&!s?.dry_run){let o=Pe(t,s).filter((i)=>!a.modules.includes(i)&&(a.moduleBlocks[i]??0)<1);if(o.length){for(let i of o)a.moduleBlocks[i]=(a.moduleBlocks[i]??0)+1;return a.blocks++,`GROUND FIRST (${o.join(", ")}): this change was decided without the context engine for ${o.join(", ")}. Facts needed: the element's current values, its param-def schema (allowed params, ranges, literals, multiplicity), the consistency rules that will be checked, and the constraints from the ingested specifications.`}}if(q.has(t)&&!s?.dry_run&&a.grounded.length===0&&a.firstBlocks<2)return a.blocks++,a.firstBlocks++,"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 e=K(s);if((t==="edit"||t==="write"||t==="multiedit")&&he.test(e)&&!ge.test(e)){if(!a.grounded.includes("autosar_build_context")&&!a.grounded.includes("autosar_audit"))return a.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 ${e}. For C that is not runnable code, autosar_audit grounds BSW usage instead. Then retry.`}return}function Z(n,t,s,a){let f=F(n),e=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(a)||a.includes("edit rejected");if(De.has(t)&&!e){if(!f.grounded.includes(t))f.grounded.push(t);if(t==="autosar_build_context"){let i=String(s?.target??s?.runnable??s?.swc??"");if(i&&!f.contextFor.includes(i))f.contextFor.push(i);let r=new Set,d=O(i);if(d)r.add(d);for(let c of a.matchAll(/"@path":\s*"(\/[^"]+)"/g)){let u=O(c[1]);if(u)r.add(u);if(r.size>8)break}for(let c of r)if(!f.modules.includes(c))f.modules.push(c)}}if(q.has(t)&&!e&&!s?.dry_run&&!/^Dry run/.test(a)){f.validation=/AUTO-VALIDATE: clean/.test(a)?"clean":/AUTO-VALIDATE/.test(a)?"errors":"stale",f.docs="pending";for(let i of Fe(t,s,a))if(!f.changed.includes(i))f.changed.push(i)}let o=K(s);if((t==="edit"||t==="write"||t==="multiedit")&&he.test(o)&&!ge.test(o)&&!e){if(!f.cFiles.includes(o))f.cFiles.push(o);f.rte="pending"}if(t==="ecuc_validate"&&!e){let i=a.split(`
3
+ `)[0]??"",r=/^NEW since/.test(i)?/"error":\s*[1-9]/.test(i):/"error":\s*[1-9]/.test(i)||/^\S+:\d+ error /m.test(a);if(f.validation=r?"errors":"clean",s?.docs&&f.docs==="pending"&&!/DOCUMENT CHECK UNAVAILABLE/.test(a))f.docs="done"}if(t==="autosar_codegen"&&!/^\s*(Blocked|GROUND FIRST)/.test(a))f.codegen=!0;if(t==="autosar_verify_rte"&&!e)f.rte=/\u2014 FAILING/.test(a)?"fail":"pass"}function Fe(n,t,s){let a=[];if(n==="ecuc_edit"){let f=z(t?.ops);for(let e of f){let o=String(e.path??""),i=e.param?`${o}/${e.param}`:e.container?`${o}/${e.container}`:o;a.push(e.value!==void 0?`${i} = ${JSON.stringify(e.value).slice(0,80)}`:`${i} (${e.op})`)}}else if(n==="arxml_edit"){let f=s.match(/created (\[[^\]]*\])/);if(f)try{a.push(...JSON.parse(f[1]))}catch{}for(let e of z(t?.ops))if(e.op==="set")a.push(`${e.path}/${e.element} = ${JSON.stringify(e.value)}`)}else if(n==="autosar_add_signal")a.push(`new Com signal ${t?.name} in ${t?.ipdu}`);else if(n==="autosar_add_like"){let f=s.match(/Created:\n((?: .*\n?)+)/);if(f)a.push(...f[1].split(`
4
+ `).map((e)=>e.trim()).filter(Boolean));else a.push(`${t?.name} like ${t?.like}`)}return a.filter(Boolean)}function z(n){let t=n;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 me(n){let t=Y.get(n??"-");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((a)=>`- ${a}`)].join(`
5
+ `)}var Be=/^(?: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,ye=new Map;function He(n){let t=n.trim().replace(/[\p{Extended_Pictographic}\u200D\uFE0F]/gu,"").replace(/[!.?,:;~\-]+/g," ").replace(/\s+/g," ").trim();return t.length>0&&t.length<=40&&Be.test(t)}function be(n,t){ye.set(n??"-",He(t))}function we(n,t){if(process.env.AUTOSAR_LOOP_GATES==="0")return;if(!ye.get(n??"-"))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 We}from"fs";import{dirname as Je,join as Q}from"path";import{fileURLToPath as Ge}from"url";var Ve="autosar-data==0.17.0";function Xe(){let n=Je(Ge(import.meta.url)),t=[Q(n,"..","python"),Q(n,"..","..","python")].find((s)=>We(Q(s,"ecuc_engine","__main__.py")));if(!t)throw Error(`ECUC engine not found next to ${n} (expected ../python/ecuc_engine)`);return t}async function qe(n){try{return await Bun.spawn([...n,"-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 H={};async function Ye(){if(H.cmd!==void 0)return H.cmd;let n=process.env.AUTOSAR_PYTHON?.trim(),s=n?[[n]]:[["uv","run","--no-project","--quiet","--with",Ve,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let a of s)if(await qe(a))return H.cmd=a,a;return H.cmd=null,null}async function w(n,t,s){let a=await Ye();if(!a)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 f=Xe(),e=Bun.spawn([...a,"-m","ecuc_engine","--root",n,...t,"--json"],{cwd:n,env:{...process.env,PYTHONPATH:[f,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:s}),[o,i]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text()]);await e.exited;let r=o.trim().split(`
6
+ `).filter(Boolean).at(-1);if(!r)return{ok:!1,error:`engine produced no output (exit ${e.exitCode}): ${i.trim().slice(-2000)}`};try{return JSON.parse(r)}catch(d){return{ok:!1,error:`engine output was not JSON (${String(d)}): ${r.slice(0,500)} ${i.slice(-500)}`}}}var l=S.schema,Qe=["# 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
+ `);function N(n){if(typeof n!=="string")return n;let t=n.trim();if(!t.startsWith("[")&&!t.startsWith("{")&&!t.startsWith('"'))return n;try{return N(JSON.parse(t))}catch{return n}}var R=(n)=>l.preprocess(N,n);function T(n){let t=N(n);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 I=()=>l.preprocess(T,l.array(l.string()).optional()),C=" 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 D(n,t=200){let s=n.slice(0,t).map((a)=>`${a.file}:${a.line} ${a.severity.toUpperCase()} ${a.rule} ${a.path} \u2014 ${a.message}${a.defRef?` [def ${a.defRef}]`:""}`);if(n.length>t)s.push(`\u2026 ${n.length-t} more`);return s}function A(n){let t=n.didYouMean?`
8
+ Did you mean: ${n.didYouMean.join(", ")}`:"",s=n.schema?`
9
+ Schema errors: ${JSON.stringify(n.schema)}`:"";return`ERROR: ${n.error}${t}${s}`}function v(n){let t=n.warnings??[];return t.length?t.map((s)=>`WARNING: ${s}`).join(`
10
10
  `)+`
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(`
11
+ `:""}function _(n,t){if(!t)return n;return Ke(t)?t:Ze(n,t)}async function et(n){let t=Bun.file(te(n,".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 tt(n,t){let s=(await et(n))[t];if(typeof s==="string")return{command:s};if(s&&typeof s==="object"&&typeof s.command==="string")return s;return}function _e(n,t=150){let s=n.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 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
- ${r.answer.trim()}
13
+ `):n}async function nt(n,t,s,a){let f=process.platform==="win32"?["cmd","/d","/s","/c",n]:["sh","-c",n],e=Date.now(),o=Bun.spawn(f,{cwd:t,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([a,AbortSignal.timeout(s*1000)])}),[i,r]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text()]);return{code:await o.exited,out:i,err:r,secs:Math.round((Date.now()-e)/1000)}}var it=(n)=>(n??[]).map((t)=>`CAN ID ${t.canIdHex??"?"} (${t.canId??"?"}) ${t.direction} via ${t.canIfPdu}, controller ${t.controller??"?"}, network ${(t.network??[]).join(", ")||"?"}`).join("; ");async function $e(n,t,s){let a=t.filter((i)=>i?.path&&/\/Com((Group)?Signal|IPdu)$/.test(String(i.definition_ref??""))&&i.ipdu===void 0&&i.direction===void 0);if(!a.length)return[];let f=await w(n,["signal-owners",...new Set(a.map((i)=>i.path))],s);if(!f.ok)return[`NOTE: owning I-PDU not computed locally (${f.error})`];let e=f.owners,o=[];for(let i of a){let r=e[i.path];if(r===null||r===void 0){o.push(`NOTE: ${i.path} is not in the local checkout (${n}); owning I-PDU/direction unknown`);continue}i.ipdu_local=r,o.push(r.length?`${i.path}: owning I-PDU ${r.map((d)=>`${d.ipdu} (ComIPduDirection=${d.direction??"?"}${d.can?.length?`; ${it(d.can)}`:""})`).join(", ")} [local ECUC]`:`${i.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return o}var rt=(n)=>{if(typeof n==="number"&&Number.isSafeInteger(n))return n;if(typeof n==="string"&&/^\s*-?(0x[0-9a-f]+|\d+)\s*$/i.test(n)){let t=n.trim(),s=t.startsWith("-")?-Number(t.slice(1)):Number(t);return Number.isSafeInteger(s)?s:null}return null},ve=(n)=>n<0?`-0x${(-n).toString(16).toUpperCase()}`:`0x${n.toString(16).toUpperCase()}`;async function Se(n,t,s){let a=t.filter((i)=>typeof i?.path==="string");if(!a.length)return[];let f=await w(n,["value-sites",...new Set(a.map((i)=>i.path))],s),e=f.ok?f.sites:{},o=[];if(!f.ok)o.push(`NOTE: value lines not computed locally (${f.error})`);for(let i of a){let r=e[i.path];if(r){i.values_local=r.values,o.push(`VALUES ${i.path} (container ${r.at}) [local ECUC; cite these lines]:`);for(let[u,p]of Object.entries(r.values))for(let h of Array.isArray(p)?p:[p])o.push(` ${u} = ${JSON.stringify(h.value)}${h.hex?` (dec ${h.dec}, hex ${h.hex})`:""} @ ${h.at}`);continue}let d=i.values&&typeof i.values==="object"?i.values:{},c={};for(let[u,p]of Object.entries(d)){let h=rt(p);if(h!==null)c[u]=`dec ${h}, hex ${ve(h)}`}if(Object.keys(c).length)i.values_int=c;if(f.ok)o.push(`NOTE: ${i.path} is not in the local checkout (${n}): its file:line${i.file?` ${i.file}:${i.line??"?"}`:""} is where the ELEMENT starts, not a value line. To cite a value's line, read that file; never estimate one.`)}return o}var ke=(n)=>{let t=n.notes??[],s=n.errors??[];return[...t.map((a)=>`NOTE: ${typeof a==="string"?a:JSON.stringify(a)}`),...s.map((a)=>`BACKEND ERROR: ${typeof a==="string"?a:JSON.stringify(a)}`)]};async function st(n,t){try{let s=await t(),a=typeof s==="string"?s:s.output;if(a&&a.trim())return s;return`${n}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(s){return`ERROR (${n}): ${s instanceof Error?s.message:String(s)}`}}function ot(n){for(let[t,s]of Object.entries(n)){let a=s.execute;s.execute=(f,e)=>st(t,()=>a(f,e))}return n}function at(n,t=process.env){let s=new Set;for(let a of(t.AUTOSAR_DISABLE_TOOLS??"").split(/[\s,]+/))if(a)s.add(a);if(n)try{let a=JSON.parse(ze(te(n,".hydron","autosar.json"),"utf8"));if(Array.isArray(a.disableTools)){for(let f of a.disableTools)if(typeof f==="string"&&f)s.add(f)}}catch{}return s}function ct(n,t){if(t.size===0)return n;return Object.fromEntries(Object.entries(n).filter(([s])=>!t.has(s)))}function dt(n,t){if(!t)return;if(n==="autosar_add_like")return typeof t.like==="string"?t.like:void 0;if(n==="autosar_add_signal")return typeof t.ipdu==="string"?t.ipdu:void 0;let s=N(t.ops);if(!Array.isArray(s))s=s&&typeof s==="object"?[s]:[];for(let a of s){let f=a?.path??a?.parent_path;if(typeof f==="string"&&f.trim())return f.trim()}return}var lt=/\b(generat\w*|codegen|regenerat\w*)\b|_(?:Cfg|PBcfg|Lcfg)\.[ch]\b|\.[ch]\b(?:\s+files?)?/i;async function ut(n,t,s){let a=await w(n,["info"],s);return((a.ok?a.modules:void 0)??[]).map((o)=>({m:o,i:t.search(new RegExp(`\\b${o}(?=[A-Z_\\s.,:;/)]|$)|\\b${o.toUpperCase()}\\b`))})).filter((o)=>o.i>=0).sort((o,i)=>o.i-i.i).map((o)=>o.m)}async function ft(n,t,s){if(!t)return"";let a=await w(n,["rules"],s),f=(a.ok?a.rules:void 0)??[],e=new RegExp(`\\b(?:SWS_)?(?:${t}|${t.toUpperCase()})\\b`);return f.filter((i)=>e.test(i.title)||e.test(i.cite)).map((i)=>`- ${i.id} (${i.severity}): ${i.title} [${i.cite}]`).join(`
14
+ `)}async function ht(n,t,s){let a=[...new Set(t.match(/\b[A-Za-z][A-Za-z0-9]*_[A-Za-z0-9_]*[A-Za-z0-9]\b/g)??[])].filter((e)=>!/^(?:SWS|SRS|ECUC|TPS|RS|PRS|AUTOSAR|STD|E|GPT_CH|PORT_PIN)_/i.test(e)).slice(0,6),f=[];for(let e of a){let o=await w(n,["read",e,"--depth","1"],s);if(!o.ok)continue;let{ok:i,engine:r,ms:d,...c}=o;if(f.push(`${e}:
15
+ ${JSON.stringify(c,null,1).slice(0,1800)}`),f.length>=4)break}return f.join(`
16
+ `)}var Ae=new Map;async function ee(n,t,s,a,f=300000){let e=`${t??"-"}|${s??""}|${n}`,o=Ae.get(e);if(o)return o;let i;try{let r=await P(s,a),d=await M("/api/v1/mcp/retriever/query",r,{query:n,workspace_id:Number(r)||r},a,f),c=(d.citations??[]).slice(0,12).map((u,p)=>{let h=u.file?`${u.file}${u.start_line?`:${u.start_line}`:""}`:`${u.doc_name??"?"}${u.title?` > ${u.title}`:""}`;return` [D${p+1}] ${h}: "${(u.excerpt??"").replace(/\s+/g," ").slice(0,280)}"`});i=d.answer?`(project ${r}; retriever answer, ${c.length} citation(s). Trust a statement only where a citation supports it.)
17
+ ${d.answer.trim()}
15
18
  Citations:
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(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}
19
+ ${c.join(`
20
+ `)||" (none)"}`:`(project ${r}: no answer${d.error_message?`: ${d.error_message}`:""})`}catch(r){return`UNAVAILABLE: ${r instanceof Error?r.message:String(r)} -- select a Hydron project with the documents ingested (hydron projects select) or pass workspace_id.`}return Ae.set(e,i),i}var gt=async(n)=>{let t=at(n?.directory),s=(e)=>S({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:l.string().optional().describe("module name substituted for {module} in the command, if used"),args:l.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(o,i){let r=_(i.directory,o.project_dir),d=await tt(r,e);if(!d)return`No \`${e}\` command configured. Add it to ${te(r,".hydron","autosar.json")}, e.g.
21
+ {"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let c=o.args??"",u=d.command.replaceAll("{module}",o.module??""),p=u.includes("{args}")?u.replaceAll("{args}",c):`${u}${c?` ${c}`:""}`,h=_(r,d.cwd);await i.ask({permission:`autosar_${e}`,patterns:[p],always:[d.command],metadata:{command:p,cwd:h}}),i.metadata({title:`${e}: ${p}`});let g=await nt(p,h,d.timeoutSec??3600,i.abort),m=g.code===0?"OK":`FAILED (exit ${g.code})`;return{title:`autosar_${e} ${m}`,output:[`$ ${p} (cwd ${h}, ${g.secs}s) -> ${m}`,g.out.trim()?`--- stdout (tail) ---
22
+ ${_e(g.out)}`:"",g.err.trim()?`--- stderr (tail) ---
23
+ ${_e(g.err,80)}`:""].filter(Boolean).join(`
24
+ `),metadata:{exit:g.code}}}}),a={},f=n?.directory;return{"chat.message":async(e,o)=>{let i=(o?.parts??[]).map((r)=>r.type==="text"?String(r.text??""):"").join(" ");be(e.sessionID,i)},"tool.execute.before":async(e,o)=>{let i=we(e.sessionID,e.tool);if(i)throw Error(i);let r=le(e.tool,o.args)??ue(e.tool,o.args);if(r)throw Error(r);let d=pe(e.sessionID,e.tool,o.args);if(d){let c=dt(e.tool,o.args),u="";if(c&&a.autosar_build_context)try{let p=c.split("/"),h=O(c),g=[c,p.slice(0,-1).join("/"),h?`/${p[1]}/${h}`:""].filter((y,x,B)=>y&&B.indexOf(y)===x),m=c;for(let y of g)if((await w(f??process.cwd(),["read",y,"--depth","0"])).ok){m=y;break}let b=await a.autosar_build_context.execute({target:m,task:`ground the ${e.tool} about to change ${c}`,doc_timeout_s:120},{directory:f,worktree:f,sessionID:e.sessionID,abort:new AbortController().signal,metadata(){},async ask(){}});if(u=typeof b==="string"?b:String(b?.output??""),u&&!u.startsWith("ERROR"))Z(e.sessionID,"autosar_build_context",{target:m},u);else u=""}catch{u=""}throw Error(u?`${d}
22
25
 
23
- The context engine was run for you on ${o}; these are the facts to plan from:
26
+ The context engine was run for you on ${c}; these are the facts to plan from:
24
27
  ${u.slice(0,14000)}
25
28
 
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?`
29
+ List the facts your edit relies on (F#/D#), adjust the edit to them, then retry it.`:d)}},"tool.execute.after":async(e,o)=>{if(e.tool==="query_hydron_project"&&o&&typeof o.output==="string"&&f)try{let i=String(e.args?.question??""),r=await ht(f,i),d=/Failed to query knowledge base|timed out/i.test(o.output);if(r||d)o.output+=(d?`
30
+
31
+ NOTE: the documents index did not answer. For specification facts ask again with ONE short, specific question, or use autosar_build_context target=<module/element> (project facts + schema + rules + documents).`:"")+(r?`
32
+
33
+ LOCAL PROJECT FACTS (from this workspace's ECUC ARXML; the documents index does not contain this project's configuration, so for its current values use these and ecuc_read, not the answer above):
34
+ `+r:"")}catch{}Z(e.sessionID,e.tool,e.args,String(o?.output??""))},"experimental.chat.system.transform":async(e,o)=>{o.system.push(Qe);let i=me(e?.sessionID);if(i)o.system.push(i)},tool:a=ct(ot({ecuc_read:S({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."+C,args:{path:l.string().optional().describe("AUTOSAR path, SHORT-NAME or partial path of a module/container/parameter, or a def path"),depth:l.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:l.boolean().optional().describe("include the param-def summary for the element"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=["read"];if(e.path)i.push(e.path);if(i.push("--depth",String(e.depth??2)),e.schema)i.push("--schema");let r=await w(_(o.directory,e.project_dir),i,o.abort);if(!r.ok)return v(r)+A(r);let{ok:d,engine:c,ms:u,warnings:p,...h}=r;return v(r)+JSON.stringify(h,null,1)}}),ecuc_edit:S({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]]}. A NEW module configuration (e.g. adding the Pwm/Icu/Adc driver config): {op:'add', path:'/ActiveEcuC', container:'Pwm'[, file:'Config/Pwm_ecuc.arxml']} creates its file and module element; then add its containers (validation lists the mandatory ones still missing). 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."+C,args:{ops:R(l.array(R(l.object({op:l.enum(["set","add","remove"]),path:l.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:l.string().optional().describe("parameter/reference def short-name"),value:l.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:l.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:R(l.record(l.string(),l.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:l.boolean().optional().describe("compute and show the diff without writing"),force:l.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)i.push("--dry-run");if(e.force)i.push("--force");let r=await w(_(o.directory,e.project_dir),i,o.abort);if(!r.ok){let p=r.changes??[],h=(r.notes??[]).map((g)=>`
35
+ NOTE: ${g}`).join("");return v(r)+A(r)+h+(p.length?`
28
36
  Rejected diff:
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")?`
37
+ ${p.map((g)=>g.diff).join(`
38
+ `)}`:"")}let d=r.changes??[],c=r.validation,u=[`${r.written?"Written":"Dry run (nothing written)"}: ${r.applied} op(s), ${d.length} file(s) changed.`,...(r.notes??[]).map((p)=>`NOTE: ${p}`),...d.map((p)=>p.diff)];if(c)u.push(c.validated?c.baseline==="git HEAD"?`Validation of touched files, NEW since git HEAD: ${JSON.stringify(c.summary)}`+(c.preexisting&&Object.keys(c.preexisting).length?` (pre-existing, not listed: ${JSON.stringify(c.preexisting)})`:""):`Validation of touched files: ${JSON.stringify(c.summary)}`:"Validation skipped: no param defs loaded.",...D(c.diagnostics,50));return{title:`ecuc_edit ${d.map((p)=>p.file).join(", ")}`,output:v(r)+u.join(`
39
+ `)}}}),ecuc_validate:S({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."+C,args:{files:I().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:l.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),new_only:l.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:l.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:l.string().optional().describe("with docs=true: the elements/values to check when nothing was changed in this session"),workspace_id:l.union([l.string(),l.number()]).optional().describe("Hydron project for docs=true (default: the selected one)"),max:l.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:l.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:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=["validate"];for(let k of T(e.files)??[])r.push("--file",k);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??F(o.sessionID).changed.length>0)r.push("--new-only");let c=await w(i,r,o.abort);if(!c.ok)return v(c)+A(c);let{diagnostics:u,scope:p}=c,h=u.filter((k)=>k.rule!=="H2L-DISCOVERY"),{summaryNew:g,preexisting:m}=c,b=g?`NEW since ${c.baseline}: ${Object.keys(g).some((k)=>k!=="info")?JSON.stringify(g):"no new findings"}`+(m&&Object.keys(m).length?`; pre-existing, not listed: ${JSON.stringify(m)} (new_only=false lists them)`:""):"",x=p.configFiles===0&&c.scope.inputFiles?`Checked ${c.scope.inputFiles} extract/SWC file(s) (AUTOSAR schema + references): ${h.length?JSON.stringify(c.summary):"CLEAN, no findings"}`:c.validated?`Validated ${c.modules.join(", ")||"(no modules)"} against ${c.defsLoaded} module def(s): ${h.length?JSON.stringify(c.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${h.length?JSON.stringify(c.summary):"no findings"}`,B=[`Loaded ${p.configFiles} config file(s) and ${c.scope.inputFiles??0} extract/SWC file(s)`+(p.filter?`; files filter ${JSON.stringify(p.filter.files)} matched ${p.filter.matchedCount}`:"")+(p.module?`; module filter ${p.module}`:"")+":",...p.files.slice(0,30).map((k)=>` ${k.file} (${k.modules.join(", ")})`),...p.files.length>30||p.filesTruncated?[` \u2026 ${p.files.length-30+(p.filesTruncated??0)} more`]:[]],j="";if(e.docs){let k=F(o.sessionID).changed,L=e.about?.trim()||k.join("; ");if(!L)j="\n\nDOCUMENT CHECK UNAVAILABLE: nothing was changed in this session; pass `about` with the elements/values to check.";else{let U=await ee(`Check these AUTOSAR configuration elements and values against the specifications and manuals in this knowledge base: ${L}. 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.`,o.sessionID,e.workspace_id,o.abort);j=U.startsWith("UNAVAILABLE")?`
32
40
 
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(`
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?`
41
+ DOCUMENT CHECK UNAVAILABLE: ${U}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${L}`,U,"","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(`
42
+ `)}}return{title:`ecuc_validate ${JSON.stringify(g??c.summary)}`,output:v(c)+[b||x,...b?[x]:[],...D(u,e.max??200),...B].join(`
43
+ `)+j}}}),arxml_diff:S({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:l.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:l.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=await w(i,["diff",e.a,e.b],o.abort);if(!r.ok)return A(r);let{ok:d,engine:c,ms:u,...p}=r;return JSON.stringify(p,null,1)}}),autosar_trace:S({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."+C,args:{query:l.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:l.number().int().optional().describe("restrict to one code data source"),limit:l.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:l.union([l.string(),l.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:l.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,o){let i=await P(e.workspace_id,o.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 d=await M("/api/v1/mcp/autosar/trace",i,r,o.abort),c=d.matches??[],u=_(o.directory,e.project_dir),p=c.map((b)=>b.arxml).filter((b)=>!!b),[h,g]=await Promise.all([$e(u,p,o.abort),Se(u,p,o.abort)]),m=[`${c.length} match(es) for "${e.query}" in workspace ${i}`+(d.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(d.data_sources_queried)})`:""),...ke(d),...h,...g,JSON.stringify(c,null,1)];if(!c.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(`
44
+ `)}}}),autosar_config_lookup:S({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."+C,args:{path:l.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:l.number().int().optional().describe("restrict to one code data source"),workspace_id:l.union([l.string(),l.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:l.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,o){let i=await P(e.workspace_id,o.abort),r={path:e.path};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;let d=await M("/api/v1/mcp/autosar/config-lookup",i,r,o.abort),c=d.matches??[],u=_(o.directory,e.project_dir),p=c.map((m)=>m.element).filter((m)=>!!m),[h,g]=await Promise.all([$e(u,p,o.abort),Se(u,p,o.abort)]);return{title:`autosar_config_lookup ${e.path}`,output:[`${c.length} match(es) for ${e.path} in workspace ${i}`,...ke(d),...h,...g,JSON.stringify(c,null,1)].join(`
45
+ `)}}}),ecuc_find:S({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>".`+C,args:{module:l.string().optional(),container_def:l.string().optional().describe("container definition short-name"),where:l.union([l.string(),l.record(l.string(),l.any())]).optional().describe("conditions on parameter values"),ref_to:l.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:l.string().optional().describe("container whose references define the result set"),limit:l.number().int().min(1).max(500).optional(),project_dir:l.string().optional()},async execute(e,o){let i=["find"];if(e.module)i.push("--module",e.module);if(e.container_def)i.push("--container-def",e.container_def);if(e.where)i.push("--where",typeof e.where==="string"?e.where:JSON.stringify(e.where));if(e.ref_to)i.push("--ref-to",e.ref_to);if(e.referenced_by)i.push("--referenced-by",e.referenced_by);i.push("--limit",String(e.limit??50));let r=await w(_(o.directory,e.project_dir),i,o.abort);if(!r.ok)return v(r)+A(r);let{ok:d,engine:c,ms:u,warnings:p,...h}=r;return v(r)+JSON.stringify(h,null,1)}}),autosar_spec_id_check:S({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:I().describe("requirement IDs to check (a list, a JSON-encoded list, or one ID)"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=T(e.ids)??[];if(!i.length)return'ERROR: pass ids, e.g. ["SWS_Com_00197"]';let r=await w(_(o.directory,e.project_dir),["spec-ids",...i],o.abort);if(!r.ok)return A(r);let d=r.results;return{title:`autosar_spec_id_check ${JSON.stringify(r.counts)}`,output:[`Checked ${d.length} ID(s) against ${r.docs} spec text file(s) (${r.docsOrigin}; ${r.indexedIds} IDs indexed): ${JSON.stringify(r.counts)}`,...d.map((c)=>`${c.id} ${c.status}`+(c.doc?` \u2014 ${c.doc}:${c.line}`:"")+(c.didYouMean?` (did you mean ${c.didYouMean}?)`:"")+(c.text?`
46
+ ${c.text}`:"")),d.some((c)=>c.status!=="DEFINED")?"Do not cite IDs that are not DEFINED; state the rule without an ID instead.":""].filter(Boolean).join(`
47
+ `)}}}),ecuc_crosscheck:S({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."+C,args:{module:l.string().describe("module name, e.g. PduR"),project_dir:l.string().optional()},async execute(e,o){let i=await w(_(o.directory,e.project_dir),["crosscheck",e.module],o.abort);if(!i.ok)return v(i)+A(i);let r=i.rows,d=i.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${i.summary}`,output:[`${e.module}: ${i.summary} (element kinds: ${i.elementKinds.join(", ")||"none"})`,...r.map((c)=>`${c.element} (${c.at})
48
+ ${c.findings.join(`
49
+ `)}`),...D(d,50),...(i.notes??[]).map((c)=>`NOTE: ${c}`)].join(`
50
+ `)}}}),arxml_edit:S({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(l.array(R(l.record(l.string(),l.any()))).min(1)).describe("list of ops"),dry_run:l.boolean().optional(),project_dir:l.string().optional()},async execute(e,o){let i=["arxml-edit","--ops",JSON.stringify(N(e.ops))];if(e.dry_run)i.push("--dry-run");let r=await w(_(o.directory,e.project_dir),i,o.abort),d=r.changes??[];if(!r.ok)return A(r)+(r.problems?.length?`
43
51
  ${r.problems.join(`
44
- `)}`:"")+(l.length?`
52
+ `)}`:"")+(d.length?`
45
53
  Rejected diff:
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(`
54
+ ${d.map((h)=>h.diff).join(`
55
+ `)}`:"");let c=r.notes??[],u=r.createdPackages??[],p="";if(r.written){let h=await w(_(o.directory,e.project_dir),["validate","--no-check-generated","--new-only","--max","40"],o.abort);if(h.ok!==!1&&h.diagnostics){let g=h.diagnostics.filter((m)=>m.severity==="error"||m.severity==="warning");p=g.length?`
56
+ AUTO-VALIDATE (new since ${h.baseline??"?"}): ${JSON.stringify(h.summaryNew??h.summary)} -- FIX these before going on:
57
+ ${D(g,25).join(`
50
58
  `)}`:`
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(`
59
+ 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(", ")}`:"")+(c.length?`
60
+ NOTE: ${c.join(`
53
61
  NOTE: `)}`:"")+`
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?`
58
- ${j(r.diagnostics,20).join(`
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}
62
+ ${d.map((h)=>h.diff).join(`
63
+ `)}`+(p||`
64
+ Next: ecuc_validate (checks extract/SWC files too).`)}}),autosar_add_like:S({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:l.string().describe("name stem of the template element, e.g. BCM_DoorStatus (an existing message), DoorLockActuatorFault (a Dem event)"),name:l.string().describe("the new stem, e.g. BCM_SettingsAck"),also:R(l.record(l.string(),l.string())).optional().describe("template members to clone and rename too: {template stem: new stem}"),set:R(l.record(l.string(),l.any())).optional().describe("values on the clones: {ParamDefName | XML-TAG | 'Owner:key': value}"),seed:l.string().optional().describe("one element of the template chain, when several separate chains carry the stem"),keep_members:l.boolean().optional().describe("also copy the template's own members (default false)"),dry_run:l.boolean().optional(),project_dir:l.string().optional()},async execute(e,o){let i=["add-like","--like",e.like,"--name",e.name];if(e.also)i.push("--also",JSON.stringify(N(e.also)));if(e.set)i.push("--set",JSON.stringify(N(e.set)));if(e.seed)i.push("--seed",e.seed);if(e.keep_members)i.push("--keep-members");if(e.dry_run)i.push("--dry-run");let r=await w(_(o.directory,e.project_dir),i,o.abort),d=(u)=>r[u]??[],c=[r.ok?`${r.written?"Written":"Dry run OK"}: ${d("created").length} element(s) like ${e.like} as ${e.name}`:`NOT DONE: ${r.error}`,...d("created").length?["Created:",...d("created").map((u)=>` ${u}`)]:[],...d("set").length?["Set:",...d("set").map((u)=>` ${u}`)]:[],...d("ids").length?["Handle IDs:",...d("ids").map((u)=>` ${u}`)]:[],...d("linked").length?["Linked:",...d("linked").map((u)=>` ${u}`)]:[],...d("notCopied").length?[`Not copied (the template's own members): ${d("notCopied").length}`,...d("notCopied").slice(0,12).map((u)=>` ${u}`)]:[],...d("singleValuedNotLinked").length?["Single-valued references to the template NOT changed (add/point your own if the new element needs one):",...d("singleValuedNotLinked").map((u)=>` ${u}`)]:[],...d("notes").map((u)=>`NOTE: ${u}`),...d("todo").length?["STILL TO DO (completeness, not undone):",...d("todo").map((u)=>` ${u}`)]:[],...(r.problems??[]).map((u)=>`PROBLEM: ${u}`),...(r.diagnostics??[]).length?D(r.diagnostics,20):[]];if(r.ok&&!r.written)c.push("Next: run again without dry_run.");if(r.ok&&r.written)c.push(String(r.next??""));return c.join(`
65
+ `)}}),autosar_add_signal:S({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:l.string(),ipdu:l.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:l.number().int().min(1).max(64).optional(),type:l.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:l.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:l.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:l.union([l.number(),l.string()]).optional(),transfer_property:l.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:l.boolean().optional(),project_dir:l.string().optional()},async execute(e,o){let i=["add-signal","--name",e.name,"--ipdu",e.ipdu,"--type",e.type??"UINT8"];if(e.bit_size!==void 0)i.push("--bit-size",String(e.bit_size));if(e.bit_position!==void 0)i.push("--bit-position",String(e.bit_position));if(e.endianness)i.push("--endianness",e.endianness);if(e.init!==void 0)i.push("--init",String(e.init));if(e.transfer_property)i.push("--transfer-property",e.transfer_property);if(e.dry_run)i.push("--dry-run");let r=await w(_(o.directory,e.project_dir),i,o.abort);if(!r.ok)return A(r)+(r.diagnostics?.length?`
66
+ ${D(r.diagnostics,20).join(`
67
+ `)}`:"");let{ok:d,engine:c,ms:u,...p}=r;return JSON.stringify(p,null,1)}}),autosar_audit:S({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:I().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:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=await w(i,["audit",...T(e.paths)??[]],o.abort);if(!r.ok)return v(r)+A(r);let d=(r.notes??[]).map((m)=>`NOTE: ${m}`),{findings:c,unchecked:u,scanned:p}=r,h=[`Scanned ${p.sources.length} C file(s), ${p.calls} BSW call(s): ${c.length?JSON.stringify(r.summary):"no findings"}`,...c.map((m)=>`${m.file}:${m.line} ${m.severity.toUpperCase()} ${m.rule} ${m.call}
60
68
  ${m.message}
61
69
  evidence: ${JSON.stringify(m.evidence)}
62
70
  spec: ${m.cite}${m.fix?`
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(`
71
+ fix: ${m.fix}`:""}`)];if(u.length)h.push(`Unchecked (${u.length}):`,...u.slice(0,50).map((m)=>` ${m.file}:${m.line} ${m.call} \u2014 ${m.reason}`));let g=r.unreferenced??{};for(let[m,b]of Object.entries(g))h.push(`INFO configured but never referenced in the scanned code \u2014 ${m}: ${b.count} (e.g. ${b.sample.slice(0,5).join(", ")})`);return h.push(...d),{title:`autosar_audit ${JSON.stringify(r.summary)}`,output:v(r)+h.join(`
72
+ `)}}}),autosar_verify_rte:S({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:I().describe("C files, directories or globs (default: all in-house C)"),diff_against:l.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:l.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:l.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=["verify-rte",...T(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 d=await w(i,r,o.abort);if(!d.ok)return A(d);let{findings:c,counts:u}=d,p=c.filter((y)=>y.status!=="OK"),h=d.scanned,g=[`Verified ${h.calls} Rte_* call(s) in ${h.files.length} file(s) against SW-C(s) ${d.swcs.join(", ")}: OK ${u.OK}, NOT-ALLOWED ${u["NOT-ALLOWED"]}, INVENTED ${u.INVENTED}`+(p.length?" \u2014 FAILING":" \u2014 PASS")];for(let y of p){if(g.push(`${y.at} ${y.status} ${y.call} in ${y.function}() [${y.swc??"?"}${y.runnable?`/${y.runnable}`:""}]`,` ${y.why}`),y.expected)g.push(` expected: ${y.expected} [${y.cite}]`);if(y.hint)g.push(` hint: ${y.hint}`);if(y.arxml_edit?.length)g.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=d.notChecked??[];if(m.length)g.push(`Not checked (${m.length}): ${m.map((y)=>`${y.call} @ ${y.at}`).join(", ")}`);let b=d.runnablesWithoutCode??[];if(b.length)g.push(`Runnables without a C definition: ${b.map((y)=>`${y.swc}.${y.runnable} (${y.symbol})`).join(", ")}`);for(let y of d.notes??[])g.push(`NOTE: ${y}`);if(p.length)g.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 ${p.length?"FAIL":"PASS"} ${JSON.stringify(u)}`,output:g.join(`
73
+ `),metadata:{counts:u}}}}),autosar_build_context:S({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:l.string().optional().describe("SW-C short name or AUTOSAR path (runnable/C mode)"),target:l.string().optional().describe("configuration mode: module, container or element (AUTOSAR path, SHORT-NAME or partial path), e.g. 'Can', 'CanController_0'"),docs:l.boolean().optional().describe("add DOC FACTS from the ingested documents (default true)"),runnable:l.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:l.string().describe("the task, verbatim"),budget_tokens:l.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:l.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:l.union([l.string(),l.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=e.docs!==!1;if(!e.swc){let g="",m=await ut(i,e.task,o.abort);if(!e.target){if(!m.length)return"ERROR: give target (the module, container or element the configuration change is about) or swc (+runnable, for C code); the task names no configured module.";e.target=m[0]}if(lt.test(e.task)){let re=m.length?m:[O(e.target)??e.target];g=`## 0. GENERATED CODE
74
+ The configuration code (${re.map((se)=>`${se}_Cfg.h, ${se}_Cfg.c/_PBcfg.c`).join("; ")}) is derived from the ECUC ARXML. Do not write it by hand: make the ARXML right (ecuc_edit, ecuc_validate until clean), then autosar_codegen modules=${JSON.stringify(re)} out_dir='Output' (or the folder the user named), then autosar_codegen_diff against what was there before.`}let b=await w(i,["read",e.target,"--depth","3","--schema"],o.abort),{ok:y,engine:x,ms:B,...j}=b,k=b.ok?JSON.stringify(j,null,1).split(`
75
+ `):[`(${e.target} is not an ECUC element this engine can read: ${String(b.error??"").slice(0,300)}; for System/SWC ARXML read the element or its file, and use autosar_config_lookup / ecuc_find)`],L=k.length>400?`${k.slice(0,400).join(`
67
76
  `)}
68
- \u2026 (${N.length-400} more lines: narrow the target)`:N.join(`
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
77
+ \u2026 (${k.length-400} more lines: narrow the target)`:k.join(`
78
+ `),U=r?await ee(`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.`,o.sessionID,e.workspace_id,o.abort,(Number(e.doc_timeout_s)||300)*1000):"(skipped: docs=false)",ne=O(e.target)??O(String(JSON.stringify(j).match(/"@path":\s*"(\/[^"]+)"/)?.[1]??""))??m[0],ie=await ft(i,ne,o.abort);return{title:`autosar_build_context target ${e.target}`,output:["# CONTEXT (configuration change)",...g?[g]:[],`## 1. TASK
70
79
  ${e.task}`,`## 2. PROJECT FACTS [F]: current values with @at file:line, and the param-def schema (what may be set)
71
- ${I}`,`## 3. DOC FACTS [D]: from the ingested documents
72
- ${v}`,`## 4. NEXT
80
+ ${L}`,...ie?[`## 2b. CONSISTENCY RULES ecuc_validate will check for ${ne} (plan the change so it passes them)
81
+ ${ie}`]:[],`## 3. DOC FACTS [D]: from the ingested documents
82
+ ${U}`,`## 4. NEXT
73
83
  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(`
74
84
 
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+=`
85
+ `)}}let d=["build-context","--swc",e.swc,"--task",e.task,"--budget-tokens",String(e.budget_tokens??24000)];if(e.runnable)d.push("--runnable",e.runnable);let c=await w(i,d,o.abort);if(!c.ok)return A(c);let u=c.text,p=c.codeMissing??[];if(p.length&&e.use_backend){let g=[];try{let m=await P(e.workspace_id,o.abort);for(let b of p){let y=await M("/api/v1/mcp/autosar/trace",m,{query:b,limit:3},o.abort);g.push(`### backend trace for ${b} (workspace ${m})
86
+ ${JSON.stringify(y.matches??[],null,1).slice(0,6000)}`)}}catch(m){g.push(`(backend lookup unavailable: ${m instanceof Error?m.message:String(m)})`)}u+=`
77
87
  ## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
78
- ${f.join(`
88
+ ${g.join(`
79
89
  `)}
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+=`
90
+ `}if(r){let g=await ee(`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.`,o.sessionID,e.workspace_id,o.abort);u+=`
81
91
  ## 9. DOC FACTS [D] from the ingested documents (not part of the deterministic context)
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}
92
+ ${g}
93
+ `}let h={swc:c.swc,runnables:c.runnables,estimatedTokens:c.estimatedTokens,budgetTokens:c.budgetTokens,reductions:c.reductions,overBudget:c.overBudget??!1,sha1:c.sha1,sections:c.sections,sources:c.manifest};return{title:`autosar_build_context ${c.swc}${c.runnables.length===1?`/${c.runnables[0]}`:""} ~${c.estimatedTokens} tok`,output:`${u}
84
94
  ---
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)=>`
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"}):
89
- `+u.assigned.slice(0,40).map((f)=>` ${f.path}/${f.param} = ${f.value} (hex ${we(f.value)})`).join(`
95
+ MANIFEST ${JSON.stringify(h)}`,metadata:{sha1:c.sha1,estimatedTokens:c.estimatedTokens}}}}),autosar_codegen:S({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:I().describe("modules to generate (default: every supported module that is configured)"),out_dir:l.string().optional().describe("output dir, relative to the project or absolute; 'project' = codegen.outDir / Output. Default: scratch .hydron/codegen/out"),write_back:l.boolean().optional().describe("write assigned handle IDs into the ECUC ARXML (default true)"),binding:l.string().optional().describe("force a static-code binding (e.g. 'sip-standin'), or 'none' for generic tables only"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=["codegen"];for(let g of T(e.modules)??[])r.push("--module",g);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 d=await w(i,r,o.abort);if(!d.ok){let g=d.handleErrors??[];return v(d)+A(d)+(g.length?`
96
+ ${g.map((m)=>` ${m}`).join(`
97
+ `)}`:"")}let{modules:c,handles:u,timings:p}=d,h=[`Generated ${Object.keys(c).length} module(s) into ${d.outDir} in ${p.total_ms} ms (AUTOSAR R${d.release}):`,...Object.entries(c).map(([g,m])=>` ${g} (${m.variant}${m.binding?`, binding ${m.binding}`:", generic tables"}): ${m.files.join(", ")}; ${m.symbols} symbol(s)`+m.notes.map((b)=>`
98
+ NOTE: ${b}`).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"}):
99
+ `+u.assigned.slice(0,40).map((g)=>` ${g.path}/${g.param} = ${g.value} (hex ${ve(g.value)})`).join(`
90
100
  `)+(u.changes.length?`
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(`
94
- `)}}}),autosar_generate:s("generate"),autosar_build:s("build")}),t)}},tt=et;export{tt as Autosar};
101
+ ${u.changes.map((g)=>g.diff).join(`
102
+ `)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(d.notes??[]).map((g)=>`NOTE: ${g}`)];return{title:`autosar_codegen ${Object.keys(c).join(", ")}`,output:v(d)+h.join(`
103
+ `)}}}),autosar_codegen_diff:S({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:l.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:l.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:I().describe("only these modules"),project_dir:l.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=_(o.directory,e.project_dir),r=["codegen-diff",e.reference_dir];if(e.generated_dir)r.push(e.generated_dir);for(let p of T(e.modules)??[])r.push("--module",p);let d=await w(i,r,o.abort);if(!d.ok)return A(d);let c=d.modules,u=[`Semantic diff ${d.reference} (reference) vs ${d.generated} (generated): ${JSON.stringify(d.total)}`,`Not generated (reference only): ${d.notGenerated.join(", ")||"-"}; not in reference: ${d.notInReference.join(", ")||"-"}`];for(let[p,h]of Object.entries(c)){if(u.push(`== ${p}: ${h.summary.matching} matching, ${h.summary.missing} missing, ${h.summary.extra} extra, ${h.summary.mismatches} mismatch(es); table elements ${h.elements.match} equal / ${h.elements.mismatch} different`),h.defines.missing.length)u.push(` missing #define: ${h.defines.missing.slice(0,30).join(", ")}`);for(let g of h.defines.mismatch.slice(0,30))u.push(` #define ${g.name}: reference ${g.reference} | generated ${g.generated}`);if(h.objects.missing.length)u.push(` missing object: ${h.objects.missing.join(", ")}`);if(h.objects.extra.length)u.push(` extra object: ${h.objects.extra.join(", ")}`);for(let g of h.objects.order)u.push(` order differs: ${g.name} (same rows)`);for(let g of h.objects.mismatch)u.push(` ${g.name}: ${g.count} element(s) differ`,...g.elements.slice(0,12).map((m)=>` ${m.element}: reference ${m.reference} | generated ${m.generated}`));if(h.defines.extra.length)u.push(` extra #define (${h.defines.extra.length}): ${h.defines.extra.slice(0,12).join(", ")}${h.defines.extra.length>12?", \u2026":""}`)}return{title:`autosar_codegen_diff ${JSON.stringify(d.total)}`,output:u.join(`
104
+ `)}}}),autosar_generate:s("generate"),autosar_build:s("build")}),t)}},pt=gt;export{pt as Autosar};
@@ -66,7 +66,9 @@ def main(argv=None) -> int:
66
66
  ap.add_argument("--config", action="append", help="ECUC value file/dir/glob (overrides discovery)")
67
67
  ap.add_argument("--json", action="store_true", help="JSON output (always on; accepted for clarity)")
68
68
  sub = ap.add_subparsers(dest="cmd", required=True)
69
- sub.add_parser("info")
69
+ sub.add_parser("info").add_argument("--json", action="store_true", help=argparse.SUPPRESS)
70
+ sub.add_parser("rules", help="list the semantic rules (id, severity, title, citation)").add_argument(
71
+ "--json", action="store_true", help=argparse.SUPPRESS)
70
72
  r = sub.add_parser("read")
71
73
  r.add_argument("path", nargs="?")
72
74
  r.add_argument("--depth", type=int, default=2)
@@ -178,6 +180,9 @@ def main(argv=None) -> int:
178
180
 
179
181
 
180
182
  def run(a) -> dict:
183
+ if a.cmd == "rules":
184
+ from .rules import RULES, chain, com, handles, mcal, mem, nvm, pdur, system # noqa: F401 (register the packs)
185
+ return {"rules": [{"id": r.id, "severity": r.severity, "title": r.title, "cite": r.cite} for r in RULES]}
181
186
  if a.cmd in ("edit", "arxml-edit"):
182
187
  try:
183
188
  a.ops = _ops(a.ops)
@@ -628,11 +628,109 @@ def schema_check(path: str, data: bytes) -> Optional[str]:
628
628
  return str(e)
629
629
 
630
630
 
631
+ def _module_text(pkg_segs: list, mod: D.DefNode, variant: str, schema_loc: str) -> bytes:
632
+ ind = lambda n: " " * n # noqa: E731
633
+ lines = ['<?xml version="1.0" encoding="UTF-8"?>',
634
+ f'<AUTOSAR xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
635
+ f'xsi:schemaLocation="{schema_loc}">']
636
+ d = 1
637
+ for s in pkg_segs:
638
+ lines += [ind(d) + "<AR-PACKAGES>", ind(d + 1) + "<AR-PACKAGE>", ind(d + 2) + f"<SHORT-NAME>{escape(s)}</SHORT-NAME>"]
639
+ d += 2
640
+ lines += [ind(d) + "<ELEMENTS>", ind(d + 1) + "<ECUC-MODULE-CONFIGURATION-VALUES>",
641
+ ind(d + 2) + f"<SHORT-NAME>{escape(mod.name)}</SHORT-NAME>",
642
+ ind(d + 2) + f'<DEFINITION-REF DEST="ECUC-MODULE-DEF">{escape(mod.path)}</DEFINITION-REF>',
643
+ ind(d + 2) + f"<IMPLEMENTATION-CONFIG-VARIANT>{variant}</IMPLEMENTATION-CONFIG-VARIANT>",
644
+ ind(d + 2) + "<CONTAINERS>", ind(d + 2) + "</CONTAINERS>",
645
+ ind(d + 1) + "</ECUC-MODULE-CONFIGURATION-VALUES>", ind(d) + "</ELEMENTS>"]
646
+ for _ in pkg_segs:
647
+ d -= 2
648
+ lines += [ind(d + 1) + "</AR-PACKAGE>", ind(d) + "</AR-PACKAGES>"]
649
+ lines.append("</AUTOSAR>")
650
+ return ("\n".join(lines) + "\n").encode()
651
+
652
+
653
+ def new_modules(project: Project, ed: "Editor", ops: list) -> list:
654
+ """Create the ECUC module configurations the ops need and the project does not have yet.
655
+
656
+ {"op": "add", "path": "/ActiveEcuC", "container": "Pwm"} creates the Pwm module configuration (also when the
657
+ container is written "Pwm:Pwm"); an op whose path is "/<Pkg>/<Module>/..." for a module that has a definition but
658
+ no configuration creates it first. Optional keys on the creating op: "file" (default: next to the existing
659
+ module files, named like them), "variant" (default: the variant most existing modules use, if the def supports
660
+ it, else the def's first). The new file is created in memory (dry runs show it) and written with the edit."""
661
+ if not project.defs or not isinstance(ops, list):
662
+ return ops
663
+ mods_by_name = {m.name: m for m in project.defs.modules.values()}
664
+ have = {e.name: e for es in project.by_path.values() for e in es if e.parent is None}
665
+ out = []
666
+ for i, op in enumerate(ops):
667
+ if not isinstance(op, dict):
668
+ out.append(op)
669
+ continue
670
+ path = str(op.get("path") or "").rstrip("/")
671
+ segs = [s for s in path.split("/") if s]
672
+ want, creating_op = None, False
673
+ cont = op.get("container")
674
+ cname = cont.split(":")[-1] if isinstance(cont, str) else None
675
+ cdef = cont.split(":")[0] if isinstance(cont, str) else None
676
+ if op.get("op") == "add" and len(segs) >= 1 and not project.find(path) and cname in mods_by_name \
677
+ and cdef in (cname, "ECUC-MODULE-CONFIGURATION-VALUES", "EcucModuleConfigurationValues"):
678
+ want, pkg, creating_op = cname, segs, True
679
+ elif len(segs) >= 2 and segs[1] in mods_by_name and segs[1] not in have and not project.find("/" + "/".join(segs[:2])):
680
+ want, pkg = segs[1], segs[:1]
681
+ if want is None or want in have:
682
+ if creating_op is False or want is None:
683
+ out.append(op)
684
+ continue
685
+ mdef = mods_by_name[want]
686
+ cfgs = sorted({e.file for e in have.values()})
687
+ ref = cfgs[0] if cfgs else None
688
+ if op.get("file"):
689
+ f = op["file"] if os.path.isabs(op["file"]) else os.path.join(project.root, op["file"])
690
+ elif ref:
691
+ base = os.path.basename(ref)
692
+ other = next((e.name for e in have.values() if e.file == ref), "")
693
+ fname = base.replace(other, want, 1) if other and base.startswith(other) else f"{want}_ecuc.arxml"
694
+ f = os.path.join(os.path.dirname(ref), fname)
695
+ else:
696
+ f = os.path.join(project.root, "Config", f"{want}_ecuc.arxml")
697
+ if os.path.exists(f) or f in project.files:
698
+ raise EditError(f"cannot create module {want}: {project.rel(f)} already exists (pass 'file')")
699
+ used = [e.node.child_text("IMPLEMENTATION-CONFIG-VARIANT") if hasattr(e.node, "child_text") else None
700
+ for e in have.values()]
701
+ supported = mdef.variants or []
702
+ variant = op.get("variant") or next((u for u in sorted(set(u for u in used if u), key=used.count, reverse=True)
703
+ if not supported or u in supported), None) \
704
+ or (supported[0] if supported else "VARIANT-PRE-COMPILE")
705
+ schema_loc = "http://autosar.org/schema/r4.0 AUTOSAR_00054.xsd"
706
+ if ref:
707
+ import re as _re
708
+ m = _re.search(rb'xsi:schemaLocation="([^"]+)"', project.files[ref].data[:2000])
709
+ if m:
710
+ schema_loc = m.group(1).decode()
711
+ data = _module_text(pkg, mdef, variant, schema_loc)
712
+ err = schema_check(f, data)
713
+ if err:
714
+ raise EditError(f"internal: new module file for {want} is not schema-valid: {err}")
715
+ ed.original[f] = b""
716
+ project._load(f, data)
717
+ if f not in project.sources.config:
718
+ project.sources.config.append(f)
719
+ project.reindex()
720
+ have = {e.name: e for es in project.by_path.values() for e in es if e.parent is None}
721
+ ed.notes.append(f"op {i}: created module configuration {want} (/{'/'.join(pkg)}/{want}, {variant}) in "
722
+ f"{project.rel(f)}")
723
+ if not creating_op:
724
+ out.append(op)
725
+ return out
726
+
727
+
631
728
  def edit(project: Project, ops: list, dry_run: bool = False, force: bool = False, run_validate: bool = True) -> dict:
632
729
  ed = Editor(project)
633
730
  ed.notes = []
634
731
  try:
635
732
  ops = normalize_ops(project, ops, ed.notes)
733
+ ops = new_modules(project, ed, ops)
636
734
  ed.apply(ops, force=force)
637
735
  for op in ops if isinstance(ops, list) else []:
638
736
  if not isinstance(op, dict):
@@ -650,7 +748,7 @@ def edit(project: Project, ops: list, dry_run: bool = False, force: bool = False
650
748
  res: dict = {"ok": True, "applied": len(ops), "changes": changes, "written": False, "notes": ed.notes}
651
749
  schema = []
652
750
  for f, before in ed.original.items():
653
- if schema_check(f, before) is None:
751
+ if before == b"" or schema_check(f, before) is None:
654
752
  err = schema_check(f, ed.data(f))
655
753
  if err:
656
754
  schema.append({"file": project.rel(f), "error": err})
@@ -81,7 +81,7 @@ grounding, no tools, no exploring the project.
81
81
  | Review C code that calls Com/NvM/Dem/PduR/RTE APIs | `autosar_audit` (first), then confirm with `autosar_trace` / `ecuc_read` |
82
82
  | Context for implementing / changing a runnable (allowed RTE API, code, callees, config, similar code/changes) | `autosar_build_context swc=… runnable=… task=…` |
83
83
  | Check that C only calls the RTE APIs its runnable may call (OK / NOT-ALLOWED / INVENTED + ARXML fix ops) | `autosar_verify_rte` (`diff_against=<ref>` for a change) |
84
- | Generate BSW config code ourselves (NvM/Fee/MemIf/Dem/PduR/CanIf/Port/Dio) | `autosar_codegen`, then `autosar_codegen_diff reference_dir=Output` (see `references/codegen.md`) |
84
+ | Generate BSW/MCAL config code (`<Mip>_Cfg.h`, `_Cfg.c`/`_PBcfg.c`: NvM/Fee/MemIf/Dem/PduR/CanIf and every MCAL driver: Mcu/Port/Dio/Gpt/Can/Adc/Pwm/Icu/Spi/Wdg/...) | fix the ARXML first, then `autosar_codegen modules=[..] out_dir='Output'`, then `autosar_codegen_diff reference_dir=Output`; never hand-write these files (see `references/codegen.md`) |
85
85
  | Regenerate code with the vendor tool | `autosar_generate` (configured command, asks permission) |
86
86
  | Compile/link | `autosar_build` |
87
87
  | Is this requirement ID real, and what does it say? | `autosar_spec_id_check ids=[…]` (needs `specDocs` / `$AUTOSAR_SPEC_DOCS`) |