@anik-2/autosar 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,7 @@ Deterministic tools for AUTOSAR Classic integration work, so the agent never han
13
13
  | `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
14
14
  | `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
15
15
  | `autosar_config_lookup` | element + children + refs in/out + links from the code graph | H2Loop backend |
16
+ | `autosar_audit` | integration review of C code: BSW API handles, direction, widths, NvM NULL_PTR vs ECUC | local |
16
17
  | `autosar_generate` / `autosar_build` | run the project's configured generator / build command (asks permission) | local |
17
18
 
18
19
  Plus the `autosar` skill (ECUC model, symbolic-name rule, config classes, project layout, the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anik-2/autosar",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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,
@@ -16,6 +16,7 @@
16
16
  "plugins/index.js",
17
17
  "python/pyproject.toml",
18
18
  "python/ecuc_engine/*.py",
19
+ "python/ecuc_engine/rules/*.py",
19
20
  "README.md"
20
21
  ],
21
22
  "scripts": {
package/plugins/index.js CHANGED
@@ -1,21 +1,26 @@
1
1
  // @bun
2
- import{isAbsolute as W,join as T,resolve as G}from"path";import{tool as p}from"@kilocode/plugin";import{homedir as j}from"os";import{join as h}from"path";var I=()=>process.env.HYDRON_TEST_HOME||j(),R=(t,n)=>process.env[t]||h(I(),n),D=()=>h(R("XDG_CONFIG_HOME",".config"),"hydron-cli"),L=()=>h(R("XDG_DATA_HOME",".local/share"),"hydron-cli"),M=()=>h(R("XDG_STATE_HOME",".local/state"),"hydron-cli");async function v(t){let n=Bun.file(t);if(!await n.exists())return;return n.json().catch(()=>{return})}async function N(){let t=process.env.KILO_API_URL?.trim();if(t)return t.replace(/\/+$/,"");let n=await v(h(D(),"server-config.json")),e=typeof n?.apiBaseUrl==="string"?n.apiBaseUrl:void 0;if(!e)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return e.replace(/\/+$/,"")}function F(t){let n=t?.split(".")[1];if(!n)return"";try{let e=JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof e.sub==="string"?e.sub:""}catch{return""}}async function J(t){let n=F(t.access);if(n)return n;if(!t.refresh)return"";return new Bun.CryptoHasher("sha256").update(t.refresh).digest("hex").slice(0,12)}async function E(){let n=(await v(h(L(),"auth.json")))?.hydron;if(!n||n.type!=="oauth"||!n.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return n}async function x(){let t=await E();if(typeof t.expires==="number"&&t.expires>0&&Date.now()>=t.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 t.access}async function A(t){if(t!==void 0&&String(t).trim())return String(t).trim();let n=await v(h(M(),"h2loop-project.json")),e=await E(),o=await J(e),i=n?.project??void 0;if(i?.id!==void 0&&typeof n?.account==="string"&&n.account===o)return String(i.id);throw Error("No H2Loop project selected for this account. Select one in Hydron (project picker) or pass workspace_id explicitly.")}async function $(t,n,e,o){let i=`${await N()}${t}?workspace_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await x()}`},body:JSON.stringify(e),signal:o?AbortSignal.any([o,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000)}),r=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&&r.includes("Not Found"))throw Error(`${t} is not available on ${await N()} (backend predates the AUTOSAR endpoints).`);if(!a.ok)throw Error(`H2Loop ${t} failed: HTTP ${a.status} ${r.slice(0,800)}`);try{return JSON.parse(r)}catch(d){throw Error(`H2Loop ${t} returned non-JSON (${String(d)}): ${r.slice(0,300)}`)}}import{existsSync as P}from"fs";import{dirname as q,join as S}from"path";import{fileURLToPath as X}from"url";var H="autosar-data==0.17.0";function B(){let t=q(X(import.meta.url)),n=[S(t,"..","python"),S(t,"..","..","python")].find((e)=>P(S(e,"ecuc_engine","__main__.py")));if(!n)throw Error(`ECUC engine not found next to ${t} (expected ../python/ecuc_engine)`);return n}async function V(t){try{return await Bun.spawn([...t,"-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 _={};async function Y(){if(_.cmd!==void 0)return _.cmd;let t=process.env.AUTOSAR_PYTHON?.trim(),e=t?[[t]]:[["uv","run","--no-project","--quiet","--with",H,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let o of e)if(await V(o))return _.cmd=o,o;return _.cmd=null,null}async function y(t,n,e){let o=await Y();if(!o)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 i=B(),a=Bun.spawn([...o,"-m","ecuc_engine","--root",t,...n,"--json"],{cwd:t,env:{...process.env,PYTHONPATH:[i,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:e}),[r,d]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text()]);await a.exited;let u=r.trim().split(`
3
- `).filter(Boolean).at(-1);if(!u)return{ok:!1,error:`engine produced no output (exit ${a.exitCode}): ${d.trim().slice(-2000)}`};try{return JSON.parse(u)}catch(c){return{ok:!1,error:`engine output was not JSON (${String(c)}): ${u.slice(0,500)} ${d.slice(-500)}`}}}var s=p.schema,K=["# AUTOSAR pack active","For AUTOSAR/ECUC/ARXML work load the `autosar` skill. Never hand-write ARXML: use ecuc_read, ecuc_edit,","then ecuc_validate after every edit; arxml_diff to review. autosar_trace links config to C code.","Cite AUTOSAR path + DEFINITION-REF."].join(`
4
- `),b=" In your answer cite the AUTOSAR path and the DEFINITION-REF (and file:line) of every element you rely on.";function C(t,n=200){let e=t.slice(0,n).map((o)=>`${o.file}:${o.line} ${o.severity.toUpperCase()} ${o.rule} ${o.path} \u2014 ${o.message}${o.defRef?` [def ${o.defRef}]`:""}`);if(t.length>n)e.push(`\u2026 ${t.length-n} more`);return e}function w(t){let n=t.didYouMean?`
5
- Did you mean: ${t.didYouMean.join(", ")}`:"",e=t.schema?`
6
- Schema errors: ${JSON.stringify(t.schema)}`:"";return`ERROR: ${t.error}${n}${e}`}function g(t){let n=t.warnings??[];return n.length?n.map((e)=>`WARNING: ${e}`).join(`
2
+ import{isAbsolute as H_,join as w,resolve as J_}from"path";import{tool as P}from"@kilocode/plugin";import{homedir as d}from"os";import{join as N}from"path";var l=()=>process.env.HYDRON_TEST_HOME||d(),C=(q,J)=>process.env[q]||N(l(),J),c=()=>N(C("XDG_CONFIG_HOME",".config"),"hydron-cli"),i=()=>N(C("XDG_DATA_HOME",".local/share"),"hydron-cli"),g=()=>N(C("XDG_STATE_HOME",".local/state"),"hydron-cli");async function L(q){let J=Bun.file(q);if(!await J.exists())return;return J.json().catch(()=>{return})}async function O(){let q=process.env.KILO_API_URL?.trim();if(q)return q.replace(/\/+$/,"");let J=await L(N(c(),"server-config.json")),_=typeof J?.apiBaseUrl==="string"?J.apiBaseUrl:void 0;if(!_)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return _.replace(/\/+$/,"")}function n(q){let J=q?.split(".")[1];if(!J)return"";try{let _=JSON.parse(Buffer.from(J.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof _.sub==="string"?_.sub:""}catch{return""}}async function o(q){let J=n(q.access);if(J)return J;if(!q.refresh)return"";return new Bun.CryptoHasher("sha256").update(q.refresh).digest("hex").slice(0,12)}async function k(){let J=(await L(N(i(),"auth.json")))?.hydron;if(!J||J.type!=="oauth"||!J.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return J}async function z(){let q=await k();if(typeof q.expires==="number"&&q.expires>0&&Date.now()>=q.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 q.access}async function v(q){let J=await fetch(`${await O()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await z()}`},signal:q?AbortSignal.any([q,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(J.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!J.ok)throw Error(`could not list H2Loop projects: HTTP ${J.status}`);let _=await J.json();return Array.isArray(_)?_:_?.items??[]}var f=()=>N(g(),"h2loop-project.json");async function S(q,J){let _=q===void 0||q===null?"":String(q).trim();if(/^\d+$/.test(_))return _;if(_){let V=await v(J),D=V.filter((W)=>W.name===_),B=D.length?D:V.filter((W)=>W.name?.toLowerCase()===_.toLowerCase());if(B.length===1)return String(B[0].id);if(B.length>1)throw Error(`workspace "${_}" is ambiguous: ${B.map((W)=>`${W.name} (id ${W.id})`).join(", ")}; pass the numeric id`);let F=V.filter((W)=>W.name?.toLowerCase().includes(_.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${_}"`+(F.length?`; similar: ${F.map((W)=>`${W.name} (id ${W.id})`).join(", ")}`:`; you have ${V.length} project(s)`))}let H=await L(f());if(!H)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let Y=await k();if(H.project&&typeof H.project==="object"){let V=H.project;if(typeof H.account==="string"&&H.account!==await o(Y))throw Error("The selected H2Loop project belongs to another account; select one again or pass workspace_id.");if(V.id!==void 0)return String(V.id)}let Q=H;if(Q.id===void 0)throw Error(`${f()} holds no project id; select a project again or pass workspace_id.`);if(!(await v(J)).some((V)=>String(V.id)===String(Q.id)))throw Error(`The selected project ${Q.name??""} (id ${Q.id}) is not accessible to the signed-in account; select another or pass workspace_id.`);return String(Q.id)}async function T(q,J,_,H){let Y=`${await O()}${q}?workspace_id=${encodeURIComponent(J)}`,Q=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await z()}`},body:JSON.stringify(_),signal:H?AbortSignal.any([H,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000)}),Z=await Q.text();if(Q.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(Q.status===404&&Z.includes("Not Found"))throw Error(`${q} is not available on ${await O()} (backend predates the AUTOSAR endpoints).`);if(!Q.ok)throw Error(`H2Loop ${q} failed: HTTP ${Q.status} ${Z.slice(0,800)}`);try{return JSON.parse(Z)}catch(V){throw Error(`H2Loop ${q} returned non-JSON (${String(V)}): ${Z.slice(0,300)}`)}}var A=/\.arxml\b/i,b="Blocked: .arxml files must not be edited by hand (it breaks DEFINITION-REF/DEST, UUIDs and the round trip). Use ecuc_edit with ops by AUTOSAR path (read paths and allowed params with ecuc_read schema=true), then ecuc_validate.";function y(q,J){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!J)return;let _=typeof J.filePath==="string"?J.filePath:typeof J.file_path==="string"?J.file_path:"";if(["edit","write","multiedit"].includes(q)){let H=Array.isArray(J.edits)?J.edits.some((Y)=>typeof Y?.filePath==="string"&&A.test(Y.filePath)):!1;if(A.test(_)||H)return`${b} (${q} on ${_||"an .arxml file"})`;return}if(q==="apply_patch"||q==="patch"){let H=String(J.patchText??J.patch??""),Y=H.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??H.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return Y?`${b} (${q} on ${Y[1].trim()})`:void 0}if(q==="bash"){let H=String(J.command??"");if(!A.test(H))return;let Y=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(H)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(H),Q=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(H)||/\btee\b[^|;&]*\.arxml\b/i.test(H);if(Y||Q)return`${b} (bash: ${H.slice(0,120)})`}return}import{existsSync as a}from"fs";import{dirname as t,join as E}from"path";import{fileURLToPath as s}from"url";var e="autosar-data==0.17.0";function r(){let q=t(s(import.meta.url)),J=[E(q,"..","python"),E(q,"..","..","python")].find((_)=>a(E(_,"ecuc_engine","__main__.py")));if(!J)throw Error(`ECUC engine not found next to ${q} (expected ../python/ecuc_engine)`);return J}async function __(q){try{return await Bun.spawn([...q,"-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 R={};async function q_(){if(R.cmd!==void 0)return R.cmd;let q=process.env.AUTOSAR_PYTHON?.trim(),_=q?[[q]]:[["uv","run","--no-project","--quiet","--with",e,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let H of _)if(await __(H))return R.cmd=H,H;return R.cmd=null,null}async function G(q,J,_){let H=await q_();if(!H)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 Y=r(),Q=Bun.spawn([...H,"-m","ecuc_engine","--root",q,...J,"--json"],{cwd:q,env:{...process.env,PYTHONPATH:[Y,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:_}),[Z,V]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]);await Q.exited;let D=Z.trim().split(`
3
+ `).filter(Boolean).at(-1);if(!D)return{ok:!1,error:`engine produced no output (exit ${Q.exitCode}): ${V.trim().slice(-2000)}`};try{return JSON.parse(D)}catch(B){return{ok:!1,error:`engine output was not JSON (${String(B)}): ${D.slice(0,500)} ${V.slice(-500)}`}}}var $=P.schema,Q_=["# AUTOSAR pack active","Load the `autosar` skill for ARXML/ECUC work. Configured values: use ecuc_read (accepts a SHORT-NAME) or","autosar_config_lookup, not grep/read. Change config only with ecuc_edit (hand edits of .arxml are blocked),","then ecuc_validate. Reviewing C code using BSW APIs: run autosar_audit first. Cite @path (AUTOSAR path) and","@def (DEFINITION-REF) separately."].join(`
4
+ `);function x(q){if(typeof q!=="string")return q;let J=q.trim();if(!J.startsWith("[")&&!J.startsWith("{")&&!J.startsWith('"'))return q;try{return x(JSON.parse(J))}catch{return q}}var U=(q)=>$.preprocess(x,q),I=" 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.";function p(q,J=200){let _=q.slice(0,J).map((H)=>`${H.file}:${H.line} ${H.severity.toUpperCase()} ${H.rule} ${H.path} \u2014 ${H.message}${H.defRef?` [def ${H.defRef}]`:""}`);if(q.length>J)_.push(`\u2026 ${q.length-J} more`);return _}function M(q){let J=q.didYouMean?`
5
+ Did you mean: ${q.didYouMean.join(", ")}`:"",_=q.schema?`
6
+ Schema errors: ${JSON.stringify(q.schema)}`:"";return`ERROR: ${q.error}${J}${_}`}function X(q){let J=q.warnings??[];return J.length?J.map((_)=>`WARNING: ${_}`).join(`
7
7
  `)+`
8
- `:""}function l(t,n){if(!n)return t;return W(n)?n:G(t,n)}async function z(t){let n=Bun.file(T(t,".hydron","autosar.json"));if(!await n.exists())return{};return n.json().catch((e)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(e)}`)})}async function Q(t,n){let e=(await z(t))[n];if(typeof e==="string")return{command:e};if(e&&typeof e==="object"&&typeof e.command==="string")return e;return}function k(t,n=150){let e=t.split(`
9
- `);return e.length>n?[`\u2026 (${e.length-n} earlier lines omitted)`,...e.slice(-n)].join(`
10
- `):t}async function Z(t,n,e,o){let i=process.platform==="win32"?["cmd","/d","/s","/c",t]:["sh","-c",t],a=Date.now(),r=Bun.spawn(i,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([o,AbortSignal.timeout(e*1000)])}),[d,u]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:await r.exited,out:d,err:u,secs:Math.round((Date.now()-a)/1000)}}var U=(t)=>{let n=t.notes??[],e=t.errors??[];return[...n.map((o)=>`NOTE: ${typeof o==="string"?o:JSON.stringify(o)}`),...e.map((o)=>`BACKEND ERROR: ${typeof o==="string"?o:JSON.stringify(o)}`)]},ee=async(t)=>{let n=(e)=>p({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:s.string().optional().describe("module name substituted for {module} in the command, if used"),args:s.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(o,i){let a=l(i.directory,o.project_dir),r=await Q(a,e);if(!r)return`No \`${e}\` command configured. Add it to ${T(a,".hydron","autosar.json")}, e.g.
11
- {"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let d=o.args??"",u=r.command.replaceAll("{module}",o.module??""),c=u.includes("{args}")?u.replaceAll("{args}",d):`${u}${d?` ${d}`:""}`,m=l(a,r.cwd);await i.ask({permission:`autosar_${e}`,patterns:[c],always:[r.command],metadata:{command:c,cwd:m}}),i.metadata({title:`${e}: ${c}`});let f=await Z(c,m,r.timeoutSec??3600,i.abort),O=f.code===0?"OK":`FAILED (exit ${f.code})`;return{title:`autosar_${e} ${O}`,output:[`$ ${c} (cwd ${m}, ${f.secs}s) -> ${O}`,f.out.trim()?`--- stdout (tail) ---
12
- ${k(f.out)}`:"",f.err.trim()?`--- stderr (tail) ---
13
- ${k(f.err,80)}`:""].filter(Boolean).join(`
14
- `),metadata:{exit:f.code}}}});return{"experimental.chat.system.transform":async(e,o)=>{o.system.push(K)},tool:{ecuc_read:p({description:'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). No path: lists modules and the param-def/config files found. A module/container path: 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."+b,args:{path:s.string().optional().describe("AUTOSAR path of a module/container/parameter, or a def path"),depth:s.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:s.boolean().optional().describe("include the param-def summary for the element"),project_dir:s.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 a=await y(l(o.directory,e.project_dir),i,o.abort);if(!a.ok)return g(a)+w(a);let{ok:r,engine:d,ms:u,warnings:c,...m}=a;return g(a)+JSON.stringify(m,null,1)}}),ecuc_edit:p({description:"Edit ECUC ARXML in place \u2014 the ONLY way to change configuration (never write ARXML yourself). 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."+b,args:{ops:s.array(s.object({op:s.enum(["set","add","remove"]),path:s.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:s.string().optional().describe("parameter/reference def short-name"),value:s.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:s.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:s.record(s.string(),s.any()).optional().describe("for add: ECUC JSON of the new container")})).min(1),dry_run:s.boolean().optional().describe("compute and show the diff without writing"),force:s.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:s.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 a=await y(l(o.directory,e.project_dir),i,o.abort);if(!a.ok){let c=a.changes??[];return g(a)+w(a)+(c.length?`
8
+ `:""}function K(q,J){if(!J)return q;return H_(J)?J:J_(q,J)}async function V_(q){let J=Bun.file(w(q,".hydron","autosar.json"));if(!await J.exists())return{};return J.json().catch((_)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(_)}`)})}async function Y_(q,J){let _=(await V_(q))[J];if(typeof _==="string")return{command:_};if(_&&typeof _==="object"&&typeof _.command==="string")return _;return}function m(q,J=150){let _=q.split(`
9
+ `);return _.length>J?[`\u2026 (${_.length-J} earlier lines omitted)`,..._.slice(-J)].join(`
10
+ `):q}async function Z_(q,J,_,H){let Y=process.platform==="win32"?["cmd","/d","/s","/c",q]:["sh","-c",q],Q=Date.now(),Z=Bun.spawn(Y,{cwd:J,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([H,AbortSignal.timeout(_*1000)])}),[V,D]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{code:await Z.exited,out:V,err:D,secs:Math.round((Date.now()-Q)/1000)}}async function u(q,J,_){let H=J.filter((V)=>V?.path&&/\/Com(Group)?Signal$/.test(String(V.definition_ref??""))&&V.ipdu===void 0&&V.direction===void 0);if(!H.length)return[];let Y=await G(q,["signal-owners",...new Set(H.map((V)=>V.path))],_);if(!Y.ok)return[`NOTE: owning I-PDU not computed locally (${Y.error})`];let Q=Y.owners,Z=[];for(let V of H){let D=Q[V.path];if(D===null||D===void 0){Z.push(`NOTE: ${V.path} is not in the local checkout (${q}); owning I-PDU/direction unknown`);continue}V.ipdu_local=D,Z.push(D.length?`${V.path}: owning I-PDU ${D.map((B)=>`${B.ipdu} (ComIPduDirection=${B.direction??"?"})`).join(", ")} [local ECUC]`:`${V.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return Z}var h=(q)=>{let J=q.notes??[],_=q.errors??[];return[...J.map((H)=>`NOTE: ${typeof H==="string"?H:JSON.stringify(H)}`),..._.map((H)=>`BACKEND ERROR: ${typeof H==="string"?H:JSON.stringify(H)}`)]};async function $_(q,J){try{let _=await J(),H=typeof _==="string"?_:_.output;if(H&&H.trim())return _;return`${q}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(_){return`ERROR (${q}): ${_ instanceof Error?_.message:String(_)}`}}function B_(q){for(let[J,_]of Object.entries(q)){let H=_.execute;_.execute=(Y,Q)=>$_(J,()=>H(Y,Q))}return q}var D_=async(q)=>{let J=(_)=>P({description:_==="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:$.string().optional().describe("module name substituted for {module} in the command, if used"),args:$.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(H,Y){let Q=K(Y.directory,H.project_dir),Z=await Y_(Q,_);if(!Z)return`No \`${_}\` command configured. Add it to ${w(Q,".hydron","autosar.json")}, e.g.
11
+ {"${_}": {"command": "${_==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let V=H.args??"",D=Z.command.replaceAll("{module}",H.module??""),B=D.includes("{args}")?D.replaceAll("{args}",V):`${D}${V?` ${V}`:""}`,F=K(Q,Z.cwd);await Y.ask({permission:`autosar_${_}`,patterns:[B],always:[Z.command],metadata:{command:B,cwd:F}}),Y.metadata({title:`${_}: ${B}`});let W=await Z_(B,F,Z.timeoutSec??3600,Y.abort),j=W.code===0?"OK":`FAILED (exit ${W.code})`;return{title:`autosar_${_} ${j}`,output:[`$ ${B} (cwd ${F}, ${W.secs}s) -> ${j}`,W.out.trim()?`--- stdout (tail) ---
12
+ ${m(W.out)}`:"",W.err.trim()?`--- stderr (tail) ---
13
+ ${m(W.err,80)}`:""].filter(Boolean).join(`
14
+ `),metadata:{exit:W.code}}}});return{"tool.execute.before":async(_,H)=>{let Y=y(_.tool,H.args);if(Y)throw Error(Y)},"experimental.chat.system.transform":async(_,H)=>{H.system.push(Q_)},tool:B_({ecuc_read:P({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, and @def = its DEFINITION-REF). 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."+I,args:{path:$.string().optional().describe("AUTOSAR path, SHORT-NAME or partial path of a module/container/parameter, or a def path"),depth:$.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:$.boolean().optional().describe("include the param-def summary for the element"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,H){let Y=["read"];if(_.path)Y.push(_.path);if(Y.push("--depth",String(_.depth??2)),_.schema)Y.push("--schema");let Q=await G(K(H.directory,_.project_dir),Y,H.abort);if(!Q.ok)return X(Q)+M(Q);let{ok:Z,engine:V,ms:D,warnings:B,...F}=Q;return X(Q)+JSON.stringify(F,null,1)}}),ecuc_edit:P({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."+I,args:{ops:U($.array(U($.object({op:$.enum(["set","add","remove"]),path:$.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:$.string().optional().describe("parameter/reference def short-name"),value:$.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:$.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:U($.record($.string(),$.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:$.boolean().optional().describe("compute and show the diff without writing"),force:$.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,H){let Y=["edit","--ops",JSON.stringify(_.ops)];if(_.dry_run)Y.push("--dry-run");if(_.force)Y.push("--force");let Q=await G(K(H.directory,_.project_dir),Y,H.abort);if(!Q.ok){let B=Q.changes??[];return X(Q)+M(Q)+(B.length?`
15
15
  Rejected diff:
16
- ${c.map((m)=>m.diff).join(`
17
- `)}`:"")}let r=a.changes??[],d=a.validation,u=[`${a.written?"Written":"Dry run (nothing written)"}: ${a.applied} op(s), ${r.length} file(s) changed.`,...(a.notes??[]).map((c)=>`NOTE: ${c}`),...r.map((c)=>c.diff)];if(d)u.push(d.validated?`Validation of touched files: ${JSON.stringify(d.summary)}`:"Validation skipped: no param defs loaded.",...C(d.diagnostics,50));return{title:`ecuc_edit ${r.map((c)=>c.file).join(", ")}`,output:g(a)+u.join(`
18
- `)}}}),ecuc_validate:p({description:"Validate 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. Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit and before "+"autosar_generate. Without param defs it only warns."+b,args:{files:s.array(s.string()).optional().describe("only report diagnostics in these files"),module:s.string().optional().describe("only validate this module (e.g. Com)"),max:s.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=l(o.directory,e.project_dir),a=["validate"];for(let c of e.files??[])a.push("--file",l(i,c));if(e.module)a.push("--module",e.module);let r=await y(i,a,o.abort);if(!r.ok)return g(r)+w(r);let d=r.diagnostics,u=r.validated?`Validated ${r.modules.join(", ")||"(no modules)"} against ${r.defsLoaded} module def(s): ${d.length?JSON.stringify(r.summary):"no findings"}`:"NOT validated: no param definitions loaded.";return{title:`ecuc_validate ${JSON.stringify(r.summary)}`,output:g(r)+[u,...C(d,e.max??200)].join(`
19
- `)}}}),arxml_diff:p({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:s.string().describe("old file or directory"),b:s.string().describe("new file or directory"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=l(o.directory,e.project_dir),a=await y(i,["diff",l(i,e.a),l(i,e.b)],o.abort);if(!a.ok)return w(a);let{ok:r,engine:d,ms:u,...c}=a;return JSON.stringify(c,null,1)}}),autosar_trace:p({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. 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."+b,args:{query:s.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:s.number().int().optional().describe("restrict to one code data source"),limit:s.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:s.string().optional().describe("H2Loop project id (default: the selected project)")},async execute(e,o){let i=await A(e.workspace_id),a={query:e.query};if(e.data_source_id!==void 0)a.data_source_id=e.data_source_id;if(e.limit!==void 0)a.limit=e.limit;let r=await $("/api/v1/mcp/autosar/trace",i,a,o.abort),d=r.matches??[],u=[`${d.length} match(es) for "${e.query}" in workspace ${i}`+(r.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(r.data_sources_queried)})`:""),...U(r),JSON.stringify(d,null,1)];if(!d.length)u.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:u.join(`
20
- `)}}}),autosar_config_lookup:p({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. 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."+b,args:{path:s.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:s.number().int().optional().describe("restrict to one code data source"),workspace_id:s.string().optional().describe("H2Loop project id (default: the selected project)")},async execute(e,o){let i=await A(e.workspace_id),a={path:e.path};if(e.data_source_id!==void 0)a.data_source_id=e.data_source_id;let r=await $("/api/v1/mcp/autosar/config-lookup",i,a,o.abort),d=r.matches??[];return{title:`autosar_config_lookup ${e.path}`,output:[`${d.length} match(es) for ${e.path} in workspace ${i}`,...U(r),JSON.stringify(d,null,1)].join(`
21
- `)}}}),autosar_generate:n("generate"),autosar_build:n("build")}}},te=ee;export{te as Autosar};
16
+ ${B.map((F)=>F.diff).join(`
17
+ `)}`:"")}let Z=Q.changes??[],V=Q.validation,D=[`${Q.written?"Written":"Dry run (nothing written)"}: ${Q.applied} op(s), ${Z.length} file(s) changed.`,...(Q.notes??[]).map((B)=>`NOTE: ${B}`),...Z.map((B)=>B.diff)];if(V)D.push(V.validated?`Validation of touched files: ${JSON.stringify(V.summary)}`:"Validation skipped: no param defs loaded.",...p(V.diagnostics,50));return{title:`ecuc_edit ${Z.map((B)=>B.file).join(", ")}`,output:X(Q)+D.join(`
18
+ `)}}}),ecuc_validate:P({description:"Validate 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. Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit and before "+"autosar_generate. Without param defs it only warns."+I,args:{files:U($.array($.string()).optional()).describe("only report diagnostics in these files"),module:$.string().optional().describe("only validate this module (e.g. Com)"),max:$.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,H){let Y=K(H.directory,_.project_dir),Q=["validate"];for(let B of _.files??[])Q.push("--file",K(Y,B));if(_.module)Q.push("--module",_.module);let Z=await G(Y,Q,H.abort);if(!Z.ok)return X(Z)+M(Z);let V=Z.diagnostics,D=Z.validated?`Validated ${Z.modules.join(", ")||"(no modules)"} against ${Z.defsLoaded} module def(s): ${V.length?JSON.stringify(Z.summary):"no findings"}`:"NOT validated: no param definitions loaded.";return{title:`ecuc_validate ${JSON.stringify(Z.summary)}`,output:X(Z)+[D,...p(V,_.max??200)].join(`
19
+ `)}}}),arxml_diff:P({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:$.string().describe("old file or directory"),b:$.string().describe("new file or directory"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,H){let Y=K(H.directory,_.project_dir),Q=await G(Y,["diff",K(Y,_.a),K(Y,_.b)],H.abort);if(!Q.ok)return M(Q);let{ok:Z,engine:V,ms:D,...B}=Q;return JSON.stringify(B,null,1)}}),autosar_trace:P({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). 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."+I,args:{query:$.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:$.number().int().optional().describe("restrict to one code data source"),limit:$.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:$.union([$.string(),$.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:$.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(_,H){let Y=await S(_.workspace_id,H.abort),Q={query:_.query};if(_.data_source_id!==void 0)Q.data_source_id=_.data_source_id;if(_.limit!==void 0)Q.limit=_.limit;let Z=await T("/api/v1/mcp/autosar/trace",Y,Q,H.abort),V=Z.matches??[],D=await u(K(H.directory,_.project_dir),V.map((F)=>F.arxml).filter((F)=>!!F),H.abort),B=[`${V.length} match(es) for "${_.query}" in workspace ${Y}`+(Z.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(Z.data_sources_queried)})`:""),...h(Z),...D,JSON.stringify(V,null,1)];if(!V.length)B.push("No match: try a SHORT-NAME, a full AUTOSAR path from ecuc_read, or the C symbol.");return{title:`autosar_trace ${_.query}`,output:B.join(`
20
+ `)}}}),autosar_config_lookup:P({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. 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."+I,args:{path:$.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:$.number().int().optional().describe("restrict to one code data source"),workspace_id:$.union([$.string(),$.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:$.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(_,H){let Y=await S(_.workspace_id,H.abort),Q={path:_.path};if(_.data_source_id!==void 0)Q.data_source_id=_.data_source_id;let Z=await T("/api/v1/mcp/autosar/config-lookup",Y,Q,H.abort),V=Z.matches??[],D=await u(K(H.directory,_.project_dir),V.map((B)=>B.element).filter((B)=>!!B),H.abort);return{title:`autosar_config_lookup ${_.path}`,output:[`${V.length} match(es) for ${_.path} in workspace ${Y}`,...h(Z),...D,JSON.stringify(V,null,1)].join(`
21
+ `)}}}),autosar_audit:P({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 Source/) 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:U($.array($.string()).optional()).describe("C files/dirs to scan (default: audit paths or Source/)"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,H){let Y=K(H.directory,_.project_dir),Q=await G(Y,["audit",...(_.paths??[]).map((F)=>K(Y,F))],H.abort);if(!Q.ok)return X(Q)+M(Q);let{findings:Z,unchecked:V,scanned:D}=Q,B=[`Scanned ${D.sources.length} C file(s), ${D.calls} BSW call(s): ${Z.length?JSON.stringify(Q.summary):"no findings"}`,...Z.map((F)=>`${F.file}:${F.line} ${F.severity.toUpperCase()} ${F.rule} ${F.call}
22
+ ${F.message}
23
+ evidence: ${JSON.stringify(F.evidence)}
24
+ spec: ${F.cite}${F.fix?`
25
+ fix: ${F.fix}`:""}`)];if(V.length)B.push(`Unchecked (${V.length}):`,...V.slice(0,50).map((F)=>` ${F.file}:${F.line} ${F.call} \u2014 ${F.reason}`));return{title:`autosar_audit ${JSON.stringify(Q.summary)}`,output:X(Q)+B.join(`
26
+ `)}}}),autosar_generate:J("generate"),autosar_build:J("build")})}},F_=D_;export{F_ as Autosar};
@@ -1,2 +1,2 @@
1
1
  """ECUC engine: load, read, edit, validate and diff AUTOSAR ECUC ARXML without regenerating files."""
2
- ENGINE_VERSION = "0.1.0"
2
+ ENGINE_VERSION = "0.1.2"
@@ -0,0 +1,452 @@
1
+ """Deterministic audit of BSW API calls in integration C code against the ECUC configuration.
2
+
3
+ Finds calls that take a configuration handle (Com signals/groups, NvM blocks, Dem events, PduR
4
+ source PDUs; Rte_Write_/Rte_Read_ macros resolved through the generated RTE headers), resolves the
5
+ handle to its ECUC container via the symbolic-name rule (<Mod>Conf_<ContainerDef>_<ShortName>,
6
+ TPS_ECUC_02108) or a raw number via the module's handle-ID parameter, and checks:
7
+
8
+ H2L-API-001 raw numeric handle (use the symbolic name)
9
+ H2L-API-002 unknown handle (symbol or number matches no configured container)
10
+ H2L-API-003 direction mismatch (send on a RECEIVE I-PDU signal, receive on a SEND one)
11
+ H2L-API-004 C object width differs from the signal's ComSignalType / ComBitSize
12
+ H2L-API-005 NvM NULL_PTR without a permanent RAM block or explicit synchronization
13
+
14
+ Width is checked only when the C type is known (compound literal, or a declaration in the same
15
+ translation unit); anything else is listed under "unchecked", never guessed.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import re
21
+ from dataclasses import dataclass
22
+ from typing import Optional
23
+
24
+ from .model import Elem, Project
25
+ from .values import parse_int
26
+
27
+ C_EXT = (".c", ".h")
28
+ SKIP_DIRS = {".git", "node_modules", ".hydron", "Output", "build", "Build"}
29
+
30
+
31
+ @dataclass
32
+ class Api:
33
+ module: str
34
+ defs: tuple # container def names the handle may refer to
35
+ handle_param: str
36
+ kind: str # send | receive | nvm | dem | pdur
37
+ data: Optional[int] # index of the data pointer argument
38
+ cite: str
39
+
40
+
41
+ APIS = {
42
+ "Com_SendSignal": Api("Com", ("ComSignal", "ComGroupSignal"), "ComHandleId", "send", 1, "SWS_Com_00197"),
43
+ "Com_ReceiveSignal": Api("Com", ("ComSignal", "ComGroupSignal"), "ComHandleId", "receive", 1, "SWS_Com_00198"),
44
+ "Com_SendSignalGroup": Api("Com", ("ComSignalGroup",), "ComHandleId", "send", None, "SWS_Com_00200"),
45
+ "Com_ReceiveSignalGroup": Api("Com", ("ComSignalGroup",), "ComHandleId", "receive", None, "SWS_Com_00201"),
46
+ "NvM_ReadBlock": Api("NvM", ("NvMBlockDescriptor",), "NvMNvramBlockIdentifier", "nvm", 1, "SWS_NvM_00454"),
47
+ "NvM_WriteBlock": Api("NvM", ("NvMBlockDescriptor",), "NvMNvramBlockIdentifier", "nvm", 1, "SWS_NvM_00455"),
48
+ "NvM_RestoreBlockDefaults": Api("NvM", ("NvMBlockDescriptor",), "NvMNvramBlockIdentifier", "nvm", 1, "SWS_NvM_00456"),
49
+ "Dem_SetEventStatus": Api("Dem", ("DemEventParameter",), "DemEventId", "dem", None, "SWS_Dem_00183"),
50
+ "Dem_ReportErrorStatus": Api("Dem", ("DemEventParameter",), "DemEventId", "dem", None, "SWS_Dem (Dem_ReportErrorStatus, pre-R4.2 releases)"),
51
+ }
52
+ PDUR = Api("PduR", ("PduRSrcPdu",), "PduRSourcePduHandleId", "pdur", None, "SWS_PduR_00406")
53
+ CALL = re.compile(r"\b(Com_(?:Send|Receive)Signal(?:Group)?|NvM_(?:ReadBlock|WriteBlock|RestoreBlockDefaults)|"
54
+ r"Dem_(?:SetEventStatus|ReportErrorStatus)|PduR_\w*Transmit|Rte_(?:Write|Read)_\w+)\s*\(")
55
+ NUM = re.compile(r"^\(?\s*(?:\(\s*\w+\s*\)\s*)?(0[xX][0-9a-fA-F]+|\d+)[uUlL]*\s*\)?$")
56
+ SYM = re.compile(r"^(\w+?)Conf_(\w+?)_(\w+)$")
57
+ NULLS = {"NULL_PTR", "NULL", "0", "((void*)0)", "(void*)0"}
58
+ TYPE_BITS = {"boolean": 8, "uint8": 8, "sint8": 8, "uint16": 16, "sint16": 16, "uint32": 32, "sint32": 32,
59
+ "uint64": 64, "sint64": 64, "float32": 32, "float64": 64, "char": 8, "int8_t": 8, "uint8_t": 8,
60
+ "int16_t": 16, "uint16_t": 16, "int32_t": 32, "uint32_t": 32, "int64_t": 64, "uint64_t": 64,
61
+ "float": 32, "double": 64, "bool": 8}
62
+ SIG_BITS = {"BOOLEAN": 8, "UINT8": 8, "SINT8": 8, "UINT16": 16, "SINT16": 16, "UINT32": 32, "SINT32": 32,
63
+ "UINT64": 64, "SINT64": 64, "FLOAT32": 32, "FLOAT64": 64}
64
+
65
+
66
+ def strip_comments(src: str) -> str:
67
+ """Blank out comments and string literals, keeping offsets and newlines."""
68
+ out = list(src)
69
+ i, n = 0, len(src)
70
+ while i < n:
71
+ c = src[i]
72
+ if src.startswith("/*", i):
73
+ j = src.find("*/", i + 2)
74
+ j = n if j < 0 else j + 2
75
+ for k in range(i, j):
76
+ if out[k] != "\n":
77
+ out[k] = " "
78
+ i = j
79
+ elif src.startswith("//", i):
80
+ j = src.find("\n", i)
81
+ j = n if j < 0 else j
82
+ for k in range(i, j):
83
+ out[k] = " "
84
+ i = j
85
+ elif c in "\"'":
86
+ j = i + 1
87
+ while j < n and src[j] != c:
88
+ j += 2 if src[j] == "\\" else 1
89
+ for k in range(i + 1, min(j, n)):
90
+ if out[k] != "\n":
91
+ out[k] = " "
92
+ i = j + 1
93
+ else:
94
+ i += 1
95
+ return "".join(out)
96
+
97
+
98
+ def split_args(src: str, open_idx: int):
99
+ """Args of the call whose '(' is at open_idx -> (list of arg strings, index after ')')."""
100
+ depth, args, cur, i = 0, [], [], open_idx
101
+ while i < len(src):
102
+ c = src[i]
103
+ if c in "([{":
104
+ depth += 1
105
+ if depth > 1:
106
+ cur.append(c)
107
+ elif c in ")]}":
108
+ depth -= 1
109
+ if depth == 0:
110
+ args.append("".join(cur).strip())
111
+ return [a for a in args if a != "" or len(args) > 1], i + 1
112
+ cur.append(c)
113
+ elif c == "," and depth == 1:
114
+ args.append("".join(cur).strip())
115
+ cur = []
116
+ else:
117
+ cur.append(c)
118
+ i += 1
119
+ return None, i
120
+
121
+
122
+ def parse_defines(files: list) -> dict:
123
+ """NAME -> (params|None, body, file, line) for every #define in the given headers."""
124
+ out: dict = {}
125
+ rx = re.compile(r"^[ \t]*#[ \t]*define[ \t]+(\w+)(\([^)]*\))?[ \t]*(.*)$")
126
+ for f in files:
127
+ try:
128
+ text = strip_comments(open(f, encoding="utf-8", errors="replace").read())
129
+ except OSError:
130
+ continue
131
+ lines = text.split("\n")
132
+ i = 0
133
+ while i < len(lines):
134
+ line = lines[i]
135
+ start = i
136
+ while line.endswith("\\") and i + 1 < len(lines):
137
+ i += 1
138
+ line = line[:-1] + " " + lines[i]
139
+ m = rx.match(line)
140
+ if m:
141
+ params = [p.strip() for p in m.group(2)[1:-1].split(",")] if m.group(2) else None
142
+ out.setdefault(m.group(1), (params, m.group(3).strip(), f, start + 1))
143
+ i += 1
144
+ return out
145
+
146
+
147
+ def _files(root: str, paths: list, exts=C_EXT, skip=SKIP_DIRS) -> list:
148
+ res = []
149
+ for p in paths:
150
+ full = p if os.path.isabs(p) else os.path.join(root, p)
151
+ if os.path.isfile(full):
152
+ res.append(full)
153
+ continue
154
+ for dp, dns, fns in os.walk(full):
155
+ dns[:] = sorted(d for d in dns if d not in skip and not d.startswith("."))
156
+ res.extend(os.path.join(dp, fn) for fn in sorted(fns) if fn.endswith(exts))
157
+ return res
158
+
159
+
160
+ class Auditor:
161
+ def __init__(self, project: Project, defines: dict):
162
+ self.p = project
163
+ self.defines = defines
164
+ self.findings: list = []
165
+ self.unchecked: list = []
166
+ self.calls = 0
167
+ self._handles: dict = {}
168
+
169
+ # ---------- ECUC lookups ----------
170
+ def module(self, name: str) -> list:
171
+ return [m for m in self.p.modules if (m.def_ref or "").rsplit("/", 1)[-1] == name or m.name == name]
172
+
173
+ def containers(self, module: str, defnames: tuple) -> list:
174
+ out = []
175
+ for m in self.module(module):
176
+ stack = list(m.children)
177
+ while stack:
178
+ e = stack.pop()
179
+ stack.extend(e.children)
180
+ if (e.def_ref or "").rsplit("/", 1)[-1] in defnames:
181
+ out.append(e)
182
+ return out
183
+
184
+ def val(self, e: Elem, name: str) -> Optional[str]:
185
+ for g in self.p.find(e.path):
186
+ for pv in g.params:
187
+ if pv.name == name:
188
+ return pv.value
189
+ return None
190
+
191
+ def by_handle(self, api: Api, num: int) -> list:
192
+ key = (api.module, api.defs)
193
+ if key not in self._handles:
194
+ idx: dict = {}
195
+ for e in self.containers(api.module, api.defs):
196
+ v = parse_int(self.val(e, api.handle_param) or "")
197
+ if v is not None:
198
+ idx.setdefault(v, []).append(e)
199
+ self._handles[key] = idx
200
+ return self._handles[key].get(num, [])
201
+
202
+ def by_symbol(self, api: Api, sym: str) -> Optional[Elem]:
203
+ m = SYM.match(sym)
204
+ if not m:
205
+ return None
206
+ mod, dname, short = m.groups()
207
+ if mod != api.module:
208
+ return None
209
+ for e in self.containers(api.module, (dname,)):
210
+ if e.name == short:
211
+ return e
212
+ return None
213
+
214
+ def symbol_of(self, e: Elem, api: Api) -> str:
215
+ return f"{api.module}Conf_{(e.def_ref or '').rsplit('/', 1)[-1]}_{e.name}"
216
+
217
+ def ipdus_of(self, sig: Elem) -> list:
218
+ """I-PDUs that reference this signal (or, for a group signal, its signal group)."""
219
+ targets = {sig.path}
220
+ if (sig.def_ref or "").endswith("/ComGroupSignal") and sig.parent is not None:
221
+ targets = {sig.parent.path}
222
+ out = []
223
+ for ip in self.containers("Com", ("ComIPdu",)):
224
+ for g in self.p.find(ip.path):
225
+ if any(pv.is_ref and pv.name in ("ComIPduSignalRef", "ComIPduSignalGroupRef") and (pv.value or "").strip() in targets
226
+ for pv in g.params):
227
+ out.append(ip)
228
+ break
229
+ return out
230
+
231
+ # ---------- findings ----------
232
+ def add(self, rule, sev, f, line, call, msg, cite, evidence, fix=None):
233
+ d = {"rule": rule, "severity": sev, "file": self.p.rel(f), "line": line, "call": call,
234
+ "message": msg, "cite": cite, "evidence": evidence}
235
+ if fix:
236
+ d["fix"] = fix
237
+ self.findings.append(d)
238
+
239
+ # ---------- per call ----------
240
+ def handle_value(self, expr: str):
241
+ """-> ("num", int) | ("sym", name, resolved_int|None) | ("expr", text)."""
242
+ e = expr.strip()
243
+ m = NUM.match(e)
244
+ if m:
245
+ return ("num", int(m.group(1), 0))
246
+ while e.startswith("(") and e.endswith(")") and split_args("x" + e, 1)[1] == len(e) + 1:
247
+ e = e[1:-1].strip()
248
+ if re.fullmatch(r"\w+", e):
249
+ d = self.defines.get(e)
250
+ num = None
251
+ if d and d[0] is None:
252
+ mm = NUM.match(d[1])
253
+ num = int(mm.group(1), 0) if mm else None
254
+ return ("sym", e, num)
255
+ return ("expr", e)
256
+
257
+ def audit_call(self, f: str, line: int, name: str, args: list, unit: str, via: Optional[str] = None):
258
+ if name.startswith("Rte_"):
259
+ self.audit_rte(f, line, name, args, unit)
260
+ return
261
+ api = APIS.get(name) or (PDUR if name.startswith("PduR_") else None)
262
+ if api is None or not args:
263
+ return
264
+ self.calls += 1
265
+ call = f"{name}({', '.join(args)})" + (f" via {via}" if via else "")
266
+ h = self.handle_value(args[0])
267
+ target: Optional[Elem] = None
268
+ cite_sym = "TPS_ECUC_02108 symbolic name values"
269
+ if h[0] == "num":
270
+ hits = self.by_handle(api, h[1])
271
+ if not hits:
272
+ self.add("H2L-API-002", "error", f, line, call,
273
+ f"handle {args[0]} matches no {'/'.join(api.defs)} with {api.handle_param}={h[1]}",
274
+ f"{api.cite}; {cite_sym}", {"handleParam": api.handle_param, "value": h[1]})
275
+ return
276
+ target = hits[0]
277
+ sym = self.symbol_of(target, api)
278
+ self.add("H2L-API-001", "warning", f, line, call,
279
+ f"raw numeric handle {args[0]} = {target.path} ({api.handle_param}={h[1]}); use {sym} so the call "
280
+ "survives handle re-assignment", f"{cite_sym}; TPS_ECUConfiguration 3.4.1.1",
281
+ {"path": target.path, api.handle_param: h[1]}, fix=f"replace {args[0]} with {sym}")
282
+ elif h[0] == "sym":
283
+ target = self.by_symbol(api, h[1])
284
+ if target is None and h[2] is not None:
285
+ hits = self.by_handle(api, h[2])
286
+ target = hits[0] if hits else None
287
+ if target is None:
288
+ if SYM.match(h[1]) or h[2] is not None:
289
+ self.add("H2L-API-002", "error", f, line, call,
290
+ f"handle {h[1]} resolves to no configured {'/'.join(api.defs)} in {api.module}",
291
+ f"{api.cite}; {cite_sym}", {"symbol": h[1], "define": h[2]})
292
+ else:
293
+ self.unchecked.append({"file": self.p.rel(f), "line": line, "call": call,
294
+ "reason": f"handle {h[1]} is not a configured symbol or constant"})
295
+ return
296
+ else:
297
+ self.unchecked.append({"file": self.p.rel(f), "line": line, "call": call, "reason": "handle is an expression"})
298
+ return
299
+ if api.kind in ("send", "receive"):
300
+ self.check_direction(f, line, call, api, target)
301
+ if api.data is not None and len(args) > api.data:
302
+ self.check_width(f, line, call, target, args[api.data], unit)
303
+ if api.kind == "nvm" and api.data is not None and len(args) > api.data:
304
+ self.check_nvm_null(f, line, call, name, target, args[api.data])
305
+
306
+ def audit_rte(self, f, line, name, args, unit):
307
+ d = self.defines.get(name)
308
+ if d is None or d[0] is None:
309
+ self.unchecked.append({"file": self.p.rel(f), "line": line, "call": f"{name}(...)",
310
+ "reason": "RTE API not a macro in the generated headers (function-mapped)"})
311
+ return
312
+ params, body = d[0], d[1]
313
+ subst = body
314
+ for prm, arg in zip(params, args):
315
+ subst = re.sub(rf"\b{re.escape(prm)}\b", lambda _m, a=arg: f"({a})", subst)
316
+ clean = strip_comments(subst)
317
+ for m in CALL.finditer(clean):
318
+ inner, _ = split_args(clean, m.end() - 1)
319
+ if inner is not None and not m.group(1).startswith("Rte_"):
320
+ self.audit_call(f, line, m.group(1), inner, unit, via=f"{name} ({self.p.rel(d[2])}:{d[3]})")
321
+
322
+ def check_direction(self, f, line, call, api, sig):
323
+ ipdus = self.ipdus_of(sig)
324
+ dirs = [(ip, (self.val(ip, "ComIPduDirection") or "").strip()) for ip in ipdus]
325
+ want = "SEND" if api.kind == "send" else "RECEIVE"
326
+ bad = [(ip, d) for ip, d in dirs if d and d != want]
327
+ if bad and not any(d == want for _, d in dirs):
328
+ ip, d = bad[0]
329
+ self.add("H2L-API-003", "error", f, line, call,
330
+ f"{sig.name} belongs to I-PDU {ip.name} with ComIPduDirection={d}; {call.split('(')[0]} needs a "
331
+ f"{want} signal (Com returns COM_SERVICE_NOT_AVAILABLE / E_NOT_OK)",
332
+ f"ECUC_Com_00493 ComIPduDirection; {api.cite}",
333
+ {"signal": sig.path, "ipdu": ip.path, "ComIPduDirection": d})
334
+
335
+ def c_type(self, expr: str, unit: str):
336
+ """Type of the object a data-pointer argument points to -> (type, array_len|None), or None if unknown."""
337
+ e = expr.strip()
338
+ while e.startswith("(") and e.endswith(")") and split_args("x" + e, 1)[1] == len(e) + 1:
339
+ e = e[1:-1].strip()
340
+ lit = re.fullmatch(r"&\s*\(\s*(\w+)\s*\)\s*\{.*\}", e, re.S) # &(uint8){ x }
341
+ if lit:
342
+ return lit.group(1), None
343
+ ref = re.fullmatch(r"&\s*(\w+)", e) # &var
344
+ elem = re.fullmatch(r"&\s*(\w+)\s*\[[^\]]*\]", e) # &buf[i]
345
+ bare = re.fullmatch(r"(\w+)", e) # buf (array decays) or a pointer variable
346
+ var = (ref or elem or bare).group(1) if (ref or elem or bare) else None
347
+ if var is None:
348
+ return None
349
+ decl = re.search(rf"\b(?:(?:static|volatile|const|extern)\s+)*(\w+)\s+(?:const\s+)?{re.escape(var)}"
350
+ rf"\s*(\[\s*(\w*)\s*\])?\s*[;=,)]", unit)
351
+ if not decl or decl.group(1) in ("return", "else", "case", "goto", "sizeof", "struct", "union", "enum"):
352
+ return None
353
+ is_array = bool(decl.group(2))
354
+ if ref:
355
+ return decl.group(1), (decl.group(3) if is_array else None)
356
+ if elem or (bare and is_array):
357
+ return decl.group(1), None
358
+ return None # bare non-array variable: a pointer whose pointee is not visible here
359
+
360
+ def check_width(self, f, line, call, sig, arg, unit):
361
+ typ = (self.val(sig, "ComSignalType") or "").strip()
362
+ if typ in ("UINT8_N", "UINT8_DYN"):
363
+ self.unchecked.append({"file": self.p.rel(f), "line": line, "call": call, "reason": f"array signal type {typ}"})
364
+ return
365
+ expect = SIG_BITS.get(typ)
366
+ ct = self.c_type(arg, unit)
367
+ if expect is None or ct is None or ct[0] not in TYPE_BITS:
368
+ self.unchecked.append({"file": self.p.rel(f), "line": line, "call": call,
369
+ "reason": f"width unknown (C type {ct[0] if ct else '?'}, ComSignalType {typ or '?'})"})
370
+ return
371
+ cbits = TYPE_BITS[ct[0]]
372
+ if ct[1]:
373
+ n = parse_int(ct[1])
374
+ cbits = cbits * n if n is not None else cbits
375
+ if cbits != expect:
376
+ bs = self.val(sig, "ComBitSize")
377
+ self.add("H2L-API-004", "error", f, line, call,
378
+ f"{arg} is a {ct[0]}{'[' + ct[1] + ']' if ct[1] else ''} ({cbits} bits) but {sig.name} is "
379
+ f"ComSignalType={typ} ({expect // 8}-byte object, ComBitSize={bs}); Com accesses {expect // 8} "
380
+ f"byte(s) at that address — wrong signal or wrong variable",
381
+ "SWS_Com_00197/00198 SignalDataPtr points to an object of the ComSignalType; ECUC_Com_00127 ComSignalType",
382
+ {"signal": sig.path, "ComSignalType": typ, "ComBitSize": bs, "cType": ct[0]})
383
+
384
+ def check_nvm_null(self, f, line, call, name, blk, arg):
385
+ if arg.replace(" ", "") not in NULLS:
386
+ return
387
+ ram = (self.val(blk, "NvMRamBlockDataAddress") or "").strip()
388
+ sync = (self.val(blk, "NvMBlockUseSyncMechanism") or "").strip().lower() in ("true", "1")
389
+ if ram or sync:
390
+ return # valid: SWS_NvM_00898/00900 (permanent RAM) or 00899/00901 (explicit sync)
391
+ self.add("H2L-API-005", "error", f, line, call,
392
+ f"{name} with NULL_PTR on {blk.name}, which has no permanent RAM block (NvMRamBlockDataAddress unset) and "
393
+ "no explicit synchronization; NvM rejects the request (DET parameter error)",
394
+ "SWS_NvM_00898/00899 (ReadBlock), SWS_NvM_00900/00901 (WriteBlock), SWS_NvM_00278/00280",
395
+ {"block": blk.path, "NvMRamBlockDataAddress": None, "NvMBlockUseSyncMechanism": sync})
396
+
397
+
398
+ def audit(project: Project, paths: Optional[list] = None, headers: Optional[list] = None) -> dict:
399
+ root = project.root
400
+ cfg = {}
401
+ try:
402
+ import json
403
+ with open(os.path.join(root, ".hydron", "autosar.json")) as fh:
404
+ raw = json.load(fh).get("audit")
405
+ cfg = raw if isinstance(raw, dict) else ({"paths": raw} if isinstance(raw, list) else {})
406
+ except (OSError, ValueError):
407
+ pass
408
+ paths = paths or cfg.get("paths") or (["Source"] if os.path.isdir(os.path.join(root, "Source")) else ["."])
409
+ headers = headers or cfg.get("headers") or [d for d in ("Output",) if os.path.isdir(os.path.join(root, d))]
410
+ sources = [f for f in _files(root, paths) if f.endswith(".c")]
411
+ hdrs = _files(root, headers, exts=(".h",), skip={".git", "node_modules"}) + [f for f in _files(root, paths) if f.endswith(".h")]
412
+ a = Auditor(project, parse_defines(hdrs))
413
+ for f in sources:
414
+ try:
415
+ unit = strip_comments(open(f, encoding="utf-8", errors="replace").read())
416
+ except OSError:
417
+ continue
418
+ for m in CALL.finditer(unit):
419
+ ls = unit.rfind("\n", 0, m.start()) + 1
420
+ if unit[ls:m.start()].lstrip().startswith("#"):
421
+ continue # macro definition, not a call
422
+ before = unit[ls:m.start()].rstrip()
423
+ prev = re.search(r"(\w+)\s*$", before)
424
+ if prev and prev.group(1) not in ("return", "void") and not before.endswith(")"):
425
+ continue # a declaration/prototype ("Std_ReturnType Com_SendSignal(")
426
+ args, _ = split_args(unit, m.end() - 1)
427
+ if args is None:
428
+ continue
429
+ a.audit_call(f, unit.count("\n", 0, m.start()) + 1, m.group(1), args, unit)
430
+ a.findings.sort(key=lambda d: (d["file"], d["line"], d["rule"]))
431
+ summary: dict = {}
432
+ for d in a.findings:
433
+ summary[d["severity"]] = summary.get(d["severity"], 0) + 1
434
+ return {"scanned": {"sources": [project.rel(f) for f in sources], "headers": len(hdrs), "calls": a.calls},
435
+ "summary": summary, "findings": a.findings, "unchecked": a.unchecked}
436
+
437
+
438
+ def signal_owners(project: Project, paths: list) -> dict:
439
+ """AUTOSAR path of a ComSignal / ComGroupSignal -> [{ipdu, direction, pdu}] from the local ECUC."""
440
+ a = Auditor(project, {})
441
+ out: dict = {}
442
+ for p in paths:
443
+ g = project.find(p)
444
+ if not g:
445
+ out[p] = None # not in the local checkout
446
+ continue
447
+ sig = g[0]
448
+ if not (sig.def_ref or "").endswith(("/ComSignal", "/ComGroupSignal", "/ComSignalGroup")):
449
+ continue
450
+ out[p] = [{"ipdu": ip.path, "direction": (a.val(ip, "ComIPduDirection") or "").strip() or None,
451
+ "pdu": (a.val(ip, "ComPduIdRef") or "").strip() or None} for ip in a.ipdus_of(sig)]
452
+ return out
@@ -21,6 +21,11 @@ def _ops(arg: str):
21
21
  if arg == "-":
22
22
  arg = sys.stdin.read()
23
23
  ops = json.loads(arg)
24
+ for _ in range(3): # tolerate JSON that was encoded more than once ("[{...}]" as a string)
25
+ if isinstance(ops, str):
26
+ ops = json.loads(ops)
27
+ if isinstance(ops, dict) and isinstance(ops.get("ops"), (list, str)):
28
+ return _ops(json.dumps(ops["ops"]))
24
29
  return ops if isinstance(ops, list) else [ops]
25
30
 
26
31
 
@@ -45,10 +50,15 @@ def main(argv=None) -> int:
45
50
  v.add_argument("--file", action="append")
46
51
  v.add_argument("--module")
47
52
  v.add_argument("--max", type=int, default=0, help="cap the number of diagnostics returned (0 = all)")
53
+ au = sub.add_parser("audit")
54
+ au.add_argument("paths", nargs="*", help="C files/dirs to scan (default: audit.paths in .hydron/autosar.json, else Source/)")
55
+ au.add_argument("--headers", action="append", help="generated header dirs for symbols and RTE macros (default Output/)")
56
+ so = sub.add_parser("signal-owners")
57
+ so.add_argument("paths", nargs="+")
48
58
  d = sub.add_parser("diff")
49
59
  d.add_argument("a")
50
60
  d.add_argument("b")
51
- for p in (r, e, v, d): # allow --json after the subcommand too
61
+ for p in (r, e, v, d, au, so): # allow --json after the subcommand too
52
62
  p.add_argument("--json", action="store_true", help=argparse.SUPPRESS)
53
63
  a = ap.parse_args(argv)
54
64
  t0 = time.time()
@@ -64,6 +74,11 @@ def main(argv=None) -> int:
64
74
 
65
75
 
66
76
  def run(a) -> dict:
77
+ if a.cmd == "edit":
78
+ try:
79
+ a.ops = _ops(a.ops)
80
+ except (ValueError, OSError) as ex:
81
+ return {"error": f"ops is not valid JSON: {ex}"}
67
82
  if a.cmd == "diff":
68
83
  from .diff import diff
69
84
  for x in (a.a, a.b):
@@ -74,6 +89,15 @@ def run(a) -> dict:
74
89
  return diff(a.a, a.b, rel)
75
90
  from .model import Project
76
91
  project = Project(a.root, config_files=a.config, def_files=a.defs, load_input=a.cmd in ("validate", "edit"))
92
+ if a.cmd == "signal-owners":
93
+ from .audit import signal_owners
94
+ return {"owners": signal_owners(project, a.paths)}
95
+ if a.cmd == "audit":
96
+ from .audit import audit
97
+ res = audit(project, paths=a.paths or None, headers=a.headers)
98
+ if project.warnings:
99
+ res["warnings"] = project.warnings
100
+ return res
77
101
  if a.cmd == "info":
78
102
  s = project.sources
79
103
  return {"root": s.root, "origin": s.origin, "config": [project.rel(f) for f in s.config],
@@ -85,7 +109,7 @@ def run(a) -> dict:
85
109
  return read(project, a.path, depth=a.depth, schema=a.schema)
86
110
  if a.cmd == "edit":
87
111
  from .edit import edit
88
- res = edit(project, _ops(a.ops), dry_run=a.dry_run, force=a.force, run_validate=not a.no_validate)
112
+ res = edit(project, a.ops, dry_run=a.dry_run, force=a.force, run_validate=not a.no_validate)
89
113
  if project.warnings:
90
114
  res["warnings"] = project.warnings
91
115
  return res
@@ -78,6 +78,13 @@ def read(project: Project, path: Optional[str], depth: int = 2, schema: bool = F
78
78
  res["hint"] = "read a module or container by its AUTOSAR path, e.g. path=" + (
79
79
  res["modules"][0]["path"] if res["modules"] else "/Pkg/Module")
80
80
  return res
81
+ resolved = resolve(project, path)
82
+ if isinstance(resolved, dict):
83
+ res.update(resolved)
84
+ return res
85
+ if resolved != path:
86
+ res["resolved"] = f"{path} -> {resolved}"
87
+ path = resolved
81
88
  group = project.find(path)
82
89
  if group:
83
90
  res["ecuc"] = {key_of(group[0]): render(project, group, depth)}
@@ -116,3 +123,32 @@ def _walk(e: Elem):
116
123
  x = stack.pop()
117
124
  yield x
118
125
  stack.extend(x.children)
126
+
127
+
128
+ def resolve(project: Project, q: str):
129
+ """Exact path, def path, or param path pass through. Otherwise resolve a SHORT-NAME or partial
130
+ path ("ComConfig/DoorLatch", "DoorLatch", "DoorLatch/ComBitPosition") against value paths.
131
+ Returns the path, or {"error", "candidates"} when ambiguous / not found."""
132
+ q = q.strip()
133
+ if project.find(q) or project.defs.get(q):
134
+ return q
135
+ parent, _, last = q.rstrip("/").rpartition("/")
136
+ if parent.startswith("/") and project.find(parent):
137
+ return q
138
+ tail = q.strip("/")
139
+ paths = list(project.by_path)
140
+ hits = [p for p in paths if p == "/" + tail or p.endswith("/" + tail)]
141
+ param = None
142
+ if not hits and "/" in tail: # last segment may be a parameter
143
+ head, _, param = tail.rpartition("/")
144
+ hits = [p for p in paths if p.endswith("/" + head)]
145
+ hits = [p for p in hits if any(pv.name == param for e in project.find(p) for pv in e.params)]
146
+ if not hits:
147
+ low = tail.lower().rsplit("/", 1)[-1]
148
+ sugg = sorted(p for p in paths if low in p.rsplit("/", 1)[-1].lower())[:15]
149
+ return {"error": f"no ECUC element matches '{q}'", "didYouMean": sugg} if sugg else \
150
+ {"error": f"no ECUC element or definition at {q}; call ecuc_read with no path to list modules"}
151
+ if len(hits) > 1:
152
+ return {"error": f"'{q}' is ambiguous ({len(hits)} matches); pass one of these full paths",
153
+ "didYouMean": sorted(hits)[:25]}
154
+ return hits[0] + (f"/{param}" if param else "")
@@ -206,6 +206,7 @@ class Editor:
206
206
  # ---------- ops ----------
207
207
  def apply(self, ops: list, force: bool = False):
208
208
  self.force = force
209
+ check_ops(ops)
209
210
  for i, op in enumerate(ops):
210
211
  kind = op.get("op")
211
212
  try:
@@ -355,6 +356,35 @@ class Editor:
355
356
  os.replace(tmp, f)
356
357
 
357
358
 
359
+ OP_KEYS = {"op", "path", "param", "value", "container", "values"}
360
+
361
+
362
+ def check_ops(ops) -> None:
363
+ """Shape-check ops before touching anything: clear errors instead of tracebacks."""
364
+ if not isinstance(ops, list) or not ops:
365
+ raise EditError(f"ops must be a non-empty list of op objects, got {type(ops).__name__}")
366
+ for i, op in enumerate(ops):
367
+ if not isinstance(op, dict):
368
+ raise EditError(f"op {i} must be an object like {{\"op\": \"set\", \"path\": ..., \"param\": ..., \"value\": ...}}, "
369
+ f"got {type(op).__name__}: {str(op)[:120]}")
370
+ unknown = set(op) - OP_KEYS
371
+ if unknown:
372
+ raise EditError(f"op {i}: unknown key(s) {sorted(unknown)}; allowed: {sorted(OP_KEYS)}")
373
+ if op.get("op") not in ("set", "add", "remove"):
374
+ raise EditError(f"op {i}: 'op' must be set, add or remove (got {op.get('op')!r})")
375
+ if not isinstance(op.get("path"), str) or not op["path"].startswith("/"):
376
+ raise EditError(f"op {i}: 'path' must be an absolute AUTOSAR path string ('/Pkg/Module/...'), got {op.get('path')!r}")
377
+ for k in ("param", "container"):
378
+ if k in op and op[k] is not None and not isinstance(op[k], str):
379
+ raise EditError(f"op {i}: '{k}' must be a string, got {type(op[k]).__name__}")
380
+ if "values" in op and op["values"] is not None and not isinstance(op["values"], dict):
381
+ raise EditError(f"op {i}: 'values' must be an object of ECUC JSON, got {type(op['values']).__name__}")
382
+ if op["op"] == "set" and "value" not in op:
383
+ raise EditError(f"op {i}: set needs 'value'")
384
+ if op["op"] == "add" and not op.get("container") and not op.get("param"):
385
+ raise EditError(f"op {i}: add needs 'container' (\"DefName:ShortName\") or 'param' + 'value'")
386
+
387
+
358
388
  def schema_check(path: str, data: bytes) -> Optional[str]:
359
389
  """Strict schema load with autosar-data when available. Returns an error string or None."""
360
390
  try:
@@ -0,0 +1,82 @@
1
+ """Hand-written semantic rule packs (the "H" checks the param defs cannot express).
2
+
3
+ A rule is a function registered with @rule(...). It receives a RuleContext and yields
4
+ (elem, line, message, def_ref) tuples; the registry adds the rule id, severity and spec citation.
5
+ Rules are keyed by module-relative DEFINITION-REFs ("Com/ComConfig/ComSignal/ComBitPosition"), so
6
+ they work for /AUTOSAR/EcucDefs/... and vendor-relocated defs alike, and run with or without the
7
+ param defs loaded. To add a pack: create a module here with @rule functions and import it below.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Callable, Iterable, Optional
13
+
14
+ from ..model import Elem, ParamVal, Project
15
+
16
+
17
+ @dataclass
18
+ class Rule:
19
+ id: str
20
+ severity: str
21
+ cite: str
22
+ title: str
23
+ fn: Callable
24
+
25
+
26
+ RULES: list = []
27
+
28
+
29
+ def rule(id: str, severity: str, cite: str, title: str):
30
+ def deco(fn):
31
+ RULES.append(Rule(id, severity, cite, title, fn))
32
+ return fn
33
+ return deco
34
+
35
+
36
+ class RuleContext:
37
+ def __init__(self, project: Project):
38
+ self.p = project
39
+ self.defs = project.defs
40
+ self._by_rel: Optional[dict] = None
41
+
42
+ def rel(self, def_ref: Optional[str]) -> str:
43
+ return self.defs.rel(def_ref) if def_ref else ""
44
+
45
+ def containers(self, rel_def: str) -> list:
46
+ """All container values (first fragment per path) whose def is ``rel_def`` (module-relative)."""
47
+ if self._by_rel is None:
48
+ self._by_rel = {}
49
+ for path, group in self.p.by_path.items():
50
+ self._by_rel.setdefault(self.rel(group[0].def_ref), []).append(group[0])
51
+ return self._by_rel.get(rel_def, [])
52
+
53
+ def values(self, e: Elem, name: str) -> list:
54
+ return [pv for g in self.p.find(e.path) for pv in g.params if pv.name == name]
55
+
56
+ def value(self, e: Elem, name: str) -> Optional[ParamVal]:
57
+ v = self.values(e, name)
58
+ return v[0] if v else None
59
+
60
+ def text(self, e: Elem, name: str) -> Optional[str]:
61
+ v = self.value(e, name)
62
+ return v.value if v is not None else None
63
+
64
+ def target(self, pv: Optional[ParamVal]) -> Optional[Elem]:
65
+ if pv is None or not pv.value:
66
+ return None
67
+ hit = self.p.find(pv.value.strip())
68
+ return hit[0] if hit else None
69
+
70
+ def module_of(self, e: Elem) -> Elem:
71
+ while e.parent is not None:
72
+ e = e.parent
73
+ return e
74
+
75
+
76
+ def run_rules(project: Project) -> Iterable[dict]:
77
+ from . import com, handles # noqa: F401 (registers the packs)
78
+ ctx = RuleContext(project)
79
+ for r in RULES:
80
+ for e, line, msg, def_ref in r.fn(ctx):
81
+ yield {"file": project.rel(e.file), "line": line, "path": e.path, "rule": r.id,
82
+ "severity": r.severity, "message": f"{msg} [{r.cite}]", "defRef": def_ref}
@@ -0,0 +1,107 @@
1
+ """COM I-PDU packing rules: signals inside the I-PDU, no overlapping signals."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional
5
+
6
+ from . import rule
7
+ from ..values import parse_int
8
+
9
+ TYPE_BITS = {"BOOLEAN": 1, "UINT8": 8, "SINT8": 8, "UINT16": 16, "SINT16": 16, "UINT32": 32, "SINT32": 32,
10
+ "UINT64": 64, "SINT64": 64, "FLOAT32": 32, "FLOAT64": 64}
11
+ CITE_BOUNDS = "ECUC_Com_00259 ComBitPosition (position within the I-PDU), ECUC_Com_00158 ComBitSize, ECUC_EcuC_00003 PduLength"
12
+ CITE_OVERLAP = "SWS_Com_CONSTR_00102 Signals Separated in I-PDU"
13
+
14
+
15
+ def _size(ctx, s) -> Optional[int]:
16
+ bs = parse_int(ctx.text(s, "ComBitSize") or "")
17
+ if bs is not None:
18
+ return bs
19
+ typ = (ctx.text(s, "ComSignalType") or "").strip()
20
+ if typ in ("UINT8_N", "UINT8_DYN"):
21
+ n = parse_int(ctx.text(s, "ComSignalLength") or "")
22
+ return n * 8 if n is not None else None
23
+ return TYPE_BITS.get(typ)
24
+
25
+
26
+ def bits(pos: int, size: int, endian: str) -> list:
27
+ """Occupied bit indices (byte*8 + bit). ComBitPosition is the LSB. BIG_ENDIAN (Motorola) walks
28
+ toward the MSB by going up within a byte, then to bit 0 of the previous byte."""
29
+ if endian == "BIG_ENDIAN":
30
+ out, b = [], pos
31
+ for _ in range(size):
32
+ out.append(b)
33
+ b = b + 1 if b % 8 != 7 else b - 15
34
+ return out
35
+ return list(range(pos, pos + size)) # LITTLE_ENDIAN and OPAQUE (bit0 of first byte, little-endian order)
36
+
37
+
38
+ def _ipdus(ctx):
39
+ """(ipdu, length_bytes|None, [(member, kind)]) for every ComIPdu."""
40
+ for ipdu in ctx.containers("Com/ComConfig/ComIPdu"):
41
+ pdu = ctx.target(ctx.value(ipdu, "ComPduIdRef"))
42
+ length = parse_int(ctx.text(pdu, "PduLength") or "") if pdu is not None else None
43
+ members = []
44
+ for ref in ctx.values(ipdu, "ComIPduSignalRef"):
45
+ s = ctx.target(ref)
46
+ if s is not None:
47
+ members.append(s)
48
+ for ref in ctx.values(ipdu, "ComIPduSignalGroupRef"):
49
+ grp = ctx.target(ref)
50
+ if grp is None:
51
+ continue
52
+ members.extend(c for g in ctx.p.find(grp.path) for c in g.children
53
+ if ctx.rel(c.def_ref).endswith("/ComGroupSignal"))
54
+ members.append(grp) # contributes only its update bit
55
+ yield ipdu, length, pdu, members
56
+
57
+
58
+ def _layout(ctx, s):
59
+ """[(label, bitset, line)] a signal/group occupies: its value bits and its update bit."""
60
+ out = []
61
+ pos = parse_int(ctx.text(s, "ComBitPosition") or "")
62
+ size = _size(ctx, s)
63
+ if pos is not None and size:
64
+ endian = (ctx.text(s, "ComSignalEndianness") or "LITTLE_ENDIAN").strip()
65
+ out.append((s.name, bits(pos, size, endian), ctx.value(s, "ComBitPosition").node.line, pos, size, endian))
66
+ ub = parse_int(ctx.text(s, "ComUpdateBitPosition") or "")
67
+ if ub is not None:
68
+ out.append((f"{s.name}.updateBit", [ub], ctx.value(s, "ComUpdateBitPosition").node.line, ub, 1, "LITTLE_ENDIAN"))
69
+ return out
70
+
71
+
72
+ @rule("H2L-COM-001", "error", CITE_BOUNDS, "signal bits lie inside its I-PDU (PduLength * 8)")
73
+ def signal_in_pdu(ctx):
74
+ for ipdu, length, pdu, members in _ipdus(ctx):
75
+ if length is None:
76
+ continue
77
+ limit = length * 8
78
+ for s in members:
79
+ for label, bs, line, pos, size, endian in _layout(ctx, s):
80
+ lo, hi = min(bs), max(bs)
81
+ if lo < 0 or hi >= limit:
82
+ yield s, line, (f"{label}: ComBitPosition={pos} ComBitSize={size} ({endian}) occupies bits {lo}..{hi}, "
83
+ f"outside I-PDU {ipdu.name} ({pdu.path} PduLength={length} bytes = bits 0..{limit - 1})"), \
84
+ (ctx.value(s, "ComBitPosition") or ctx.value(s, "ComUpdateBitPosition")).def_ref
85
+
86
+
87
+ @rule("H2L-COM-002", "error", CITE_OVERLAP, "signals of one I-PDU do not overlap")
88
+ def no_overlap(ctx):
89
+ for ipdu, length, pdu, members in _ipdus(ctx):
90
+ owner: dict = {}
91
+ reported = set()
92
+ for s in members:
93
+ for label, bs, line, pos, size, endian in _layout(ctx, s):
94
+ for b in bs:
95
+ prev = owner.get(b)
96
+ if prev is None:
97
+ owner[b] = (label, s)
98
+ continue
99
+ if prev[0] == label:
100
+ continue
101
+ key = tuple(sorted((prev[0], label)))
102
+ if key in reported:
103
+ continue
104
+ reported.add(key)
105
+ yield s, line, (f"{label} overlaps {prev[0]} at bit {b} in I-PDU {ipdu.name} "
106
+ f"({label}: pos {pos} size {size} {endian})"), \
107
+ (ctx.value(s, "ComBitPosition") or ctx.value(s, "ComUpdateBitPosition")).def_ref
@@ -0,0 +1,42 @@
1
+ """Handle-ID uniqueness (TPS_ECUConfiguration 3.4.1.1 "Handle ID concept")."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from . import rule
7
+ from ..values import parse_int
8
+
9
+ # Handle-ID params by name when no defs say so; with defs, any SYMBOLIC-NAME-VALUE integer counts.
10
+ NAME = re.compile(r"(HandleId|^CanIfTxPduId|^CanIfRxPduId)$")
11
+
12
+
13
+ @rule("H2L-HID-001", "error",
14
+ "TPS_ECUConfiguration 3.4.1.1 Handle ID concept; ECUC_Com_00165/00175, ECUC_PduR_00322, ECUC_CanIf_00591/00597",
15
+ "handle IDs are unique per module and handle-ID parameter")
16
+ def unique_handle_ids(ctx):
17
+ seen: dict = {} # (module path, rel def) -> {value: [(elem, pv)]}
18
+ for path, group in ctx.p.by_path.items():
19
+ e = group[0]
20
+ if e.kind != "container":
21
+ continue
22
+ mod = ctx.module_of(e)
23
+ for g in group:
24
+ for pv in g.params:
25
+ if pv.is_ref or pv.value is None:
26
+ continue
27
+ d = ctx.defs.get(pv.def_ref)
28
+ is_handle = (d.kind == "INTEGER" and d.symbolic_name) if d is not None else False
29
+ if not is_handle and not NAME.search(pv.name):
30
+ continue
31
+ v = parse_int(pv.value)
32
+ if v is None:
33
+ continue
34
+ key = (mod.path, ctx.rel(pv.def_ref))
35
+ seen.setdefault(key, {}).setdefault(v, []).append((g, pv))
36
+ for (mod, rel), by_val in seen.items():
37
+ for v, hits in by_val.items():
38
+ if len(hits) < 2:
39
+ continue
40
+ names = ", ".join(sorted({h[0].name for h in hits}))
41
+ for g, pv in hits:
42
+ yield g, pv.node.line, f"{pv.name}={v} is used by {len(hits)} containers in {mod} ({names}); handle IDs must be unique", pv.def_ref
@@ -17,6 +17,7 @@ Rules:
17
17
  ECUC-REF-UNRESOLVED foreign reference target not in any loaded file (warning)
18
18
  ECUC-DUP-NAME two containers with the same AUTOSAR path
19
19
  ECUC-OBSOLETE value for an obsolete def (warning)
20
+ Hand-written semantic rules (ecuc_engine/rules, ids H2L-*) run afterwards, with or without defs.
20
21
  """
21
22
  from __future__ import annotations
22
23
 
@@ -205,6 +206,9 @@ def validate(project: Project, files: Optional[list] = None, module: Optional[st
205
206
  continue
206
207
  check_elem_group(m.path)
207
208
 
209
+ from .rules import run_rules
210
+ dg.items.extend(run_rules(project))
211
+
208
212
  items = dg.items
209
213
  if files:
210
214
  want = {project.rel(f) for f in files} | set(files)
@@ -215,6 +219,7 @@ def validate(project: Project, files: Optional[list] = None, module: Optional[st
215
219
  summary[i["severity"]] = summary.get(i["severity"], 0) + 1
216
220
  return {
217
221
  "validated": bool(defs),
222
+ "rules": "semantic rule packs ran (H2L-*)",
218
223
  "defsLoaded": len(defs.modules),
219
224
  "modules": sorted({m.name for m in project.modules}),
220
225
  "summary": summary,
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ecuc-engine"
3
- version = "0.1.0"
3
+ version = "0.1.2"
4
4
  description = "Load, read, edit in place, validate and diff AUTOSAR ECUC ARXML (Hydron AUTOSAR pack)"
5
5
  requires-python = ">=3.10"
6
6
  # The core is stdlib-only; autosar-data adds a strict schema check of every edited file.
@@ -15,7 +15,10 @@ You are working on an AUTOSAR Classic ECU project. The configuration is ECUC ARX
15
15
  in `Output/` is derived from it; in-house code in `Source/` calls the generated symbols.
16
16
 
17
17
  ## Hard rules
18
- 1. **Never hand-write or hand-edit ARXML** (no `write`/`edit`/`sed` on `.arxml`). Every change goes
18
+ 0. **Configured values are answered with `ecuc_read`** (it accepts a SHORT-NAME or partial path) or
19
+ `autosar_config_lookup` — not grep/read on ARXML. A value's AUTOSAR path is its `@path`; `@def` is its
20
+ DEFINITION-REF. Never give one when the other is asked.
21
+ 1. **Never hand-write or hand-edit ARXML** (no `write`/`edit`/`sed` on `.arxml`; the pack blocks them). Every change goes
19
22
  through `ecuc_edit`, which picks the value element, DEFINITION-REF/DEST and VALUE-REF DEST from
20
23
  the param defs and patches only the changed bytes. Reading raw ARXML for context is fine; prefer `ecuc_read`.
21
24
  2. **Validate after every edit**: `ecuc_validate` (scoped with `files`/`module` if large). Fix
@@ -38,6 +41,7 @@ in `Output/` is derived from it; in-house code in `Source/` calls the generated
38
41
  | Review a change / PR / two versions | `arxml_diff a b` |
39
42
  | Which C symbols does this config produce, who calls them / where does this symbol come from | `autosar_trace query=…` |
40
43
  | Refs in/out, children of an element in the ingested repo | `autosar_config_lookup path=…` |
44
+ | Review C code that calls Com/NvM/Dem/PduR/RTE APIs | `autosar_audit` (first), then confirm with `autosar_trace` / `ecuc_read` |
41
45
  | Regenerate code | `autosar_generate` (configured command, asks permission) |
42
46
  | Compile/link | `autosar_build` |
43
47
  | Spec questions (SWS/TPS requirement text) | the project's ingested docs search tools |
@@ -46,6 +50,28 @@ in `Output/` is derived from it; in-house code in `Source/` calls the generated
46
50
  `ecuc_read (schema) → ecuc_edit → ecuc_validate → autosar_generate → arxml_diff / inspect Output → autosar_build → autosar_trace (impact on Source/)`.
47
51
  Details and failure handling: `references/workflow.md`.
48
52
 
53
+ ## Integration review recipe (C code against the configuration)
54
+ 1. `autosar_audit` (scope with `paths` if asked about specific files). It resolves every BSW call's handle
55
+ through the ECUC and reports raw numeric handles, unknown handles, direction mismatches, C-width vs
56
+ ComSignalType mismatches and invalid NvM NULL_PTR use, each with evidence and a spec citation.
57
+ 2. Confirm each finding before reporting it: `ecuc_read <signal/block>` for the configured values and
58
+ `autosar_trace <symbol>` for the owning I-PDU, generated symbol and other callers.
59
+ 3. Review what the audit lists as *unchecked* by hand (pointer arguments, expressions as handles), and
60
+ look for logic issues it cannot see (wrong signal chosen although types match, missing error handling).
61
+ 4. Report: file:line, the call, the configured facts (AUTOSAR paths + values), the spec ID, the fix.
62
+
63
+ Facts that decide common review calls:
64
+ - **Direction lives on the I-PDU**, not the signal: a ComSignal is TX or RX through the `ComIPduDirection`
65
+ of the ComIPdu that references it (`ComIPduSignalRef`). Sending an RX signal (or receiving a TX one)
66
+ fails at runtime (ECUC_Com_00493, SWS_Com_00197/00198).
67
+ - **NvM `NULL_PTR` is valid** for `NvM_ReadBlock`/`NvM_WriteBlock` when the block has a permanent RAM block
68
+ (`NvMRamBlockDataAddress` set) or explicit synchronization: NvM then uses that RAM block
69
+ (SWS_NvM_00898/00899, SWS_NvM_00900/00901). It is an error only for a block with neither.
70
+ - The data pointer of `Com_SendSignal`/`Com_ReceiveSignal` must point to an object of the signal's
71
+ `ComSignalType` size; a smaller variable is overread/overwritten.
72
+ - Raw numeric handles break silently when the generator re-assigns IDs: use the symbolic name
73
+ `<Mod>Conf_<ContainerDef>_<ShortName>` (TPS_ECUC_02108).
74
+
49
75
  ## References (load when relevant)
50
76
  - `references/ecuc-model.md` — module/container/param/ref values vs defs, DEFINITION-REF, ECUC JSON, multiplicity, choice containers, refs vs foreign refs.
51
77
  - `references/symbolic-names.md` — the symbolic-name rule (TPS_ECUC_02108) that links config to generated `#define`s, handle IDs.
@@ -59,5 +85,9 @@ ECUC-MULT-CONTAINER/-PARAM, ECUC-CHOICE, ECUC-RANGE, ECUC-ENUM, ECUC-TYPE, ECUC-
59
85
  ECUC-REF-DANGLING, ECUC-REF-DEST, ECUC-REF-UNRESOLVED (foreign target not loaded: add System/SWC
60
86
  ARXML to `input`), ECUC-UNKNOWN-DEF (often a release mismatch between config and param defs),
61
87
  ECUC-DUP-NAME, ECUC-NO-DEF (module defs not loaded → module not validated), ECUC-VALUE-TYPE,
62
- ECUC-DEST-MISMATCH, ECUC-OBSOLETE. These are mechanical checks from the defs; they do not cover
63
- SWS cross-module rules — reason about those explicitly.
88
+ ECUC-DEST-MISMATCH, ECUC-OBSOLETE. These are mechanical checks from the defs.
89
+ Semantic rule packs (run even without defs; each message carries its spec citation):
90
+ H2L-COM-001 signal/update bit outside its I-PDU (ComBitPosition/ComBitSize vs EcuC PduLength*8),
91
+ H2L-COM-002 overlapping signals in one I-PDU (Motorola numbering for BIG_ENDIAN; ComBitPosition = LSB),
92
+ H2L-HID-001 duplicate handle IDs per module. Other SWS cross-module rules are not checked yet — reason
93
+ about them explicitly.