@h2loop/autosar 0.0.0-stage → 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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "engines": { "hydron": ">=1.0.0" }
3
+ }
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @h2loop/autosar — AUTOSAR Classic pack for Hydron
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Deterministic tools for AUTOSAR Classic integration work, so the agent never hand-writes ARXML:
4
+
5
+ | Tool | What it does | Runs |
6
+ |---|---|---|
7
+ | `ecuc_read` | ECUC configuration as compact ECUC JSON; def summaries (`schema`) | local (Python engine) |
8
+ | `ecuc_edit` | set / add / remove by AUTOSAR path; in-place byte patches; all-or-nothing; schema check | local |
9
+ | `ecuc_validate` | multiplicity, mandatory, range, enum, type, string, ref target/dest, dangling, duplicates → LSP-like diagnostics | local |
10
+ | `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
11
+ | `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
12
+ | `autosar_config_lookup` | element + children + refs in/out + links from the code graph | H2Loop backend |
13
+ | `autosar_audit` | integration review of C code: BSW API handles, direction, widths, NvM NULL_PTR vs ECUC | local |
14
+ | `autosar_generate` / `autosar_build` | run the project's configured generator / build command (asks permission) | local |
15
+
16
+ Plus the `autosar` skill (ECUC model, symbolic-name rule, config classes, project layout, the
17
+ edit → validate → generate → build → trace loop), the `autosar-integrator` subagent, and the
18
+ `/autosar-validate` and `/autosar-trace` commands.
19
+
20
+ ## Install
21
+ ```bash
22
+ hydron plugin add @h2loop/autosar # or a local path / --project
23
+ ```
24
+ Requirements: [uv](https://docs.astral.sh/uv/) (preferred; adds the strict ARXML schema check via
25
+ `autosar-data`) or Python ≥ 3.10 on PATH (`AUTOSAR_PYTHON` overrides). The backend tools use the
26
+ Hydron login and selected H2Loop project (or `workspace_id`); `KILO_API_URL` overrides the backend.
27
+
28
+ ## Project configuration
29
+ Param definitions are not bundled. The engine finds them in this order: `.hydron/autosar.json`
30
+ `paramDefs` globs → any project `.arxml` containing `ECUC-MODULE-DEF` (vendor BSWMD) →
31
+ `$AUTOSAR_PARAMDEFS` (path list). Without defs, values are readable but not validated.
32
+
33
+ ```json
34
+ {
35
+ "paramDefs": ["SIP/**/bswmd/*.arxml"],
36
+ "config": ["Config/**/*.arxml"],
37
+ "input": ["Input/**/*.arxml"],
38
+ "generate": {"command": "<vendor-cli> --project Config/Ecu.dpa --generate {module}", "timeoutSec": 3600},
39
+ "build": "make -C Build all"
40
+ }
41
+ ```
42
+
43
+ ## Engine CLI
44
+ ```bash
45
+ cd python && uv run --no-project --with autosar-data==0.17.0 python -m ecuc_engine --root <project> \
46
+ <info|read [path] [--depth N] [--schema]|edit --ops '<json>' [--dry-run]|validate [--module M] [--file F]|diff A B> --json
47
+ ```
48
+
49
+ ## Develop
50
+ ```bash
51
+ bun install && bun run build && bun run typecheck
52
+ bun run test:py # pytest; R25-11 integration tests run when AUTOSAR_R25_DEFS (or the eval_work copy) exists
53
+ hydron plugin validate .
54
+ ```
@@ -0,0 +1,44 @@
1
+ ---
2
+ mode: subagent
3
+ displayName: AUTOSAR Integrator
4
+ description: >-
5
+ Carries out one AUTOSAR Classic integration task end to end — e.g. "add a TX signal DoorLatch to
6
+ ComIPdu DoorStatus_Tx", "fix the ecuc_validate errors in Com", "what breaks if I rename this
7
+ PduR path?" — through the edit → validate → generate → build → trace loop, and returns a short
8
+ change report with AUTOSAR paths, DEFINITION-REFs, validation and build results. Use for
9
+ multi-step configuration work; for a single read or lookup call the tool directly.
10
+ permission:
11
+ # deny-all first, then allow specifics (last matching rule wins).
12
+ "*": deny
13
+ read: allow
14
+ grep: allow
15
+ glob: allow
16
+ list: allow
17
+ skill: allow
18
+ "ecuc_read": allow
19
+ "ecuc_edit": allow
20
+ "ecuc_validate": allow
21
+ "arxml_diff": allow
22
+ "autosar_trace": allow
23
+ "autosar_config_lookup": allow
24
+ "autosar_generate": ask
25
+ "autosar_build": ask
26
+ ---
27
+ You are an AUTOSAR Classic integrator. Load the `autosar` skill first and follow it.
28
+
29
+ Method:
30
+ 1. Orient with `ecuc_read` (no path). If no param defs are loaded, stop and report what is needed.
31
+ 2. Read every container you will touch with `schema=true`, and the containers its references point to.
32
+ 3. Before renaming or removing anything, `autosar_trace` it and list impacted symbols/callers.
33
+ 4. Make all related changes in one `ecuc_edit` call. Never write or patch `.arxml` with other tools,
34
+ and never edit generated `Output/` files.
35
+ 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
37
+ of new errors; map generator/compiler errors back to AUTOSAR paths and fix them in config.
38
+
39
+ Report (concise):
40
+ - Changes: `AUTOSAR path` (DEFINITION-REF, file:line): old → new, with config class when known.
41
+ - Validation: counts before/after; any remaining finding with its rule.
42
+ - Generate/build: status and the relevant error lines.
43
+ - Impact: C symbols and callers from `autosar_trace`; assumptions (e.g. handle-ID convention) and
44
+ open questions for the human integrator.
@@ -0,0 +1,11 @@
1
+ ---
2
+ description: Trace an AUTOSAR config element or C symbol to its generated code and callers (or back).
3
+ ---
4
+ Load the `autosar` skill. Call `autosar_trace` with query `$ARGUMENTS` (an AUTOSAR path, a SHORT-NAME,
5
+ or a C symbol). If it returns several matches, list them and pick the one that fits, saying why.
6
+
7
+ Report, for the chosen match: the ARXML element (AUTOSAR path, DEFINITION-REF, module, file:line,
8
+ key values), each linked C symbol with file, kind, link method and score, and the callers in
9
+ in-house code (function, file:line). Relay any NOTE / BACKEND ERROR lines verbatim (e.g. a data source
10
+ that must be re-ingested). If the local checkout has the config, cross-check values with `ecuc_read`.
11
+ End with what would be impacted by changing this element.
@@ -0,0 +1,12 @@
1
+ ---
2
+ description: Validate the project's ECUC configuration against its param defs and explain the findings.
3
+ ---
4
+ Load the `autosar` skill. Run `ecuc_read` with no path to confirm which param defs and config files
5
+ are loaded, then `ecuc_validate`$ARGUMENTS (if arguments name a module, pass it as `module`; if they
6
+ name files, pass them as `files`).
7
+
8
+ Summarise: counts by severity and rule, then group the errors by module and container. For each group
9
+ give the AUTOSAR path, the DEFINITION-REF, file:line, what the def requires, and the concrete fix
10
+ (as the `ecuc_edit` op you would apply). Flag findings that look like a release/vendor param-def
11
+ mismatch (bursts of ECUC-UNKNOWN-DEF) or missing input files (ECUC-REF-UNRESOLVED) separately.
12
+ Do not apply fixes unless asked.
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@h2loop/autosar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
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
+ "type": "module",
6
+ "private": false,
7
+ "license": "UNLICENSED",
8
+ "engines": {
9
+ "hydron": ">=1.0.0"
10
+ },
11
+ "files": [
12
+ ".hydron-plugin",
13
+ "agents",
14
+ "commands",
15
+ "skills",
16
+ "plugins/index.js",
17
+ "python/pyproject.toml",
18
+ "python/ecuc_engine/*.py",
19
+ "python/ecuc_engine/rules/*.py",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "typecheck": "tsc --noEmit -p src",
24
+ "test": "bun test && bun run test:py",
25
+ "test:py": "cd python && uv run --no-project --with autosar-data==0.17.0 --with pytest python -m pytest -q -p no:anyio",
26
+ "build": "bun build.ts",
27
+ "guard": "bun script/guard.ts",
28
+ "prepublishOnly": "bun run build && bun run guard"
29
+ },
30
+ "publishConfig": {
31
+ "registry": "https://registry.npmjs.org",
32
+ "access": "public"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/h2loop/hydron-autosar-pack.git"
37
+ },
38
+ "dependencies": {
39
+ "@kilocode/plugin": "*"
40
+ },
41
+ "devDependencies": {
42
+ "@types/bun": "latest",
43
+ "@typescript/native-preview": "^7.0.0-dev.20260707.2",
44
+ "typescript": "^5.5.0"
45
+ }
46
+ }
@@ -0,0 +1,26 @@
1
+ // @bun
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
+ `)+`
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
+ Rejected diff:
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};
@@ -0,0 +1,2 @@
1
+ """ECUC engine: load, read, edit, validate and diff AUTOSAR ECUC ARXML without regenerating files."""
2
+ ENGINE_VERSION = "0.1.2"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())