@h2loop/autosar 1.5.2 → 1.5.4
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/package.json +1 -1
- package/plugins/index.js +30 -30
- package/python/ecuc_engine/arxml_edit.py +219 -16
- package/python/ecuc_engine/cli.py +35 -3
package/package.json
CHANGED
package/plugins/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{readFileSync as
|
|
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
|
|
4
|
-
`)}import{existsSync as
|
|
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,
|
|
2
|
+
import{readFileSync as Le}from"fs";import{isAbsolute as Ue,join as W,resolve as Pe}from"path";import{tool as w}from"@kilocode/plugin";import{homedir as me}from"os";import{join as A}from"path";var ye=()=>process.env.HYDRON_TEST_HOME||me(),U=(i,t)=>process.env[i]||A(ye(),t),be=()=>A(U("XDG_CONFIG_HOME",".config"),"hydron-cli"),we=()=>A(U("XDG_DATA_HOME",".local/share"),"hydron-cli"),_e=()=>A(U("XDG_STATE_HOME",".local/state"),"hydron-cli");async function P(i){let t=Bun.file(i);if(!await t.exists())return;return t.json().catch(()=>{return})}async function L(){let i=process.env.KILO_API_URL?.trim();if(i)return i.replace(/\/+$/,"");let t=await P(A(be(),"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 $e(i){let t=i?.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 Se(i){let t=$e(i.access);if(t)return t;if(!i.refresh)return"";return new Bun.CryptoHasher("sha256").update(i.refresh).digest("hex").slice(0,12)}async function X(){let t=(await P(A(we(),"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 i=await X();if(typeof i.expires==="number"&&i.expires>0&&Date.now()>=i.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 i.access}async function G(i){let t=await fetch(`${await L()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await q()}`},signal:i?AbortSignal.any([i,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(_e(),"h2loop-project.json");async function C(i,t){let o=i===void 0||i===null?"":String(i).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 Se(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 T(i,t,o,e,s=120000){let a=`${await L()}${i}?workspace_id=${encodeURIComponent(t)}`,r=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 r.text();if(r.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(r.status===404&&n.includes("Not Found"))throw Error(`${i} is not available on ${await L()} (backend predates the AUTOSAR endpoints).`);if(!r.ok)throw Error(`H2Loop ${i} failed: HTTP ${r.status} ${n.slice(0,800)}`);try{return JSON.parse(n)}catch(c){throw Error(`H2Loop ${i} returned non-JSON (${String(c)}): ${n.slice(0,300)}`)}}var M=/\.arxml\b/i,F="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(i,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(i)){let e=Array.isArray(t.edits)?t.edits.some((s)=>typeof s?.filePath==="string"&&M.test(s.filePath)):!1;if(M.test(o)||e)return`${F} (${i} on ${o||"an .arxml file"})`;return}if(i==="apply_patch"||i==="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?`${F} (${i} on ${s[1].trim()})`:void 0}if(i==="bash"){let e=String(t.command??"");if(!M.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),r=/\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||r)return`${F} (bash: ${e.slice(0,120)})`}return}var ve=/(?:^|[;&|(]\s*|\bnode\s+\S*|\bnpx\s+)(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\b/m,Ae='Not a shell command: ecuc_*/arxml_*/autosar_* are TOOLS of this session. Call the tool directly (a tool call, not bash) with its arguments as JSON, e.g. arxml_edit with {"ops": [ ... ]}. If a tool call fails, read its error, fix the arguments and call the tool again.';function K(i,t){if(i!=="bash"||!t)return;let o=String(t.command??""),e=/\s(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\s+(?:--|<|\{|\[|'|")/.test(o);if(ve.test(o)||e)return`${Ae} (bash: ${o.slice(0,100)})`;if(/\becuc_engine\b|hydron-cli[\\/]store[\\/]/.test(o))return`Blocked: do not run the AUTOSAR pack's engine or files from the plugin store by hand. Use its tools (ecuc_read/ecuc_edit/arxml_edit/ecuc_validate ...) as tool calls. (bash: ${o.slice(0,100)})`;if(/(?:^|[;&|]\s*)(?:\S*\/)?(?:hydron|kilo|opencode)\s+(?:run|serve)\b/m.test(o))return"Blocked: do not start another agent session from inside this one; do the work here with your tools.";return}var ke=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"]),Q=/\.(c|h)$/i,ee=/(^|[\\/])(Output|gen|Gen|GenData|generated)[\\/]/;var H=new Map;function x(i){let t=i??"-",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 te(i){if(!i)return"";return String(i.filePath??i.file_path??"")}function ne(i,t,o){if(process.env.AUTOSAR_LOOP_GATES==="0")return;let e=x(i);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=te(o);if((t==="edit"||t==="write"||t==="multiedit")&&Q.test(s)&&!ee.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 ie(i,t,o,e){let s=x(i),a=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(e)||e.includes("edit rejected");if(ke.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 Re(t,o,e))if(!s.changed.includes(n))s.changed.push(n)}let r=te(o);if((t==="edit"||t==="write"||t==="multiedit")&&Q.test(r)&&!ee.test(r)&&!a){if(!s.cFiles.includes(r))s.cFiles.push(r);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 Re(i,t,o){let e=[];if(i==="ecuc_edit"){let s=z(t?.ops);for(let a of s){let r=String(a.path??""),n=a.param?`${r}/${a.param}`:a.container?`${r}/${a.container}`:r;e.push(a.value!==void 0?`${n} = ${JSON.stringify(a.value).slice(0,80)}`:`${n} (${a.op})`)}}else if(i==="arxml_edit"){let s=o.match(/created (\[[^\]]*\])/);if(s)try{e.push(...JSON.parse(s[1]))}catch{}for(let a of z(t?.ops))if(a.op==="set")e.push(`${a.path}/${a.element} = ${JSON.stringify(a.value)}`)}else if(i==="autosar_add_signal")e.push(`new Com signal ${t?.name} in ${t?.ipdu}`);return e.filter(Boolean)}function z(i){let t=i;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 re(i){let t=H.get(i??"-");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
|
+
`)}var Oe=/^(?:hi+|hello+|hey+|hiya|yo|hola|namaste|good\s+(?:morning|afternoon|evening|day)|thanks?|thank\s+you|thx|ty|ok(?:ay)?|cool|nice|great|bye|good\s*bye|see\s+you)(?:\s+(?:there|all|team|hydron|again|so\s+much|a\s+lot))*$/i,se=new Map;function Ee(i){let t=i.trim().replace(/[\p{Extended_Pictographic}\u200D\uFE0F]/gu,"").replace(/[!.?,:;~\-]+/g," ").replace(/\s+/g," ").trim();return t.length>0&&t.length<=40&&Oe.test(t)}function oe(i,t){se.set(i??"-",Ee(t))}function ae(i,t){if(process.env.AUTOSAR_LOOP_GATES==="0")return;if(!se.get(i??"-"))return;return`NO TOOLS: the user only greeted you (no task). Do not call ${t} or any other tool, and do not read or explore the project. Reply in one short line (e.g. what you can help with here) and stop.`}import{existsSync as Ce}from"fs";import{dirname as Te,join as B}from"path";import{fileURLToPath as je}from"url";var xe="autosar-data==0.17.0";function Ne(){let i=Te(je(import.meta.url)),t=[B(i,"..","python"),B(i,"..","..","python")].find((o)=>Ce(B(o,"ecuc_engine","__main__.py")));if(!t)throw Error(`ECUC engine not found next to ${i} (expected ../python/ecuc_engine)`);return t}async function Ie(i){try{return await Bun.spawn([...i,"-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 N={};async function De(){if(N.cmd!==void 0)return N.cmd;let i=process.env.AUTOSAR_PYTHON?.trim(),o=i?[[i]]:[["uv","run","--no-project","--quiet","--with",xe,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let e of o)if(await Ie(e))return N.cmd=e,e;return N.cmd=null,null}async function y(i,t,o){let e=await De();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=Ne(),a=Bun.spawn([...e,"-m","ecuc_engine","--root",i,...t,"--json"],{cwd:i,env:{...process.env,PYTHONPATH:[s,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:o}),[r,n]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text()]);await a.exited;let c=r.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,Me=["# AUTOSAR pack: only for AUTOSAR work","If the request is about this AUTOSAR project or its work (ARXML/ECUC config, BSW/RTE/MCAL code, AUTOSAR","specs): load the `autosar` skill and use its tools (ecuc_read/find, ecuc_edit/arxml_edit, ecuc_validate,","autosar_build_context). Otherwise (a greeting, an unrelated question) just answer: no tools, no exploring."].join(`
|
|
6
6
|
`);function D(i){if(typeof i!=="string")return i;let t=i.trim();if(!t.startsWith("[")&&!t.startsWith("{")&&!t.startsWith('"'))return i;try{return D(JSON.parse(t))}catch{return i}}var j=(i)=>d.preprocess(D,i);function R(i){let t=D(i);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 O=()=>d.preprocess(R,d.array(d.string()).optional()),k=" 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(i,t=200){let o=i.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(i.length>t)o.push(`\u2026 ${i.length-t} more`);return o}function _(i){let t=i.didYouMean?`
|
|
7
7
|
Did you mean: ${i.didYouMean.join(", ")}`:"",o=i.schema?`
|
|
8
8
|
Schema errors: ${JSON.stringify(i.schema)}`:"";return`ERROR: ${i.error}${t}${o}`}function S(i){let t=i.warnings??[];return t.length?t.map((o)=>`WARNING: ${o}`).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`:""}function
|
|
10
|
+
`:""}function b(i,t){if(!t)return i;return Ue(t)?t:Pe(i,t)}async function Fe(i){let t=Bun.file(W(i,".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 He(i,t){let o=(await Fe(i))[t];if(typeof o==="string")return{command:o};if(o&&typeof o==="object"&&typeof o.command==="string")return o;return}function ce(i,t=150){let o=i.split(`
|
|
11
11
|
`);return o.length>t?[`\u2026 (${o.length-t} earlier lines omitted)`,...o.slice(-t)].join(`
|
|
12
|
-
`):i}async function
|
|
12
|
+
`):i}async function Be(i,t,o,e){let s=process.platform==="win32"?["cmd","/d","/s","/c",i]:["sh","-c",i],a=Date.now(),r=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(r.stdout).text(),new Response(r.stderr).text()]);return{code:await r.exited,out:n,err:c,secs:Math.round((Date.now()-a)/1000)}}var Je=(i)=>(i??[]).map((t)=>`CAN ID ${t.canIdHex??"?"} (${t.canId??"?"}) ${t.direction} via ${t.canIfPdu}, controller ${t.controller??"?"}, network ${(t.network??[]).join(", ")||"?"}`).join("; ");async function de(i,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(i,["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,r=[];for(let n of e){let c=a[n.path];if(c===null||c===void 0){r.push(`NOTE: ${n.path} is not in the local checkout (${i}); owning I-PDU/direction unknown`);continue}n.ipdu_local=c,r.push(c.length?`${n.path}: owning I-PDU ${c.map((l)=>`${l.ipdu} (ComIPduDirection=${l.direction??"?"}${l.can?.length?`; ${Je(l.can)}`:""})`).join(", ")} [local ECUC]`:`${n.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return r}var We=(i)=>{if(typeof i==="number"&&Number.isSafeInteger(i))return i;if(typeof i==="string"&&/^\s*-?(0x[0-9a-f]+|\d+)\s*$/i.test(i)){let t=i.trim(),o=t.startsWith("-")?-Number(t.slice(1)):Number(t);return Number.isSafeInteger(o)?o:null}return null},he=(i)=>i<0?`-0x${(-i).toString(16).toUpperCase()}`:`0x${i.toString(16).toUpperCase()}`;async function le(i,t,o){let e=t.filter((n)=>typeof n?.path==="string");if(!e.length)return[];let s=await y(i,["value-sites",...new Set(e.map((n)=>n.path))],o),a=s.ok?s.sites:{},r=[];if(!s.ok)r.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,r.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])r.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=We(u);if(h!==null)f[p]=`dec ${h}, hex ${he(h)}`}if(Object.keys(f).length)n.values_int=f;if(s.ok)r.push(`NOTE: ${n.path} is not in the local checkout (${i}): 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 r}var ue=(i)=>{let t=i.notes??[],o=i.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 Ge(i,t){try{let o=await t(),e=typeof o==="string"?o:o.output;if(e&&e.trim())return o;return`${i}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(o){return`ERROR (${i}): ${o instanceof Error?o.message:String(o)}`}}function Ve(i){for(let[t,o]of Object.entries(i)){let e=o.execute;o.execute=(s,a)=>Ge(t,()=>e(s,a))}return i}function Xe(i,t=process.env){let o=new Set;for(let e of(t.AUTOSAR_DISABLE_TOOLS??"").split(/[\s,]+/))if(e)o.add(e);if(i)try{let e=JSON.parse(Le(W(i,".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 qe(i,t){if(t.size===0)return i;return Object.fromEntries(Object.entries(i).filter(([o])=>!t.has(o)))}var fe=new Map;async function J(i,t,o,e){let s=`${t??"-"}|${o??""}|${i}`,a=fe.get(s);if(a)return a;let r;try{let n=await C(o,e),c=await T("/api/v1/mcp/retriever/query",n,{query:i,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)}"`});r=c.answer?`(project ${n}; retriever answer, ${l.length} citation(s). Trust a statement only where a citation supports it.)
|
|
13
13
|
${c.answer.trim()}
|
|
14
14
|
Citations:
|
|
15
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
|
|
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=
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`),metadata:{exit:u.code}}}});return{"tool.execute.before":async(e,s)=>{let a=Y(e.tool,s.args)??K(e.tool,s.args);if(
|
|
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 fe.set(s,r),r}var Ye=async(i)=>{let t=Xe(i?.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 r=b(a.directory,s.project_dir),n=await He(r,e);if(!n)return`No \`${e}\` command configured. Add it to ${W(r,".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(r,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 Be(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
|
+
${ce(u.out)}`:"",u.err.trim()?`--- stderr (tail) ---
|
|
19
|
+
${ce(u.err,80)}`:""].filter(Boolean).join(`
|
|
20
|
+
`),metadata:{exit:u.code}}}});return{"chat.message":async(e,s)=>{let a=(s?.parts??[]).map((r)=>r.type==="text"?String(r.text??""):"").join(" ");oe(e.sessionID,a)},"tool.execute.before":async(e,s)=>{let a=ae(e.sessionID,e.tool);if(a)throw Error(a);let r=Y(e.tool,s.args)??K(e.tool,s.args);if(r)throw Error(r);let n=ne(e.sessionID,e.tool,s.args);if(n)throw Error(n)},"tool.execute.after":async(e,s)=>{ie(e.sessionID,e.tool,e.args,String(s?.output??""))},"experimental.chat.system.transform":async(e,s)=>{s.system.push(Me);let a=re(e?.sessionID);if(a)s.system.push(a)},tool:qe(Ve({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."+k,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 r=await y(b(s.directory,e.project_dir),a,s.abort);if(!r.ok)return S(r)+_(r);let{ok:n,engine:c,ms:l,warnings:f,...p}=r;return S(r)+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."+k,args:{ops:j(d.array(j(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:j(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 r=await y(b(s.directory,e.project_dir),a,s.abort);if(!r.ok){let f=r.changes??[];return S(r)+_(r)+(f.length?`
|
|
21
21
|
Rejected diff:
|
|
22
22
|
${f.map((p)=>p.diff).join(`
|
|
23
23
|
`)}`:"")}let n=r.changes??[],c=r.validation,l=[`${r.written?"Written":"Dry run (nothing written)"}: ${r.applied} op(s), ${n.length} file(s) changed.`,...(r.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(r)+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."+k,args:{files:O().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=
|
|
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."+k,args:{files:O().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),r=["validate"];for(let g of R(e.files)??[])r.push("--file",g);if(e.module)r.push("--module",e.module);if(e.checkGenerated===!0)r.push("--check-generated");if(e.checkGenerated===!1)r.push("--no-check-generated");let n=await y(a,r,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=x(s.sessionID).changed,E=e.about?.trim()||g.join("; ");if(!E)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: ${E}. 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
25
|
|
|
26
26
|
DOCUMENT CHECK UNAVAILABLE: ${v}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${E}`,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
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=
|
|
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."+k,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),r={path:e.path};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;let n=await T("/api/v1/mcp/autosar/config-lookup",a,r,s.abort),c=n.matches??[],l=
|
|
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>".`+k,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 r=await b(
|
|
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),r=await y(a,["diff",e.a,e.b],s.abort);if(!r.ok)return _(r);let{ok:n,engine:c,ms:l,...f}=r;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."+k,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),r={query:e.query};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;if(e.limit!==void 0)r.limit=e.limit;let n=await T("/api/v1/mcp/autosar/trace",a,r,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([de(l,f,s.abort),le(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)})`:""),...ue(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."+k,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),r={path:e.path};if(e.data_source_id!==void 0)r.data_source_id=e.data_source_id;let n=await T("/api/v1/mcp/autosar/config-lookup",a,r,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([de(l,f,s.abort),le(l,f,s.abort)]);return{title:`autosar_config_lookup ${e.path}`,output:[`${c.length} match(es) for ${e.path} in workspace ${a}`,...ue(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>".`+k,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 r=await y(b(s.directory,e.project_dir),a,s.abort);if(!r.ok)return S(r)+_(r);let{ok:n,engine:c,ms:l,warnings:f,...p}=r;return S(r)+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:O().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=R(e.ids)??[];if(!a.length)return'ERROR: pass ids, e.g. ["SWS_Com_00197"]';let r=await y(b(s.directory,e.project_dir),["spec-ids",...a],s.abort);if(!r.ok)return _(r);let n=r.results;return{title:`autosar_spec_id_check ${JSON.stringify(r.counts)}`,output:[`Checked ${n.length} ID(s) against ${r.docs} spec text file(s) (${r.docsOrigin}; ${r.indexedIds} IDs indexed): ${JSON.stringify(r.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
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."+k,args:{module:d.string().describe("module name, e.g. PduR"),project_dir:d.string().optional()},async execute(e,s){let a=await b(
|
|
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."+k,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 r=a.rows,n=a.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${a.summary}`,output:[`${e.module}: ${a.summary} (element kinds: ${a.elementKinds.join(", ")||"none"})`,...r.map((c)=>`${c.element} (${c.at})
|
|
33
33
|
${c.findings.join(`
|
|
34
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:j(d.array(j(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 r=await b(
|
|
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:j(d.array(j(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 r=await y(b(s.directory,e.project_dir),a,s.abort),n=r.changes??[];if(!r.ok)return _(r)+(r.problems?.length?`
|
|
36
36
|
${r.problems.join(`
|
|
37
37
|
`)}`:"")+(n.length?`
|
|
38
38
|
Rejected diff:
|
|
@@ -42,25 +42,25 @@ NOTE: ${c.join(`
|
|
|
42
42
|
NOTE: `)}`:"")+`
|
|
43
43
|
${n.map((f)=>f.diff).join(`
|
|
44
44
|
`)}
|
|
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 r=await b(
|
|
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 r=await y(b(s.directory,e.project_dir),a,s.abort);if(!r.ok)return _(r)+(r.diagnostics?.length?`
|
|
46
46
|
${I(r.diagnostics,20).join(`
|
|
47
|
-
`)}`:"");let{ok:n,engine:c,ms:l,...f}=r;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:O().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=
|
|
47
|
+
`)}`:"");let{ok:n,engine:c,ms:l,...f}=r;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:O().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),r=await y(a,["audit",...R(e.paths)??[]],s.abort);if(!r.ok)return S(r)+_(r);let n=(r.notes??[]).map((h)=>`NOTE: ${h}`),{findings:c,unchecked:l,scanned:f}=r,p=[`Scanned ${f.sources.length} C file(s), ${f.calls} BSW call(s): ${c.length?JSON.stringify(r.summary):"no findings"}`,...c.map((h)=>`${h.file}:${h.line} ${h.severity.toUpperCase()} ${h.rule} ${h.call}
|
|
48
48
|
${h.message}
|
|
49
49
|
evidence: ${JSON.stringify(h.evidence)}
|
|
50
50
|
spec: ${h.cite}${h.fix?`
|
|
51
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=r.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(r.summary)}`,output:S(r)+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:O().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=
|
|
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=
|
|
54
|
-
`),
|
|
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:O().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),r=["verify-rte",...R(e.paths)??[]];if(e.diff_against)r.push("--diff-against",e.diff_against);if(e.swc)r.push("--swc",e.swc);if(e.runnable)r.push("--runnable",e.runnable);let n=await y(a,r,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),r=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,...E}=u,v=JSON.stringify(E,null,1).split(`
|
|
54
|
+
`),pe=v.length>400?`${v.slice(0,400).join(`
|
|
55
55
|
`)}
|
|
56
56
|
\u2026 (${v.length-400} more lines: narrow the target)`:v.join(`
|
|
57
|
-
`),
|
|
57
|
+
`),ge=r?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
58
|
${e.task}`,`## 2. PROJECT FACTS [F]: current values with @at file:line, and the param-def schema (what may be set)
|
|
59
|
-
${
|
|
60
|
-
${
|
|
59
|
+
${pe}`,`## 3. DOC FACTS [D]: from the ingested documents
|
|
60
|
+
${ge}`,`## 4. NEXT
|
|
61
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
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
|
|
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 T("/api/v1/mcp/autosar/trace",h,{query:m,limit:3},s.abort);u.push(`### backend trace for ${m} (workspace ${h})
|
|
64
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+=`
|
|
65
65
|
## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
|
|
66
66
|
${u.join(`
|
|
@@ -70,13 +70,13 @@ ${u.join(`
|
|
|
70
70
|
${u}
|
|
71
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}
|
|
72
72
|
---
|
|
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:O().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=
|
|
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:O().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),r=["codegen"];for(let u of R(e.modules)??[])r.push("--module",u);if(e.out_dir)r.push("--out",e.out_dir);if(e.write_back===!1)r.push("--no-write-back");if(e.binding)r.push("--binding",e.binding);let n=await y(a,r,s.abort);if(!n.ok){let u=n.handleErrors??[];return S(n)+_(n)+(u.length?`
|
|
74
74
|
${u.map((h)=>` ${h}`).join(`
|
|
75
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
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 ${
|
|
77
|
+
`+l.assigned.slice(0,40).map((u)=>` ${u.path}/${u.param} = ${u.value} (hex ${he(u.value)})`).join(`
|
|
78
78
|
`)+(l.changes.length?`
|
|
79
79
|
${l.changes.map((u)=>u.diff).join(`
|
|
80
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:O().describe("only these modules"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=
|
|
82
|
-
`)}}}),autosar_generate:o("generate"),autosar_build:o("build")}),t)}},
|
|
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:O().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),r=["codegen-diff",e.reference_dir];if(e.generated_dir)r.push(e.generated_dir);for(let f of R(e.modules)??[])r.push("--module",f);let n=await y(a,r,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)}},Ke=Ye;export{Ke as Autosar};
|
|
@@ -31,6 +31,10 @@ from .model import Project
|
|
|
31
31
|
from .xmltree import Node, escape, escape_attr, line_indent, parse
|
|
32
32
|
|
|
33
33
|
|
|
34
|
+
_PRED = re.compile(r"""^([A-Za-z][\w-]*)\[\s*(?:@?[\w-]*\s*=\s*)?['"]?([^'"\]]*)['"]?\s*\]$""")
|
|
35
|
+
_SHORT = re.compile(r"[A-Za-z][A-Za-z0-9_]*\Z")
|
|
36
|
+
|
|
37
|
+
|
|
34
38
|
class ArxmlEditError(Exception):
|
|
35
39
|
pass
|
|
36
40
|
|
|
@@ -102,6 +106,10 @@ class ArxmlEditor:
|
|
|
102
106
|
self.added_tags: dict = {} # path -> tag of elements added in this call
|
|
103
107
|
self.created_packages: list = []
|
|
104
108
|
self.new_files: list = []
|
|
109
|
+
self.notes: list = []
|
|
110
|
+
self._tags: Optional[set] = None
|
|
111
|
+
self._typed: Optional[str] = None
|
|
112
|
+
self._idtags: set = set()
|
|
105
113
|
|
|
106
114
|
# ---------- files / lookup ----------
|
|
107
115
|
def tree_for(self, path: str) -> tuple:
|
|
@@ -144,15 +152,144 @@ class ArxmlEditor:
|
|
|
144
152
|
raise ArxmlEditError("a new top-level package needs \"file\" (which ARXML file to put it in); one of: "
|
|
145
153
|
+ ", ".join(self.p.rel(c) for c in cands[:20]))
|
|
146
154
|
|
|
155
|
+
# ---------- path dialects ----------
|
|
156
|
+
# Agents write XML/XPath-style paths ("/AR-PACKAGE/AR-PACKAGE[2]/APPLICATION-SW-COMPONENT-TYPE[SHORT-NAME='X']/
|
|
157
|
+
# PORTS", "/PT/Swc/TqLim/PORTS", ".../I-SIGNAL-TO-I-PDU-MAPPING/m/TRANSFER-PROPERTY"). 124 arxml_edit errors in 30
|
|
158
|
+
# held-out Qwen runs were mostly these. An AUTOSAR path is SHORT-NAMEs only: tag segments are dropped, a
|
|
159
|
+
# [SHORT-NAME='x'] predicate gives x, and a trailing collection tag is kept as the collection to add into.
|
|
160
|
+
def known_tags(self) -> set:
|
|
161
|
+
if self._tags is None:
|
|
162
|
+
tags = {"AUTOSAR", "ELEMENT"}
|
|
163
|
+
for f in self.p.sources.input + self.p.sources.config:
|
|
164
|
+
try:
|
|
165
|
+
ft = self.load(f)
|
|
166
|
+
except Exception: # noqa: BLE001
|
|
167
|
+
continue
|
|
168
|
+
for n in ft.root.iter():
|
|
169
|
+
tags.add(n.tag.upper())
|
|
170
|
+
if n.short_name is not None:
|
|
171
|
+
self._idtags.add(n.tag.upper())
|
|
172
|
+
self._tags = tags
|
|
173
|
+
return self._tags
|
|
174
|
+
|
|
175
|
+
def normalize(self, raw: str) -> tuple:
|
|
176
|
+
"""(SHORT-NAME path, trailing collection tag or None, changed?) for an XML/XPath-style path."""
|
|
177
|
+
out, trailing, changed = [], None, False
|
|
178
|
+
self._typed = None
|
|
179
|
+
tags = self.known_tags()
|
|
180
|
+
for seg in [x for x in raw.strip().strip("/").split("/") if x]:
|
|
181
|
+
m = _PRED.match(seg)
|
|
182
|
+
if m:
|
|
183
|
+
inner = m.group(2).strip()
|
|
184
|
+
changed = True
|
|
185
|
+
if not inner or inner.isdigit():
|
|
186
|
+
raise ArxmlEditError(f"path segment {seg!r} selects by position; name the element by its SHORT-NAME "
|
|
187
|
+
"instead (e.g. /PT/Swc/CruiseCtl)")
|
|
188
|
+
out.append(inner)
|
|
189
|
+
trailing = None
|
|
190
|
+
continue
|
|
191
|
+
if seg.upper() in tags or "-" in seg:
|
|
192
|
+
changed = True
|
|
193
|
+
if seg.upper() in self._idtags: # an element type (APPLICATION-SW-COMPONENT-TYPE): not a collection
|
|
194
|
+
self._typed, trailing = seg.upper(), None
|
|
195
|
+
else: # a collection (PORTS) or wrapper: add into it, if it fits
|
|
196
|
+
trailing = seg.upper() if (out or self._typed) else None
|
|
197
|
+
continue
|
|
198
|
+
out.append(seg)
|
|
199
|
+
trailing = None
|
|
200
|
+
return "/" + "/".join(out), trailing, changed
|
|
201
|
+
|
|
202
|
+
def suggest(self, path: str, k: int = 5) -> list:
|
|
203
|
+
names = [x for x in path.strip("/").split("/") if x and _SHORT.match(x)]
|
|
204
|
+
if not names:
|
|
205
|
+
return []
|
|
206
|
+
known = set(self.p.identifiables) | {q for ft in self.files.values() for q in ft.by_path}
|
|
207
|
+
last = names[-1]
|
|
208
|
+
hits = [q for q in known if q.rsplit("/", 1)[-1] == last] or \
|
|
209
|
+
[q for q in known if q.rsplit("/", 1)[-1].lower() == last.lower()]
|
|
210
|
+
hits.sort(key=lambda q: (-sum(n in q.split("/") for n in names), len(q)))
|
|
211
|
+
return hits[:k]
|
|
212
|
+
|
|
213
|
+
def not_found(self, raw: str, norm: Optional[str]) -> str:
|
|
214
|
+
msg = f"no ARXML element at {raw}"
|
|
215
|
+
if norm and norm != raw:
|
|
216
|
+
msg += f" (read as {norm}, which does not exist either)"
|
|
217
|
+
msg += (". An AUTOSAR path is the SHORT-NAMEs joined by '/', e.g. /PT/Swc/TqLim: no XML tags (AR-PACKAGE, "
|
|
218
|
+
"ELEMENTS, PORTS, APPLICATION-SW-COMPONENT-TYPE), no [SHORT-NAME='x'] predicates.")
|
|
219
|
+
sugg = self.suggest(norm or raw)
|
|
220
|
+
if sugg:
|
|
221
|
+
msg += " Did you mean: " + ", ".join(sugg)
|
|
222
|
+
return msg
|
|
223
|
+
|
|
224
|
+
def by_type(self, tag: str, file: Optional[str]) -> list:
|
|
225
|
+
trees = []
|
|
226
|
+
if file:
|
|
227
|
+
f = os.path.normpath(os.path.join(self.p.root, file))
|
|
228
|
+
for cand in self.p.sources.input + self.p.sources.config + list(self.files):
|
|
229
|
+
if os.path.realpath(cand) == os.path.realpath(f):
|
|
230
|
+
trees = [self.load(cand)]
|
|
231
|
+
break
|
|
232
|
+
else:
|
|
233
|
+
trees = [self.load(f) for f in self.p.sources.input]
|
|
234
|
+
return sorted({q for ft in trees for q, n in ft.by_path.items() if n.tag == tag})
|
|
235
|
+
|
|
236
|
+
def resolve(self, raw: str, what: str, file: Optional[str] = None) -> tuple:
|
|
237
|
+
"""(FileTree, node, SHORT-NAME path, collection hint) for a path in any of the dialects above."""
|
|
238
|
+
p = raw.rstrip("/")
|
|
239
|
+
try:
|
|
240
|
+
ft, node = self.tree_for(p)
|
|
241
|
+
return ft, node, p, None
|
|
242
|
+
except ArxmlEditError:
|
|
243
|
+
pass
|
|
244
|
+
norm, trailing, changed = self.normalize(p)
|
|
245
|
+
if changed and norm != "/":
|
|
246
|
+
try:
|
|
247
|
+
ft, node = self.tree_for(norm)
|
|
248
|
+
self.notes.append(f"{what} {raw!r} read as {norm!r}" + (f" (collection {trailing})" if trailing else ""))
|
|
249
|
+
return ft, node, norm, trailing
|
|
250
|
+
except ArxmlEditError:
|
|
251
|
+
pass
|
|
252
|
+
# only tags ("/AR-PACKAGES/AR-PACKAGE/ELEMENTS/APPLICATION-SW-COMPONENT-TYPE/PORTS"): the one element of that type
|
|
253
|
+
if changed and norm == "/" and self._typed:
|
|
254
|
+
hits = self.by_type(self._typed, file)
|
|
255
|
+
if len(hits) == 1:
|
|
256
|
+
ft, node = self.tree_for(hits[0])
|
|
257
|
+
self.notes.append(f"{what} {raw!r} read as {hits[0]!r} (the only {self._typed}"
|
|
258
|
+
+ (f" in {file}" if file else "") + ")" + (f" (collection {trailing})" if trailing else ""))
|
|
259
|
+
return ft, node, hits[0], trailing
|
|
260
|
+
if hits:
|
|
261
|
+
raise ArxmlEditError(f"{raw} names no element, and there are several {self._typed}: {', '.join(hits[:8])}; "
|
|
262
|
+
"give the SHORT-NAME path of the one you mean")
|
|
263
|
+
# package names left out ("/ExtLightCtrl/PpLightStatus"): accept the one element whose path ends that way
|
|
264
|
+
tail = "/" + norm.strip("/") if changed else "/" + p.strip("/")
|
|
265
|
+
if tail != "/":
|
|
266
|
+
known = set(self.p.identifiables) | {q for ft in self.files.values() for q in ft.by_path}
|
|
267
|
+
hits = sorted(q for q in known if q == tail or q.endswith(tail))
|
|
268
|
+
if len(hits) == 1:
|
|
269
|
+
ft, node = self.tree_for(hits[0])
|
|
270
|
+
self.notes.append(f"{what} {raw!r} read as {hits[0]!r} (the only element whose path ends with {tail})"
|
|
271
|
+
+ (f" (collection {trailing})" if trailing else ""))
|
|
272
|
+
return ft, node, hits[0], trailing
|
|
273
|
+
if len(hits) > 1:
|
|
274
|
+
raise ArxmlEditError(f"{raw} is ambiguous: several elements end with {tail}: {', '.join(hits[:8])}; give the full path")
|
|
275
|
+
raise ArxmlEditError(self.not_found(raw, norm if changed else None))
|
|
276
|
+
|
|
147
277
|
def parent_for(self, parent_path: str, file: Optional[str]) -> tuple:
|
|
148
|
-
"""(FileTree, node) of parent_path
|
|
278
|
+
"""(FileTree, node, path, collection hint) of parent_path; creates missing AR-PACKAGEs below the deepest
|
|
279
|
+
existing package, but only for a plain SHORT-NAME path (never from a tag-style or mistyped path)."""
|
|
149
280
|
pp = parent_path.rstrip("/")
|
|
281
|
+
if pp and pp != "/" and self.normalize(pp)[0] == "/" and not self._typed: # "/AUTOSAR/AR-PACKAGES": the root
|
|
282
|
+
self.notes.append(f"parent_path {parent_path!r} read as the file's top level")
|
|
283
|
+
pp = ""
|
|
150
284
|
if pp == "":
|
|
151
|
-
|
|
285
|
+
ft, node = self.root_of(file)
|
|
286
|
+
return ft, node, "", None
|
|
152
287
|
try:
|
|
153
|
-
return self.
|
|
154
|
-
except ArxmlEditError:
|
|
155
|
-
|
|
288
|
+
return self.resolve(pp, "parent_path", file)
|
|
289
|
+
except ArxmlEditError as miss:
|
|
290
|
+
segs = [x for x in pp.split("/") if x]
|
|
291
|
+
if not segs or not all(_SHORT.match(x) for x in segs) or segs[0].upper() == "AUTOSAR":
|
|
292
|
+
raise miss
|
|
156
293
|
segs = [s for s in pp.split("/") if s]
|
|
157
294
|
anc, k = "", 0
|
|
158
295
|
for i in range(len(segs) - 1, 0, -1):
|
|
@@ -170,7 +307,8 @@ class ArxmlEditor:
|
|
|
170
307
|
self.op_add({"parent_path": anc or "/", "element": "AR-PACKAGE", "short_name": s, "file": file})
|
|
171
308
|
anc = f"{anc}/{s}"
|
|
172
309
|
self.created_packages.append(anc)
|
|
173
|
-
|
|
310
|
+
ft, node = self.tree_for(pp)
|
|
311
|
+
return ft, node, pp, None
|
|
174
312
|
|
|
175
313
|
def load(self, f: str) -> FileTree:
|
|
176
314
|
if f not in self.files:
|
|
@@ -218,8 +356,14 @@ class ArxmlEditor:
|
|
|
218
356
|
for k in keys:
|
|
219
357
|
v = values[k]
|
|
220
358
|
for one in (v if isinstance(v, list) else [v]):
|
|
221
|
-
|
|
222
|
-
|
|
359
|
+
try:
|
|
360
|
+
sub = etype.find_sub_element(k, version) if etype is not None else None
|
|
361
|
+
except Exception: # noqa: BLE001 -- autosar-data rejects a name that is no AUTOSAR tag at all
|
|
362
|
+
raise ArxmlEditError(f"{k!r} is not an AUTOSAR element name (sub-elements of {tag}: "
|
|
363
|
+
f"{', '.join(o for o in order if o != 'SHORT-NAME')[:500]})") from None
|
|
364
|
+
is_ref = k.endswith(("-REF", "-TREF", "-IREF")) and isinstance(one, dict) and \
|
|
365
|
+
any(x in one for x in ("ref", "$ref", "REF", "DEST", "dest"))
|
|
366
|
+
if isinstance(one, dict) and not is_ref:
|
|
223
367
|
sn = one.get("SHORT-NAME")
|
|
224
368
|
lines.extend(self.render(k, sn, one, sub, version, depth + 1))
|
|
225
369
|
else:
|
|
@@ -228,6 +372,10 @@ class ArxmlEditor:
|
|
|
228
372
|
return lines
|
|
229
373
|
|
|
230
374
|
def leaf(self, tag: str, v) -> str:
|
|
375
|
+
if isinstance(v, dict) and not ("ref" in v) and any(k in v for k in ("$ref", "REF", "path", "#text", "value")) \
|
|
376
|
+
and (tag.endswith("-REF") or tag.endswith("-TREF") or tag.endswith("-IREF")):
|
|
377
|
+
ref = v.get("$ref") or v.get("REF") or v.get("path") or v.get("#text") or v.get("value")
|
|
378
|
+
v = {"ref": str(ref).lstrip("->").strip(), "dest": v.get("dest") or v.get("DEST")}
|
|
231
379
|
if isinstance(v, dict) and "ref" in v:
|
|
232
380
|
target, dest = str(v["ref"]), v.get("dest") or self.dest_of(str(v["ref"]))
|
|
233
381
|
if not dest:
|
|
@@ -267,10 +415,22 @@ class ArxmlEditor:
|
|
|
267
415
|
if not parent_path or not tag:
|
|
268
416
|
raise ArxmlEditError("add needs parent_path (the package or element to add under) and element (the XML "
|
|
269
417
|
"tag), e.g. " + ADD_EXAMPLE)
|
|
270
|
-
|
|
418
|
+
if tag.upper() == "SHORT-NAME":
|
|
419
|
+
raise ArxmlEditError("SHORT-NAME is not an element to add: give short_name on the add of the element itself; "
|
|
420
|
+
"to rename an element use {op:'set', path:<element path>, element:'SHORT-NAME', value:<new>}")
|
|
421
|
+
ft, parent, parent_path, coll_hint = self.parent_for(parent_path, op.get("file"))
|
|
422
|
+
if tag.upper().startswith("ECUC-") or parent.tag.startswith("ECUC-"):
|
|
423
|
+
raise ArxmlEditError(
|
|
424
|
+
"this is ECUC configuration: use ecuc_edit, not arxml_edit, e.g. {op:'add', path:'" + (parent_path or "/<Pkg>/<Module>")
|
|
425
|
+
+ "', container:'<ContainerDef>:<ShortName>', values:{<ParamDef>: <value>}} (ecuc_read schema=true lists "
|
|
426
|
+
"the containers and params that may be added there)")
|
|
271
427
|
version = _version(ft.data)
|
|
272
428
|
ptype = _etype(ft.chain(parent), version)
|
|
273
429
|
coll = op.get("collection")
|
|
430
|
+
if coll is None and coll_hint and ptype is not None:
|
|
431
|
+
hold = ptype.find_sub_element(coll_hint, version)
|
|
432
|
+
if hold is not None and hold.find_sub_element(tag, version) is not None:
|
|
433
|
+
coll = coll_hint
|
|
274
434
|
if coll is None and ptype is not None:
|
|
275
435
|
if ptype.find_sub_element(tag, version) is None:
|
|
276
436
|
for c in _order(ptype):
|
|
@@ -278,6 +438,21 @@ class ArxmlEditor:
|
|
|
278
438
|
if ct is not None and ct.find_sub_element(tag, version) is not None:
|
|
279
439
|
coll = c
|
|
280
440
|
break
|
|
441
|
+
if coll is None and parent_path:
|
|
442
|
+
holders = []
|
|
443
|
+
for q, n in ft.by_path.items():
|
|
444
|
+
if not q.startswith(parent_path + "/") or n is parent:
|
|
445
|
+
continue
|
|
446
|
+
nt = _etype(ft.chain(n), version)
|
|
447
|
+
if nt is None:
|
|
448
|
+
continue
|
|
449
|
+
if nt.find_sub_element(tag, version) is not None or any(
|
|
450
|
+
(ct := nt.find_sub_element(c, version)) is not None and ct.find_sub_element(tag, version) is not None
|
|
451
|
+
for c in _order(nt)):
|
|
452
|
+
holders.append(q)
|
|
453
|
+
if len(holders) == 1:
|
|
454
|
+
self.notes.append(f"{tag} cannot go directly under {parent_path}; added under {holders[0]}")
|
|
455
|
+
return self.op_add(dict(op, parent_path=holders[0], collection=None))
|
|
281
456
|
if coll is None:
|
|
282
457
|
raise ArxmlEditError(f"{tag} cannot be placed under {parent.tag} {parent_path} in this schema; "
|
|
283
458
|
f"{parent.tag} takes: {', '.join(_placeable(ptype, version))[:600]}")
|
|
@@ -360,8 +535,9 @@ class ArxmlEditor:
|
|
|
360
535
|
def op_set(self, op: dict):
|
|
361
536
|
path, tag = op.get("path"), op.get("element")
|
|
362
537
|
if not path or not tag or "value" not in op:
|
|
363
|
-
raise ArxmlEditError("set needs path, element
|
|
364
|
-
|
|
538
|
+
raise ArxmlEditError("set needs path (the element that holds the value), element (the XML tag of the value) "
|
|
539
|
+
"and value, e.g. {op:'set', path:'/PT/Com/ISignals/ENG_TEMP', element:'LENGTH', value:8}")
|
|
540
|
+
ft, node, _, _ = self.resolve(path, "path")
|
|
365
541
|
leaf = self.own_child(node, tag)
|
|
366
542
|
text = self.leaf(tag, op["value"]).encode("utf-8")
|
|
367
543
|
if leaf is None:
|
|
@@ -385,7 +561,9 @@ class ArxmlEditor:
|
|
|
385
561
|
|
|
386
562
|
def op_remove(self, op: dict):
|
|
387
563
|
path = (op.get("path") or "").rstrip("/")
|
|
388
|
-
|
|
564
|
+
if not path:
|
|
565
|
+
raise ArxmlEditError("remove needs path (the element to remove)")
|
|
566
|
+
ft, node, _, _ = self.resolve(path, "path")
|
|
389
567
|
start = node.start
|
|
390
568
|
if line_indent(ft.data, start) is not None:
|
|
391
569
|
nl = ft.data.rfind(b"\n", 0, start)
|
|
@@ -444,16 +622,28 @@ def _placeable(ptype, version) -> list:
|
|
|
444
622
|
return out
|
|
445
623
|
|
|
446
624
|
|
|
625
|
+
_TAG_ANYCASE = re.compile(r"[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)+\Z|[A-Za-z]+\Z")
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _upper_keys(v):
|
|
629
|
+
"""Upper-case element-name keys of a values tree ("Init-Value" -> INIT-VALUE); '@'/'$' keys and ref dicts stay."""
|
|
630
|
+
if isinstance(v, list):
|
|
631
|
+
return [_upper_keys(x) for x in v]
|
|
632
|
+
if not isinstance(v, dict) or "ref" in v or "$ref" in v:
|
|
633
|
+
return v
|
|
634
|
+
return {(k.upper() if _TAG_ANYCASE.match(k) and k not in ("ref", "dest") else k): _upper_keys(x) for k, x in v.items()}
|
|
635
|
+
|
|
636
|
+
|
|
447
637
|
def normalize(op: dict, notes: list, i: int) -> dict:
|
|
448
|
-
"""Accept the shapes agents mix up (ecuc_edit's path/container, name/tag
|
|
449
|
-
if op.get("op")
|
|
638
|
+
"""Accept the shapes agents mix up (ecuc_edit's path/container/param, name/tag, any-case tags); note each rewrite."""
|
|
639
|
+
if op.get("op") not in ("add", "set"):
|
|
450
640
|
return op
|
|
451
641
|
op = dict(op)
|
|
452
|
-
if not op.get("parent_path") and op.get("path"):
|
|
642
|
+
if op.get("op") == "add" and not op.get("parent_path") and op.get("path"):
|
|
453
643
|
op["parent_path"] = op.pop("path")
|
|
454
644
|
notes.append(f"op {i}: 'path' read as parent_path")
|
|
455
645
|
cont = op.get("container")
|
|
456
|
-
if not op.get("element") and isinstance(cont, str):
|
|
646
|
+
if op.get("op") == "add" and not op.get("element") and isinstance(cont, str):
|
|
457
647
|
tag, _, sn = cont.partition(":")
|
|
458
648
|
if _TAG.match(tag):
|
|
459
649
|
op.pop("container")
|
|
@@ -465,6 +655,15 @@ def normalize(op: dict, notes: list, i: int) -> dict:
|
|
|
465
655
|
if alias in op and not op.get(key):
|
|
466
656
|
op[key] = op.pop(alias)
|
|
467
657
|
notes.append(f"op {i}: {alias!r} read as {key!r}")
|
|
658
|
+
if op.get("op") == "set" and not op.get("element") and op.get("param"):
|
|
659
|
+
op["element"] = op.pop("param")
|
|
660
|
+
notes.append(f"op {i}: 'param' read as 'element'")
|
|
661
|
+
el = op.get("element")
|
|
662
|
+
if isinstance(el, str) and _TAG_ANYCASE.match(el) and el != el.upper():
|
|
663
|
+
op["element"] = el.upper()
|
|
664
|
+
notes.append(f"op {i}: element {el!r} read as {el.upper()!r} (AUTOSAR tags are upper case)")
|
|
665
|
+
if isinstance(op.get("values"), dict):
|
|
666
|
+
op["values"] = _upper_keys(op["values"])
|
|
468
667
|
vals = op.get("values")
|
|
469
668
|
if isinstance(vals, dict) and "SHORT-NAME" in vals and not op.get("short_name"):
|
|
470
669
|
vals = dict(vals)
|
|
@@ -483,6 +682,7 @@ def arxml_edit(project: Project, ops, dry_run: bool = False) -> dict:
|
|
|
483
682
|
created = []
|
|
484
683
|
notes: list = []
|
|
485
684
|
ops = [normalize(o, notes, i) for i, o in enumerate(ops)]
|
|
685
|
+
ed.notes = notes
|
|
486
686
|
try:
|
|
487
687
|
for i, op in enumerate(ops):
|
|
488
688
|
kind = op.get("op")
|
|
@@ -499,6 +699,9 @@ def arxml_edit(project: Project, ops, dry_run: bool = False) -> dict:
|
|
|
499
699
|
raise ArxmlEditError(f"unknown op {kind!r} (new_file/add/set/remove)")
|
|
500
700
|
except ArxmlEditError as e:
|
|
501
701
|
raise ArxmlEditError(f"op {i} ({kind} {op.get('path') or op.get('parent_path') or op.get('file')}): {e}") from None
|
|
702
|
+
except Exception as e: # noqa: BLE001 -- never let a library error escape as a bare engine failure
|
|
703
|
+
raise ArxmlEditError(f"op {i} ({kind} {op.get('path') or op.get('parent_path') or op.get('file')}): "
|
|
704
|
+
f"{type(e).__name__}: {e}") from None
|
|
502
705
|
except ArxmlEditError as e:
|
|
503
706
|
return {"ok": False, "error": str(e), "written": False, "notes": notes}
|
|
504
707
|
problems = ed.check()
|
|
@@ -8,6 +8,7 @@ from __future__ import annotations
|
|
|
8
8
|
|
|
9
9
|
import argparse
|
|
10
10
|
import json
|
|
11
|
+
import re
|
|
11
12
|
import os
|
|
12
13
|
import sys
|
|
13
14
|
import time
|
|
@@ -15,16 +16,44 @@ import time
|
|
|
15
16
|
from . import ENGINE_VERSION
|
|
16
17
|
|
|
17
18
|
|
|
19
|
+
REPAIRED: list = []
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _loads(text: str):
|
|
23
|
+
"""json.loads, then the slips models make in long hand-written JSON: trailing commas, missing commas between
|
|
24
|
+
objects/values, Python literals (True/None, single quotes). The first error is re-raised if nothing parses."""
|
|
25
|
+
try:
|
|
26
|
+
return json.loads(text)
|
|
27
|
+
except json.JSONDecodeError as first:
|
|
28
|
+
fixed = re.sub(r",\s*([}\]])", r"\1", text)
|
|
29
|
+
fixed = re.sub(r"([}\]\"])\s*\n?\s*([{\"])", lambda m: m.group(1) + ("," if m.group(2) in "{\"" else "") + m.group(2), fixed) \
|
|
30
|
+
if fixed.count('"') % 2 == 0 else fixed
|
|
31
|
+
for cand in (fixed, ):
|
|
32
|
+
try:
|
|
33
|
+
v = json.loads(cand)
|
|
34
|
+
REPAIRED.append(f"ops JSON had a syntax error ({first.msg} at char {first.pos}) and was repaired; check the result")
|
|
35
|
+
return v
|
|
36
|
+
except json.JSONDecodeError:
|
|
37
|
+
pass
|
|
38
|
+
try:
|
|
39
|
+
import ast
|
|
40
|
+
v = ast.literal_eval(text.replace("true", "True").replace("false", "False").replace("null", "None"))
|
|
41
|
+
REPAIRED.append(f"ops were not strict JSON ({first.msg} at char {first.pos}) and were read as a literal")
|
|
42
|
+
return v
|
|
43
|
+
except Exception: # noqa: BLE001
|
|
44
|
+
raise first from None
|
|
45
|
+
|
|
46
|
+
|
|
18
47
|
def _ops(arg: str):
|
|
19
48
|
if arg.startswith("@"):
|
|
20
49
|
with open(arg[1:]) as f:
|
|
21
50
|
arg = f.read()
|
|
22
51
|
if arg == "-":
|
|
23
52
|
arg = sys.stdin.read()
|
|
24
|
-
ops =
|
|
53
|
+
ops = _loads(arg)
|
|
25
54
|
for _ in range(3): # tolerate JSON that was encoded more than once ("[{...}]" as a string)
|
|
26
55
|
if isinstance(ops, str):
|
|
27
|
-
ops =
|
|
56
|
+
ops = _loads(ops)
|
|
28
57
|
if isinstance(ops, dict) and isinstance(ops.get("ops"), (list, str)):
|
|
29
58
|
return _ops(json.dumps(ops["ops"]))
|
|
30
59
|
return ops if isinstance(ops, list) else [ops]
|
|
@@ -207,7 +236,10 @@ def run(a) -> dict:
|
|
|
207
236
|
return arxml_check(project, a.file or None)
|
|
208
237
|
if a.cmd == "arxml-edit":
|
|
209
238
|
from .arxml_edit import arxml_edit
|
|
210
|
-
|
|
239
|
+
res = arxml_edit(project, a.ops, dry_run=a.dry_run)
|
|
240
|
+
if REPAIRED:
|
|
241
|
+
res.setdefault("notes", []).extend(REPAIRED)
|
|
242
|
+
return res
|
|
211
243
|
if a.cmd == "find":
|
|
212
244
|
from .find import find
|
|
213
245
|
where = a.where
|