@anik-2/autosar 0.0.0-stage → 0.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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "engines": { "hydron": ">=1.0.0" }
3
+ }
package/README.md CHANGED
@@ -1,3 +1,56 @@
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
+ > Test builds are published as `@anik-2/autosar` (temporary scope). The release name is
4
+ > `@h2loop/autosar`; see PACKAGING.md.
5
+
6
+ Deterministic tools for AUTOSAR Classic integration work, so the agent never hand-writes ARXML:
7
+
8
+ | Tool | What it does | Runs |
9
+ |---|---|---|
10
+ | `ecuc_read` | ECUC configuration as compact ECUC JSON; def summaries (`schema`) | local (Python engine) |
11
+ | `ecuc_edit` | set / add / remove by AUTOSAR path; in-place byte patches; all-or-nothing; schema check | local |
12
+ | `ecuc_validate` | multiplicity, mandatory, range, enum, type, string, ref target/dest, dangling, duplicates → LSP-like diagnostics | local |
13
+ | `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
14
+ | `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
15
+ | `autosar_config_lookup` | element + children + refs in/out + links from the code graph | H2Loop backend |
16
+ | `autosar_generate` / `autosar_build` | run the project's configured generator / build command (asks permission) | local |
17
+
18
+ Plus the `autosar` skill (ECUC model, symbolic-name rule, config classes, project layout, the
19
+ edit → validate → generate → build → trace loop), the `autosar-integrator` subagent, and the
20
+ `/autosar-validate` and `/autosar-trace` commands.
21
+
22
+ ## Install
23
+ ```bash
24
+ hydron plugin add @h2loop/autosar # or a local path / --project
25
+ ```
26
+ Requirements: [uv](https://docs.astral.sh/uv/) (preferred; adds the strict ARXML schema check via
27
+ `autosar-data`) or Python ≥ 3.10 on PATH (`AUTOSAR_PYTHON` overrides). The backend tools use the
28
+ Hydron login and selected H2Loop project (or `workspace_id`); `KILO_API_URL` overrides the backend.
29
+
30
+ ## Project configuration
31
+ Param definitions are not bundled. The engine finds them in this order: `.hydron/autosar.json`
32
+ `paramDefs` globs → any project `.arxml` containing `ECUC-MODULE-DEF` (vendor BSWMD) →
33
+ `$AUTOSAR_PARAMDEFS` (path list). Without defs, values are readable but not validated.
34
+
35
+ ```json
36
+ {
37
+ "paramDefs": ["SIP/**/bswmd/*.arxml"],
38
+ "config": ["Config/**/*.arxml"],
39
+ "input": ["Input/**/*.arxml"],
40
+ "generate": {"command": "<vendor-cli> --project Config/Ecu.dpa --generate {module}", "timeoutSec": 3600},
41
+ "build": "make -C Build all"
42
+ }
43
+ ```
44
+
45
+ ## Engine CLI
46
+ ```bash
47
+ cd python && uv run --no-project --with autosar-data==0.17.0 python -m ecuc_engine --root <project> \
48
+ <info|read [path] [--depth N] [--schema]|edit --ops '<json>' [--dry-run]|validate [--module M] [--file F]|diff A B> --json
49
+ ```
50
+
51
+ ## Develop
52
+ ```bash
53
+ bun install && bun run build && bun run typecheck
54
+ bun run test:py # pytest; R25-11 integration tests run when AUTOSAR_R25_DEFS (or the eval_work copy) exists
55
+ hydron plugin validate .
56
+ ```
@@ -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,45 @@
1
1
  {
2
2
  "name": "@anik-2/autosar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "typecheck": "tsc --noEmit -p src",
23
+ "test": "bun test && bun run test:py",
24
+ "test:py": "cd python && uv run --no-project --with autosar-data==0.17.0 --with pytest python -m pytest -q -p no:anyio",
25
+ "build": "bun build.ts",
26
+ "guard": "bun script/guard.ts",
27
+ "prepublishOnly": "bun run build && bun run guard"
28
+ },
29
+ "publishConfig": {
30
+ "registry": "https://registry.npmjs.org",
31
+ "access": "public"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/h2loop/hydron-autosar-pack.git"
36
+ },
37
+ "dependencies": {
38
+ "@kilocode/plugin": "*"
39
+ },
40
+ "devDependencies": {
41
+ "@types/bun": "latest",
42
+ "@typescript/native-preview": "^7.0.0-dev.20260707.2",
43
+ "typescript": "^5.5.0"
44
+ }
45
+ }
@@ -0,0 +1,21 @@
1
+ // @bun
2
+ import{isAbsolute as W,join as T,resolve as G}from"path";import{tool as p}from"@kilocode/plugin";import{homedir as j}from"os";import{join as h}from"path";var I=()=>process.env.HYDRON_TEST_HOME||j(),R=(t,n)=>process.env[t]||h(I(),n),D=()=>h(R("XDG_CONFIG_HOME",".config"),"hydron-cli"),L=()=>h(R("XDG_DATA_HOME",".local/share"),"hydron-cli"),M=()=>h(R("XDG_STATE_HOME",".local/state"),"hydron-cli");async function v(t){let n=Bun.file(t);if(!await n.exists())return;return n.json().catch(()=>{return})}async function N(){let t=process.env.KILO_API_URL?.trim();if(t)return t.replace(/\/+$/,"");let n=await v(h(D(),"server-config.json")),e=typeof n?.apiBaseUrl==="string"?n.apiBaseUrl:void 0;if(!e)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return e.replace(/\/+$/,"")}function F(t){let n=t?.split(".")[1];if(!n)return"";try{let e=JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof e.sub==="string"?e.sub:""}catch{return""}}async function J(t){let n=F(t.access);if(n)return n;if(!t.refresh)return"";return new Bun.CryptoHasher("sha256").update(t.refresh).digest("hex").slice(0,12)}async function E(){let n=(await v(h(L(),"auth.json")))?.hydron;if(!n||n.type!=="oauth"||!n.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return n}async function x(){let t=await E();if(typeof t.expires==="number"&&t.expires>0&&Date.now()>=t.expires-30000)throw Error("The H2Loop session token has expired. Send any message in Hydron (the CLI refreshes it) or re-login with `hydron auth login`, then retry.");return t.access}async function A(t){if(t!==void 0&&String(t).trim())return String(t).trim();let n=await v(h(M(),"h2loop-project.json")),e=await E(),o=await J(e),i=n?.project??void 0;if(i?.id!==void 0&&typeof n?.account==="string"&&n.account===o)return String(i.id);throw Error("No H2Loop project selected for this account. Select one in Hydron (project picker) or pass workspace_id explicitly.")}async function $(t,n,e,o){let i=`${await N()}${t}?workspace_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await x()}`},body:JSON.stringify(e),signal:o?AbortSignal.any([o,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000)}),r=await a.text();if(a.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(a.status===404&&r.includes("Not Found"))throw Error(`${t} is not available on ${await N()} (backend predates the AUTOSAR endpoints).`);if(!a.ok)throw Error(`H2Loop ${t} failed: HTTP ${a.status} ${r.slice(0,800)}`);try{return JSON.parse(r)}catch(d){throw Error(`H2Loop ${t} returned non-JSON (${String(d)}): ${r.slice(0,300)}`)}}import{existsSync as P}from"fs";import{dirname as q,join as S}from"path";import{fileURLToPath as X}from"url";var H="autosar-data==0.17.0";function B(){let t=q(X(import.meta.url)),n=[S(t,"..","python"),S(t,"..","..","python")].find((e)=>P(S(e,"ecuc_engine","__main__.py")));if(!n)throw Error(`ECUC engine not found next to ${t} (expected ../python/ecuc_engine)`);return n}async function V(t){try{return await Bun.spawn([...t,"-c","import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"],{stdout:"ignore",stderr:"ignore",stdin:"ignore"}).exited===0}catch{return!1}}var _={};async function Y(){if(_.cmd!==void 0)return _.cmd;let t=process.env.AUTOSAR_PYTHON?.trim(),e=t?[[t]]:[["uv","run","--no-project","--quiet","--with",H,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let o of e)if(await V(o))return _.cmd=o,o;return _.cmd=null,null}async function y(t,n,e){let o=await Y();if(!o)return{ok:!1,error:"no Python >= 3.10 found. Install uv (https://docs.astral.sh/uv/) or Python 3.10+, or set AUTOSAR_PYTHON to an interpreter path."};let i=B(),a=Bun.spawn([...o,"-m","ecuc_engine","--root",t,...n,"--json"],{cwd:t,env:{...process.env,PYTHONPATH:[i,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:e}),[r,d]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text()]);await a.exited;let u=r.trim().split(`
3
+ `).filter(Boolean).at(-1);if(!u)return{ok:!1,error:`engine produced no output (exit ${a.exitCode}): ${d.trim().slice(-2000)}`};try{return JSON.parse(u)}catch(c){return{ok:!1,error:`engine output was not JSON (${String(c)}): ${u.slice(0,500)} ${d.slice(-500)}`}}}var s=p.schema,K=["# AUTOSAR pack active","For AUTOSAR/ECUC/ARXML work load the `autosar` skill. Never hand-write ARXML: use ecuc_read, ecuc_edit,","then ecuc_validate after every edit; arxml_diff to review. autosar_trace links config to C code.","Cite AUTOSAR path + DEFINITION-REF."].join(`
4
+ `),b=" In your answer cite the AUTOSAR path and the DEFINITION-REF (and file:line) of every element you rely on.";function C(t,n=200){let e=t.slice(0,n).map((o)=>`${o.file}:${o.line} ${o.severity.toUpperCase()} ${o.rule} ${o.path} \u2014 ${o.message}${o.defRef?` [def ${o.defRef}]`:""}`);if(t.length>n)e.push(`\u2026 ${t.length-n} more`);return e}function w(t){let n=t.didYouMean?`
5
+ Did you mean: ${t.didYouMean.join(", ")}`:"",e=t.schema?`
6
+ Schema errors: ${JSON.stringify(t.schema)}`:"";return`ERROR: ${t.error}${n}${e}`}function g(t){let n=t.warnings??[];return n.length?n.map((e)=>`WARNING: ${e}`).join(`
7
+ `)+`
8
+ `:""}function l(t,n){if(!n)return t;return W(n)?n:G(t,n)}async function z(t){let n=Bun.file(T(t,".hydron","autosar.json"));if(!await n.exists())return{};return n.json().catch((e)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(e)}`)})}async function Q(t,n){let e=(await z(t))[n];if(typeof e==="string")return{command:e};if(e&&typeof e==="object"&&typeof e.command==="string")return e;return}function k(t,n=150){let e=t.split(`
9
+ `);return e.length>n?[`\u2026 (${e.length-n} earlier lines omitted)`,...e.slice(-n)].join(`
10
+ `):t}async function Z(t,n,e,o){let i=process.platform==="win32"?["cmd","/d","/s","/c",t]:["sh","-c",t],a=Date.now(),r=Bun.spawn(i,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([o,AbortSignal.timeout(e*1000)])}),[d,u]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:await r.exited,out:d,err:u,secs:Math.round((Date.now()-a)/1000)}}var U=(t)=>{let n=t.notes??[],e=t.errors??[];return[...n.map((o)=>`NOTE: ${typeof o==="string"?o:JSON.stringify(o)}`),...e.map((o)=>`BACKEND ERROR: ${typeof o==="string"?o:JSON.stringify(o)}`)]},ee=async(t)=>{let n=(e)=>p({description:e==="generate"?"Run the project's AUTOSAR code generator (e.g. the vendor's configurator CLI) as configured in .hydron/autosar.json `generate` ({command, cwd?, timeoutSec?} or a string; `{module}` and `{args}` placeholders are substituted). Run it only after ecuc_validate reports no errors. Asks the user for permission. Returns the exit code and the output tail; follow with arxml_diff/autosar_build.":"Run the project's build command as configured in .hydron/autosar.json `build` ({command, cwd?, timeoutSec?} or a string; `{module}`/`{args}` substituted). Asks the user for permission. Returns the exit code and the output tail (compiler/linker errors). Use after autosar_generate.",args:{module:s.string().optional().describe("module name substituted for {module} in the command, if used"),args:s.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(o,i){let a=l(i.directory,o.project_dir),r=await Q(a,e);if(!r)return`No \`${e}\` command configured. Add it to ${T(a,".hydron","autosar.json")}, e.g.
11
+ {"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let d=o.args??"",u=r.command.replaceAll("{module}",o.module??""),c=u.includes("{args}")?u.replaceAll("{args}",d):`${u}${d?` ${d}`:""}`,m=l(a,r.cwd);await i.ask({permission:`autosar_${e}`,patterns:[c],always:[r.command],metadata:{command:c,cwd:m}}),i.metadata({title:`${e}: ${c}`});let f=await Z(c,m,r.timeoutSec??3600,i.abort),O=f.code===0?"OK":`FAILED (exit ${f.code})`;return{title:`autosar_${e} ${O}`,output:[`$ ${c} (cwd ${m}, ${f.secs}s) -> ${O}`,f.out.trim()?`--- stdout (tail) ---
12
+ ${k(f.out)}`:"",f.err.trim()?`--- stderr (tail) ---
13
+ ${k(f.err,80)}`:""].filter(Boolean).join(`
14
+ `),metadata:{exit:f.code}}}});return{"experimental.chat.system.transform":async(e,o)=>{o.system.push(K)},tool:{ecuc_read:p({description:'Read AUTOSAR ECUC configuration as compact ECUC JSON (keyed by def names: "<DefName>:<ShortName>" for containers, params by def short-name, references as "->/path"; every container carries @path). No path: lists modules and the param-def/config files found. A module/container path: its values to '+"`depth` levels (merged across split files). A param path (\u2026/Container/Param) or a def path "+"(/AUTOSAR/EcucDefs/\u2026): the value and/or the definition. schema=true adds the def summary (allowed "+"params with type/range/literals/multiplicity, allowed sub-containers) \u2014 read it before ecuc_edit. "+"Never read or edit ARXML by hand."+b,args:{path:s.string().optional().describe("AUTOSAR path of a module/container/parameter, or a def path"),depth:s.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:s.boolean().optional().describe("include the param-def summary for the element"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=["read"];if(e.path)i.push(e.path);if(i.push("--depth",String(e.depth??2)),e.schema)i.push("--schema");let a=await y(l(o.directory,e.project_dir),i,o.abort);if(!a.ok)return g(a)+w(a);let{ok:r,engine:d,ms:u,warnings:c,...m}=a;return g(a)+JSON.stringify(m,null,1)}}),ecuc_edit:p({description:"Edit ECUC ARXML in place \u2014 the ONLY way to change configuration (never write ARXML yourself). Ops by "+"AUTOSAR path: {op:'set', path, param, value} (value scalar, '->/ref/path', or a list for multi-valued "+"params), {op:'add', path:<parent>, container:'DefName:ShortName', values:{\u2026ECUC JSON\u2026}}, {op:'add', "+"path, param, value} (append a value), {op:'remove', path[, param[, value]]}. The engine picks the value element type, DEFINITION-REF/DEST and VALUE-REF DEST from the param defs, rejects out-of-range/non-literal values, patches only the changed bytes in the file each element lives in (UUIDs, order, comments preserved), applies all ops or none, and checks ARXML schema validity. Returns the unified diff and the validation of touched files. ALWAYS run ecuc_validate after editing and fix what it reports."+b,args:{ops:s.array(s.object({op:s.enum(["set","add","remove"]),path:s.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:s.string().optional().describe("parameter/reference def short-name"),value:s.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:s.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:s.record(s.string(),s.any()).optional().describe("for add: ECUC JSON of the new container")})).min(1),dry_run:s.boolean().optional().describe("compute and show the diff without writing"),force:s.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)i.push("--dry-run");if(e.force)i.push("--force");let a=await y(l(o.directory,e.project_dir),i,o.abort);if(!a.ok){let c=a.changes??[];return g(a)+w(a)+(c.length?`
15
+ Rejected diff:
16
+ ${c.map((m)=>m.diff).join(`
17
+ `)}`:"")}let r=a.changes??[],d=a.validation,u=[`${a.written?"Written":"Dry run (nothing written)"}: ${a.applied} op(s), ${r.length} file(s) changed.`,...(a.notes??[]).map((c)=>`NOTE: ${c}`),...r.map((c)=>c.diff)];if(d)u.push(d.validated?`Validation of touched files: ${JSON.stringify(d.summary)}`:"Validation skipped: no param defs loaded.",...C(d.diagnostics,50));return{title:`ecuc_edit ${r.map((c)=>c.file).join(", ")}`,output:g(a)+u.join(`
18
+ `)}}}),ecuc_validate:p({description:"Validate ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions. Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit and before "+"autosar_generate. Without param defs it only warns."+b,args:{files:s.array(s.string()).optional().describe("only report diagnostics in these files"),module:s.string().optional().describe("only validate this module (e.g. Com)"),max:s.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=l(o.directory,e.project_dir),a=["validate"];for(let c of e.files??[])a.push("--file",l(i,c));if(e.module)a.push("--module",e.module);let r=await y(i,a,o.abort);if(!r.ok)return g(r)+w(r);let d=r.diagnostics,u=r.validated?`Validated ${r.modules.join(", ")||"(no modules)"} against ${r.defsLoaded} module def(s): ${d.length?JSON.stringify(r.summary):"no findings"}`:"NOT validated: no param definitions loaded.";return{title:`ecuc_validate ${JSON.stringify(r.summary)}`,output:g(r)+[u,...C(d,e.max??200)].join(`
19
+ `)}}}),arxml_diff:p({description:"Semantic ARXML diff by AUTOSAR path between two files or directories (e.g. a git checkout of the old Config/ vs the current one, or Output/ before/after generation inputs). Ignores UUIDs, whitespace, comments, element order and file splits; ECUC values are compared per parameter. Returns added/removed/changed elements with the changed parameter values. Use it to review edits and PRs instead of a textual diff.",args:{a:s.string().describe("old file or directory"),b:s.string().describe("new file or directory"),project_dir:s.string().optional().describe("project root (default: session directory)")},async execute(e,o){let i=l(o.directory,e.project_dir),a=await y(i,["diff",l(i,e.a),l(i,e.b)],o.abort);if(!a.ok)return w(a);let{ok:r,engine:d,ms:u,...c}=a;return JSON.stringify(c,null,1)}}),autosar_trace:p({description:"Trace AUTOSAR configuration to code through the H2Loop code graph of the selected project: query with an AUTOSAR path, a SHORT-NAME, or a C symbol (reverse lookup). Returns the ARXML element (path, module, DEFINITION-REF, file:line, values), the C symbols it configures (generated macros/const tables via the symbolic-name rule or token/value matching, with method + score) and their callers in in-house code. Use for impact analysis ('what code changes if I change X?') and 'where does this symbol come from?'. Requires the project's code to be ingested."+b,args:{query:s.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:s.number().int().optional().describe("restrict to one code data source"),limit:s.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:s.string().optional().describe("H2Loop project id (default: the selected project)")},async execute(e,o){let i=await A(e.workspace_id),a={query:e.query};if(e.data_source_id!==void 0)a.data_source_id=e.data_source_id;if(e.limit!==void 0)a.limit=e.limit;let r=await $("/api/v1/mcp/autosar/trace",i,a,o.abort),d=r.matches??[],u=[`${d.length} match(es) for "${e.query}" in workspace ${i}`+(r.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(r.data_sources_queried)})`:""),...U(r),JSON.stringify(d,null,1)];if(!d.length)u.push("No match: try a SHORT-NAME, a full AUTOSAR path from ecuc_read, or the C symbol.");return{title:`autosar_trace ${e.query}`,output:u.join(`
20
+ `)}}}),autosar_config_lookup:p({description:"Look up one ARXML element in the H2Loop code graph by AUTOSAR path: the element (module, DEFINITION-REF, file:line, values), its direct children, references out and in (who points at it), and linked C symbols. Use it to navigate config relations across the ingested repo (including files not in the local checkout); for local edits use ecuc_read/ecuc_edit."+b,args:{path:s.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:s.number().int().optional().describe("restrict to one code data source"),workspace_id:s.string().optional().describe("H2Loop project id (default: the selected project)")},async execute(e,o){let i=await A(e.workspace_id),a={path:e.path};if(e.data_source_id!==void 0)a.data_source_id=e.data_source_id;let r=await $("/api/v1/mcp/autosar/config-lookup",i,a,o.abort),d=r.matches??[];return{title:`autosar_config_lookup ${e.path}`,output:[`${d.length} match(es) for ${e.path} in workspace ${i}`,...U(r),JSON.stringify(d,null,1)].join(`
21
+ `)}}}),autosar_generate:n("generate"),autosar_build:n("build")}}},te=ee;export{te as Autosar};
@@ -0,0 +1,2 @@
1
+ """ECUC engine: load, read, edit, validate and diff AUTOSAR ECUC ARXML without regenerating files."""
2
+ ENGINE_VERSION = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,101 @@
1
+ """CLI: python -m ecuc_engine [--root DIR] <info|read|edit|validate|diff> ... --json
2
+
3
+ Always prints one JSON object on stdout. {"ok": false, "error": ...} on failure (exit code 0 for
4
+ handled errors, so callers parse stdout rather than the status).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ import time
13
+
14
+ from . import ENGINE_VERSION
15
+
16
+
17
+ def _ops(arg: str):
18
+ if arg.startswith("@"):
19
+ with open(arg[1:]) as f:
20
+ arg = f.read()
21
+ if arg == "-":
22
+ arg = sys.stdin.read()
23
+ ops = json.loads(arg)
24
+ return ops if isinstance(ops, list) else [ops]
25
+
26
+
27
+ def main(argv=None) -> int:
28
+ ap = argparse.ArgumentParser(prog="ecuc_engine")
29
+ ap.add_argument("--root", default=os.getcwd(), help="project root (default: cwd)")
30
+ ap.add_argument("--defs", action="append", help="param-def file/dir/glob (overrides discovery)")
31
+ ap.add_argument("--config", action="append", help="ECUC value file/dir/glob (overrides discovery)")
32
+ ap.add_argument("--json", action="store_true", help="JSON output (always on; accepted for clarity)")
33
+ sub = ap.add_subparsers(dest="cmd", required=True)
34
+ sub.add_parser("info")
35
+ r = sub.add_parser("read")
36
+ r.add_argument("path", nargs="?")
37
+ r.add_argument("--depth", type=int, default=2)
38
+ r.add_argument("--schema", action="store_true")
39
+ e = sub.add_parser("edit")
40
+ e.add_argument("--ops", required=True, help="JSON op or list, @file, or - for stdin")
41
+ e.add_argument("--dry-run", action="store_true")
42
+ e.add_argument("--force", action="store_true")
43
+ e.add_argument("--no-validate", action="store_true")
44
+ v = sub.add_parser("validate")
45
+ v.add_argument("--file", action="append")
46
+ v.add_argument("--module")
47
+ v.add_argument("--max", type=int, default=0, help="cap the number of diagnostics returned (0 = all)")
48
+ d = sub.add_parser("diff")
49
+ d.add_argument("a")
50
+ d.add_argument("b")
51
+ for p in (r, e, v, d): # allow --json after the subcommand too
52
+ p.add_argument("--json", action="store_true", help=argparse.SUPPRESS)
53
+ a = ap.parse_args(argv)
54
+ t0 = time.time()
55
+ try:
56
+ res = run(a)
57
+ except Exception as ex: # noqa: BLE001
58
+ res = {"ok": False, "error": f"{type(ex).__name__}: {ex}"}
59
+ res.setdefault("ok", "error" not in res)
60
+ res["engine"] = ENGINE_VERSION
61
+ res["ms"] = int((time.time() - t0) * 1000)
62
+ sys.stdout.write(json.dumps(res, ensure_ascii=False, indent=None if a.json else 1, default=str) + "\n")
63
+ return 0
64
+
65
+
66
+ def run(a) -> dict:
67
+ if a.cmd == "diff":
68
+ from .diff import diff
69
+ for x in (a.a, a.b):
70
+ if not os.path.exists(x):
71
+ return {"error": f"{x} does not exist"}
72
+ root = os.path.abspath(a.root)
73
+ rel = lambda f: os.path.relpath(f, root) if not os.path.relpath(f, root).startswith("..") else f # noqa: E731
74
+ return diff(a.a, a.b, rel)
75
+ from .model import Project
76
+ project = Project(a.root, config_files=a.config, def_files=a.defs, load_input=a.cmd in ("validate", "edit"))
77
+ if a.cmd == "info":
78
+ s = project.sources
79
+ return {"root": s.root, "origin": s.origin, "config": [project.rel(f) for f in s.config],
80
+ "paramDefs": [project.rel(f) for f in s.defs], "input": [project.rel(f) for f in s.input][:200],
81
+ "defModules": len(project.defs.modules), "modules": sorted({m.name for m in project.modules}),
82
+ "warnings": project.warnings}
83
+ if a.cmd == "read":
84
+ from .ecucjson import read
85
+ return read(project, a.path, depth=a.depth, schema=a.schema)
86
+ if a.cmd == "edit":
87
+ from .edit import edit
88
+ res = edit(project, _ops(a.ops), dry_run=a.dry_run, force=a.force, run_validate=not a.no_validate)
89
+ if project.warnings:
90
+ res["warnings"] = project.warnings
91
+ return res
92
+ if a.cmd == "validate":
93
+ from .validate import validate
94
+ res = validate(project, files=a.file, module=a.module)
95
+ if a.max and len(res["diagnostics"]) > a.max:
96
+ res["truncated"] = len(res["diagnostics"]) - a.max
97
+ res["diagnostics"] = res["diagnostics"][: a.max]
98
+ if project.warnings:
99
+ res["warnings"] = project.warnings
100
+ return res
101
+ return {"error": f"unknown command {a.cmd}"}