@h2loop/autosar 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -3
- package/agents/autosar-integrator.md +7 -9
- package/package.json +1 -1
- package/plugins/index.js +72 -55
- package/python/ecuc_engine/arxml_edit.py +55 -12
- package/python/ecuc_engine/validate.py +9 -1
- package/skills/autosar/SKILL.md +26 -17
package/README.md
CHANGED
|
@@ -9,9 +9,7 @@ Deterministic tools for AUTOSAR Classic integration work, so the agent never han
|
|
|
9
9
|
| `ecuc_validate` | multiplicity, mandatory, range, enum, type, string, ref target/dest, dangling, duplicates → LSP-like diagnostics | local |
|
|
10
10
|
| `ecuc_find` | structured queries over the ECUC (conditions, references to/from) | local |
|
|
11
11
|
| `ecuc_crosscheck` | per-module cross-check table (extract, gateway, NvM sizeof, capacity, packing, handles) | local |
|
|
12
|
-
| `
|
|
13
|
-
| `arxml_new` | create a new, empty R25-11 ARXML file (header + AR-PACKAGE tree) for `arxml_edit` to fill | local |
|
|
14
|
-
| `arxml_edit` | structured in-place edits of System extract / SWC ARXML (DEST inferred, schema-ordered, missing packages created) | local |
|
|
12
|
+
| `arxml_edit` | structured edits of System extract / SWC ARXML, incl. `new_file` (DEST inferred, schema-ordered, missing packages created) | local |
|
|
15
13
|
| `autosar_add_signal` | add a signal end to end (ECUC + extract chain + DBC), validate or roll back | local |
|
|
16
14
|
| `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
|
|
17
15
|
| `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
|
|
@@ -18,8 +18,6 @@ permission:
|
|
|
18
18
|
"ecuc_read": allow
|
|
19
19
|
"ecuc_find": allow
|
|
20
20
|
"ecuc_crosscheck": allow
|
|
21
|
-
"arxml_new": allow
|
|
22
|
-
"arxml_check": allow
|
|
23
21
|
"arxml_edit": allow
|
|
24
22
|
"autosar_add_signal": allow
|
|
25
23
|
"autosar_audit": allow
|
|
@@ -42,15 +40,15 @@ permission:
|
|
|
42
40
|
---
|
|
43
41
|
You are an AUTOSAR Classic integrator. Load the `autosar` skill first and follow it.
|
|
44
42
|
|
|
45
|
-
Every change follows the skill's ground → decide → change → verify loop:
|
|
46
|
-
|
|
47
|
-
BEFORE deciding; plan only from those facts (no guessed values, ids or reference targets); change only with the
|
|
48
|
-
structured tools; then verify (
|
|
49
|
-
every check is clean. Never report done with a failing or unrun check.
|
|
43
|
+
Every change follows the skill's ground → decide → change → verify loop: start with the context engine
|
|
44
|
+
(`autosar_build_context target=…` for configuration, `swc/runnable` for C; it includes the ingested documents), add
|
|
45
|
+
`ecuc_find` / `ecuc_crosscheck` as needed, and list each fact with its source (F#/D#) BEFORE deciding; plan only from those facts (no guessed values, ids or reference targets); change only with the
|
|
46
|
+
structured tools; then verify in two steps (1: `ecuc_validate`, generate/build/verify_rte; 2: `ecuc_validate docs=true` and
|
|
47
|
+
answer its checklist), fix and verify again until every check is clean. Never report done with a failing or unrun check.
|
|
50
48
|
|
|
51
49
|
Method (new extract / SWC / interface file):
|
|
52
|
-
- `
|
|
53
|
-
until
|
|
50
|
+
- One `arxml_edit` call: `new_file` (file + packages) first, then the add ops in dependency order; then
|
|
51
|
+
`ecuc_validate` until clean. Never write ARXML by hand, by script, or via a renamed temp file.
|
|
54
52
|
|
|
55
53
|
Method (validation / fix tasks):
|
|
56
54
|
- `ecuc_validate` unfiltered first — necessary, NOT sufficient. Never conclude "no faults" from one validate call.
|
package/package.json
CHANGED
package/plugins/index.js
CHANGED
|
@@ -1,65 +1,82 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{readFileSync as
|
|
3
|
-
`).
|
|
4
|
-
`)
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
import{readFileSync as Oe}from"fs";import{isAbsolute as Ce,join as W,resolve as je}from"path";import{tool as w}from"@kilocode/plugin";import{homedir as fe}from"os";import{join as A}from"path";var he=()=>process.env.HYDRON_TEST_HOME||fe(),U=(r,t)=>process.env[r]||A(he(),t),pe=()=>A(U("XDG_CONFIG_HOME",".config"),"hydron-cli"),ge=()=>A(U("XDG_DATA_HOME",".local/share"),"hydron-cli"),me=()=>A(U("XDG_STATE_HOME",".local/state"),"hydron-cli");async function P(r){let t=Bun.file(r);if(!await t.exists())return;return t.json().catch(()=>{return})}async function L(){let r=process.env.KILO_API_URL?.trim();if(r)return r.replace(/\/+$/,"");let t=await P(A(pe(),"server-config.json")),o=typeof t?.apiBaseUrl==="string"?t.apiBaseUrl:void 0;if(!o)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return o.replace(/\/+$/,"")}function ye(r){let t=r?.split(".")[1];if(!t)return"";try{let o=JSON.parse(Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof o.sub==="string"?o.sub:""}catch{return""}}async function be(r){let t=ye(r.access);if(t)return t;if(!r.refresh)return"";return new Bun.CryptoHasher("sha256").update(r.refresh).digest("hex").slice(0,12)}async function X(){let t=(await P(A(ge(),"auth.json")))?.hydron;if(!t||t.type!=="oauth"||!t.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return t}async function q(){let r=await X();if(typeof r.expires==="number"&&r.expires>0&&Date.now()>=r.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 r.access}async function G(r){let t=await fetch(`${await L()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await q()}`},signal:r?AbortSignal.any([r,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(t.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!t.ok)throw Error(`could not list H2Loop projects: HTTP ${t.status}`);let o=await t.json();return Array.isArray(o)?o:o?.items??[]}var V=()=>A(me(),"h2loop-project.json");async function C(r,t){let o=r===void 0||r===null?"":String(r).trim();if(/^\d+$/.test(o))return o;if(o){let n=await G(t),c=n.filter((p)=>p.name===o),l=c.length?c:n.filter((p)=>p.name?.toLowerCase()===o.toLowerCase());if(l.length===1)return String(l[0].id);if(l.length>1)throw Error(`workspace "${o}" is ambiguous: ${l.map((p)=>`${p.name} (id ${p.id})`).join(", ")}; pass the numeric id`);let f=n.filter((p)=>p.name?.toLowerCase().includes(o.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${o}"`+(f.length?`; similar: ${f.map((p)=>`${p.name} (id ${p.id})`).join(", ")}`:`; you have ${n.length} project(s)`))}let e=await P(V());if(!e)throw Error("No H2Loop project selected (run `hydron projects select <id>`), or pass workspace_id (id or name).");let s=await X();if(e.project&&typeof e.project==="object"){let n=e.project;if(typeof e.account==="string"&&e.account!==await be(s))throw Error("The selected H2Loop project belongs to another account; select one again or pass workspace_id.");if(n.id!==void 0)return String(n.id)}let a=e;if(a.id===void 0)throw Error(`${V()} holds no project id; select a project again or pass workspace_id.`);if(!(await G(t)).some((n)=>String(n.id)===String(a.id)))throw Error(`The selected project ${a.name??""} (id ${a.id}) is not accessible to the signed-in account; select another or pass workspace_id.`);return String(a.id)}async function j(r,t,o,e,s=120000){let a=`${await L()}${r}?workspace_id=${encodeURIComponent(t)}`,i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await q()}`},body:JSON.stringify(o),signal:e?AbortSignal.any([e,AbortSignal.timeout(s)]):AbortSignal.timeout(s)}),n=await i.text();if(i.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(i.status===404&&n.includes("Not Found"))throw Error(`${r} is not available on ${await L()} (backend predates the AUTOSAR endpoints).`);if(!i.ok)throw Error(`H2Loop ${r} failed: HTTP ${i.status} ${n.slice(0,800)}`);try{return JSON.parse(n)}catch(c){throw Error(`H2Loop ${r} returned non-JSON (${String(c)}): ${n.slice(0,300)}`)}}var F=/\.arxml\b/i,M="Blocked: .arxml files must not be edited by hand (it breaks DEFINITION-REF/DEST, UUIDs and the round trip). Use ecuc_edit for ECUC values, arxml_edit for System-extract/SWC elements (or autosar_add_signal for a new signal), then ecuc_validate. To start a NEW .arxml file, use arxml_edit with {op:'new_file', file, packages} followed by add ops.";function Y(r,t){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!t)return;let o=typeof t.filePath==="string"?t.filePath:typeof t.file_path==="string"?t.file_path:"";if(["edit","write","multiedit"].includes(r)){let e=Array.isArray(t.edits)?t.edits.some((s)=>typeof s?.filePath==="string"&&F.test(s.filePath)):!1;if(F.test(o)||e)return`${M} (${r} on ${o||"an .arxml file"})`;return}if(r==="apply_patch"||r==="patch"){let e=String(t.patchText??t.patch??""),s=e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??e.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return s?`${M} (${r} on ${s[1].trim()})`:void 0}if(r==="bash"){let e=String(t.command??"");if(!F.test(e))return;let s=/\b(?:sed|gsed)\b[^|;&]*\s-(?:[a-zA-Z]*i|-in-place)\b/.test(e)||/\bperl\b[^|;&]*\s-[a-zA-Z]*i/.test(e),a=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(e)||/\btee\b[^|;&]*\.arxml\b/i.test(e),i=/\b(?:mv|cp|ln|install|rsync)\b[^|;&]*\.arxml['"]?\s*(?:$|[|;&])/im.test(e)||/\b(?:os\.(?:rename|replace)|shutil\.(?:move|copy\w*)|fs\.(?:rename|copyFile)\w*|Path\([^)]*\)\.rename)\([^)]*\.arxml/i.test(e)||/\.(?:rename|replace)\(\s*['"][^'"]*\.arxml/i.test(e),n=/open\([^)]*\.arxml[^)]*,\s*(?:mode\s*=\s*)?['"][wa+]/i.test(e)||/\.arxml['"]?\s*\)?\s*\.write_(?:text|bytes)\b/i.test(e)||/write_(?:text|bytes)\([^)]*\)[^;\n]*\.arxml/i.test(e)||/\bwriteFile(?:Sync)?\([^)]*\.arxml/i.test(e)||/\.write\(\s*['"][^'"]*\.arxml/i.test(e)||/\b(?:awk|gawk)\b[^|;&]*-i\s+inplace/.test(e)||/\bed\b\s+-s\s+[^|;&]*\.arxml/.test(e);if(s||a||n||i)return`${M} (bash: ${e.slice(0,120)})`}return}var we=new Set(["autosar_build_context","ecuc_read","ecuc_find","ecuc_crosscheck","autosar_config_lookup","autosar_trace","autosar_audit","query_hydron_project","get_symbol_info"]),z=new Set(["ecuc_edit","arxml_edit","autosar_add_signal"]),Z=/\.(c|h)$/i,Q=/(^|[\\/])(Output|gen|Gen|GenData|generated)[\\/]/;var H=new Map;function N(r){let t=r??"-",o=H.get(t);if(!o)o={grounded:[],contextFor:[],changed:[],validation:"never",cFiles:[],rte:"n/a",docs:"n/a",blocks:0},H.set(t,o);return o}function ee(r){if(!r)return"";return String(r.filePath??r.file_path??"")}function te(r,t,o){if(process.env.AUTOSAR_LOOP_GATES==="0")return;let e=N(r);if(e.blocks>=2)return;if(z.has(t)&&!o?.dry_run&&e.grounded.length===0)return e.blocks++,"GROUND FIRST: no facts have been gathered in this session, so this change would be decided from memory. Before editing, get every fact the change depends on from the tools and list them with their source: autosar_build_context (target = the module/container/element, or swc+runnable) gives the project facts AND the facts from the ingested documents in one call; ecuc_read (schema=true) for what may be set; ecuc_find for what exists and references what. Then plan from those facts only and retry this edit.";let s=ee(o);if((t==="edit"||t==="write"||t==="multiedit")&&Z.test(s)&&!Q.test(s)){if(!e.grounded.includes("autosar_build_context")&&!e.grounded.includes("autosar_audit"))return e.blocks++,`GROUND FIRST: call autosar_build_context for the SW-C/runnable this C file implements (it lists the allowed RTE APIs with exact signatures, the related configuration and the relevant document facts) before changing ${s}. For C that is not runnable code, autosar_audit grounds BSW usage instead. Then retry.`}return}function ne(r,t,o,e){let s=N(r),a=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(e)||e.includes("edit rejected");if(we.has(t)&&!a){if(!s.grounded.includes(t))s.grounded.push(t);if(t==="autosar_build_context"){let n=String(o?.target??o?.runnable??o?.swc??"");if(n&&!s.contextFor.includes(n))s.contextFor.push(n)}}if(z.has(t)&&!a&&!o?.dry_run&&!/^Dry run/.test(e)){s.validation="stale",s.docs="pending";for(let n of _e(t,o,e))if(!s.changed.includes(n))s.changed.push(n)}let i=ee(o);if((t==="edit"||t==="write"||t==="multiedit")&&Z.test(i)&&!Q.test(i)&&!a){if(!s.cFiles.includes(i))s.cFiles.push(i);s.rte="pending"}if(t==="ecuc_validate"&&!a){let n=/"error":\s*[1-9]/.test(e.split(`
|
|
3
|
+
`)[0]??"")||/^\S+:\d+ error /m.test(e);if(s.validation=n?"errors":"clean",o?.docs&&s.docs==="pending"&&!/DOCUMENT CHECK UNAVAILABLE/.test(e))s.docs="done"}if(t==="autosar_verify_rte"&&!a)s.rte=/\u2014 FAILING/.test(e)?"fail":"pass"}function _e(r,t,o){let e=[];if(r==="ecuc_edit"){let s=K(t?.ops);for(let a of s){let i=String(a.path??""),n=a.param?`${i}/${a.param}`:a.container?`${i}/${a.container}`:i;e.push(a.value!==void 0?`${n} = ${JSON.stringify(a.value).slice(0,80)}`:`${n} (${a.op})`)}}else if(r==="arxml_edit"){let s=o.match(/created (\[[^\]]*\])/);if(s)try{e.push(...JSON.parse(s[1]))}catch{}for(let a of K(t?.ops))if(a.op==="set")e.push(`${a.path}/${a.element} = ${JSON.stringify(a.value)}`)}else if(r==="autosar_add_signal")e.push(`new Com signal ${t?.name} in ${t?.ipdu}`);return e.filter(Boolean)}function K(r){let t=r;for(let o=0;o<3&&typeof t==="string";o++)try{t=JSON.parse(t)}catch{return[]}if(Array.isArray(t))return t.filter((o)=>o&&typeof o==="object");if(t&&typeof t==="object")return[t];return[]}function ie(r){let t=H.get(r??"-");if(!t)return;let o=[];if(t.validation==="stale")o.push("Config/ARXML changed since the last ecuc_validate: run it (unfiltered) now.");if(t.validation==="errors")o.push("The last ecuc_validate reported errors: fix them and validate again.");if(t.rte==="pending")o.push(`C changed (${t.cFiles.slice(-5).join(", ")}): run autosar_verify_rte on it.`);if(t.rte==="fail")o.push("autosar_verify_rte is FAILING: fix the calls (or apply its arxml_edit ops) and verify again.");if(t.docs==="pending"&&t.validation==="clean")o.push(`Changed elements not yet checked against the ingested documents (${t.changed.slice(0,8).join("; ")}${t.changed.length>8?"; \u2026":""}): run ecuc_validate docs=true and answer its checklist item by item.`);if(!o.length)return;return["# AUTOSAR: open verification items (do not report the task as done until each is resolved)",...o.map((e)=>`- ${e}`)].join(`
|
|
4
|
+
`)}import{existsSync as $e}from"fs";import{dirname as Se,join as B}from"path";import{fileURLToPath as ve}from"url";var Ae="autosar-data==0.17.0";function Re(){let r=Se(ve(import.meta.url)),t=[B(r,"..","python"),B(r,"..","..","python")].find((o)=>$e(B(o,"ecuc_engine","__main__.py")));if(!t)throw Error(`ECUC engine not found next to ${r} (expected ../python/ecuc_engine)`);return t}async function ke(r){try{return await Bun.spawn([...r,"-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 x={};async function Ee(){if(x.cmd!==void 0)return x.cmd;let r=process.env.AUTOSAR_PYTHON?.trim(),o=r?[[r]]:[["uv","run","--no-project","--quiet","--with",Ae,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let e of o)if(await ke(e))return x.cmd=e,e;return x.cmd=null,null}async function y(r,t,o){let e=await Ee();if(!e)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 s=Re(),a=Bun.spawn([...e,"-m","ecuc_engine","--root",r,...t,"--json"],{cwd:r,env:{...process.env,PYTHONPATH:[s,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:o}),[i,n]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text()]);await a.exited;let c=i.trim().split(`
|
|
5
|
+
`).filter(Boolean).at(-1);if(!c)return{ok:!1,error:`engine produced no output (exit ${a.exitCode}): ${n.trim().slice(-2000)}`};try{return JSON.parse(c)}catch(l){return{ok:!1,error:`engine output was not JSON (${String(l)}): ${c.slice(0,500)} ${n.slice(-500)}`}}}var d=w.schema,Te=["# AUTOSAR pack active","Load the `autosar` skill. Config: ecuc_read/ecuc_find, not grep. Edit via ecuc_edit/arxml_edit/","autosar_add_signal (.arxml hand edits blocked), then ecuc_validate + ecuc_crosscheck per module.","C review: autosar_audit. Runnables: autosar_build_context, autosar_verify_rte, autosar_build.","Cite @path/@def/file:line/hex as tools print; req IDs only if tool/spec text shows them."].join(`
|
|
6
|
+
`);function D(r){if(typeof r!=="string")return r;let t=r.trim();if(!t.startsWith("[")&&!t.startsWith("{")&&!t.startsWith('"'))return r;try{return D(JSON.parse(t))}catch{return r}}var T=(r)=>d.preprocess(D,r);function k(r){let t=D(r);if(t===void 0||t===null||t==="")return;if(typeof t==="string")return[t];if(Array.isArray(t))return t.map(String).filter((o)=>o.trim());return[String(t)]}var E=()=>d.preprocess(k,d.array(d.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. A value's file:line is its "@at:<Param>" (the VALUE element; "@at" is`+' the container); integers come with "@hex:<Param>" \u2014 copy both, never compute a line or a base conversion'+" yourself. Cite a requirement ID only if it appears verbatim in a tool result or spec text read this session.";function I(r,t=200){let o=r.slice(0,t).map((e)=>`${e.file}:${e.line} ${e.severity.toUpperCase()} ${e.rule} ${e.path} \u2014 ${e.message}${e.defRef?` [def ${e.defRef}]`:""}`);if(r.length>t)o.push(`\u2026 ${r.length-t} more`);return o}function _(r){let t=r.didYouMean?`
|
|
7
|
+
Did you mean: ${r.didYouMean.join(", ")}`:"",o=r.schema?`
|
|
8
|
+
Schema errors: ${JSON.stringify(r.schema)}`:"";return`ERROR: ${r.error}${t}${o}`}function S(r){let t=r.warnings??[];return t.length?t.map((o)=>`WARNING: ${o}`).join(`
|
|
7
9
|
`)+`
|
|
8
|
-
`:""}function
|
|
9
|
-
`);return
|
|
10
|
-
`):r}async function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
${
|
|
14
|
-
`)
|
|
10
|
+
`:""}function b(r,t){if(!t)return r;return Ce(t)?t:je(r,t)}async function Ne(r){let t=Bun.file(W(r,".hydron","autosar.json"));if(!await t.exists())return{};return t.json().catch((o)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(o)}`)})}async function xe(r,t){let o=(await Ne(r))[t];if(typeof o==="string")return{command:o};if(o&&typeof o==="object"&&typeof o.command==="string")return o;return}function re(r,t=150){let o=r.split(`
|
|
11
|
+
`);return o.length>t?[`\u2026 (${o.length-t} earlier lines omitted)`,...o.slice(-t)].join(`
|
|
12
|
+
`):r}async function Ie(r,t,o,e){let s=process.platform==="win32"?["cmd","/d","/s","/c",r]:["sh","-c",r],a=Date.now(),i=Bun.spawn(s,{cwd:t,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([e,AbortSignal.timeout(o*1000)])}),[n,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text()]);return{code:await i.exited,out:n,err:c,secs:Math.round((Date.now()-a)/1000)}}var De=(r)=>(r??[]).map((t)=>`CAN ID ${t.canIdHex??"?"} (${t.canId??"?"}) ${t.direction} via ${t.canIfPdu}, controller ${t.controller??"?"}, network ${(t.network??[]).join(", ")||"?"}`).join("; ");async function se(r,t,o){let e=t.filter((n)=>n?.path&&/\/Com((Group)?Signal|IPdu)$/.test(String(n.definition_ref??""))&&n.ipdu===void 0&&n.direction===void 0);if(!e.length)return[];let s=await y(r,["signal-owners",...new Set(e.map((n)=>n.path))],o);if(!s.ok)return[`NOTE: owning I-PDU not computed locally (${s.error})`];let a=s.owners,i=[];for(let n of e){let c=a[n.path];if(c===null||c===void 0){i.push(`NOTE: ${n.path} is not in the local checkout (${r}); owning I-PDU/direction unknown`);continue}n.ipdu_local=c,i.push(c.length?`${n.path}: owning I-PDU ${c.map((l)=>`${l.ipdu} (ComIPduDirection=${l.direction??"?"}${l.can?.length?`; ${De(l.can)}`:""})`).join(", ")} [local ECUC]`:`${n.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return i}var Le=(r)=>{if(typeof r==="number"&&Number.isSafeInteger(r))return r;if(typeof r==="string"&&/^\s*-?(0x[0-9a-f]+|\d+)\s*$/i.test(r)){let t=r.trim(),o=t.startsWith("-")?-Number(t.slice(1)):Number(t);return Number.isSafeInteger(o)?o:null}return null},de=(r)=>r<0?`-0x${(-r).toString(16).toUpperCase()}`:`0x${r.toString(16).toUpperCase()}`;async function oe(r,t,o){let e=t.filter((n)=>typeof n?.path==="string");if(!e.length)return[];let s=await y(r,["value-sites",...new Set(e.map((n)=>n.path))],o),a=s.ok?s.sites:{},i=[];if(!s.ok)i.push(`NOTE: value lines not computed locally (${s.error})`);for(let n of e){let c=a[n.path];if(c){n.values_local=c.values,i.push(`VALUES ${n.path} (container ${c.at}) [local ECUC; cite these lines]:`);for(let[p,u]of Object.entries(c.values))for(let h of Array.isArray(u)?u:[u])i.push(` ${p} = ${JSON.stringify(h.value)}${h.hex?` (dec ${h.dec}, hex ${h.hex})`:""} @ ${h.at}`);continue}let l=n.values&&typeof n.values==="object"?n.values:{},f={};for(let[p,u]of Object.entries(l)){let h=Le(u);if(h!==null)f[p]=`dec ${h}, hex ${de(h)}`}if(Object.keys(f).length)n.values_int=f;if(s.ok)i.push(`NOTE: ${n.path} is not in the local checkout (${r}): its file:line${n.file?` ${n.file}:${n.line??"?"}`:""} is where the ELEMENT starts, not a value line. To cite a value's line, read that file; never estimate one.`)}return i}var ae=(r)=>{let t=r.notes??[],o=r.errors??[];return[...t.map((e)=>`NOTE: ${typeof e==="string"?e:JSON.stringify(e)}`),...o.map((e)=>`BACKEND ERROR: ${typeof e==="string"?e:JSON.stringify(e)}`)]};async function Ue(r,t){try{let o=await t(),e=typeof o==="string"?o:o.output;if(e&&e.trim())return o;return`${r}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(o){return`ERROR (${r}): ${o instanceof Error?o.message:String(o)}`}}function Pe(r){for(let[t,o]of Object.entries(r)){let e=o.execute;o.execute=(s,a)=>Ue(t,()=>e(s,a))}return r}function Fe(r,t=process.env){let o=new Set;for(let e of(t.AUTOSAR_DISABLE_TOOLS??"").split(/[\s,]+/))if(e)o.add(e);if(r)try{let e=JSON.parse(Oe(W(r,".hydron","autosar.json"),"utf8"));if(Array.isArray(e.disableTools)){for(let s of e.disableTools)if(typeof s==="string"&&s)o.add(s)}}catch{}return o}function Me(r,t){if(t.size===0)return r;return Object.fromEntries(Object.entries(r).filter(([o])=>!t.has(o)))}var ce=new Map;async function J(r,t,o,e){let s=`${t??"-"}|${o??""}|${r}`,a=ce.get(s);if(a)return a;let i;try{let n=await C(o,e),c=await j("/api/v1/mcp/retriever/query",n,{query:r,workspace_id:Number(n)||n},e,300000),l=(c.citations??[]).slice(0,12).map((f,p)=>{let u=f.file?`${f.file}${f.start_line?`:${f.start_line}`:""}`:`${f.doc_name??"?"}${f.title?` > ${f.title}`:""}`;return` [D${p+1}] ${u}: "${(f.excerpt??"").replace(/\s+/g," ").slice(0,280)}"`});i=c.answer?`(project ${n}; retriever answer, ${l.length} citation(s). Trust a statement only where a citation supports it.)
|
|
13
|
+
${c.answer.trim()}
|
|
14
|
+
Citations:
|
|
15
|
+
${l.join(`
|
|
16
|
+
`)||" (none)"}`:`(project ${n}: no answer${c.error_message?`: ${c.error_message}`:""})`}catch(n){return`UNAVAILABLE: ${n instanceof Error?n.message:String(n)} -- select a Hydron project with the documents ingested (hydron projects select) or pass workspace_id.`}return ce.set(s,i),i}var He=async(r)=>{let t=Fe(r?.directory),o=(e)=>w({description:e==="generate"?"Run the project's AUTOSAR code generator (e.g. the vendor's configurator CLI) as configured in .hydron/autosar.json `generate` ({command, cwd?, timeoutSec?} or a string; `{module}` and `{args}` placeholders are substituted). Run it only after ecuc_validate reports no errors. Asks the user for permission. Returns the exit code and the output tail; follow with arxml_diff/autosar_build.":"Run the project's build command as configured in .hydron/autosar.json `build` ({command, cwd?, timeoutSec?} or a string; `{module}`/`{args}` substituted). Asks the user for permission. Returns the exit code and the output tail (compiler/linker errors). Use after autosar_generate.",args:{module:d.string().optional().describe("module name substituted for {module} in the command, if used"),args:d.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(s,a){let i=b(a.directory,s.project_dir),n=await xe(i,e);if(!n)return`No \`${e}\` command configured. Add it to ${W(i,".hydron","autosar.json")}, e.g.
|
|
17
|
+
{"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let c=s.args??"",l=n.command.replaceAll("{module}",s.module??""),f=l.includes("{args}")?l.replaceAll("{args}",c):`${l}${c?` ${c}`:""}`,p=b(i,n.cwd);await a.ask({permission:`autosar_${e}`,patterns:[f],always:[n.command],metadata:{command:f,cwd:p}}),a.metadata({title:`${e}: ${f}`});let u=await Ie(f,p,n.timeoutSec??3600,a.abort),h=u.code===0?"OK":`FAILED (exit ${u.code})`;return{title:`autosar_${e} ${h}`,output:[`$ ${f} (cwd ${p}, ${u.secs}s) -> ${h}`,u.out.trim()?`--- stdout (tail) ---
|
|
18
|
+
${re(u.out)}`:"",u.err.trim()?`--- stderr (tail) ---
|
|
19
|
+
${re(u.err,80)}`:""].filter(Boolean).join(`
|
|
20
|
+
`),metadata:{exit:u.code}}}});return{"tool.execute.before":async(e,s)=>{let a=Y(e.tool,s.args);if(a)throw Error(a);let i=te(e.sessionID,e.tool,s.args);if(i)throw Error(i)},"tool.execute.after":async(e,s)=>{ne(e.sessionID,e.tool,e.args,String(s?.output??""))},"experimental.chat.system.transform":async(e,s)=>{s.system.push(Te);let a=ie(e?.sessionID);if(a)s.system.push(a)},tool:Me(Pe({ecuc_read:w({description:`THE way to answer any question about configured ECUC values (use it instead of grep/read on .arxml). Read AUTOSAR ECUC configuration as compact ECUC JSON (keyed by def names: "<DefName>:<ShortName>" for containers, params by def short-name, references as "->/path"; every container carries @path = its AUTOSAR path, @def = its DEFINITION-REF and @at = its file:line; every value is followed by "@at:<Param>" = file:line of its VALUE element, and integers by "@hex:<Param>" ("@dec:<Param>" when the ARXML text is hex)). No path: lists modules and the param-def/config files found. path may be a full AUTOSAR path, a SHORT-NAME ('DoorLatch') or a partial path ('ComConfig/DoorLatch', 'DoorLatch/ComBitPosition'); ambiguous names return candidate paths. A module/container: its values to `+"`depth` levels (merged across split files). A param path (\u2026/Container/Param) or a def path "+"(/AUTOSAR/EcucDefs/\u2026): the value and/or the definition. schema=true adds the def summary (allowed "+"params with type/range/literals/multiplicity, allowed sub-containers) \u2014 read it before ecuc_edit. "+"Never read or edit ARXML by hand."+R,args:{path:d.string().optional().describe("AUTOSAR path, SHORT-NAME or partial path of a module/container/parameter, or a def path"),depth:d.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:d.boolean().optional().describe("include the param-def summary for the element"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=["read"];if(e.path)a.push(e.path);if(a.push("--depth",String(e.depth??2)),e.schema)a.push("--schema");let i=await y(b(s.directory,e.project_dir),a,s.abort);if(!i.ok)return S(i)+_(i);let{ok:n,engine:c,ms:l,warnings:f,...p}=i;return S(i)+JSON.stringify(p,null,1)}}),ecuc_edit:w({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:T(d.array(T(d.object({op:d.enum(["set","add","remove"]),path:d.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:d.string().optional().describe("parameter/reference def short-name"),value:d.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:d.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:T(d.record(d.string(),d.any()).optional()).describe("for add: ECUC JSON of the new container")}))).min(1)).describe("list of ops (a JSON array; a JSON-encoded string is also accepted)"),dry_run:d.boolean().optional().describe("compute and show the diff without writing"),force:d.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)a.push("--dry-run");if(e.force)a.push("--force");let i=await y(b(s.directory,e.project_dir),a,s.abort);if(!i.ok){let f=i.changes??[];return S(i)+_(i)+(f.length?`
|
|
15
21
|
Rejected diff:
|
|
16
|
-
${
|
|
17
|
-
`)}`:"")}let
|
|
18
|
-
`)}}}),ecuc_validate:
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
`)}}
|
|
22
|
-
|
|
23
|
-
`)}}}),
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
`)}}}),
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
`)}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
${n.problems.join(`
|
|
33
|
-
`)}`:"")+(t.length?`
|
|
22
|
+
${f.map((p)=>p.diff).join(`
|
|
23
|
+
`)}`:"")}let n=i.changes??[],c=i.validation,l=[`${i.written?"Written":"Dry run (nothing written)"}: ${i.applied} op(s), ${n.length} file(s) changed.`,...(i.notes??[]).map((f)=>`NOTE: ${f}`),...n.map((f)=>f.diff)];if(c)l.push(c.validated?`Validation of touched files: ${JSON.stringify(c.summary)}`:"Validation skipped: no param defs loaded.",...I(c.diagnostics,50));return{title:`ecuc_edit ${n.map((f)=>f.file).join(", ")}`,output:S(i)+l.join(`
|
|
24
|
+
`)}}}),ecuc_validate:w({description:"Validate ALL ARXML of the project. ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions, plus semantic rule packs (H2L-*: Com signals inside their I-PDU and non-overlapping incl. Motorola bit order, unique handle IDs) that run even without defs. System/ECU extract, SWC and interface files: strict AUTOSAR schema load and every *-REF resolves with the right DEST (H2L-ARXML-*). Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit / arxml_edit and before "+"autosar_generate. `files` takes files, directories or globs; omit it to validate everything (preferred). The output always lists which files/modules were loaded; a filter that matches nothing is an ERROR. If it reports nothing on a project you expect to have issues, rerun unfiltered and check the loaded-file list."+R,args:{files:E().describe("only report diagnostics in these: files, directories (recursive, trailing slash optional) or globs (`**/Com*.arxml`), relative to the project root or absolute. A filter that matches no loaded file is reported as an ERROR (H2L-FILTER-NOMATCH), never as clean"),module:d.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),docs:d.boolean().optional().describe("validation step 2: after the deterministic checks, check the elements changed in this session (or `about`) against the ingested specs/manuals of the selected Hydron project; returns a checklist to answer item by item"),about:d.string().optional().describe("with docs=true: the elements/values to check when nothing was changed in this session"),workspace_id:d.union([d.string(),d.number()]).optional().describe("Hydron project for docs=true (default: the selected one)"),max:d.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:d.boolean().optional().describe("regenerate in a scratch copy and report stale generated files (H2L-GEN-001). Default: on when a generate command is configured and the configuration is < 5 MB"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=["validate"];for(let g of k(e.files)??[])i.push("--file",g);if(e.module)i.push("--module",e.module);if(e.checkGenerated===!0)i.push("--check-generated");if(e.checkGenerated===!1)i.push("--no-check-generated");let n=await y(a,i,s.abort);if(!n.ok)return S(n)+_(n);let{diagnostics:c,scope:l}=n,f=c.filter((g)=>g.rule!=="H2L-DISCOVERY"),u=l.configFiles===0&&n.scope.inputFiles?`Checked ${n.scope.inputFiles} extract/SWC file(s) (AUTOSAR schema + references): ${f.length?JSON.stringify(n.summary):"CLEAN, no findings"}`:n.validated?`Validated ${n.modules.join(", ")||"(no modules)"} against ${n.defsLoaded} module def(s): ${f.length?JSON.stringify(n.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${f.length?JSON.stringify(n.summary):"no findings"}`,h=[`Loaded ${l.configFiles} config file(s) and ${n.scope.inputFiles??0} extract/SWC file(s)`+(l.filter?`; files filter ${JSON.stringify(l.filter.files)} matched ${l.filter.matchedCount}`:"")+(l.module?`; module filter ${l.module}`:"")+":",...l.files.slice(0,30).map((g)=>` ${g.file} (${g.modules.join(", ")})`),...l.files.length>30||l.filesTruncated?[` \u2026 ${l.files.length-30+(l.filesTruncated??0)} more`]:[]],m="";if(e.docs){let g=N(s.sessionID).changed,O=e.about?.trim()||g.join("; ");if(!O)m="\n\nDOCUMENT CHECK UNAVAILABLE: nothing was changed in this session; pass `about` with the elements/values to check.";else{let v=await J(`Check these AUTOSAR configuration elements and values against the specifications and manuals in this knowledge base: ${O}. For each one, give every constraint that applies (allowed range or literals, multiplicity, dependencies on other parameters/modules, hardware limits of the target microcontroller) with the document name and section or requirement ID, and say whether the value satisfies it.`,s.sessionID,e.workspace_id,s.abort);m=v.startsWith("UNAVAILABLE")?`
|
|
25
|
+
|
|
26
|
+
DOCUMENT CHECK UNAVAILABLE: ${v}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${O}`,v,"","Answer this checklist before finishing, one line per element: `<element> = <value>: OK | VIOLATED | NOT COVERED \u2014 [D#]`.","VIOLATED \u2192 fix with ecuc_edit/arxml_edit and validate again. NOT COVERED \u2192 say so; never invent a constraint.","Check every requirement ID you cite with autosar_spec_id_check."].join(`
|
|
27
|
+
`)}}return{title:`ecuc_validate ${JSON.stringify(n.summary)}`,output:S(n)+[u,...I(c,e.max??200),...h].join(`
|
|
28
|
+
`)+m}}}),arxml_diff:w({description:"Semantic ARXML diff by AUTOSAR path between two files or directories (e.g. a git checkout of the old Config/ vs the current one, or Output/ before/after generation inputs). Ignores UUIDs, whitespace, comments, element order and file splits; ECUC values are compared per parameter. Returns added/removed/changed elements with the changed parameter values. Use it to review edits and PRs instead of a textual diff.",args:{a:d.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:d.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=await y(a,["diff",e.a,e.b],s.abort);if(!i.ok)return _(i);let{ok:n,engine:c,ms:l,...f}=i;return JSON.stringify(f,null,1)}}),autosar_trace:w({description:"Trace AUTOSAR configuration to code through the H2Loop code graph of the selected project: query with an AUTOSAR path, a SHORT-NAME, or a C symbol (reverse lookup). Returns the ARXML element (path, module, DEFINITION-REF, file:line, values), the C symbols it configures (generated macros/const tables via the symbolic-name rule or token/value matching, with method + score) and their callers in in-house code. For a ComSignal it also shows the owning I-PDU and its ComIPduDirection (direction lives on the I-PDU). Elements in the local checkout get a VALUES block: each value with the file:line of its VALUE element and integers in dec + hex (the graph's file:line is only where the element starts). Use for impact analysis ('what code changes if I change X?') and 'where does this symbol come from?'. Requires the project's code to be ingested."+R,args:{query:d.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:d.number().int().optional().describe("restrict to one code data source"),limit:d.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:d.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,s){let a=await C(e.workspace_id,s.abort),i={query:e.query};if(e.data_source_id!==void 0)i.data_source_id=e.data_source_id;if(e.limit!==void 0)i.limit=e.limit;let n=await j("/api/v1/mcp/autosar/trace",a,i,s.abort),c=n.matches??[],l=b(s.directory,e.project_dir),f=c.map((m)=>m.arxml).filter((m)=>!!m),[p,u]=await Promise.all([se(l,f,s.abort),oe(l,f,s.abort)]),h=[`${c.length} match(es) for "${e.query}" in workspace ${a}`+(n.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(n.data_sources_queried)})`:""),...ae(n),...p,...u,JSON.stringify(c,null,1)];if(!c.length)h.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:h.join(`
|
|
29
|
+
`)}}}),autosar_config_lookup:w({description:"Look up one ARXML element in the H2Loop code graph by AUTOSAR path: the element (module, DEFINITION-REF, file:line, values), its direct children, references out and in (who points at it), and linked C symbols. Elements in the local checkout get a VALUES block with each value's VALUE-element file:line and integers in dec + hex. Use it to navigate config relations across the ingested repo (including files not in the local checkout); for local edits use ecuc_read/ecuc_edit."+R,args:{path:d.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:d.number().int().optional().describe("restrict to one code data source"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:d.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,s){let a=await C(e.workspace_id,s.abort),i={path:e.path};if(e.data_source_id!==void 0)i.data_source_id=e.data_source_id;let n=await j("/api/v1/mcp/autosar/config-lookup",a,i,s.abort),c=n.matches??[],l=b(s.directory,e.project_dir),f=c.map((h)=>h.element).filter((h)=>!!h),[p,u]=await Promise.all([se(l,f,s.abort),oe(l,f,s.abort)]);return{title:`autosar_config_lookup ${e.path}`,output:[`${c.length} match(es) for ${e.path} in workspace ${a}`,...ae(n),...p,...u,JSON.stringify(c,null,1)].join(`
|
|
30
|
+
`)}}}),ecuc_find:w({description:"Structured query over the ECUC configuration \u2014 use it instead of grep/read on ARXML. Filter containers by "+`module, container_def (def short-name, e.g. PduRRoutingPath, ComSignal, NvMBlockDescriptor), where ("ComIPduDirection=SEND, ComBitSize>8"; =, !=, >, <, >=, <=, ~regex), ref_to (containers that reference this path directly or through up to 2 references, e.g. all routing paths whose destination is an EcuC Pdu), and referenced_by (e.g. all ComSignals referenced by I-PDU Y). Returns AUTOSAR paths, the container's file:line (at) and its values, each with "@at:<Param>" (file:line of the VALUE element) and, for integers, "@hex:<Param>".`+R,args:{module:d.string().optional(),container_def:d.string().optional().describe("container definition short-name"),where:d.union([d.string(),d.record(d.string(),d.any())]).optional().describe("conditions on parameter values"),ref_to:d.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:d.string().optional().describe("container whose references define the result set"),limit:d.number().int().min(1).max(500).optional(),project_dir:d.string().optional()},async execute(e,s){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 i=await y(b(s.directory,e.project_dir),a,s.abort);if(!i.ok)return S(i)+_(i);let{ok:n,engine:c,ms:l,warnings:f,...p}=i;return S(i)+JSON.stringify(p,null,1)}}),autosar_spec_id_check:w({description:"Check AUTOSAR requirement IDs (SWS_/SRS_/TPS_/ECUC_/RS_ \u2026, e.g. SWS_Com_00197, 'SWS_NvM_00898/00899') "+"against the project's own AUTOSAR spec texts (.hydron/autosar.json `specDocs` globs of .txt/.md exports, or $AUTOSAR_SPEC_DOCS). Returns per ID: DEFINED (with document, line and the requirement text), MENTIONED-ONLY (occurs only in trace tables / running text), NOT-FOUND or MALFORMED. Run it BEFORE citing any ID that did not come verbatim from a tool result; never cite an ID it does not report DEFINED, and describe the rule with the returned text, not from memory.",args:{ids:E().describe("requirement IDs to check (a list, a JSON-encoded list, or one ID)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=k(e.ids)??[];if(!a.length)return'ERROR: pass ids, e.g. ["SWS_Com_00197"]';let i=await y(b(s.directory,e.project_dir),["spec-ids",...a],s.abort);if(!i.ok)return _(i);let n=i.results;return{title:`autosar_spec_id_check ${JSON.stringify(i.counts)}`,output:[`Checked ${n.length} ID(s) against ${i.docs} spec text file(s) (${i.docsOrigin}; ${i.indexedIds} IDs indexed): ${JSON.stringify(i.counts)}`,...n.map((c)=>`${c.id} ${c.status}`+(c.doc?` \u2014 ${c.doc}:${c.line}`:"")+(c.didYouMean?` (did you mean ${c.didYouMean}?)`:"")+(c.text?`
|
|
31
|
+
${c.text}`:"")),n.some((c)=>c.status!=="DEFINED")?"Do not cite IDs that are not DEFINED; state the rule without an ID instead.":""].filter(Boolean).join(`
|
|
32
|
+
`)}}}),ecuc_crosscheck:w({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:d.string().describe("module name, e.g. PduR"),project_dir:d.string().optional()},async execute(e,s){let a=await y(b(s.directory,e.project_dir),["crosscheck",e.module],s.abort);if(!a.ok)return S(a)+_(a);let i=a.rows,n=a.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${a.summary}`,output:[`${e.module}: ${a.summary} (element kinds: ${a.elementKinds.join(", ")||"none"})`,...i.map((c)=>`${c.element} (${c.at})
|
|
33
|
+
${c.findings.join(`
|
|
34
|
+
`)}`),...I(n,50),...(a.notes??[]).map((c)=>`NOTE: ${c}`)].join(`
|
|
35
|
+
`)}}}),arxml_edit:w({description:"Structured edit of NON-ECUC ARXML (System/ECU extract, SWC, interfaces), including NEW files \u2014 never write "+"that XML by hand. Ops: {op:'new_file', file:'Input/SWC_X.arxml', packages:['/Swcs','/Interfaces']} (empty R25-11 file; later ops in the same call can fill it), {op:'add', parent_path, element:'I-SIGNAL', short_name, values:{TAG: value | '->/ref/path' | {nested} | [list]}}, {op:'set', path, element:'START-POSITION', value}, {op:'remove', path}. Missing packages along parent_path are created (top level needs `file` when the project has several ARXML files). Every *-REF gets its DEST from the referenced element's real tag (targets must exist or be added earlier in the same call), elements are placed and ordered per the AUTOSAR schema, references are re-checked and the file is strictly re-loaded; nothing is written if anything fails. For ECUC values use ecuc_edit; to add a whole signal use autosar_add_signal.",args:{ops:T(d.array(T(d.record(d.string(),d.any()))).min(1)).describe("list of ops"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,s){let a=["arxml-edit","--ops",JSON.stringify(D(e.ops))];if(e.dry_run)a.push("--dry-run");let i=await y(b(s.directory,e.project_dir),a,s.abort),n=i.changes??[];if(!i.ok)return _(i)+(i.problems?.length?`
|
|
36
|
+
${i.problems.join(`
|
|
37
|
+
`)}`:"")+(n.length?`
|
|
34
38
|
Rejected diff:
|
|
35
|
-
${
|
|
36
|
-
`)}`:"");let
|
|
37
|
-
NOTE: ${
|
|
39
|
+
${n.map((f)=>f.diff).join(`
|
|
40
|
+
`)}`:"");let c=i.notes??[],l=i.createdPackages??[];return`${i.written?"Written":"Dry run"}; `+((i.newFiles??[]).length?`new file(s) ${i.newFiles.join(", ")}; `:"")+`created ${JSON.stringify(i.created)}`+(l.length?`; new packages ${l.join(", ")}`:"")+(c.length?`
|
|
41
|
+
NOTE: ${c.join(`
|
|
38
42
|
NOTE: `)}`:"")+`
|
|
39
|
-
${
|
|
43
|
+
${n.map((f)=>f.diff).join(`
|
|
40
44
|
`)}
|
|
41
|
-
Next:
|
|
42
|
-
${
|
|
43
|
-
`)}`:"");let{ok:
|
|
44
|
-
${
|
|
45
|
-
evidence: ${JSON.stringify(
|
|
46
|
-
spec: ${
|
|
47
|
-
fix: ${
|
|
48
|
-
`)}}}),autosar_verify_rte:
|
|
49
|
-
`),metadata:{counts:l}}}}),autosar_build_context:
|
|
50
|
-
|
|
45
|
+
Next: ecuc_validate (checks extract/SWC files too).`}}),autosar_add_signal:w({description:"Add one Com signal end to end, consistently: ComSignal (ComHandleId = lowest unused; existing handles never move) + ComIPduSignalRef in the ECUC, SYSTEM-SIGNAL / I-SIGNAL / I-SIGNAL-TO-I-PDU-MAPPING and the rest of the signal chain (triggering, port, extract references) in the System extract, and the DBC SG_ line when a .dbc carries the frame. Everything is derived by following references from an existing signal of the same I-PDU. It refuses on overlap or out-of-bounds bits, picks the first free byte-aligned position when bit_position is omitted, runs ecuc_validate after writing and rolls back on any new finding. Then run autosar_generate, use ComConf_ComSignal_<name> in the C code, and autosar_build.",args:{name:d.string(),ipdu:d.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:d.number().int().min(1).max(64).optional(),type:d.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:d.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:d.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:d.union([d.number(),d.string()]).optional(),transfer_property:d.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:d.boolean().optional(),project_dir:d.string().optional()},async execute(e,s){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 i=await y(b(s.directory,e.project_dir),a,s.abort);if(!i.ok)return _(i)+(i.diagnostics?.length?`
|
|
46
|
+
${I(i.diagnostics,20).join(`
|
|
47
|
+
`)}`:"");let{ok:n,engine:c,ms:l,...f}=i;return JSON.stringify(f,null,1)}}),autosar_audit:w({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:E().describe("C files, directories or globs to scan (default: .hydron/autosar.json audit paths, else every .c under the project except generator output); matching nothing is an ERROR"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=await y(a,["audit",...k(e.paths)??[]],s.abort);if(!i.ok)return S(i)+_(i);let n=(i.notes??[]).map((h)=>`NOTE: ${h}`),{findings:c,unchecked:l,scanned:f}=i,p=[`Scanned ${f.sources.length} C file(s), ${f.calls} BSW call(s): ${c.length?JSON.stringify(i.summary):"no findings"}`,...c.map((h)=>`${h.file}:${h.line} ${h.severity.toUpperCase()} ${h.rule} ${h.call}
|
|
48
|
+
${h.message}
|
|
49
|
+
evidence: ${JSON.stringify(h.evidence)}
|
|
50
|
+
spec: ${h.cite}${h.fix?`
|
|
51
|
+
fix: ${h.fix}`:""}`)];if(l.length)p.push(`Unchecked (${l.length}):`,...l.slice(0,50).map((h)=>` ${h.file}:${h.line} ${h.call} \u2014 ${h.reason}`));let u=i.unreferenced??{};for(let[h,m]of Object.entries(u))p.push(`INFO configured but never referenced in the scanned code \u2014 ${h}: ${m.count} (e.g. ${m.sample.slice(0,5).join(", ")})`);return p.push(...n),{title:`autosar_audit ${JSON.stringify(i.summary)}`,output:S(i)+p.join(`
|
|
52
|
+
`)}}}),autosar_verify_rte:w({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:E().describe("C files, directories or globs (default: all in-house C)"),diff_against:d.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:d.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:d.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=["verify-rte",...k(e.paths)??[]];if(e.diff_against)i.push("--diff-against",e.diff_against);if(e.swc)i.push("--swc",e.swc);if(e.runnable)i.push("--runnable",e.runnable);let n=await y(a,i,s.abort);if(!n.ok)return _(n);let{findings:c,counts:l}=n,f=c.filter((g)=>g.status!=="OK"),p=n.scanned,u=[`Verified ${p.calls} Rte_* call(s) in ${p.files.length} file(s) against SW-C(s) ${n.swcs.join(", ")}: OK ${l.OK}, NOT-ALLOWED ${l["NOT-ALLOWED"]}, INVENTED ${l.INVENTED}`+(f.length?" \u2014 FAILING":" \u2014 PASS")];for(let g of f){if(u.push(`${g.at} ${g.status} ${g.call} in ${g.function}() [${g.swc??"?"}${g.runnable?`/${g.runnable}`:""}]`,` ${g.why}`),g.expected)u.push(` expected: ${g.expected} [${g.cite}]`);if(g.hint)u.push(` hint: ${g.hint}`);if(g.arxml_edit?.length)u.push(` fix (arxml_edit ops${g.opsChecked===!0?", dry-run OK":g.opsChecked?`, dry-run FAILED: ${g.opsChecked}`:""}): ${JSON.stringify(g.arxml_edit)}`)}let h=n.notChecked??[];if(h.length)u.push(`Not checked (${h.length}): ${h.map((g)=>`${g.call} @ ${g.at}`).join(", ")}`);let m=n.runnablesWithoutCode??[];if(m.length)u.push(`Runnables without a C definition: ${m.map((g)=>`${g.swc}.${g.runnable} (${g.symbol})`).join(", ")}`);for(let g of n.notes??[])u.push(`NOTE: ${g}`);if(f.length)u.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 ${f.length?"FAIL":"PASS"} ${JSON.stringify(l)}`,output:u.join(`
|
|
53
|
+
`),metadata:{counts:l}}}}),autosar_build_context:w({description:"GROUND step: call this FIRST for any change. Two modes. (1) target=<module, container or element> for a configuration change (e.g. an MCAL Can/Fls/Port change): the element's current values with file:line and its param-def schema (allowed params, types, ranges, literals, multiplicity), plus the constraints the ingested specs/manuals give for it. (2) swc(+runnable) for C: assemble the context for implementing or changing a runnable, deterministically (same inputs -> byte-identical text) in a fixed order: 1 task, 2 SW-C definition (ports, interfaces, types, runnables, events), 3 ALLOWED RTE API for the runnable with the exact declarations from Rte_<Swc>.h (else SWS_RTE signatures), 4 the runnable's current C body, 5 functions it calls, 6 related config (Com signals / NvM blocks behind its ports), 7 FUZZY similar functions in other SW-Cs, 8 FUZZY similar past git changes (ARXML delta + C hunks). Fits budget_tokens (~4 chars/token) by dropping 8, 7, then shortening bodies; never the allowed API. Returns the text plus a JSON manifest of every source included. Call it FIRST for any runnable task and use only the allowed APIs it lists. Both modes append DOC FACTS from the selected Hydron project's ingested documents (docs=false skips; the retriever can take minutes, results are cached per session). Plan only from these facts and cite them (F#/D#); a fact you could not ground is an open question, not a guess.",args:{swc:d.string().optional().describe("SW-C short name or AUTOSAR path (runnable/C mode)"),target:d.string().optional().describe("configuration mode: module, container or element (AUTOSAR path, SHORT-NAME or partial path), e.g. 'Can', 'CanController_0'"),docs:d.boolean().optional().describe("add DOC FACTS from the ingested documents (default true)"),runnable:d.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:d.string().describe("the task, verbatim"),budget_tokens:d.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:d.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:d.union([d.string(),d.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=e.docs!==!1;if(!e.swc){if(!e.target)return"ERROR: give target (configuration change) or swc (+runnable, for C code).";let u=await y(a,["read",e.target,"--depth","3","--schema"],s.abort);if(!u.ok)return _(u);let{ok:h,engine:m,ms:g,...O}=u,v=JSON.stringify(O,null,1).split(`
|
|
54
|
+
`),le=v.length>400?`${v.slice(0,400).join(`
|
|
55
|
+
`)}
|
|
56
|
+
\u2026 (${v.length-400} more lines: narrow the target)`:v.join(`
|
|
57
|
+
`),ue=i?await J(`For this AUTOSAR configuration task: "${e.task}". The element concerned is ${e.target}. From the specifications and manuals in this knowledge base, list every constraint, default, allowed range or literal, multiplicity, dependency on other parameters or modules, and hardware limit of the target microcontroller that applies to it and to what the task changes, each with the document name and section or requirement ID.`,s.sessionID,e.workspace_id,s.abort):"(skipped: docs=false)";return{title:`autosar_build_context target ${e.target}`,output:["# CONTEXT (configuration change)",`## 1. TASK
|
|
58
|
+
${e.task}`,`## 2. PROJECT FACTS [F]: current values with @at file:line, and the param-def schema (what may be set)
|
|
59
|
+
${le}`,`## 3. DOC FACTS [D]: from the ingested documents
|
|
60
|
+
${ue}`,`## 4. NEXT
|
|
61
|
+
Write the facts you will rely on as a numbered list (F1.. from section 2 with their @at, D1.. from section 3 with their citation). Plan the change from those facts only, in dependency order, citing them. Anything you could not ground: look it up (ecuc_find, ecuc_read, autosar_config_lookup) or ask; never guess a value, id or reference target. Then edit (ecuc_edit / arxml_edit), ecuc_validate until clean, then ecuc_validate docs=true and answer its checklist.`].join(`
|
|
62
|
+
|
|
63
|
+
`)}}let 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 c=await y(a,n,s.abort);if(!c.ok)return _(c);let l=c.text,f=c.codeMissing??[];if(f.length&&e.use_backend){let u=[];try{let h=await C(e.workspace_id,s.abort);for(let m of f){let g=await j("/api/v1/mcp/autosar/trace",h,{query:m,limit:3},s.abort);u.push(`### backend trace for ${m} (workspace ${h})
|
|
64
|
+
${JSON.stringify(g.matches??[],null,1).slice(0,6000)}`)}}catch(h){u.push(`(backend lookup unavailable: ${h instanceof Error?h.message:String(h)})`)}l+=`
|
|
51
65
|
## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
|
|
52
|
-
${
|
|
66
|
+
${u.join(`
|
|
53
67
|
`)}
|
|
54
|
-
`}let
|
|
68
|
+
`}if(i){let u=await J(`For this AUTOSAR task: "${e.task}" in SW-C ${e.swc}${e.runnable?`, runnable ${e.runnable}`:""}. From the specifications and manuals in this knowledge base, list the requirements and constraints that apply (RTE API semantics, timing, data handling, BSW service usage), each with the document name and section or requirement ID.`,s.sessionID,e.workspace_id,s.abort);l+=`
|
|
69
|
+
## 9. DOC FACTS [D] from the ingested documents (not part of the deterministic context)
|
|
70
|
+
${u}
|
|
71
|
+
`}let p={swc:c.swc,runnables:c.runnables,estimatedTokens:c.estimatedTokens,budgetTokens:c.budgetTokens,reductions:c.reductions,overBudget:c.overBudget??!1,sha1:c.sha1,sections:c.sections,sources:c.manifest};return{title:`autosar_build_context ${c.swc}${c.runnables.length===1?`/${c.runnables[0]}`:""} ~${c.estimatedTokens} tok`,output:`${l}
|
|
55
72
|
---
|
|
56
|
-
MANIFEST ${JSON.stringify(
|
|
57
|
-
${
|
|
58
|
-
`)}`:"")}let{modules:
|
|
59
|
-
NOTE: ${
|
|
60
|
-
`+l.assigned.slice(0,40).map((
|
|
73
|
+
MANIFEST ${JSON.stringify(p)}`,metadata:{sha1:c.sha1,estimatedTokens:c.estimatedTokens}}}}),autosar_codegen:w({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:E().describe("modules to generate (default: every supported module that is configured)"),out_dir:d.string().optional().describe("output dir, relative to the project or absolute; 'project' = codegen.outDir / Output. Default: scratch .hydron/codegen/out"),write_back:d.boolean().optional().describe("write assigned handle IDs into the ECUC ARXML (default true)"),binding:d.string().optional().describe("force a static-code binding (e.g. 'sip-standin'), or 'none' for generic tables only"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=["codegen"];for(let u of k(e.modules)??[])i.push("--module",u);if(e.out_dir)i.push("--out",e.out_dir);if(e.write_back===!1)i.push("--no-write-back");if(e.binding)i.push("--binding",e.binding);let n=await y(a,i,s.abort);if(!n.ok){let u=n.handleErrors??[];return S(n)+_(n)+(u.length?`
|
|
74
|
+
${u.map((h)=>` ${h}`).join(`
|
|
75
|
+
`)}`:"")}let{modules:c,handles:l,timings:f}=n,p=[`Generated ${Object.keys(c).length} module(s) into ${n.outDir} in ${f.total_ms} ms (AUTOSAR R${n.release}):`,...Object.entries(c).map(([u,h])=>` ${u} (${h.variant}${h.binding?`, binding ${h.binding}`:", generic tables"}): ${h.files.join(", ")}; ${h.symbols} symbol(s)`+h.notes.map((m)=>`
|
|
76
|
+
NOTE: ${m}`).join("")),l.assigned.length?`Assigned ${l.assigned.length} handle ID(s) (${l.writtenBack?"written back into the ECUC ARXML":"in memory only, NOT written back"}):
|
|
77
|
+
`+l.assigned.slice(0,40).map((u)=>` ${u.path}/${u.param} = ${u.value} (hex ${de(u.value)})`).join(`
|
|
61
78
|
`)+(l.changes.length?`
|
|
62
|
-
${l.changes.map((
|
|
63
|
-
`)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(
|
|
64
|
-
`)}}}),autosar_codegen_diff:
|
|
65
|
-
`)}}}),autosar_generate:
|
|
79
|
+
${l.changes.map((u)=>u.diff).join(`
|
|
80
|
+
`)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(n.notes??[]).map((u)=>`NOTE: ${u}`)];return{title:`autosar_codegen ${Object.keys(c).join(", ")}`,output:S(n)+p.join(`
|
|
81
|
+
`)}}}),autosar_codegen_diff:w({description:"Semantic diff of generated C configuration code against a reference dir (e.g. the vendor-generated Output/): compares #define names and values and the contents of every initialised table/struct element by element, plus table ordering, after normalising numbers (0x2A0u == 672), casts, parentheses and macro references. Ignores formatting, comments, banners and include order. Reports per module: matching symbols, missing (in reference only), extra (generated only), value mismatches with both values.",args:{reference_dir:d.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:d.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:E().describe("only these modules"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),i=["codegen-diff",e.reference_dir];if(e.generated_dir)i.push(e.generated_dir);for(let f of k(e.modules)??[])i.push("--module",f);let n=await y(a,i,s.abort);if(!n.ok)return _(n);let c=n.modules,l=[`Semantic diff ${n.reference} (reference) vs ${n.generated} (generated): ${JSON.stringify(n.total)}`,`Not generated (reference only): ${n.notGenerated.join(", ")||"-"}; not in reference: ${n.notInReference.join(", ")||"-"}`];for(let[f,p]of Object.entries(c)){if(l.push(`== ${f}: ${p.summary.matching} matching, ${p.summary.missing} missing, ${p.summary.extra} extra, ${p.summary.mismatches} mismatch(es); table elements ${p.elements.match} equal / ${p.elements.mismatch} different`),p.defines.missing.length)l.push(` missing #define: ${p.defines.missing.slice(0,30).join(", ")}`);for(let u of p.defines.mismatch.slice(0,30))l.push(` #define ${u.name}: reference ${u.reference} | generated ${u.generated}`);if(p.objects.missing.length)l.push(` missing object: ${p.objects.missing.join(", ")}`);if(p.objects.extra.length)l.push(` extra object: ${p.objects.extra.join(", ")}`);for(let u of p.objects.order)l.push(` order differs: ${u.name} (same rows)`);for(let u of p.objects.mismatch)l.push(` ${u.name}: ${u.count} element(s) differ`,...u.elements.slice(0,12).map((h)=>` ${h.element}: reference ${h.reference} | generated ${h.generated}`));if(p.defines.extra.length)l.push(` extra #define (${p.defines.extra.length}): ${p.defines.extra.slice(0,12).join(", ")}${p.defines.extra.length>12?", \u2026":""}`)}return{title:`autosar_codegen_diff ${JSON.stringify(n.total)}`,output:l.join(`
|
|
82
|
+
`)}}}),autosar_generate:o("generate"),autosar_build:o("build")}),t)}},Be=He;export{Be as Autosar};
|
|
@@ -6,6 +6,7 @@ Ops (paths are AUTOSAR paths of identifiables; tags are XML element names):
|
|
|
6
6
|
"INIT-VALUE": {"NUMERICAL-VALUE-SPECIFICATION": {"VALUE": 0}}}}
|
|
7
7
|
{"op": "set", "path": "/Communication/Pdus/P/X", "element": "START-POSITION", "value": 40}
|
|
8
8
|
{"op": "remove", "path": "/Communication/ISignals/X"}
|
|
9
|
+
{"op": "new_file", "file": "Input/SWC_X.arxml", "packages": ["/Swcs", "/Interfaces"]} # then add into it
|
|
9
10
|
|
|
10
11
|
- A parent_path that does not exist yet is created as AR-PACKAGEs below its deepest existing package (or at the
|
|
11
12
|
top level of ``file``, or of the only non-ECUC ARXML file), so a new file from arxml_new can be filled
|
|
@@ -100,6 +101,7 @@ class ArxmlEditor:
|
|
|
100
101
|
self.original: dict = {}
|
|
101
102
|
self.added_tags: dict = {} # path -> tag of elements added in this call
|
|
102
103
|
self.created_packages: list = []
|
|
104
|
+
self.new_files: list = []
|
|
103
105
|
|
|
104
106
|
# ---------- files / lookup ----------
|
|
105
107
|
def tree_for(self, path: str) -> tuple:
|
|
@@ -123,7 +125,10 @@ class ArxmlEditor:
|
|
|
123
125
|
def root_of(self, file: Optional[str]) -> tuple:
|
|
124
126
|
"""(FileTree, AUTOSAR root node) for a top-level package: ``file`` or the only non-ECUC ARXML."""
|
|
125
127
|
if file:
|
|
126
|
-
|
|
128
|
+
nf = os.path.normpath(os.path.join(self.p.root, file))
|
|
129
|
+
if nf in self.files:
|
|
130
|
+
return self.files[nf], self.files[nf].root
|
|
131
|
+
f = os.path.realpath(nf)
|
|
127
132
|
known = [os.path.realpath(x) for x in self.p.sources.input + self.p.sources.config]
|
|
128
133
|
if f not in known:
|
|
129
134
|
raise ArxmlEditError(f"file {file!r} is not an ARXML file of this project (create it with arxml_new)")
|
|
@@ -327,6 +332,31 @@ class ArxmlEditor:
|
|
|
327
332
|
stack.extend(c.children)
|
|
328
333
|
return None
|
|
329
334
|
|
|
335
|
+
def op_new_file(self, op: dict):
|
|
336
|
+
from .arxml_new import _schema, render
|
|
337
|
+
file, packages = op.get("file"), op.get("packages")
|
|
338
|
+
if isinstance(packages, str):
|
|
339
|
+
packages = [packages]
|
|
340
|
+
if not file or not str(file).lower().endswith(".arxml"):
|
|
341
|
+
raise ArxmlEditError("new_file needs file (project-relative, ending in .arxml) and packages, e.g. "
|
|
342
|
+
'{"op": "new_file", "file": "Input/SWC_X.arxml", "packages": ["/Swcs", "/Interfaces"]}')
|
|
343
|
+
if not packages:
|
|
344
|
+
raise ArxmlEditError("new_file needs at least one package path (an ARXML file needs an AR-PACKAGE)")
|
|
345
|
+
path = os.path.normpath(os.path.join(self.p.root, str(file)))
|
|
346
|
+
real_root = os.path.realpath(self.p.root)
|
|
347
|
+
if os.path.commonpath([real_root, os.path.realpath(path)]) != real_root:
|
|
348
|
+
raise ArxmlEditError(f"{file} is outside the project directory")
|
|
349
|
+
if os.path.exists(path) or path in self.files:
|
|
350
|
+
raise ArxmlEditError(f"{self.p.rel(path)} already exists; add to it instead of creating it")
|
|
351
|
+
try:
|
|
352
|
+
data = render(packages, _schema(op.get("schema"))).encode("utf-8")
|
|
353
|
+
except ValueError as e:
|
|
354
|
+
raise ArxmlEditError(str(e)) from None
|
|
355
|
+
self.original[path] = b""
|
|
356
|
+
self.files[path] = FileTree(path, data)
|
|
357
|
+
self.new_files.append(path)
|
|
358
|
+
return self.p.rel(path)
|
|
359
|
+
|
|
330
360
|
def op_set(self, op: dict):
|
|
331
361
|
path, tag = op.get("path"), op.get("element")
|
|
332
362
|
if not path or not tag or "value" not in op:
|
|
@@ -389,7 +419,7 @@ class ArxmlEditor:
|
|
|
389
419
|
elif dest and hit[0] != dest:
|
|
390
420
|
problems.append(f"{self.p.rel(f)}:{n.line} {n.tag} DEST={dest} but {tgt} is a {hit[0]}")
|
|
391
421
|
from .edit import schema_check
|
|
392
|
-
if schema_check(f, self.original[f]) is None:
|
|
422
|
+
if f in self.new_files or schema_check(f, self.original[f]) is None:
|
|
393
423
|
err = schema_check(f, ft.data)
|
|
394
424
|
if err:
|
|
395
425
|
problems.append(f"{self.p.rel(f)}: schema: {err}")
|
|
@@ -463,10 +493,12 @@ def arxml_edit(project: Project, ops, dry_run: bool = False) -> dict:
|
|
|
463
493
|
ed.op_set(op)
|
|
464
494
|
elif kind == "remove":
|
|
465
495
|
ed.op_remove(op)
|
|
496
|
+
elif kind == "new_file":
|
|
497
|
+
ed.op_new_file(op)
|
|
466
498
|
else:
|
|
467
|
-
raise ArxmlEditError(f"unknown op {kind!r} (add/set/remove)")
|
|
499
|
+
raise ArxmlEditError(f"unknown op {kind!r} (new_file/add/set/remove)")
|
|
468
500
|
except ArxmlEditError as e:
|
|
469
|
-
raise ArxmlEditError(f"op {i} ({kind} {op.get('path') or op.get('parent_path')}): {e}") from None
|
|
501
|
+
raise ArxmlEditError(f"op {i} ({kind} {op.get('path') or op.get('parent_path') or op.get('file')}): {e}") from None
|
|
470
502
|
except ArxmlEditError as e:
|
|
471
503
|
return {"ok": False, "error": str(e), "written": False, "notes": notes}
|
|
472
504
|
problems = ed.check()
|
|
@@ -483,11 +515,13 @@ def arxml_edit(project: Project, ops, dry_run: bool = False) -> dict:
|
|
|
483
515
|
if not dry_run:
|
|
484
516
|
for f, ft in ed.files.items():
|
|
485
517
|
if ft.data != ed.original[f]:
|
|
518
|
+
os.makedirs(os.path.dirname(f), exist_ok=True)
|
|
486
519
|
tmp = f + ".arxml-tmp"
|
|
487
520
|
with open(tmp, "wb") as fh:
|
|
488
521
|
fh.write(ft.data)
|
|
489
522
|
os.replace(tmp, f)
|
|
490
523
|
return {"ok": True, "written": not dry_run, "created": [c for c in created if c],
|
|
524
|
+
"newFiles": [project.rel(f) for f in ed.new_files],
|
|
491
525
|
"createdPackages": ed.created_packages, "notes": notes, "changes": changes,
|
|
492
526
|
"schemaChecked": _ad() is not None}
|
|
493
527
|
|
|
@@ -518,26 +552,35 @@ def arxml_check(project: Project, files: Optional[list] = None) -> dict:
|
|
|
518
552
|
if isinstance(ft, FileTree):
|
|
519
553
|
for p, n in ft.by_path.items():
|
|
520
554
|
known.setdefault(p, n.tag)
|
|
521
|
-
|
|
555
|
+
items, refs = [], 0
|
|
556
|
+
|
|
557
|
+
def bad(rel, line, rule, path, msg):
|
|
558
|
+
items.append({"file": rel, "line": line, "path": path, "rule": rule, "severity": "error", "message": msg,
|
|
559
|
+
"defRef": None})
|
|
560
|
+
|
|
522
561
|
for f in srcs:
|
|
523
562
|
ft = trees[f]
|
|
524
563
|
rel = project.rel(f)
|
|
525
564
|
if not isinstance(ft, FileTree):
|
|
526
|
-
|
|
565
|
+
bad(rel, 0, "H2L-ARXML-XML", "", f"not well-formed XML: {ft}")
|
|
527
566
|
continue
|
|
528
567
|
err = schema_check(f, ft.data)
|
|
529
568
|
if err:
|
|
530
|
-
|
|
569
|
+
m = re.search(r":(\d+):", err)
|
|
570
|
+
# the line goes in its own field; keep the message line-free so a finding that only moved is not "new"
|
|
571
|
+
bad(rel, int(m.group(1)) if m else 0, "H2L-ARXML-SCHEMA", "",
|
|
572
|
+
"AUTOSAR schema: " + re.sub(r"^Failed to parse [^:]*:\d+: ", "", err))
|
|
531
573
|
for n in ft.root.iter():
|
|
532
574
|
if not (n.tag.endswith("-REF") or n.tag.endswith("-TREF")) or n.children:
|
|
533
575
|
continue
|
|
534
576
|
refs += 1
|
|
535
577
|
tgt, dest = n.text.strip(), n.attrs.get("DEST")
|
|
536
578
|
if not dest:
|
|
537
|
-
|
|
579
|
+
bad(rel, n.line, "H2L-ARXML-REF", tgt, f"{n.tag} -> {tgt}: missing DEST attribute")
|
|
538
580
|
if tgt not in known:
|
|
539
|
-
|
|
581
|
+
bad(rel, n.line, "H2L-ARXML-REF", tgt, f"{n.tag} -> {tgt}: target does not exist in the project")
|
|
540
582
|
elif dest and known[tgt] != dest:
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
583
|
+
bad(rel, n.line, "H2L-ARXML-REF", tgt, f"{n.tag} DEST={dest} but {tgt} is a {known[tgt]}")
|
|
584
|
+
problems = [f"{i['file']}:{i['line']} {i['message']}" if i["line"] else f"{i['file']}: {i['message']}" for i in items]
|
|
585
|
+
return {"ok": True, "clean": not items, "files": [project.rel(f) for f in srcs], "references": refs,
|
|
586
|
+
"problems": problems, "diagnostics": items, "schemaChecked": _ad() is not None}
|
|
@@ -225,17 +225,25 @@ def validate(project: Project, files: Optional[list] = None, module: Optional[st
|
|
|
225
225
|
if check_generated if check_generated is not None else gen.default_on(project, cfg):
|
|
226
226
|
dg.items.extend(gen.check(project, cfg))
|
|
227
227
|
|
|
228
|
+
# Non-ECUC ARXML (System/ECU extract, SWC, interfaces): strict schema + every reference and its DEST, so one
|
|
229
|
+
# validate call verifies every ARXML file of the project.
|
|
230
|
+
if project.sources.input:
|
|
231
|
+
from .arxml_edit import arxml_check
|
|
232
|
+
dg.items.extend(arxml_check(project)["diagnostics"])
|
|
233
|
+
|
|
228
234
|
items = dg.items
|
|
229
235
|
loaded = sorted(project.files)
|
|
230
236
|
by_file: dict = {}
|
|
231
237
|
for m in project.modules:
|
|
232
238
|
by_file.setdefault(project.rel(m.file), set()).add(m.name)
|
|
239
|
+
for f in project.sources.input:
|
|
240
|
+
by_file.setdefault(project.rel(f), set()).add("extract/SWC: schema + references")
|
|
233
241
|
sample = ", ".join(project.rel(f) for f in loaded[:8]) + (f", … (+{len(loaded) - 8})" if len(loaded) > 8 else "")
|
|
234
242
|
scope: dict = {"root": project.root, "configFiles": len(loaded), "paramDefFiles": len(project.sources.defs),
|
|
235
243
|
"inputFiles": len(project.sources.input)}
|
|
236
244
|
nomatch = []
|
|
237
245
|
if files:
|
|
238
|
-
matched, empty = paths.select(project.root, files, loaded)
|
|
246
|
+
matched, empty = paths.select(project.root, files, loaded + sorted(project.sources.input))
|
|
239
247
|
for raw in empty:
|
|
240
248
|
nomatch.append(_nomatch(project, f"files filter {raw!r} matched none of the {len(loaded)} loaded config "
|
|
241
249
|
f"file(s) [{sample or 'none'}]; NOTHING was validated for it. Pass a file, "
|
package/skills/autosar/SKILL.md
CHANGED
|
@@ -21,7 +21,7 @@ in `Output/` is derived from it; in-house code in `Source/` calls the generated
|
|
|
21
21
|
1. **Never hand-write or hand-edit ARXML** (no `write`/`edit`/`sed` on `.arxml`; the pack blocks them). Every change goes
|
|
22
22
|
through `ecuc_edit`, which picks the value element, DEFINITION-REF/DEST and VALUE-REF DEST from
|
|
23
23
|
the param defs and patches only the changed bytes. Reading raw ARXML for context is fine; prefer `ecuc_read`.
|
|
24
|
-
A **new** System-extract / SWC / interface file is started with `
|
|
24
|
+
A **new** System-extract / SWC / interface file is started with `arxml_edit` op `new_file` and filled in the same call (recipe
|
|
25
25
|
below). Do not write one with Python (`autosar_data` scripts, ElementTree) or a temp file renamed to `.arxml`.
|
|
26
26
|
2. **Validate after every edit**: `ecuc_validate` (scoped with `files`/`module` if large). Fix
|
|
27
27
|
every error you introduced before moving on; report pre-existing ones separately.
|
|
@@ -62,8 +62,8 @@ in `Output/` is derived from it; in-house code in `Source/` calls the generated
|
|
|
62
62
|
| Values of a module/container | `ecuc_read path=… depth=…` |
|
|
63
63
|
| All containers matching a condition / referencing X / referenced by Y | `ecuc_find` |
|
|
64
64
|
| Cross-check one module against the extract, C types and memory | `ecuc_crosscheck module=…` |
|
|
65
|
-
| Start a NEW System extract / SWC / interface .arxml file | `
|
|
66
|
-
| Verify
|
|
65
|
+
| Start a NEW System extract / SWC / interface .arxml file | `arxml_edit` op `{op:"new_file", file, packages}` |
|
|
66
|
+
| Verify ALL ARXML (ECUC rules + extract/SWC schema, references, DEST) | `ecuc_validate` (unfiltered) |
|
|
67
67
|
| Edit System extract / SWC / interface XML | `arxml_edit` (DEST inferred, schema-ordered, refs checked) |
|
|
68
68
|
| Add a signal end to end (ECUC + extract + DBC) | `autosar_add_signal` |
|
|
69
69
|
| What may be set/added here (types, ranges, literals, multiplicity) | `ecuc_read path=… schema=true`, or a def path `/AUTOSAR/EcucDefs/<Mod>/…` |
|
|
@@ -93,27 +93,36 @@ in `Output/` is derived from it; in-house code in `Source/` calls the generated
|
|
|
93
93
|
|
|
94
94
|
## Every change: ground → decide → change → verify until clean
|
|
95
95
|
Do not decide what to change from memory or from the prompt alone. Each change goes through four steps, in order:
|
|
96
|
-
1. **Ground (facts first).**
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
96
|
+
1. **Ground (facts first).** Start with the context engine: `autosar_build_context target=<module/container/element>`
|
|
97
|
+
for a configuration change (e.g. MCAL Can/Fls/Port), or `swc=… runnable=…` for C. It returns the PROJECT FACTS
|
|
98
|
+
(current values with file:line and the param-def schema: types, ranges, literals, multiplicity) and the DOC FACTS
|
|
99
|
+
from the ingested specs and manuals of the selected Hydron project, with citations. Add what it does not cover with
|
|
100
|
+
`ecuc_find` / `autosar_config_lookup` (what exists and references what) and `ecuc_crosscheck`. Write the facts as a
|
|
101
|
+
numbered list (F#/D#) with their source.
|
|
102
102
|
2. **Decide.** From those facts only, write the plan as a todo list: every element to add/change, in dependency order
|
|
103
103
|
(reference targets first), and which tool does each. A link you could not ground (a value, an id, a target) is an
|
|
104
104
|
open question: look it up, or ask; never fill it in with a plausible guess.
|
|
105
|
-
3. **Change** with the structured tools only (`ecuc_edit`, `
|
|
105
|
+
3. **Change** with the structured tools only (`ecuc_edit`, `arxml_edit` incl. `new_file`, `autosar_add_signal`). Prefer
|
|
106
106
|
one call per coherent change; nothing is written if any op fails.
|
|
107
|
-
4. **Verify → fix → verify, until clean.**
|
|
108
|
-
|
|
107
|
+
4. **Verify in two steps → fix → verify, until clean.**
|
|
108
|
+
- Validation 1 (deterministic, the hard gate): `ecuc_validate` (ECUC and extract/SWC files alike), then
|
|
109
|
+
`autosar_generate` + `autosar_codegen_diff` / `autosar_build` and `autosar_verify_rte` where the project has them.
|
|
110
|
+
- Validation 2 (against the documents): `ecuc_validate docs=true` checks every element changed in this session
|
|
111
|
+
against the ingested specs/manuals and returns a checklist; answer it line by line (OK / VIOLATED / NOT COVERED,
|
|
112
|
+
with the [D#] citation). VIOLATED goes back to step 1 for that fact.
|
|
109
113
|
On any problem: read it, go back to step 1 for that fact, fix with the structured tools, verify again. Repeat until
|
|
110
114
|
every check is clean. Then re-read the request and tick each todo against the evidence. Never report done with a
|
|
111
115
|
failing or unrun check; if something cannot be made clean, say exactly what and why.
|
|
116
|
+
The pack enforces this: the first edit of a session is refused until a grounding tool ran, C edits need
|
|
117
|
+
`autosar_build_context` (or `autosar_audit`) first, and the system prompt lists every open verification item
|
|
118
|
+
(unvalidated edits, failing validation, unverified C, changed elements not yet checked against the documents)
|
|
119
|
+
until it is resolved.
|
|
112
120
|
|
|
113
121
|
## New ARXML file (SWC, interface, data types, extract) from nothing
|
|
114
|
-
1. `
|
|
115
|
-
|
|
116
|
-
|
|
122
|
+
1. ONE `arxml_edit` call. Its first op creates the file:
|
|
123
|
+
`{op:"new_file", file:"Input/SWC_X.arxml", packages:["/DataTypes", "/Interfaces", "/Swcs"]}` (R25-11 header and empty
|
|
124
|
+
packages; refuses to overwrite: extend existing files with add ops instead).
|
|
125
|
+
2. In the same call, the add ops in dependency order (a reference target must be added earlier in the same
|
|
117
126
|
call): base type → implementation data type → interface → SWC with ports → `SWC-INTERNAL-BEHAVIOR` → runnables
|
|
118
127
|
(with data accesses) → events. Each op is `{op:"add", parent_path, element:<XML tag>, short_name, values:{...}}`;
|
|
119
128
|
references are written `"->/Path/To/Target"` and get their DEST automatically. Example (shortened):
|
|
@@ -136,8 +145,8 @@ Do not decide what to change from memory or from the prompt alone. Each change g
|
|
|
136
145
|
```
|
|
137
146
|
3. If an op is rejected, read the error: it names the allowed sub-elements of that parent. Fix that op and resend
|
|
138
147
|
the call (nothing was written). Do not fall back to writing XML.
|
|
139
|
-
4. `
|
|
140
|
-
|
|
148
|
+
4. `ecuc_validate` until it is clean (it checks the new file's schema and every reference), then `autosar_generate` /
|
|
149
|
+
`autosar_build` when the project has a generator. Then tick every requested element against the file.
|
|
141
150
|
|
|
142
151
|
## The loop
|
|
143
152
|
`ecuc_read (schema) → ecuc_edit → ecuc_validate → autosar_generate → arxml_diff / inspect Output → autosar_build → autosar_trace (impact on Source/)`.
|