@h2loop/autosar 1.0.1 → 1.1.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.
Files changed (47) hide show
  1. package/README.md +4 -0
  2. package/agents/autosar-integrator.md +34 -2
  3. package/package.json +4 -1
  4. package/plugins/index.js +53 -23
  5. package/python/ecuc_engine/__init__.py +1 -1
  6. package/python/ecuc_engine/add_signal.py +351 -0
  7. package/python/ecuc_engine/arxml_edit.py +387 -0
  8. package/python/ecuc_engine/audit.py +328 -48
  9. package/python/ecuc_engine/cli.py +114 -5
  10. package/python/ecuc_engine/codegen/__init__.py +185 -0
  11. package/python/ecuc_engine/codegen/binding.py +210 -0
  12. package/python/ecuc_engine/codegen/bindings/sip_standin.json +111 -0
  13. package/python/ecuc_engine/codegen/cdiff.py +395 -0
  14. package/python/ecuc_engine/codegen/cwriter.py +150 -0
  15. package/python/ecuc_engine/codegen/emit.py +395 -0
  16. package/python/ecuc_engine/codegen/handles.py +89 -0
  17. package/python/ecuc_engine/codegen/mcal/tc4d.json +60 -0
  18. package/python/ecuc_engine/codegen/model.py +259 -0
  19. package/python/ecuc_engine/codegen/modules/__init__.py +7 -0
  20. package/python/ecuc_engine/codegen/modules/comstack.py +14 -0
  21. package/python/ecuc_engine/codegen/modules/dem.py +22 -0
  22. package/python/ecuc_engine/codegen/modules/mcal.py +170 -0
  23. package/python/ecuc_engine/codegen/modules/memstack.py +24 -0
  24. package/python/ecuc_engine/codegen/registry.py +133 -0
  25. package/python/ecuc_engine/codegen/schm_memmap.py +159 -0
  26. package/python/ecuc_engine/context.py +481 -0
  27. package/python/ecuc_engine/csrc.py +189 -0
  28. package/python/ecuc_engine/defs.py +30 -0
  29. package/python/ecuc_engine/find.py +162 -0
  30. package/python/ecuc_engine/gen.py +105 -0
  31. package/python/ecuc_engine/history.py +146 -0
  32. package/python/ecuc_engine/model.py +4 -1
  33. package/python/ecuc_engine/probe.py +229 -0
  34. package/python/ecuc_engine/rte_api.py +935 -0
  35. package/python/ecuc_engine/rules/__init__.py +5 -3
  36. package/python/ecuc_engine/rules/mem.py +84 -0
  37. package/python/ecuc_engine/rules/nvm.py +131 -0
  38. package/python/ecuc_engine/rules/pdur.py +87 -0
  39. package/python/ecuc_engine/rules/system.py +162 -0
  40. package/python/ecuc_engine/sysmodel.py +152 -0
  41. package/python/ecuc_engine/validate.py +15 -2
  42. package/python/ecuc_engine/verify_rte.py +445 -0
  43. package/python/pyproject.toml +1 -1
  44. package/skills/autosar/SKILL.md +47 -1
  45. package/skills/autosar/references/codegen.md +30 -0
  46. package/skills/autosar/references/project-layout.md +7 -1
  47. package/skills/autosar/references/runnable-code.md +50 -0
package/README.md CHANGED
@@ -7,6 +7,10 @@ Deterministic tools for AUTOSAR Classic integration work, so the agent never han
7
7
  | `ecuc_read` | ECUC configuration as compact ECUC JSON; def summaries (`schema`) | local (Python engine) |
8
8
  | `ecuc_edit` | set / add / remove by AUTOSAR path; in-place byte patches; all-or-nothing; schema check | local |
9
9
  | `ecuc_validate` | multiplicity, mandatory, range, enum, type, string, ref target/dest, dangling, duplicates → LSP-like diagnostics | local |
10
+ | `ecuc_find` | structured queries over the ECUC (conditions, references to/from) | local |
11
+ | `ecuc_crosscheck` | per-module cross-check table (extract, gateway, NvM sizeof, capacity, packing, handles) | local |
12
+ | `arxml_edit` | structured in-place edits of System extract / SWC ARXML (DEST inferred, schema-ordered) | local |
13
+ | `autosar_add_signal` | add a signal end to end (ECUC + extract chain + DBC), validate or roll back | local |
10
14
  | `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
11
15
  | `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
12
16
  | `autosar_config_lookup` | element + children + refs in/out + links from the code graph | H2Loop backend |
@@ -16,24 +16,56 @@ permission:
16
16
  list: allow
17
17
  skill: allow
18
18
  "ecuc_read": allow
19
+ "ecuc_find": allow
20
+ "ecuc_crosscheck": allow
21
+ "arxml_edit": allow
22
+ "autosar_add_signal": allow
23
+ "autosar_audit": allow
24
+ todowrite: allow
25
+ todoread: allow
19
26
  "ecuc_edit": allow
20
27
  "ecuc_validate": allow
21
28
  "arxml_diff": allow
22
29
  "autosar_trace": allow
23
30
  "autosar_config_lookup": allow
31
+ "autosar_codegen": allow
32
+ "autosar_codegen_diff": allow
33
+ "autosar_build_context": allow
34
+ "autosar_verify_rte": allow
35
+ edit: allow
36
+ write: allow
24
37
  "autosar_generate": ask
25
38
  "autosar_build": ask
26
39
  ---
27
40
  You are an AUTOSAR Classic integrator. Load the `autosar` skill first and follow it.
28
41
 
29
- Method:
42
+ Method (validation / fix tasks):
43
+ - `ecuc_validate` unfiltered first — necessary, NOT sufficient. Never conclude "no faults" from one validate call.
44
+ - Write a todo checklist with one item per module present (Com, PduR, CanIf, EcuC, NvM/Fee/Ea, Dem, Os, Rte) and run
45
+ `ecuc_crosscheck` for each; then `autosar_audit` for Source/ usage of the configuration.
46
+ - Fix with `ecuc_edit` (ECUC), `arxml_edit` (System extract / SWC XML) or `autosar_add_signal` (new signal), then
47
+ `autosar_generate`, `autosar_build`, and `ecuc_validate` again (`checkGenerated: true` to prove Output/ is current).
48
+ - After ANY edit run `ecuc_validate`; never finish while it reports errors you introduced.
49
+
50
+ Method (implement or change a runnable / SW-C C code):
51
+ 1. `autosar_build_context` for the SW-C and runnable with the task text, before reading or writing any C.
52
+ 2. Write the code (edit the in-house .c/.h only, never Output/ or .arxml) using only the APIs listed as allowed for
53
+ that runnable, with their exact signatures.
54
+ 3. `autosar_verify_rte` (scope with `runnable` or `diff_against`). On INVENTED/NOT-ALLOWED either rewrite with an
55
+ allowed API, or — when the behaviour truly needs new data — apply the suggested `arxml_edit` ops, run
56
+ `autosar_generate`, and verify again.
57
+ 4. `autosar_build`. Never finish with a failing verify or build; report both results.
58
+
59
+ General method:
30
60
  1. Orient with `ecuc_read` (no path). If no param defs are loaded, stop and report what is needed.
31
61
  2. Read every container you will touch with `schema=true`, and the containers its references point to.
32
62
  3. Before renaming or removing anything, `autosar_trace` it and list impacted symbols/callers.
33
63
  4. Make all related changes in one `ecuc_edit` call. Never write or patch `.arxml` with other tools,
34
64
  and never edit generated `Output/` files.
35
65
  5. `ecuc_validate` after every edit. Fix every error you introduced; list pre-existing ones separately.
36
- 6. Run `autosar_generate` then `autosar_build` only when they are configured and validation is clean
66
+ 6. For NvM/MemIf/Fee/Dem/PduR/CanIf/Port/Dio use `autosar_codegen` (scratch dir by default; it writes
67
+ assigned handle IDs back into the ARXML) and check it with `autosar_codegen_diff` against Output/.
68
+ Otherwise run `autosar_generate`. Then `autosar_build` only when they are configured and validation is clean
37
69
  of new errors; map generator/compiler errors back to AUTOSAR paths and fix them in config.
38
70
 
39
71
  Report (concise):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h2loop/autosar",
3
- "version": "1.0.1",
3
+ "version": "1.1.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,
@@ -17,6 +17,9 @@
17
17
  "python/pyproject.toml",
18
18
  "python/ecuc_engine/*.py",
19
19
  "python/ecuc_engine/rules/*.py",
20
+ "python/ecuc_engine/codegen/**/*.py",
21
+ "python/ecuc_engine/codegen/bindings/*.json",
22
+ "python/ecuc_engine/codegen/mcal/*.json",
20
23
  "README.md"
21
24
  ],
22
25
  "scripts": {
package/plugins/index.js CHANGED
@@ -1,26 +1,56 @@
1
1
  // @bun
2
- import{isAbsolute as Q_,join as l,resolve as V_}from"path";import{tool as X}from"@kilocode/plugin";import{homedir as c}from"os";import{join as G}from"path";var i=()=>process.env.HYDRON_TEST_HOME||c(),C=(q,H)=>process.env[q]||G(i(),H),g=()=>G(C("XDG_CONFIG_HOME",".config"),"hydron-cli"),n=()=>G(C("XDG_DATA_HOME",".local/share"),"hydron-cli"),o=()=>G(C("XDG_STATE_HOME",".local/state"),"hydron-cli");async function S(q){let H=Bun.file(q);if(!await H.exists())return;return H.json().catch(()=>{return})}async function O(){let q=process.env.KILO_API_URL?.trim();if(q)return q.replace(/\/+$/,"");let H=await S(G(g(),"server-config.json")),_=typeof H?.apiBaseUrl==="string"?H.apiBaseUrl:void 0;if(!_)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return _.replace(/\/+$/,"")}function t(q){let H=q?.split(".")[1];if(!H)return"";try{let _=JSON.parse(Buffer.from(H.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof _.sub==="string"?_.sub:""}catch{return""}}async function a(q){let H=t(q.access);if(H)return H;if(!q.refresh)return"";return new Bun.CryptoHasher("sha256").update(q.refresh).digest("hex").slice(0,12)}async function y(){let H=(await S(G(n(),"auth.json")))?.hydron;if(!H||H.type!=="oauth"||!H.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return H}async function m(){let q=await y();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 H=await fetch(`${await O()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await m()}`},signal:q?AbortSignal.any([q,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(H.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!H.ok)throw Error(`could not list H2Loop projects: HTTP ${H.status}`);let _=await H.json();return Array.isArray(_)?_:_?.items??[]}var z=()=>G(o(),"h2loop-project.json");async function T(q,H){let _=q===void 0||q===null?"":String(q).trim();if(/^\d+$/.test(_))return _;if(_){let V=await v(H),B=V.filter((F)=>F.name===_),D=B.length?B:V.filter((F)=>F.name?.toLowerCase()===_.toLowerCase());if(D.length===1)return String(D[0].id);if(D.length>1)throw Error(`workspace "${_}" is ambiguous: ${D.map((F)=>`${F.name} (id ${F.id})`).join(", ")}; pass the numeric id`);let W=V.filter((F)=>F.name?.toLowerCase().includes(_.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${_}"`+(W.length?`; similar: ${W.map((F)=>`${F.name} (id ${F.id})`).join(", ")}`:`; you have ${V.length} project(s)`))}let J=await S(z());if(!J)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let Y=await y();if(J.project&&typeof J.project==="object"){let V=J.project;if(typeof J.account==="string"&&J.account!==await a(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=J;if(Q.id===void 0)throw Error(`${z()} holds no project id; select a project again or pass workspace_id.`);if(!(await v(H)).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 A(q,H,_,J){let Y=`${await O()}${q}?workspace_id=${encodeURIComponent(H)}`,Q=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await m()}`},body:JSON.stringify(_),signal:J?AbortSignal.any([J,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 L=/\.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 h(q,H){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!H)return;let _=typeof H.filePath==="string"?H.filePath:typeof H.file_path==="string"?H.file_path:"";if(["edit","write","multiedit"].includes(q)){let J=Array.isArray(H.edits)?H.edits.some((Y)=>typeof Y?.filePath==="string"&&L.test(Y.filePath)):!1;if(L.test(_)||J)return`${b} (${q} on ${_||"an .arxml file"})`;return}if(q==="apply_patch"||q==="patch"){let J=String(H.patchText??H.patch??""),Y=J.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??J.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return Y?`${b} (${q} on ${Y[1].trim()})`:void 0}if(q==="bash"){let J=String(H.command??"");if(!L.test(J))return;let Y=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(J)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(J),Q=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(J)||/\btee\b[^|;&]*\.arxml\b/i.test(J);if(Y||Q)return`${b} (bash: ${J.slice(0,120)})`}return}import{existsSync as s}from"fs";import{dirname as e,join as E}from"path";import{fileURLToPath as r}from"url";var __="autosar-data==0.17.0";function q_(){let q=e(r(import.meta.url)),H=[E(q,"..","python"),E(q,"..","..","python")].find((_)=>s(E(_,"ecuc_engine","__main__.py")));if(!H)throw Error(`ECUC engine not found next to ${q} (expected ../python/ecuc_engine)`);return H}async function H_(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 J_(){if(R.cmd!==void 0)return R.cmd;let q=process.env.AUTOSAR_PYTHON?.trim(),_=q?[[q]]:[["uv","run","--no-project","--quiet","--with",__,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let J of _)if(await H_(J))return R.cmd=J,J;return R.cmd=null,null}async function U(q,H,_){let J=await J_();if(!J)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=q_(),Q=Bun.spawn([...J,"-m","ecuc_engine","--root",q,...H,"--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 B=Z.trim().split(`
3
- `).filter(Boolean).at(-1);if(!B)return{ok:!1,error:`engine produced no output (exit ${Q.exitCode}): ${V.trim().slice(-2000)}`};try{return JSON.parse(B)}catch(D){return{ok:!1,error:`engine output was not JSON (${String(D)}): ${B.slice(0,500)} ${V.slice(-500)}`}}}var $=X.schema,Y_=["# 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 f(q){if(typeof q!=="string")return q;let H=q.trim();if(!H.startsWith("[")&&!H.startsWith("{")&&!H.startsWith('"'))return q;try{return f(JSON.parse(H))}catch{return q}}var j=(q)=>$.preprocess(f,q);function k(q){let H=f(q);if(H===void 0||H===null||H==="")return;if(typeof H==="string")return[H];if(Array.isArray(H))return H.map(String).filter((_)=>_.trim());return[String(H)]}var u=()=>$.preprocess(k,$.array($.string()).optional()),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 w(q,H=200){let _=q.slice(0,H).map((J)=>`${J.file}:${J.line} ${J.severity.toUpperCase()} ${J.rule} ${J.path} \u2014 ${J.message}${J.defRef?` [def ${J.defRef}]`:""}`);if(q.length>H)_.push(`\u2026 ${q.length-H} more`);return _}function M(q){let H=q.didYouMean?`
5
- Did you mean: ${q.didYouMean.join(", ")}`:"",_=q.schema?`
6
- Schema errors: ${JSON.stringify(q.schema)}`:"";return`ERROR: ${q.error}${H}${_}`}function N(q){let H=q.warnings??[];return H.length?H.map((_)=>`WARNING: ${_}`).join(`
2
+ import{isAbsolute as ae,join as X,resolve as ce}from"path";import{tool as g}from"@kilocode/plugin";import{homedir as Y}from"os";import{join as S}from"path";var q=()=>process.env.HYDRON_TEST_HOME||Y(),x=(o,i)=>process.env[o]||S(q(),i),V=()=>S(x("XDG_CONFIG_HOME",".config"),"hydron-cli"),z=()=>S(x("XDG_DATA_HOME",".local/share"),"hydron-cli"),K=()=>S(x("XDG_STATE_HOME",".local/state"),"hydron-cli");async function I(o){let i=Bun.file(o);if(!await i.exists())return;return i.json().catch(()=>{return})}async function T(){let o=process.env.KILO_API_URL?.trim();if(o)return o.replace(/\/+$/,"");let i=await I(S(V(),"server-config.json")),e=typeof i?.apiBaseUrl==="string"?i.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 Z(o){let i=o?.split(".")[1];if(!i)return"";try{let e=JSON.parse(Buffer.from(i.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof e.sub==="string"?e.sub:""}catch{return""}}async function Q(o){let i=Z(o.access);if(i)return i;if(!o.refresh)return"";return new Bun.CryptoHasher("sha256").update(o.refresh).digest("hex").slice(0,12)}async function H(){let i=(await I(S(z(),"auth.json")))?.hydron;if(!i||i.type!=="oauth"||!i.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return i}async function F(){let o=await H();if(typeof o.expires==="number"&&o.expires>0&&Date.now()>=o.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 o.access}async function P(o){let i=await fetch(`${await T()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await F()}`},signal:o?AbortSignal.any([o,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(i.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!i.ok)throw Error(`could not list H2Loop projects: HTTP ${i.status}`);let e=await i.json();return Array.isArray(e)?e:e?.items??[]}var M=()=>S(K(),"h2loop-project.json");async function E(o,i){let e=o===void 0||o===null?"":String(o).trim();if(/^\d+$/.test(e))return e;if(e){let c=await P(i),d=c.filter((l)=>l.name===e),u=d.length?d:c.filter((l)=>l.name?.toLowerCase()===e.toLowerCase());if(u.length===1)return String(u[0].id);if(u.length>1)throw Error(`workspace "${e}" is ambiguous: ${u.map((l)=>`${l.name} (id ${l.id})`).join(", ")}; pass the numeric id`);let f=c.filter((l)=>l.name?.toLowerCase().includes(e.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${e}"`+(f.length?`; similar: ${f.map((l)=>`${l.name} (id ${l.id})`).join(", ")}`:`; you have ${c.length} project(s)`))}let t=await I(M());if(!t)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let a=await H();if(t.project&&typeof t.project==="object"){let c=t.project;if(typeof t.account==="string"&&t.account!==await Q(a))throw Error("The selected H2Loop project belongs to another account; select one again or pass workspace_id.");if(c.id!==void 0)return String(c.id)}let n=t;if(n.id===void 0)throw Error(`${M()} holds no project id; select a project again or pass workspace_id.`);if(!(await P(i)).some((c)=>String(c.id)===String(n.id)))throw Error(`The selected project ${n.name??""} (id ${n.id}) is not accessible to the signed-in account; select another or pass workspace_id.`);return String(n.id)}async function j(o,i,e,t){let a=`${await T()}${o}?workspace_id=${encodeURIComponent(i)}`,n=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await F()}`},body:JSON.stringify(e),signal:t?AbortSignal.any([t,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000)}),r=await n.text();if(n.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(n.status===404&&r.includes("Not Found"))throw Error(`${o} is not available on ${await T()} (backend predates the AUTOSAR endpoints).`);if(!n.ok)throw Error(`H2Loop ${o} failed: HTTP ${n.status} ${r.slice(0,800)}`);try{return JSON.parse(r)}catch(c){throw Error(`H2Loop ${o} returned non-JSON (${String(c)}): ${r.slice(0,300)}`)}}var D=/\.arxml\b/i,L="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.";function B(o,i){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!i)return;let e=typeof i.filePath==="string"?i.filePath:typeof i.file_path==="string"?i.file_path:"";if(["edit","write","multiedit"].includes(o)){let t=Array.isArray(i.edits)?i.edits.some((a)=>typeof a?.filePath==="string"&&D.test(a.filePath)):!1;if(D.test(e)||t)return`${L} (${o} on ${e||"an .arxml file"})`;return}if(o==="apply_patch"||o==="patch"){let t=String(i.patchText??i.patch??""),a=t.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??t.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return a?`${L} (${o} on ${a[1].trim()})`:void 0}if(o==="bash"){let t=String(i.command??"");if(!D.test(t))return;let a=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(t)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(t),n=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(t)||/\btee\b[^|;&]*\.arxml\b/i.test(t),r=/open\([^)]*\.arxml[^)]*,\s*(?:mode\s*=\s*)?['"][wa+]/i.test(t)||/\.arxml['"]?\s*\)?\s*\.write_(?:text|bytes)\b/i.test(t)||/write_(?:text|bytes)\([^)]*\)[^;\n]*\.arxml/i.test(t)||/\bwriteFile(?:Sync)?\([^)]*\.arxml/i.test(t)||/\.write\(\s*['"][^'"]*\.arxml/i.test(t)||/\b(?:awk|gawk)\b[^|;&]*-i\s+inplace/.test(t)||/\bed\b\s+-s\s+[^|;&]*\.arxml/.test(t);if(a||n||r)return`${L} (bash: ${t.slice(0,120)})`}return}import{existsSync as ee}from"fs";import{dirname as te,join as U}from"path";import{fileURLToPath as ne}from"url";var re="autosar-data==0.17.0";function ie(){let o=te(ne(import.meta.url)),i=[U(o,"..","python"),U(o,"..","..","python")].find((e)=>ee(U(e,"ecuc_engine","__main__.py")));if(!i)throw Error(`ECUC engine not found next to ${o} (expected ../python/ecuc_engine)`);return i}async function oe(o){try{return await Bun.spawn([...o,"-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 C={};async function se(){if(C.cmd!==void 0)return C.cmd;let o=process.env.AUTOSAR_PYTHON?.trim(),e=o?[[o]]:[["uv","run","--no-project","--quiet","--with",re,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let t of e)if(await oe(t))return C.cmd=t,t;return C.cmd=null,null}async function b(o,i,e){let t=await se();if(!t)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 a=ie(),n=Bun.spawn([...t,"-m","ecuc_engine","--root",o,...i,"--json"],{cwd:o,env:{...process.env,PYTHONPATH:[a,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:e}),[r,c]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);await n.exited;let d=r.trim().split(`
3
+ `).filter(Boolean).at(-1);if(!d)return{ok:!1,error:`engine produced no output (exit ${n.exitCode}): ${c.trim().slice(-2000)}`};try{return JSON.parse(d)}catch(u){return{ok:!1,error:`engine output was not JSON (${String(u)}): ${d.slice(0,500)} ${c.slice(-500)}`}}}var s=g.schema,de=["# AUTOSAR pack active","Load the `autosar` skill. Config: ecuc_read/ecuc_find, not grep. Edit only via ecuc_edit, arxml_edit,","autosar_add_signal (.arxml hand edits blocked). After edits: ecuc_validate + ecuc_crosscheck per module.","C review: autosar_audit. Runnable code: autosar_build_context first, then autosar_verify_rte + autosar_build.","Cite @path + @def."].join(`
4
+ `);function N(o){if(typeof o!=="string")return o;let i=o.trim();if(!i.startsWith("[")&&!i.startsWith("{")&&!i.startsWith('"'))return o;try{return N(JSON.parse(i))}catch{return o}}var k=(o)=>s.preprocess(N,o);function v(o){let i=N(o);if(i===void 0||i===null||i==="")return;if(typeof i==="string")return[i];if(Array.isArray(i))return i.map(String).filter((e)=>e.trim());return[String(i)]}var A=()=>s.preprocess(v,s.array(s.string()).optional()),R=" 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 O(o,i=200){let e=o.slice(0,i).map((t)=>`${t.file}:${t.line} ${t.severity.toUpperCase()} ${t.rule} ${t.path} \u2014 ${t.message}${t.defRef?` [def ${t.defRef}]`:""}`);if(o.length>i)e.push(`\u2026 ${o.length-i} more`);return e}function y(o){let i=o.didYouMean?`
5
+ Did you mean: ${o.didYouMean.join(", ")}`:"",e=o.schema?`
6
+ Schema errors: ${JSON.stringify(o.schema)}`:"";return`ERROR: ${o.error}${i}${e}`}function w(o){let i=o.warnings??[];return i.length?i.map((e)=>`WARNING: ${e}`).join(`
7
7
  `)+`
8
- `:""}function P(q,H){if(!H)return q;return Q_(H)?H:V_(q,H)}async function Z_(q){let H=Bun.file(l(q,".hydron","autosar.json"));if(!await H.exists())return{};return H.json().catch((_)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(_)}`)})}async function $_(q,H){let _=(await Z_(q))[H];if(typeof _==="string")return{command:_};if(_&&typeof _==="object"&&typeof _.command==="string")return _;return}function p(q,H=150){let _=q.split(`
9
- `);return _.length>H?[`\u2026 (${_.length-H} earlier lines omitted)`,..._.slice(-H)].join(`
10
- `):q}async function B_(q,H,_,J){let Y=process.platform==="win32"?["cmd","/d","/s","/c",q]:["sh","-c",q],Q=Date.now(),Z=Bun.spawn(Y,{cwd:H,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([J,AbortSignal.timeout(_*1000)])}),[V,B]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{code:await Z.exited,out:V,err:B,secs:Math.round((Date.now()-Q)/1000)}}async function x(q,H,_){let J=H.filter((V)=>V?.path&&/\/Com(Group)?Signal$/.test(String(V.definition_ref??""))&&V.ipdu===void 0&&V.direction===void 0);if(!J.length)return[];let Y=await U(q,["signal-owners",...new Set(J.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 J){let B=Q[V.path];if(B===null||B===void 0){Z.push(`NOTE: ${V.path} is not in the local checkout (${q}); owning I-PDU/direction unknown`);continue}V.ipdu_local=B,Z.push(B.length?`${V.path}: owning I-PDU ${B.map((D)=>`${D.ipdu} (ComIPduDirection=${D.direction??"?"})`).join(", ")} [local ECUC]`:`${V.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return Z}var d=(q)=>{let H=q.notes??[],_=q.errors??[];return[...H.map((J)=>`NOTE: ${typeof J==="string"?J:JSON.stringify(J)}`),..._.map((J)=>`BACKEND ERROR: ${typeof J==="string"?J:JSON.stringify(J)}`)]};async function D_(q,H){try{let _=await H(),J=typeof _==="string"?_:_.output;if(J&&J.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 F_(q){for(let[H,_]of Object.entries(q)){let J=_.execute;_.execute=(Y,Q)=>D_(H,()=>J(Y,Q))}return q}var W_=async(q)=>{let H=(_)=>X({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(J,Y){let Q=P(Y.directory,J.project_dir),Z=await $_(Q,_);if(!Z)return`No \`${_}\` command configured. Add it to ${l(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=J.args??"",B=Z.command.replaceAll("{module}",J.module??""),D=B.includes("{args}")?B.replaceAll("{args}",V):`${B}${V?` ${V}`:""}`,W=P(Q,Z.cwd);await Y.ask({permission:`autosar_${_}`,patterns:[D],always:[Z.command],metadata:{command:D,cwd:W}}),Y.metadata({title:`${_}: ${D}`});let F=await B_(D,W,Z.timeoutSec??3600,Y.abort),K=F.code===0?"OK":`FAILED (exit ${F.code})`;return{title:`autosar_${_} ${K}`,output:[`$ ${D} (cwd ${W}, ${F.secs}s) -> ${K}`,F.out.trim()?`--- stdout (tail) ---
12
- ${p(F.out)}`:"",F.err.trim()?`--- stderr (tail) ---
13
- ${p(F.err,80)}`:""].filter(Boolean).join(`
14
- `),metadata:{exit:F.code}}}});return{"tool.execute.before":async(_,J)=>{let Y=h(_.tool,J.args);if(Y)throw Error(Y)},"experimental.chat.system.transform":async(_,J)=>{J.system.push(Y_)},tool:F_({ecuc_read:X({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(_,J){let Y=["read"];if(_.path)Y.push(_.path);if(Y.push("--depth",String(_.depth??2)),_.schema)Y.push("--schema");let Q=await U(P(J.directory,_.project_dir),Y,J.abort);if(!Q.ok)return N(Q)+M(Q);let{ok:Z,engine:V,ms:B,warnings:D,...W}=Q;return N(Q)+JSON.stringify(W,null,1)}}),ecuc_edit:X({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:j($.array(j($.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:j($.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(_,J){let Y=["edit","--ops",JSON.stringify(_.ops)];if(_.dry_run)Y.push("--dry-run");if(_.force)Y.push("--force");let Q=await U(P(J.directory,_.project_dir),Y,J.abort);if(!Q.ok){let D=Q.changes??[];return N(Q)+M(Q)+(D.length?`
8
+ `:""}function m(o,i){if(!i)return o;return ae(i)?i:ce(o,i)}async function le(o){let i=Bun.file(X(o,".hydron","autosar.json"));if(!await i.exists())return{};return i.json().catch((e)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(e)}`)})}async function ue(o,i){let e=(await le(o))[i];if(typeof e==="string")return{command:e};if(e&&typeof e==="object"&&typeof e.command==="string")return e;return}function J(o,i=150){let e=o.split(`
9
+ `);return e.length>i?[`\u2026 (${e.length-i} earlier lines omitted)`,...e.slice(-i)].join(`
10
+ `):o}async function fe(o,i,e,t){let a=process.platform==="win32"?["cmd","/d","/s","/c",o]:["sh","-c",o],n=Date.now(),r=Bun.spawn(a,{cwd:i,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([t,AbortSignal.timeout(e*1000)])}),[c,d]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:await r.exited,out:c,err:d,secs:Math.round((Date.now()-n)/1000)}}var pe=(o)=>(o??[]).map((i)=>`CAN ID ${i.canIdHex??"?"} (${i.canId??"?"}) ${i.direction} via ${i.canIfPdu}, controller ${i.controller??"?"}, network ${(i.network??[]).join(", ")||"?"}`).join("; ");async function W(o,i,e){let t=i.filter((c)=>c?.path&&/\/Com((Group)?Signal|IPdu)$/.test(String(c.definition_ref??""))&&c.ipdu===void 0&&c.direction===void 0);if(!t.length)return[];let a=await b(o,["signal-owners",...new Set(t.map((c)=>c.path))],e);if(!a.ok)return[`NOTE: owning I-PDU not computed locally (${a.error})`];let n=a.owners,r=[];for(let c of t){let d=n[c.path];if(d===null||d===void 0){r.push(`NOTE: ${c.path} is not in the local checkout (${o}); owning I-PDU/direction unknown`);continue}c.ipdu_local=d,r.push(d.length?`${c.path}: owning I-PDU ${d.map((u)=>`${u.ipdu} (ComIPduDirection=${u.direction??"?"}${u.can?.length?`; ${pe(u.can)}`:""})`).join(", ")} [local ECUC]`:`${c.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return r}var G=(o)=>{let i=o.notes??[],e=o.errors??[];return[...i.map((t)=>`NOTE: ${typeof t==="string"?t:JSON.stringify(t)}`),...e.map((t)=>`BACKEND ERROR: ${typeof t==="string"?t:JSON.stringify(t)}`)]};async function he(o,i){try{let e=await i(),t=typeof e==="string"?e:e.output;if(t&&t.trim())return e;return`${o}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(e){return`ERROR (${o}): ${e instanceof Error?e.message:String(e)}`}}function me(o){for(let[i,e]of Object.entries(o)){let t=e.execute;e.execute=(a,n)=>he(i,()=>t(a,n))}return o}var ge=async(o)=>{let i=(e)=>g({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(t,a){let n=m(a.directory,t.project_dir),r=await ue(n,e);if(!r)return`No \`${e}\` command configured. Add it to ${X(n,".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 c=t.args??"",d=r.command.replaceAll("{module}",t.module??""),u=d.includes("{args}")?d.replaceAll("{args}",c):`${d}${c?` ${c}`:""}`,f=m(n,r.cwd);await a.ask({permission:`autosar_${e}`,patterns:[u],always:[r.command],metadata:{command:u,cwd:f}}),a.metadata({title:`${e}: ${u}`});let l=await fe(u,f,r.timeoutSec??3600,a.abort),p=l.code===0?"OK":`FAILED (exit ${l.code})`;return{title:`autosar_${e} ${p}`,output:[`$ ${u} (cwd ${f}, ${l.secs}s) -> ${p}`,l.out.trim()?`--- stdout (tail) ---
12
+ ${J(l.out)}`:"",l.err.trim()?`--- stderr (tail) ---
13
+ ${J(l.err,80)}`:""].filter(Boolean).join(`
14
+ `),metadata:{exit:l.code}}}});return{"tool.execute.before":async(e,t)=>{let a=B(e.tool,t.args);if(a)throw Error(a)},"experimental.chat.system.transform":async(e,t)=>{t.system.push(de)},tool:me({ecuc_read:g({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."+R,args:{path:s.string().optional().describe("AUTOSAR path, SHORT-NAME or partial 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,t){let a=["read"];if(e.path)a.push(e.path);if(a.push("--depth",String(e.depth??2)),e.schema)a.push("--schema");let n=await b(m(t.directory,e.project_dir),a,t.abort);if(!n.ok)return w(n)+y(n);let{ok:r,engine:c,ms:d,warnings:u,...f}=n;return w(n)+JSON.stringify(f,null,1)}}),ecuc_edit:g({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."+R,args:{ops:k(s.array(k(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:k(s.record(s.string(),s.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: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,t){let a=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)a.push("--dry-run");if(e.force)a.push("--force");let n=await b(m(t.directory,e.project_dir),a,t.abort);if(!n.ok){let u=n.changes??[];return w(n)+y(n)+(u.length?`
15
15
  Rejected diff:
16
- ${D.map((W)=>W.diff).join(`
17
- `)}`:"")}let Z=Q.changes??[],V=Q.validation,B=[`${Q.written?"Written":"Dry run (nothing written)"}: ${Q.applied} op(s), ${Z.length} file(s) changed.`,...(Q.notes??[]).map((D)=>`NOTE: ${D}`),...Z.map((D)=>D.diff)];if(V)B.push(V.validated?`Validation of touched files: ${JSON.stringify(V.summary)}`:"Validation skipped: no param defs loaded.",...w(V.diagnostics,50));return{title:`ecuc_edit ${Z.map((D)=>D.file).join(", ")}`,output:N(Q)+B.join(`
18
- `)}}}),ecuc_validate:X({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. `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."+I,args:{files:u().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:$.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),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(_,J){let Y=P(J.directory,_.project_dir),Q=["validate"];for(let K of k(_.files)??[])Q.push("--file",K);if(_.module)Q.push("--module",_.module);let Z=await U(Y,Q,J.abort);if(!Z.ok)return N(Z)+M(Z);let{diagnostics:V,scope:B}=Z,D=V.filter((K)=>K.rule!=="H2L-DISCOVERY"),W=Z.validated?`Validated ${Z.modules.join(", ")||"(no modules)"} against ${Z.defsLoaded} module def(s): ${D.length?JSON.stringify(Z.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${D.length?JSON.stringify(Z.summary):"no findings"}`,F=[`Loaded ${B.configFiles} config file(s)`+(B.filter?`; files filter ${JSON.stringify(B.filter.files)} matched ${B.filter.matchedCount}`:"")+(B.module?`; module filter ${B.module}`:"")+":",...B.files.slice(0,30).map((K)=>` ${K.file} (${K.modules.join(", ")})`),...B.files.length>30||B.filesTruncated?[` \u2026 ${B.files.length-30+(B.filesTruncated??0)} more`]:[]];return{title:`ecuc_validate ${JSON.stringify(Z.summary)}`,output:N(Z)+[W,...w(V,_.max??200),...F].join(`
19
- `)}}}),arxml_diff:X({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, directory (recursive) or glob, relative to the project root or absolute"),b:$.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:$.string().optional().describe("project root (default: session directory)")},async execute(_,J){let Y=P(J.directory,_.project_dir),Q=await U(Y,["diff",_.a,_.b],J.abort);if(!Q.ok)return M(Q);let{ok:Z,engine:V,ms:B,...D}=Q;return JSON.stringify(D,null,1)}}),autosar_trace:X({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(_,J){let Y=await T(_.workspace_id,J.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 A("/api/v1/mcp/autosar/trace",Y,Q,J.abort),V=Z.matches??[],B=await x(P(J.directory,_.project_dir),V.map((W)=>W.arxml).filter((W)=>!!W),J.abort),D=[`${V.length} match(es) for "${_.query}" in workspace ${Y}`+(Z.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(Z.data_sources_queried)})`:""),...d(Z),...B,JSON.stringify(V,null,1)];if(!V.length)D.push("No match: try a SHORT-NAME, a full AUTOSAR path from ecuc_read, or the C symbol.");return{title:`autosar_trace ${_.query}`,output:D.join(`
20
- `)}}}),autosar_config_lookup:X({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(_,J){let Y=await T(_.workspace_id,J.abort),Q={path:_.path};if(_.data_source_id!==void 0)Q.data_source_id=_.data_source_id;let Z=await A("/api/v1/mcp/autosar/config-lookup",Y,Q,J.abort),V=Z.matches??[],B=await x(P(J.directory,_.project_dir),V.map((D)=>D.element).filter((D)=>!!D),J.abort);return{title:`autosar_config_lookup ${_.path}`,output:[`${V.length} match(es) for ${_.path} in workspace ${Y}`,...d(Z),...B,JSON.stringify(V,null,1)].join(`
21
- `)}}}),autosar_audit:X({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:u().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:$.string().optional().describe("project root (default: session directory)")},async execute(_,J){let Y=P(J.directory,_.project_dir),Q=await U(Y,["audit",...k(_.paths)??[]],J.abort);if(!Q.ok)return N(Q)+M(Q);let Z=(Q.notes??[]).map((F)=>`NOTE: ${F}`),V=Q.findings,B=Q.unchecked,D=Q.scanned,W=[`Scanned ${D.sources.length} C file(s), ${D.calls} BSW call(s): ${V.length?JSON.stringify(Q.summary):"no findings"}`,...V.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(B.length)W.push(`Unchecked (${B.length}):`,...B.slice(0,50).map((F)=>` ${F.file}:${F.line} ${F.call} \u2014 ${F.reason}`));return W.push(...Z),{title:`autosar_audit ${JSON.stringify(Q.summary)}`,output:N(Q)+W.join(`
26
- `)}}}),autosar_generate:H("generate"),autosar_build:H("build")})}},K_=W_;export{K_ as Autosar};
16
+ ${u.map((f)=>f.diff).join(`
17
+ `)}`:"")}let r=n.changes??[],c=n.validation,d=[`${n.written?"Written":"Dry run (nothing written)"}: ${n.applied} op(s), ${r.length} file(s) changed.`,...(n.notes??[]).map((u)=>`NOTE: ${u}`),...r.map((u)=>u.diff)];if(c)d.push(c.validated?`Validation of touched files: ${JSON.stringify(c.summary)}`:"Validation skipped: no param defs loaded.",...O(c.diagnostics,50));return{title:`ecuc_edit ${r.map((u)=>u.file).join(", ")}`,output:w(n)+d.join(`
18
+ `)}}}),ecuc_validate:g({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. `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."+R,args:{files:A().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:s.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),max:s.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:s.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:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=["validate"];for(let p of v(e.files)??[])n.push("--file",p);if(e.module)n.push("--module",e.module);if(e.checkGenerated===!0)n.push("--check-generated");if(e.checkGenerated===!1)n.push("--no-check-generated");let r=await b(a,n,t.abort);if(!r.ok)return w(r)+y(r);let{diagnostics:c,scope:d}=r,u=c.filter((p)=>p.rule!=="H2L-DISCOVERY"),f=r.validated?`Validated ${r.modules.join(", ")||"(no modules)"} against ${r.defsLoaded} module def(s): ${u.length?JSON.stringify(r.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${u.length?JSON.stringify(r.summary):"no findings"}`,l=[`Loaded ${d.configFiles} config file(s)`+(d.filter?`; files filter ${JSON.stringify(d.filter.files)} matched ${d.filter.matchedCount}`:"")+(d.module?`; module filter ${d.module}`:"")+":",...d.files.slice(0,30).map((p)=>` ${p.file} (${p.modules.join(", ")})`),...d.files.length>30||d.filesTruncated?[` \u2026 ${d.files.length-30+(d.filesTruncated??0)} more`]:[]];return{title:`ecuc_validate ${JSON.stringify(r.summary)}`,output:w(r)+[f,...O(c,e.max??200),...l].join(`
19
+ `)}}}),arxml_diff:g({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, directory (recursive) or glob, relative to the project root or absolute"),b:s.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=await b(a,["diff",e.a,e.b],t.abort);if(!n.ok)return y(n);let{ok:r,engine:c,ms:d,...u}=n;return JSON.stringify(u,null,1)}}),autosar_trace:g({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."+R,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.union([s.string(),s.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:s.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,t){let a=await E(e.workspace_id,t.abort),n={query:e.query};if(e.data_source_id!==void 0)n.data_source_id=e.data_source_id;if(e.limit!==void 0)n.limit=e.limit;let r=await j("/api/v1/mcp/autosar/trace",a,n,t.abort),c=r.matches??[],d=await W(m(t.directory,e.project_dir),c.map((f)=>f.arxml).filter((f)=>!!f),t.abort),u=[`${c.length} match(es) for "${e.query}" in workspace ${a}`+(r.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(r.data_sources_queried)})`:""),...G(r),...d,JSON.stringify(c,null,1)];if(!c.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:g({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."+R,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.union([s.string(),s.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:s.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,t){let a=await E(e.workspace_id,t.abort),n={path:e.path};if(e.data_source_id!==void 0)n.data_source_id=e.data_source_id;let r=await j("/api/v1/mcp/autosar/config-lookup",a,n,t.abort),c=r.matches??[],d=await W(m(t.directory,e.project_dir),c.map((u)=>u.element).filter((u)=>!!u),t.abort);return{title:`autosar_config_lookup ${e.path}`,output:[`${c.length} match(es) for ${e.path} in workspace ${a}`,...G(r),...d,JSON.stringify(c,null,1)].join(`
21
+ `)}}}),ecuc_find:g({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, key values and file:line.'+R,args:{module:s.string().optional(),container_def:s.string().optional().describe("container definition short-name"),where:s.union([s.string(),s.record(s.string(),s.any())]).optional().describe("conditions on parameter values"),ref_to:s.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:s.string().optional().describe("container whose references define the result set"),limit:s.number().int().min(1).max(500).optional(),project_dir:s.string().optional()},async execute(e,t){let a=["find"];if(e.module)a.push("--module",e.module);if(e.container_def)a.push("--container-def",e.container_def);if(e.where)a.push("--where",typeof e.where==="string"?e.where:JSON.stringify(e.where));if(e.ref_to)a.push("--ref-to",e.ref_to);if(e.referenced_by)a.push("--referenced-by",e.referenced_by);a.push("--limit",String(e.limit??50));let n=await b(m(t.directory,e.project_dir),a,t.abort);if(!n.ok)return w(n)+y(n);let{ok:r,engine:c,ms:d,warnings:u,...f}=n;return w(n)+JSON.stringify(f,null,1)}}),ecuc_crosscheck:g({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."+R,args:{module:s.string().describe("module name, e.g. PduR"),project_dir:s.string().optional()},async execute(e,t){let a=await b(m(t.directory,e.project_dir),["crosscheck",e.module],t.abort);if(!a.ok)return w(a)+y(a);let n=a.rows,r=a.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${a.summary}`,output:[`${e.module}: ${a.summary} (element kinds: ${a.elementKinds.join(", ")||"none"})`,...n.map((c)=>`${c.element} (${c.at})
22
+ ${c.findings.join(`
23
+ `)}`),...O(r,50),...(a.notes??[]).map((c)=>`NOTE: ${c}`)].join(`
24
+ `)}}}),arxml_edit:g({description:"Structured in-place edit of NON-ECUC ARXML (System/ECU extract, SWC, interfaces) \u2014 never write that XML by "+"hand. Ops: {op:'add', parent_path, element:'I-SIGNAL', short_name, values:{TAG: value | '->/ref/path' | {nested}}}, {op:'set', path, element:'START-POSITION', value}, {op:'remove', path}. Every *-REF gets its DEST from the referenced element's real tag (targets must exist or be added 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:k(s.array(k(s.record(s.string(),s.any()))).min(1)).describe("list of ops"),dry_run:s.boolean().optional(),project_dir:s.string().optional()},async execute(e,t){let a=["arxml-edit","--ops",JSON.stringify(N(e.ops))];if(e.dry_run)a.push("--dry-run");let n=await b(m(t.directory,e.project_dir),a,t.abort),r=n.changes??[];if(!n.ok)return y(n)+(n.problems?.length?`
25
+ ${n.problems.join(`
26
+ `)}`:"")+(r.length?`
27
+ Rejected diff:
28
+ ${r.map((c)=>c.diff).join(`
29
+ `)}`:"");return`${n.written?"Written":"Dry run"}; created ${JSON.stringify(n.created)}
30
+ ${r.map((c)=>c.diff).join(`
31
+ `)}
32
+ Next: ecuc_validate.`}}),autosar_add_signal:g({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:s.string(),ipdu:s.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:s.number().int().min(1).max(64).optional(),type:s.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:s.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:s.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:s.union([s.number(),s.string()]).optional(),transfer_property:s.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:s.boolean().optional(),project_dir:s.string().optional()},async execute(e,t){let a=["add-signal","--name",e.name,"--ipdu",e.ipdu,"--type",e.type??"UINT8"];if(e.bit_size!==void 0)a.push("--bit-size",String(e.bit_size));if(e.bit_position!==void 0)a.push("--bit-position",String(e.bit_position));if(e.endianness)a.push("--endianness",e.endianness);if(e.init!==void 0)a.push("--init",String(e.init));if(e.transfer_property)a.push("--transfer-property",e.transfer_property);if(e.dry_run)a.push("--dry-run");let n=await b(m(t.directory,e.project_dir),a,t.abort);if(!n.ok)return y(n)+(n.diagnostics?.length?`
33
+ ${O(n.diagnostics,20).join(`
34
+ `)}`:"");let{ok:r,engine:c,ms:d,...u}=n;return JSON.stringify(u,null,1)}}),autosar_audit:g({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:A().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:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=await b(a,["audit",...v(e.paths)??[]],t.abort);if(!n.ok)return w(n)+y(n);let r=(n.notes??[]).map((p)=>`NOTE: ${p}`),{findings:c,unchecked:d,scanned:u}=n,f=[`Scanned ${u.sources.length} C file(s), ${u.calls} BSW call(s): ${c.length?JSON.stringify(n.summary):"no findings"}`,...c.map((p)=>`${p.file}:${p.line} ${p.severity.toUpperCase()} ${p.rule} ${p.call}
35
+ ${p.message}
36
+ evidence: ${JSON.stringify(p.evidence)}
37
+ spec: ${p.cite}${p.fix?`
38
+ fix: ${p.fix}`:""}`)];if(d.length)f.push(`Unchecked (${d.length}):`,...d.slice(0,50).map((p)=>` ${p.file}:${p.line} ${p.call} \u2014 ${p.reason}`));let l=n.unreferenced??{};for(let[p,_]of Object.entries(l))f.push(`INFO configured but never referenced in the scanned code \u2014 ${p}: ${_.count} (e.g. ${_.sample.slice(0,5).join(", ")})`);return f.push(...r),{title:`autosar_audit ${JSON.stringify(n.summary)}`,output:w(n)+f.join(`
39
+ `)}}}),autosar_verify_rte:g({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:A().describe("C files, directories or globs (default: all in-house C)"),diff_against:s.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:s.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:s.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=["verify-rte",...v(e.paths)??[]];if(e.diff_against)n.push("--diff-against",e.diff_against);if(e.swc)n.push("--swc",e.swc);if(e.runnable)n.push("--runnable",e.runnable);let r=await b(a,n,t.abort);if(!r.ok)return y(r);let{findings:c,counts:d}=r,u=c.filter((h)=>h.status!=="OK"),f=r.scanned,l=[`Verified ${f.calls} Rte_* call(s) in ${f.files.length} file(s) against SW-C(s) ${r.swcs.join(", ")}: OK ${d.OK}, NOT-ALLOWED ${d["NOT-ALLOWED"]}, INVENTED ${d.INVENTED}`+(u.length?" \u2014 FAILING":" \u2014 PASS")];for(let h of u){if(l.push(`${h.at} ${h.status} ${h.call} in ${h.function}() [${h.swc??"?"}${h.runnable?`/${h.runnable}`:""}]`,` ${h.why}`),h.expected)l.push(` expected: ${h.expected} [${h.cite}]`);if(h.hint)l.push(` hint: ${h.hint}`);if(h.arxml_edit?.length)l.push(` fix (arxml_edit ops${h.opsChecked===!0?", dry-run OK":h.opsChecked?`, dry-run FAILED: ${h.opsChecked}`:""}): ${JSON.stringify(h.arxml_edit)}`)}let p=r.notChecked??[];if(p.length)l.push(`Not checked (${p.length}): ${p.map((h)=>`${h.call} @ ${h.at}`).join(", ")}`);let _=r.runnablesWithoutCode??[];if(_.length)l.push(`Runnables without a C definition: ${_.map((h)=>`${h.swc}.${h.runnable} (${h.symbol})`).join(", ")}`);for(let h of r.notes??[])l.push(`NOTE: ${h}`);if(u.length)l.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 ${u.length?"FAIL":"PASS"} ${JSON.stringify(d)}`,output:l.join(`
40
+ `),metadata:{counts:d}}}}),autosar_build_context:g({description:"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.",args:{swc:s.string().describe("SW-C short name or AUTOSAR path"),runnable:s.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:s.string().describe("the task, verbatim"),budget_tokens:s.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:s.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:s.union([s.string(),s.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=["build-context","--swc",e.swc,"--task",e.task,"--budget-tokens",String(e.budget_tokens??24000)];if(e.runnable)n.push("--runnable",e.runnable);let r=await b(a,n,t.abort);if(!r.ok)return y(r);let c=r.text,d=r.codeMissing??[];if(d.length&&e.use_backend){let f=[];try{let l=await E(e.workspace_id,t.abort);for(let p of d){let _=await j("/api/v1/mcp/autosar/trace",l,{query:p,limit:3},t.abort);f.push(`### backend trace for ${p} (workspace ${l})
41
+ ${JSON.stringify(_.matches??[],null,1).slice(0,6000)}`)}}catch(l){f.push(`(backend lookup unavailable: ${l instanceof Error?l.message:String(l)})`)}c+=`
42
+ ## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
43
+ ${f.join(`
44
+ `)}
45
+ `}let u={swc:r.swc,runnables:r.runnables,estimatedTokens:r.estimatedTokens,budgetTokens:r.budgetTokens,reductions:r.reductions,overBudget:r.overBudget??!1,sha1:r.sha1,sections:r.sections,sources:r.manifest};return{title:`autosar_build_context ${r.swc}${r.runnables.length===1?`/${r.runnables[0]}`:""} ~${r.estimatedTokens} tok`,output:`${c}
46
+ ---
47
+ MANIFEST ${JSON.stringify(u)}`,metadata:{sha1:r.sha1,estimatedTokens:r.estimatedTokens}}}}),autosar_codegen:g({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 (any other configured module can be named; it then gets the generic def-driven emission only). 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 ('project' = the project's Output dir). Follow with autosar_codegen_diff against the existing Output/, then autosar_build.",args:{modules:A().describe("modules to generate (default: every supported module that is configured)"),out_dir:s.string().optional().describe("output dir, relative to the project or absolute; 'project' = codegen.outDir / Output. Default: scratch .hydron/codegen/out"),write_back:s.boolean().optional().describe("write assigned handle IDs into the ECUC ARXML (default true)"),binding:s.string().optional().describe("force a static-code binding (e.g. 'sip-standin'), or 'none' for generic tables only"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=["codegen"];for(let l of v(e.modules)??[])n.push("--module",l);if(e.out_dir)n.push("--out",e.out_dir);if(e.write_back===!1)n.push("--no-write-back");if(e.binding)n.push("--binding",e.binding);let r=await b(a,n,t.abort);if(!r.ok){let l=r.handleErrors??[];return w(r)+y(r)+(l.length?`
48
+ ${l.map((p)=>` ${p}`).join(`
49
+ `)}`:"")}let{modules:c,handles:d,timings:u}=r,f=[`Generated ${Object.keys(c).length} module(s) into ${r.outDir} in ${u.total_ms} ms (AUTOSAR R${r.release}):`,...Object.entries(c).map(([l,p])=>` ${l} (${p.variant}${p.binding?`, binding ${p.binding}`:", generic tables"}): ${p.files.join(", ")}; ${p.symbols} symbol(s)`+p.notes.map((_)=>`
50
+ NOTE: ${_}`).join("")),d.assigned.length?`Assigned ${d.assigned.length} handle ID(s) (${d.writtenBack?"written back into the ECUC ARXML":"in memory only, NOT written back"}):
51
+ `+d.assigned.slice(0,40).map((l)=>` ${l.path}/${l.param} = ${l.value}`).join(`
52
+ `)+(d.changes.length?`
53
+ ${d.changes.map((l)=>l.diff).join(`
54
+ `)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(r.notes??[]).map((l)=>`NOTE: ${l}`)];return{title:`autosar_codegen ${Object.keys(c).join(", ")}`,output:w(r)+f.join(`
55
+ `)}}}),autosar_codegen_diff:g({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:s.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:s.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:A().describe("only these modules"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,t){let a=m(t.directory,e.project_dir),n=["codegen-diff",e.reference_dir];if(e.generated_dir)n.push(e.generated_dir);for(let u of v(e.modules)??[])n.push("--module",u);let r=await b(a,n,t.abort);if(!r.ok)return y(r);let c=r.modules,d=[`Semantic diff ${r.reference} (reference) vs ${r.generated} (generated): ${JSON.stringify(r.total)}`,`Not generated (reference only): ${r.notGenerated.join(", ")||"-"}; not in reference: ${r.notInReference.join(", ")||"-"}`];for(let[u,f]of Object.entries(c)){if(d.push(`== ${u}: ${f.summary.matching} matching, ${f.summary.missing} missing, ${f.summary.extra} extra, ${f.summary.mismatches} mismatch(es); table elements ${f.elements.match} equal / ${f.elements.mismatch} different`),f.defines.missing.length)d.push(` missing #define: ${f.defines.missing.slice(0,30).join(", ")}`);for(let l of f.defines.mismatch.slice(0,30))d.push(` #define ${l.name}: reference ${l.reference} | generated ${l.generated}`);if(f.objects.missing.length)d.push(` missing object: ${f.objects.missing.join(", ")}`);if(f.objects.extra.length)d.push(` extra object: ${f.objects.extra.join(", ")}`);for(let l of f.objects.order)d.push(` order differs: ${l.name} (same rows)`);for(let l of f.objects.mismatch)d.push(` ${l.name}: ${l.count} element(s) differ`,...l.elements.slice(0,12).map((p)=>` ${p.element}: reference ${p.reference} | generated ${p.generated}`));if(f.defines.extra.length)d.push(` extra #define (${f.defines.extra.length}): ${f.defines.extra.slice(0,12).join(", ")}${f.defines.extra.length>12?", \u2026":""}`)}return{title:`autosar_codegen_diff ${JSON.stringify(r.total)}`,output:d.join(`
56
+ `)}}}),autosar_generate:i("generate"),autosar_build:i("build")})}},be=ge;export{be 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 = "1.0.1"
2
+ ENGINE_VERSION = "1.3.0-pre"