@h2loop/autosar 1.5.4 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,7 @@ Deterministic tools for AUTOSAR Classic integration work, so the agent never han
10
10
  | `ecuc_find` | structured queries over the ECUC (conditions, references to/from) | local |
11
11
  | `ecuc_crosscheck` | per-module cross-check table (extract, gateway, NvM sizeof, capacity, packing, handles) | local |
12
12
  | `arxml_edit` | structured edits of System extract / SWC ARXML, incl. `new_file` (DEST inferred, schema-ordered, missing packages created) | local |
13
+ | `autosar_add_like` | add a new X like an existing Y (message, port, runnable+event, Dem event, NvM block, ...): clones the whole named chain across ECUC + System ARXML, renamed; links, handle IDs, values; validates or rolls back | local |
13
14
  | `autosar_add_signal` | add a signal end to end (ECUC + extract chain + DBC), validate or roll back | local |
14
15
  | `arxml_diff` | semantic diff by AUTOSAR path (ignores UUIDs, order, whitespace, file splits) | local |
15
16
  | `autosar_trace` | config ↔ generated C symbol ↔ in-house callers, via the H2Loop code graph | H2Loop backend |
@@ -20,6 +20,7 @@ permission:
20
20
  "ecuc_crosscheck": allow
21
21
  "arxml_edit": allow
22
22
  "autosar_add_signal": allow
23
+ "autosar_add_like": allow
23
24
  "autosar_audit": allow
24
25
  todowrite: allow
25
26
  todoread: allow
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h2loop/autosar",
3
- "version": "1.5.4",
3
+ "version": "1.6.0",
4
4
  "description": "AUTOSAR Classic pack for Hydron: ECUC read/edit-in-place/validate/diff on ARXML, config-to-code trace, generator and build runners",
5
5
  "type": "module",
6
6
  "private": false,
package/plugins/index.js CHANGED
@@ -1,82 +1,84 @@
1
1
  // @bun
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
- `);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
- Did you mean: ${i.didYouMean.join(", ")}`:"",o=i.schema?`
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(`
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 v}from"path";var ye=()=>process.env.HYDRON_TEST_HOME||me(),U=(r,n)=>process.env[r]||v(ye(),n),be=()=>v(U("XDG_CONFIG_HOME",".config"),"hydron-cli"),we=()=>v(U("XDG_DATA_HOME",".local/share"),"hydron-cli"),_e=()=>v(U("XDG_STATE_HOME",".local/state"),"hydron-cli");async function P(r){let n=Bun.file(r);if(!await n.exists())return;return n.json().catch(()=>{return})}async function L(){let r=process.env.KILO_API_URL?.trim();if(r)return r.replace(/\/+$/,"");let n=await P(v(be(),"server-config.json")),a=typeof n?.apiBaseUrl==="string"?n.apiBaseUrl:void 0;if(!a)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return a.replace(/\/+$/,"")}function $e(r){let n=r?.split(".")[1];if(!n)return"";try{let a=JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return typeof a.sub==="string"?a.sub:""}catch{return""}}async function Se(r){let n=$e(r.access);if(n)return n;if(!r.refresh)return"";return new Bun.CryptoHasher("sha256").update(r.refresh).digest("hex").slice(0,12)}async function X(){let n=(await P(v(we(),"auth.json")))?.hydron;if(!n||n.type!=="oauth"||!n.access)throw Error("Not signed in to H2Loop. Run `hydron auth login` (or sign in from the TUI), then retry.");return n}async function q(){let r=await X();if(typeof r.expires==="number"&&r.expires>0&&Date.now()>=r.expires-30000)throw Error("The H2Loop session token has expired. Send any message in Hydron (the CLI refreshes it) or re-login with `hydron auth login`, then retry.");return r.access}async function G(r){let n=await fetch(`${await L()}/api/v1/workspaces`,{headers:{Authorization:`Bearer ${await q()}`},signal:r?AbortSignal.any([r,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(n.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(!n.ok)throw Error(`could not list H2Loop projects: HTTP ${n.status}`);let a=await n.json();return Array.isArray(a)?a:a?.items??[]}var V=()=>v(_e(),"h2loop-project.json");async function N(r,n){let a=r===void 0||r===null?"":String(r).trim();if(/^\d+$/.test(a))return a;if(a){let t=await G(n),d=t.filter((p)=>p.name===a),l=d.length?d:t.filter((p)=>p.name?.toLowerCase()===a.toLowerCase());if(l.length===1)return String(l[0].id);if(l.length>1)throw Error(`workspace "${a}" is ambiguous: ${l.map((p)=>`${p.name} (id ${p.id})`).join(", ")}; pass the numeric id`);let f=t.filter((p)=>p.name?.toLowerCase().includes(a.toLowerCase())).slice(0,10);throw Error(`no H2Loop project named "${a}"`+(f.length?`; similar: ${f.map((p)=>`${p.name} (id ${p.id})`).join(", ")}`:`; you have ${t.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 t=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(t.id!==void 0)return String(t.id)}let o=e;if(o.id===void 0)throw Error(`${V()} holds no project id; select a project again or pass workspace_id.`);if(!(await G(n)).some((t)=>String(t.id)===String(o.id)))throw Error(`The selected project ${o.name??""} (id ${o.id}) is not accessible to the signed-in account; select another or pass workspace_id.`);return String(o.id)}async function x(r,n,a,e,s=120000){let o=`${await L()}${r}?workspace_id=${encodeURIComponent(n)}`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await q()}`},body:JSON.stringify(a),signal:e?AbortSignal.any([e,AbortSignal.timeout(s)]):AbortSignal.timeout(s)}),t=await i.text();if(i.status===401)throw Error("H2Loop rejected the session (401). Re-login with `hydron auth login`, then retry.");if(i.status===404&&t.includes("Not Found"))throw Error(`${r} is not available on ${await L()} (backend predates the AUTOSAR endpoints).`);if(!i.ok)throw Error(`H2Loop ${r} failed: HTTP ${i.status} ${t.slice(0,800)}`);try{return JSON.parse(t)}catch(d){throw Error(`H2Loop ${r} returned non-JSON (${String(d)}): ${t.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(r,n){if(process.env.AUTOSAR_ALLOW_ARXML_EDIT==="1"||!n)return;let a=typeof n.filePath==="string"?n.filePath:typeof n.file_path==="string"?n.file_path:"";if(["edit","write","multiedit"].includes(r)){let e=Array.isArray(n.edits)?n.edits.some((s)=>typeof s?.filePath==="string"&&M.test(s.filePath)):!1;if(M.test(a)||e)return`${F} (${r} on ${a||"an .arxml file"})`;return}if(r==="apply_patch"||r==="patch"){let e=String(n.patchText??n.patch??""),s=e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+\.arxml)\s*$/im)??e.match(/^\+\+\+ (?:b\/)?(.+\.arxml)/im);return s?`${F} (${r} on ${s[1].trim()})`:void 0}if(r==="bash"){let e=String(n.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),o=/(?:^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*\.arxml\b/i.test(e)||/\btee\b[^|;&]*\.arxml\b/i.test(e),i=/\b(?:mv|cp|ln|install|rsync)\b[^|;&]*\.arxml['"]?\s*(?:$|[|;&])/im.test(e)||/\b(?:os\.(?:rename|replace)|shutil\.(?:move|copy\w*)|fs\.(?:rename|copyFile)\w*|Path\([^)]*\)\.rename)\([^)]*\.arxml/i.test(e)||/\.(?:rename|replace)\(\s*['"][^'"]*\.arxml/i.test(e),t=/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||o||t||i)return`${F} (bash: ${e.slice(0,120)})`}return}var ke=/(?:^|[;&|(]\s*|\bnode\s+\S*|\bnpx\s+)(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\b/m,ve='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(r,n){if(r!=="bash"||!n)return;let a=String(n.command??""),e=/\s(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\s+(?:--|<|\{|\[|'|")/.test(a);if(ke.test(a)||e)return`${ve} (bash: ${a.slice(0,100)})`;if(/\becuc_engine\b|hydron-cli[\\/]store[\\/]/.test(a))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: ${a.slice(0,100)})`;if(/(?:^|[;&|]\s*)(?:\S*\/)?(?:hydron|kilo|opencode)\s+(?:run|serve)\b/m.test(a))return"Blocked: do not start another agent session from inside this one; do the work here with your tools.";return}var Ae=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","autosar_add_like"]),Q=/\.(c|h)$/i,ee=/(^|[\\/])(Output|gen|Gen|GenData|generated)[\\/]/;var H=new Map;function I(r){let n=r??"-",a=H.get(n);if(!a)a={grounded:[],contextFor:[],changed:[],validation:"never",cFiles:[],rte:"n/a",docs:"n/a",blocks:0},H.set(n,a);return a}function te(r){if(!r)return"";return String(r.filePath??r.file_path??"")}function ne(r,n,a){if(process.env.AUTOSAR_LOOP_GATES==="0")return;let e=I(r);if(e.blocks>=2)return;if(Z.has(n)&&!a?.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(a);if((n==="edit"||n==="write"||n==="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(r,n,a,e){let s=I(r),o=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(e)||e.includes("edit rejected");if(Ae.has(n)&&!o){if(!s.grounded.includes(n))s.grounded.push(n);if(n==="autosar_build_context"){let t=String(a?.target??a?.runnable??a?.swc??"");if(t&&!s.contextFor.includes(t))s.contextFor.push(t)}}if(Z.has(n)&&!o&&!a?.dry_run&&!/^Dry run/.test(e)){s.validation="stale",s.docs="pending";for(let t of Re(n,a,e))if(!s.changed.includes(t))s.changed.push(t)}let i=te(a);if((n==="edit"||n==="write"||n==="multiedit")&&Q.test(i)&&!ee.test(i)&&!o){if(!s.cFiles.includes(i))s.cFiles.push(i);s.rte="pending"}if(n==="ecuc_validate"&&!o){let t=/"error":\s*[1-9]/.test(e.split(`
3
+ `)[0]??"")||/^\S+:\d+ error /m.test(e);if(s.validation=t?"errors":"clean",a?.docs&&s.docs==="pending"&&!/DOCUMENT CHECK UNAVAILABLE/.test(e))s.docs="done"}if(n==="autosar_verify_rte"&&!o)s.rte=/\u2014 FAILING/.test(e)?"fail":"pass"}function Re(r,n,a){let e=[];if(r==="ecuc_edit"){let s=z(n?.ops);for(let o of s){let i=String(o.path??""),t=o.param?`${i}/${o.param}`:o.container?`${i}/${o.container}`:i;e.push(o.value!==void 0?`${t} = ${JSON.stringify(o.value).slice(0,80)}`:`${t} (${o.op})`)}}else if(r==="arxml_edit"){let s=a.match(/created (\[[^\]]*\])/);if(s)try{e.push(...JSON.parse(s[1]))}catch{}for(let o of z(n?.ops))if(o.op==="set")e.push(`${o.path}/${o.element} = ${JSON.stringify(o.value)}`)}else if(r==="autosar_add_signal")e.push(`new Com signal ${n?.name} in ${n?.ipdu}`);else if(r==="autosar_add_like"){let s=a.match(/Created:\n((?: .*\n?)+)/);if(s)e.push(...s[1].split(`
4
+ `).map((o)=>o.trim()).filter(Boolean));else e.push(`${n?.name} like ${n?.like}`)}return e.filter(Boolean)}function z(r){let n=r;for(let a=0;a<3&&typeof n==="string";a++)try{n=JSON.parse(n)}catch{return[]}if(Array.isArray(n))return n.filter((a)=>a&&typeof a==="object");if(n&&typeof n==="object")return[n];return[]}function re(r){let n=H.get(r??"-");if(!n)return;let a=[];if(n.validation==="stale")a.push("Config/ARXML changed since the last ecuc_validate: run it (unfiltered) now.");if(n.validation==="errors")a.push("The last ecuc_validate reported errors: fix them and validate again.");if(n.rte==="pending")a.push(`C changed (${n.cFiles.slice(-5).join(", ")}): run autosar_verify_rte on it.`);if(n.rte==="fail")a.push("autosar_verify_rte is FAILING: fix the calls (or apply its arxml_edit ops) and verify again.");if(n.docs==="pending"&&n.validation==="clean")a.push(`Changed elements not yet checked against the ingested documents (${n.changed.slice(0,8).join("; ")}${n.changed.length>8?"; \u2026":""}): run ecuc_validate docs=true and answer its checklist item by item.`);if(!a.length)return;return["# AUTOSAR: open verification items (do not report the task as done until each is resolved)",...a.map((e)=>`- ${e}`)].join(`
5
+ `)}var Ee=/^(?: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 Oe(r){let n=r.trim().replace(/[\p{Extended_Pictographic}\u200D\uFE0F]/gu,"").replace(/[!.?,:;~\-]+/g," ").replace(/\s+/g," ").trim();return n.length>0&&n.length<=40&&Ee.test(n)}function oe(r,n){se.set(r??"-",Oe(n))}function ae(r,n){if(process.env.AUTOSAR_LOOP_GATES==="0")return;if(!se.get(r??"-"))return;return`NO TOOLS: the user only greeted you (no task). Do not call ${n} 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 Ne}from"url";var xe="autosar-data==0.17.0";function je(){let r=Te(Ne(import.meta.url)),n=[B(r,"..","python"),B(r,"..","..","python")].find((a)=>Ce(B(a,"ecuc_engine","__main__.py")));if(!n)throw Error(`ECUC engine not found next to ${r} (expected ../python/ecuc_engine)`);return n}async function Ie(r){try{return await Bun.spawn([...r,"-c","import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"],{stdout:"ignore",stderr:"ignore",stdin:"ignore"}).exited===0}catch{return!1}}var D={};async function De(){if(D.cmd!==void 0)return D.cmd;let r=process.env.AUTOSAR_PYTHON?.trim(),a=r?[[r]]:[["uv","run","--no-project","--quiet","--with",xe,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let e of a)if(await Ie(e))return D.cmd=e,e;return D.cmd=null,null}async function y(r,n,a){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=je(),o=Bun.spawn([...e,"-m","ecuc_engine","--root",r,...n,"--json"],{cwd:r,env:{...process.env,PYTHONPATH:[s,process.env.PYTHONPATH].filter(Boolean).join(process.platform==="win32"?";":":")},stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a}),[i,t]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text()]);await o.exited;let d=i.trim().split(`
6
+ `).filter(Boolean).at(-1);if(!d)return{ok:!1,error:`engine produced no output (exit ${o.exitCode}): ${t.trim().slice(-2000)}`};try{return JSON.parse(d)}catch(l){return{ok:!1,error:`engine output was not JSON (${String(l)}): ${d.slice(0,500)} ${t.slice(-500)}`}}}var c=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(`
7
+ `);function C(r){if(typeof r!=="string")return r;let n=r.trim();if(!n.startsWith("[")&&!n.startsWith("{")&&!n.startsWith('"'))return r;try{return C(JSON.parse(n))}catch{return r}}var A=(r)=>c.preprocess(C,r);function E(r){let n=C(r);if(n===void 0||n===null||n==="")return;if(typeof n==="string")return[n];if(Array.isArray(n))return n.map(String).filter((a)=>a.trim());return[String(n)]}var O=()=>c.preprocess(E,c.array(c.string()).optional()),R=" In answers cite, for every element, its AUTOSAR path (the value's @path, e.g. /Pkg/Com/ComConfig/MySig), its"+" DEFINITION-REF (@def, e.g. /AUTOSAR/EcucDefs/Com/ComConfig/ComSignal) and file:line \u2014 never give the"+` DEFINITION-REF when the path is asked. A value's file:line is its "@at:<Param>" (the VALUE element; "@at" is`+' the container); integers come with "@hex:<Param>" \u2014 copy both, never compute a line or a base conversion'+" yourself. Cite a requirement ID only if it appears verbatim in a tool result or spec text read this session.";function j(r,n=200){let a=r.slice(0,n).map((e)=>`${e.file}:${e.line} ${e.severity.toUpperCase()} ${e.rule} ${e.path} \u2014 ${e.message}${e.defRef?` [def ${e.defRef}]`:""}`);if(r.length>n)a.push(`\u2026 ${r.length-n} more`);return a}function _(r){let n=r.didYouMean?`
8
+ Did you mean: ${r.didYouMean.join(", ")}`:"",a=r.schema?`
9
+ Schema errors: ${JSON.stringify(r.schema)}`:"";return`ERROR: ${r.error}${n}${a}`}function S(r){let n=r.warnings??[];return n.length?n.map((a)=>`WARNING: ${a}`).join(`
9
10
  `)+`
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
- `);return o.length>t?[`\u2026 (${o.length-t} earlier lines omitted)`,...o.slice(-t)].join(`
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
- ${c.answer.trim()}
11
+ `:""}function b(r,n){if(!n)return r;return Ue(n)?n:Pe(r,n)}async function Fe(r){let n=Bun.file(W(r,".hydron","autosar.json"));if(!await n.exists())return{};return n.json().catch((a)=>{throw Error(`.hydron/autosar.json is not valid JSON: ${String(a)}`)})}async function He(r,n){let a=(await Fe(r))[n];if(typeof a==="string")return{command:a};if(a&&typeof a==="object"&&typeof a.command==="string")return a;return}function ce(r,n=150){let a=r.split(`
12
+ `);return a.length>n?[`\u2026 (${a.length-n} earlier lines omitted)`,...a.slice(-n)].join(`
13
+ `):r}async function Be(r,n,a,e){let s=process.platform==="win32"?["cmd","/d","/s","/c",r]:["sh","-c",r],o=Date.now(),i=Bun.spawn(s,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:AbortSignal.any([e,AbortSignal.timeout(a*1000)])}),[t,d]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text()]);return{code:await i.exited,out:t,err:d,secs:Math.round((Date.now()-o)/1000)}}var Je=(r)=>(r??[]).map((n)=>`CAN ID ${n.canIdHex??"?"} (${n.canId??"?"}) ${n.direction} via ${n.canIfPdu}, controller ${n.controller??"?"}, network ${(n.network??[]).join(", ")||"?"}`).join("; ");async function de(r,n,a){let e=n.filter((t)=>t?.path&&/\/Com((Group)?Signal|IPdu)$/.test(String(t.definition_ref??""))&&t.ipdu===void 0&&t.direction===void 0);if(!e.length)return[];let s=await y(r,["signal-owners",...new Set(e.map((t)=>t.path))],a);if(!s.ok)return[`NOTE: owning I-PDU not computed locally (${s.error})`];let o=s.owners,i=[];for(let t of e){let d=o[t.path];if(d===null||d===void 0){i.push(`NOTE: ${t.path} is not in the local checkout (${r}); owning I-PDU/direction unknown`);continue}t.ipdu_local=d,i.push(d.length?`${t.path}: owning I-PDU ${d.map((l)=>`${l.ipdu} (ComIPduDirection=${l.direction??"?"}${l.can?.length?`; ${Je(l.can)}`:""})`).join(", ")} [local ECUC]`:`${t.path}: referenced by no ComIPdu (ComIPduSignalRef) in the local ECUC`)}return i}var We=(r)=>{if(typeof r==="number"&&Number.isSafeInteger(r))return r;if(typeof r==="string"&&/^\s*-?(0x[0-9a-f]+|\d+)\s*$/i.test(r)){let n=r.trim(),a=n.startsWith("-")?-Number(n.slice(1)):Number(n);return Number.isSafeInteger(a)?a:null}return null},he=(r)=>r<0?`-0x${(-r).toString(16).toUpperCase()}`:`0x${r.toString(16).toUpperCase()}`;async function le(r,n,a){let e=n.filter((t)=>typeof t?.path==="string");if(!e.length)return[];let s=await y(r,["value-sites",...new Set(e.map((t)=>t.path))],a),o=s.ok?s.sites:{},i=[];if(!s.ok)i.push(`NOTE: value lines not computed locally (${s.error})`);for(let t of e){let d=o[t.path];if(d){t.values_local=d.values,i.push(`VALUES ${t.path} (container ${d.at}) [local ECUC; cite these lines]:`);for(let[p,u]of Object.entries(d.values))for(let h of Array.isArray(u)?u:[u])i.push(` ${p} = ${JSON.stringify(h.value)}${h.hex?` (dec ${h.dec}, hex ${h.hex})`:""} @ ${h.at}`);continue}let l=t.values&&typeof t.values==="object"?t.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)t.values_int=f;if(s.ok)i.push(`NOTE: ${t.path} is not in the local checkout (${r}): its file:line${t.file?` ${t.file}:${t.line??"?"}`:""} is where the ELEMENT starts, not a value line. To cite a value's line, read that file; never estimate one.`)}return i}var ue=(r)=>{let n=r.notes??[],a=r.errors??[];return[...n.map((e)=>`NOTE: ${typeof e==="string"?e:JSON.stringify(e)}`),...a.map((e)=>`BACKEND ERROR: ${typeof e==="string"?e:JSON.stringify(e)}`)]};async function Ge(r,n){try{let a=await n(),e=typeof a==="string"?a:a.output;if(e&&e.trim())return a;return`${r}: no output (this is a bug in the AUTOSAR pack; retry or report it)`}catch(a){return`ERROR (${r}): ${a instanceof Error?a.message:String(a)}`}}function Ve(r){for(let[n,a]of Object.entries(r)){let e=a.execute;a.execute=(s,o)=>Ge(n,()=>e(s,o))}return r}function Xe(r,n=process.env){let a=new Set;for(let e of(n.AUTOSAR_DISABLE_TOOLS??"").split(/[\s,]+/))if(e)a.add(e);if(r)try{let e=JSON.parse(Le(W(r,".hydron","autosar.json"),"utf8"));if(Array.isArray(e.disableTools)){for(let s of e.disableTools)if(typeof s==="string"&&s)a.add(s)}}catch{}return a}function qe(r,n){if(n.size===0)return r;return Object.fromEntries(Object.entries(r).filter(([a])=>!n.has(a)))}var fe=new Map;async function J(r,n,a,e){let s=`${n??"-"}|${a??""}|${r}`,o=fe.get(s);if(o)return o;let i;try{let t=await N(a,e),d=await x("/api/v1/mcp/retriever/query",t,{query:r,workspace_id:Number(t)||t},e,300000),l=(d.citations??[]).slice(0,12).map((f,p)=>{let u=f.file?`${f.file}${f.start_line?`:${f.start_line}`:""}`:`${f.doc_name??"?"}${f.title?` > ${f.title}`:""}`;return` [D${p+1}] ${u}: "${(f.excerpt??"").replace(/\s+/g," ").slice(0,280)}"`});i=d.answer?`(project ${t}; retriever answer, ${l.length} citation(s). Trust a statement only where a citation supports it.)
14
+ ${d.answer.trim()}
14
15
  Citations:
15
16
  ${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 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) ---
17
+ `)||" (none)"}`:`(project ${t}: no answer${d.error_message?`: ${d.error_message}`:""})`}catch(t){return`UNAVAILABLE: ${t instanceof Error?t.message:String(t)} -- select a Hydron project with the documents ingested (hydron projects select) or pass workspace_id.`}return fe.set(s,i),i}var Ye=async(r)=>{let n=Xe(r?.directory),a=(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:c.string().optional().describe("module name substituted for {module} in the command, if used"),args:c.string().optional().describe("extra arguments substituted for {args} (or appended if no placeholder)"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(s,o){let i=b(o.directory,s.project_dir),t=await He(i,e);if(!t)return`No \`${e}\` command configured. Add it to ${W(i,".hydron","autosar.json")}, e.g.
18
+ {"${e}": {"command": "${e==="generate"?"<vendor-cli> -p Config/Ecu.dpa -g {module}":"make -C Build all"}", "cwd": ".", "timeoutSec": 1800}}`;let d=s.args??"",l=t.command.replaceAll("{module}",s.module??""),f=l.includes("{args}")?l.replaceAll("{args}",d):`${l}${d?` ${d}`:""}`,p=b(i,t.cwd);await o.ask({permission:`autosar_${e}`,patterns:[f],always:[t.command],metadata:{command:f,cwd:p}}),o.metadata({title:`${e}: ${f}`});let u=await Be(f,p,t.timeoutSec??3600,o.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
19
  ${ce(u.out)}`:"",u.err.trim()?`--- stderr (tail) ---
19
20
  ${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
+ `),metadata:{exit:u.code}}}});return{"chat.message":async(e,s)=>{let o=(s?.parts??[]).map((i)=>i.type==="text"?String(i.text??""):"").join(" ");oe(e.sessionID,o)},"tool.execute.before":async(e,s)=>{let o=ae(e.sessionID,e.tool);if(o)throw Error(o);let i=Y(e.tool,s.args)??K(e.tool,s.args);if(i)throw Error(i);let t=ne(e.sessionID,e.tool,s.args);if(t)throw Error(t)},"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 o=re(e?.sessionID);if(o)s.system.push(o)},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."+R,args:{path:c.string().optional().describe("AUTOSAR path, SHORT-NAME or partial path of a module/container/parameter, or a def path"),depth:c.number().int().min(0).max(20).optional().describe("sub-container levels to expand (default 2)"),schema:c.boolean().optional().describe("include the param-def summary for the element"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=["read"];if(e.path)o.push(e.path);if(o.push("--depth",String(e.depth??2)),e.schema)o.push("--schema");let i=await y(b(s.directory,e.project_dir),o,s.abort);if(!i.ok)return S(i)+_(i);let{ok:t,engine:d,ms:l,warnings:f,...p}=i;return S(i)+JSON.stringify(p,null,1)}}),ecuc_edit:w({description:"Edit ECUC ARXML in place \u2014 the ONLY way to change configuration (edit/write/sed on .arxml are blocked). "+"Get exact paths and allowed params from ecuc_read (schema=true) first. Ops by AUTOSAR path: {op:'set', path, param, value} (value scalar, '->/ref/path', or a list for multi-valued "+"params), {op:'add', path:<parent>, container:'DefName:ShortName', values:{\u2026ECUC JSON\u2026}}, {op:'add', "+"path, param, value} (append a value), {op:'remove', path[, param[, value]]}. The engine picks the value element type, DEFINITION-REF/DEST and VALUE-REF DEST from the param defs, rejects out-of-range/non-literal values, patches only the changed bytes in the file each element lives in (UUIDs, order, comments preserved), applies all ops or none, and checks ARXML schema validity. Returns the unified diff and the validation of touched files. ALWAYS run ecuc_validate after editing and fix what it reports."+R,args:{ops:A(c.array(A(c.object({op:c.enum(["set","add","remove"]),path:c.string().describe("AUTOSAR path of the target (or parent for add-container)"),param:c.string().optional().describe("parameter/reference def short-name"),value:c.any().optional().describe("value: number | boolean | string | '->/path' | list"),container:c.string().optional().describe("for add: 'DefName:ShortName' (or 'Name' if equal)"),values:A(c.record(c.string(),c.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:c.boolean().optional().describe("compute and show the diff without writing"),force:c.boolean().optional().describe("write values that fail def checks (avoid; explain why if used)"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=["edit","--ops",JSON.stringify(e.ops)];if(e.dry_run)o.push("--dry-run");if(e.force)o.push("--force");let i=await y(b(s.directory,e.project_dir),o,s.abort);if(!i.ok){let f=i.changes??[];return S(i)+_(i)+(f.length?`
21
22
  Rejected diff:
22
23
  ${f.map((p)=>p.diff).join(`
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=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")?`
24
+ `)}`:"")}let t=i.changes??[],d=i.validation,l=[`${i.written?"Written":"Dry run (nothing written)"}: ${i.applied} op(s), ${t.length} file(s) changed.`,...(i.notes??[]).map((f)=>`NOTE: ${f}`),...t.map((f)=>f.diff)];if(d)l.push(d.validated?`Validation of touched files: ${JSON.stringify(d.summary)}`:"Validation skipped: no param defs loaded.",...j(d.diagnostics,50));return{title:`ecuc_edit ${t.map((f)=>f.file).join(", ")}`,output:S(i)+l.join(`
25
+ `)}}}),ecuc_validate:w({description:"Validate ALL ARXML of the project. ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions, plus semantic rule packs (H2L-*: Com signals inside their I-PDU and non-overlapping incl. Motorola bit order, unique handle IDs) that run even without defs. System/ECU extract, SWC and interface files: strict AUTOSAR schema load and every *-REF resolves with the right DEST (H2L-ARXML-*). Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit / arxml_edit and before "+"autosar_generate. `files` takes files, directories or globs; omit it to validate everything (preferred). The output always lists which files/modules were loaded; a filter that matches nothing is an ERROR. If it reports nothing on a project you expect to have issues, rerun unfiltered and check the loaded-file list."+R,args:{files: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:c.string().optional().describe("only validate this module (e.g. Com); an unknown module is an ERROR, not clean"),docs:c.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:c.string().optional().describe("with docs=true: the elements/values to check when nothing was changed in this session"),workspace_id:c.union([c.string(),c.number()]).optional().describe("Hydron project for docs=true (default: the selected one)"),max:c.number().int().min(1).optional().describe("cap the diagnostics listed (default 200)"),checkGenerated:c.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:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=["validate"];for(let g of E(e.files)??[])i.push("--file",g);if(e.module)i.push("--module",e.module);if(e.checkGenerated===!0)i.push("--check-generated");if(e.checkGenerated===!1)i.push("--no-check-generated");let t=await y(o,i,s.abort);if(!t.ok)return S(t)+_(t);let{diagnostics:d,scope:l}=t,f=d.filter((g)=>g.rule!=="H2L-DISCOVERY"),u=l.configFiles===0&&t.scope.inputFiles?`Checked ${t.scope.inputFiles} extract/SWC file(s) (AUTOSAR schema + references): ${f.length?JSON.stringify(t.summary):"CLEAN, no findings"}`:t.validated?`Validated ${t.modules.join(", ")||"(no modules)"} against ${t.defsLoaded} module def(s): ${f.length?JSON.stringify(t.summary):"no findings"}`:`Param definitions NOT loaded: only the H2L-* semantic rules ran. ${f.length?JSON.stringify(t.summary):"no findings"}`,h=[`Loaded ${l.configFiles} config file(s) and ${t.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=I(s.sessionID).changed,T=e.about?.trim()||g.join("; ");if(!T)m="\n\nDOCUMENT CHECK UNAVAILABLE: nothing was changed in this session; pass `about` with the elements/values to check.";else{let k=await J(`Check these AUTOSAR configuration elements and values against the specifications and manuals in this knowledge base: ${T}. 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=k.startsWith("UNAVAILABLE")?`
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
- `)}}return{title:`ecuc_validate ${JSON.stringify(n.summary)}`,output:S(n)+[u,...I(c,e.max??200),...h].join(`
28
- `)+m}}}),arxml_diff:w({description:"Semantic ARXML diff by AUTOSAR path between two files or directories (e.g. a git checkout of the old Config/ vs the current one, or Output/ before/after generation inputs). Ignores UUIDs, whitespace, comments, element order and file splits; ECUC values are compared per parameter. Returns added/removed/changed elements with the changed parameter values. Use it to review edits and PRs instead of a textual diff.",args:{a:d.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:d.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:d.string().optional().describe("project root (default: session directory)")},async execute(e,s){let a=b(s.directory,e.project_dir),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
- ${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 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
- ${c.findings.join(`
34
- `)}`),...I(n,50),...(a.notes??[]).map((c)=>`NOTE: ${c}`)].join(`
35
- `)}}}),arxml_edit:w({description:"Structured edit of NON-ECUC ARXML (System/ECU extract, SWC, interfaces), including NEW files \u2014 never write "+"that XML by hand. Ops: {op:'new_file', file:'Input/SWC_X.arxml', packages:['/Swcs','/Interfaces']} (empty R25-11 file; later ops in the same call can fill it), {op:'add', parent_path, element:'I-SIGNAL', short_name, values:{TAG: value | '->/ref/path' | {nested} | [list]}}, {op:'set', path, element:'START-POSITION', value}, {op:'remove', path}. Missing packages along parent_path are created (top level needs `file` when the project has several ARXML files). Every *-REF gets its DEST from the referenced element's real tag (targets must exist or be added earlier in the same call), elements are placed and ordered per the AUTOSAR schema, references are re-checked and the file is strictly re-loaded; nothing is written if anything fails. For ECUC values use ecuc_edit; to add a whole signal use autosar_add_signal.",args:{ops: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
- ${r.problems.join(`
37
- `)}`:"")+(n.length?`
27
+ DOCUMENT CHECK UNAVAILABLE: ${k}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${T}`,k,"","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(`
28
+ `)}}return{title:`ecuc_validate ${JSON.stringify(t.summary)}`,output:S(t)+[u,...j(d,e.max??200),...h].join(`
29
+ `)+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:c.string().describe("old: file, directory (recursive) or glob, relative to the project root or absolute"),b:c.string().describe("new: file, directory (recursive) or glob, relative to the project root or absolute"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=await y(o,["diff",e.a,e.b],s.abort);if(!i.ok)return _(i);let{ok:t,engine:d,ms:l,...f}=i;return JSON.stringify(f,null,1)}}),autosar_trace:w({description:"Trace AUTOSAR configuration to code through the H2Loop code graph of the selected project: query with an AUTOSAR path, a SHORT-NAME, or a C symbol (reverse lookup). Returns the ARXML element (path, module, DEFINITION-REF, file:line, values), the C symbols it configures (generated macros/const tables via the symbolic-name rule or token/value matching, with method + score) and their callers in in-house code. For a ComSignal it also shows the owning I-PDU and its ComIPduDirection (direction lives on the I-PDU). Elements in the local checkout get a VALUES block: each value with the file:line of its VALUE element and integers in dec + hex (the graph's file:line is only where the element starts). Use for impact analysis ('what code changes if I change X?') and 'where does this symbol come from?'. Requires the project's code to be ingested."+R,args:{query:c.string().describe("AUTOSAR path, SHORT-NAME, or C symbol"),data_source_id:c.number().int().optional().describe("restrict to one code data source"),limit:c.number().int().min(1).max(100).optional().describe("max matches (default server-side)"),workspace_id:c.union([c.string(),c.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:c.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,s){let o=await N(e.workspace_id,s.abort),i={query:e.query};if(e.data_source_id!==void 0)i.data_source_id=e.data_source_id;if(e.limit!==void 0)i.limit=e.limit;let t=await x("/api/v1/mcp/autosar/trace",o,i,s.abort),d=t.matches??[],l=b(s.directory,e.project_dir),f=d.map((m)=>m.arxml).filter((m)=>!!m),[p,u]=await Promise.all([de(l,f,s.abort),le(l,f,s.abort)]),h=[`${d.length} match(es) for "${e.query}" in workspace ${o}`+(t.data_sources_queried!==void 0?` (data sources queried: ${JSON.stringify(t.data_sources_queried)})`:""),...ue(t),...p,...u,JSON.stringify(d,null,1)];if(!d.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(`
30
+ `)}}}),autosar_config_lookup:w({description:"Look up one ARXML element in the H2Loop code graph by AUTOSAR path: the element (module, DEFINITION-REF, file:line, values), its direct children, references out and in (who points at it), and linked C symbols. Elements in the local checkout get a VALUES block with each value's VALUE-element file:line and integers in dec + hex. Use it to navigate config relations across the ingested repo (including files not in the local checkout); for local edits use ecuc_read/ecuc_edit."+R,args:{path:c.string().describe("AUTOSAR path, e.g. /Pkg/Com/ComConfig/MySignal"),data_source_id:c.number().int().optional().describe("restrict to one code data source"),workspace_id:c.union([c.string(),c.number()]).optional().describe("H2Loop project id or name (default: the project selected with `hydron projects select`)"),project_dir:c.string().optional().describe("local project root used to add I-PDU/direction for signals (default: session directory)")},async execute(e,s){let o=await N(e.workspace_id,s.abort),i={path:e.path};if(e.data_source_id!==void 0)i.data_source_id=e.data_source_id;let t=await x("/api/v1/mcp/autosar/config-lookup",o,i,s.abort),d=t.matches??[],l=b(s.directory,e.project_dir),f=d.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:[`${d.length} match(es) for ${e.path} in workspace ${o}`,...ue(t),...p,...u,JSON.stringify(d,null,1)].join(`
31
+ `)}}}),ecuc_find:w({description:"Structured query over the ECUC configuration \u2014 use it instead of grep/read on ARXML. Filter containers by "+`module, container_def (def short-name, e.g. PduRRoutingPath, ComSignal, NvMBlockDescriptor), where ("ComIPduDirection=SEND, ComBitSize>8"; =, !=, >, <, >=, <=, ~regex), ref_to (containers that reference this path directly or through up to 2 references, e.g. all routing paths whose destination is an EcuC Pdu), and referenced_by (e.g. all ComSignals referenced by I-PDU Y). Returns AUTOSAR paths, the container's file:line (at) and its values, each with "@at:<Param>" (file:line of the VALUE element) and, for integers, "@hex:<Param>".`+R,args:{module:c.string().optional(),container_def:c.string().optional().describe("container definition short-name"),where:c.union([c.string(),c.record(c.string(),c.any())]).optional().describe("conditions on parameter values"),ref_to:c.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:c.string().optional().describe("container whose references define the result set"),limit:c.number().int().min(1).max(500).optional(),project_dir:c.string().optional()},async execute(e,s){let o=["find"];if(e.module)o.push("--module",e.module);if(e.container_def)o.push("--container-def",e.container_def);if(e.where)o.push("--where",typeof e.where==="string"?e.where:JSON.stringify(e.where));if(e.ref_to)o.push("--ref-to",e.ref_to);if(e.referenced_by)o.push("--referenced-by",e.referenced_by);o.push("--limit",String(e.limit??50));let i=await y(b(s.directory,e.project_dir),o,s.abort);if(!i.ok)return S(i)+_(i);let{ok:t,engine:d,ms:l,warnings:f,...p}=i;return S(i)+JSON.stringify(p,null,1)}}),autosar_spec_id_check:w({description:"Check AUTOSAR requirement IDs (SWS_/SRS_/TPS_/ECUC_/RS_ \u2026, e.g. SWS_Com_00197, 'SWS_NvM_00898/00899') "+"against the project's own AUTOSAR spec texts (.hydron/autosar.json `specDocs` globs of .txt/.md exports, or $AUTOSAR_SPEC_DOCS). Returns per ID: DEFINED (with document, line and the requirement text), MENTIONED-ONLY (occurs only in trace tables / running text), NOT-FOUND or MALFORMED. Run it BEFORE citing any ID that did not come verbatim from a tool result; never cite an ID it does not report DEFINED, and describe the rule with the returned text, not from memory.",args:{ids:O().describe("requirement IDs to check (a list, a JSON-encoded list, or one ID)"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=E(e.ids)??[];if(!o.length)return'ERROR: pass ids, e.g. ["SWS_Com_00197"]';let i=await y(b(s.directory,e.project_dir),["spec-ids",...o],s.abort);if(!i.ok)return _(i);let t=i.results;return{title:`autosar_spec_id_check ${JSON.stringify(i.counts)}`,output:[`Checked ${t.length} ID(s) against ${i.docs} spec text file(s) (${i.docsOrigin}; ${i.indexedIds} IDs indexed): ${JSON.stringify(i.counts)}`,...t.map((d)=>`${d.id} ${d.status}`+(d.doc?` \u2014 ${d.doc}:${d.line}`:"")+(d.didYouMean?` (did you mean ${d.didYouMean}?)`:"")+(d.text?`
32
+ ${d.text}`:"")),t.some((d)=>d.status!=="DEFINED")?"Do not cite IDs that are not DEFINED; state the rule without an ID instead.":""].filter(Boolean).join(`
33
+ `)}}}),ecuc_crosscheck:w({description:"Per-module cross-check table: runs the semantic rule packs for one module (Com, PduR, EcuC, NvM, Fee, Ea, "+"CanIf, Dem, ...) \u2014 config vs System/ECU extract (H2L-SYS), gateway routing vs extract (H2L-PDUR), NvM/Fee "+"length vs the C RAM object's sizeof (H2L-NVM), memory capacity (H2L-MEM), signal packing and handle IDs \u2014 "+"and returns, per element, the findings, plus notes on what could NOT be checked. Run it for every module present after ecuc_validate; a clean validate alone is not proof of a correct configuration."+R,args:{module:c.string().describe("module name, e.g. PduR"),project_dir:c.string().optional()},async execute(e,s){let o=await y(b(s.directory,e.project_dir),["crosscheck",e.module],s.abort);if(!o.ok)return S(o)+_(o);let i=o.rows,t=o.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${o.summary}`,output:[`${e.module}: ${o.summary} (element kinds: ${o.elementKinds.join(", ")||"none"})`,...i.map((d)=>`${d.element} (${d.at})
34
+ ${d.findings.join(`
35
+ `)}`),...j(t,50),...(o.notes??[]).map((d)=>`NOTE: ${d}`)].join(`
36
+ `)}}}),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:A(c.array(A(c.record(c.string(),c.any()))).min(1)).describe("list of ops"),dry_run:c.boolean().optional(),project_dir:c.string().optional()},async execute(e,s){let o=["arxml-edit","--ops",JSON.stringify(C(e.ops))];if(e.dry_run)o.push("--dry-run");let i=await y(b(s.directory,e.project_dir),o,s.abort),t=i.changes??[];if(!i.ok)return _(i)+(i.problems?.length?`
37
+ ${i.problems.join(`
38
+ `)}`:"")+(t.length?`
38
39
  Rejected diff:
39
- ${n.map((f)=>f.diff).join(`
40
- `)}`:"");let c=r.notes??[],l=r.createdPackages??[];return`${r.written?"Written":"Dry run"}; `+((r.newFiles??[]).length?`new file(s) ${r.newFiles.join(", ")}; `:"")+`created ${JSON.stringify(r.created)}`+(l.length?`; new packages ${l.join(", ")}`:"")+(c.length?`
41
- NOTE: ${c.join(`
40
+ ${t.map((f)=>f.diff).join(`
41
+ `)}`:"");let d=i.notes??[],l=i.createdPackages??[];return`${i.written?"Written":"Dry run"}; `+((i.newFiles??[]).length?`new file(s) ${i.newFiles.join(", ")}; `:"")+`created ${JSON.stringify(i.created)}`+(l.length?`; new packages ${l.join(", ")}`:"")+(d.length?`
42
+ NOTE: ${d.join(`
42
43
  NOTE: `)}`:"")+`
43
- ${n.map((f)=>f.diff).join(`
44
+ ${t.map((f)=>f.diff).join(`
44
45
  `)}
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
- ${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=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}
46
+ Next: ecuc_validate (checks extract/SWC files too).`}}),autosar_add_like:w({description:"Add a new X LIKE an existing Y, end to end, in one checked step: a new message (frame, I-PDU, triggerings, EcuC Pdu, CanIf PDU, PduR route, Com I-PDU), port, runnable with its event and task mapping, Dem event + DTC, NvM block + Fee block, interface... Projects name a thing's elements after it, so the engine clones every element whose SHORT-NAME contains `like` and that is linked to the others by references, across ECUC and System/SWC ARXML, renamed to `name`; lists that contain the template get the clone too; handle IDs get the lowest free value; the template's own members (a message's signals) are left out unless named in `also`. `set` then sets values on the clones by ECUC parameter name, XML tag, or 'Owner:key'. Schema + references are checked and validation runs before/after: any new finding rolls everything back. PREFER THIS over building a chain op by op with arxml_edit/ecuc_edit. Example: like='BCM_DoorStatus', name='BCM_SettingsAck', also={'DrvDoorOpenSts':'SettingsAckCounter'}, set={'IDENTIFIER':'0x4F8','CanIfTxPduCanId':'0x4F8','PduLength':2,'FRAME-LENGTH':2,'I-SIGNAL-I-PDU:LENGTH':2,'ComTxModeTimePeriod':1.0,'SettingsAckCounter:ComBitSize':8}. Pick as template the existing element most like the new one (same direction/bus/kind); dry_run first.",args:{like:c.string().describe("name stem of the template element, e.g. BCM_DoorStatus (an existing message), DoorLockActuatorFault (a Dem event)"),name:c.string().describe("the new stem, e.g. BCM_SettingsAck"),also:A(c.record(c.string(),c.string())).optional().describe("template members to clone and rename too: {template stem: new stem}"),set:A(c.record(c.string(),c.any())).optional().describe("values on the clones: {ParamDefName | XML-TAG | 'Owner:key': value}"),seed:c.string().optional().describe("one element of the template chain, when several separate chains carry the stem"),keep_members:c.boolean().optional().describe("also copy the template's own members (default false)"),dry_run:c.boolean().optional(),project_dir:c.string().optional()},async execute(e,s){let o=["add-like","--like",e.like,"--name",e.name];if(e.also)o.push("--also",JSON.stringify(C(e.also)));if(e.set)o.push("--set",JSON.stringify(C(e.set)));if(e.seed)o.push("--seed",e.seed);if(e.keep_members)o.push("--keep-members");if(e.dry_run)o.push("--dry-run");let i=await y(b(s.directory,e.project_dir),o,s.abort),t=(l)=>i[l]??[],d=[i.ok?`${i.written?"Written":"Dry run OK"}: ${t("created").length} element(s) like ${e.like} as ${e.name}`:`NOT DONE: ${i.error}`,...t("created").length?["Created:",...t("created").map((l)=>` ${l}`)]:[],...t("set").length?["Set:",...t("set").map((l)=>` ${l}`)]:[],...t("ids").length?["Handle IDs:",...t("ids").map((l)=>` ${l}`)]:[],...t("linked").length?["Linked:",...t("linked").map((l)=>` ${l}`)]:[],...t("notCopied").length?[`Not copied (the template's own members): ${t("notCopied").length}`,...t("notCopied").slice(0,12).map((l)=>` ${l}`)]:[],...t("singleValuedNotLinked").length?["Single-valued references to the template NOT changed (add/point your own if the new element needs one):",...t("singleValuedNotLinked").map((l)=>` ${l}`)]:[],...t("notes").map((l)=>`NOTE: ${l}`),...(i.problems??[]).map((l)=>`PROBLEM: ${l}`),...(i.diagnostics??[]).length?j(i.diagnostics,20):[]];if(i.ok&&!i.written)d.push("Next: run again without dry_run.");if(i.ok&&i.written)d.push(String(i.next??""));return d.join(`
47
+ `)}}),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:c.string(),ipdu:c.string().describe("ComIPdu AUTOSAR path or SHORT-NAME"),bit_size:c.number().int().min(1).max(64).optional(),type:c.string().optional().describe("ComSignalType, e.g. UINT8 (default)"),bit_position:c.number().int().min(0).optional().describe("omit for the first free byte-aligned position"),endianness:c.enum(["LITTLE_ENDIAN","BIG_ENDIAN","OPAQUE"]).optional(),init:c.union([c.number(),c.string()]).optional(),transfer_property:c.string().optional().describe("e.g. PENDING, TRIGGERED, TRIGGERED_ON_CHANGE"),dry_run:c.boolean().optional(),project_dir:c.string().optional()},async execute(e,s){let o=["add-signal","--name",e.name,"--ipdu",e.ipdu,"--type",e.type??"UINT8"];if(e.bit_size!==void 0)o.push("--bit-size",String(e.bit_size));if(e.bit_position!==void 0)o.push("--bit-position",String(e.bit_position));if(e.endianness)o.push("--endianness",e.endianness);if(e.init!==void 0)o.push("--init",String(e.init));if(e.transfer_property)o.push("--transfer-property",e.transfer_property);if(e.dry_run)o.push("--dry-run");let i=await y(b(s.directory,e.project_dir),o,s.abort);if(!i.ok)return _(i)+(i.diagnostics?.length?`
48
+ ${j(i.diagnostics,20).join(`
49
+ `)}`:"");let{ok:t,engine:d,ms:l,...f}=i;return JSON.stringify(f,null,1)}}),autosar_audit:w({description:"Integration review \u2014 run this FIRST when reviewing C code that uses BSW services. Deterministically scans "+"C files (default: .hydron/autosar.json `audit` paths, else every .c in the project except generated files, "+"recognised by banner or *_Cfg/*_PBcfg/Rte* names \u2014 folder names do not matter) for Com_Send/ReceiveSignal[Group], "+"NvM_Read/WriteBlock/RestoreBlockDefaults, Dem_SetEventStatus/ReportErrorStatus, PduR_*Transmit and Rte_Write_/Rte_Read_ (resolved through the generated Output/ RTE headers), resolves every handle through the ECUC (symbolic name or raw number), and reports: H2L-API-001 raw numeric handle, -002 unknown handle, -003 direction mismatch (send on a RECEIVE I-PDU signal or receive on SEND), -004 C object width vs ComSignalType, -005 NvM NULL_PTR without a permanent RAM block (NULL_PTR WITH one is valid, SWS_NvM_00900). Each finding has file:line, evidence (configured values + AUTOSAR paths) and a spec citation; calls it cannot check are listed as unchecked, never guessed. Confirm findings with ecuc_read / autosar_trace.",args:{paths: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:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=await y(o,["audit",...E(e.paths)??[]],s.abort);if(!i.ok)return S(i)+_(i);let t=(i.notes??[]).map((h)=>`NOTE: ${h}`),{findings:d,unchecked:l,scanned:f}=i,p=[`Scanned ${f.sources.length} C file(s), ${f.calls} BSW call(s): ${d.length?JSON.stringify(i.summary):"no findings"}`,...d.map((h)=>`${h.file}:${h.line} ${h.severity.toUpperCase()} ${h.rule} ${h.call}
48
50
  ${h.message}
49
51
  evidence: ${JSON.stringify(h.evidence)}
50
52
  spec: ${h.cite}${h.fix?`
51
- fix: ${h.fix}`:""}`)];if(l.length)p.push(`Unchecked (${l.length}):`,...l.slice(0,50).map((h)=>` ${h.file}:${h.line} ${h.call} \u2014 ${h.reason}`));let u=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=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(`
53
+ fix: ${h.fix}`:""}`)];if(l.length)p.push(`Unchecked (${l.length}):`,...l.slice(0,50).map((h)=>` ${h.file}:${h.line} ${h.call} \u2014 ${h.reason}`));let u=i.unreferenced??{};for(let[h,m]of Object.entries(u))p.push(`INFO configured but never referenced in the scanned code \u2014 ${h}: ${m.count} (e.g. ${m.sample.slice(0,5).join(", ")})`);return p.push(...t),{title:`autosar_audit ${JSON.stringify(i.summary)}`,output:S(i)+p.join(`
54
+ `)}}}),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:c.string().optional().describe("git ref: only calls on lines changed since this ref (plus untracked files)"),swc:c.string().optional().describe("restrict to one SW-C (short name or AUTOSAR path)"),runnable:c.string().optional().describe("restrict to one runnable (short name or SYMBOL)"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=["verify-rte",...E(e.paths)??[]];if(e.diff_against)i.push("--diff-against",e.diff_against);if(e.swc)i.push("--swc",e.swc);if(e.runnable)i.push("--runnable",e.runnable);let t=await y(o,i,s.abort);if(!t.ok)return _(t);let{findings:d,counts:l}=t,f=d.filter((g)=>g.status!=="OK"),p=t.scanned,u=[`Verified ${p.calls} Rte_* call(s) in ${p.files.length} file(s) against SW-C(s) ${t.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=t.notChecked??[];if(h.length)u.push(`Not checked (${h.length}): ${h.map((g)=>`${g.call} @ ${g.at}`).join(", ")}`);let m=t.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 t.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(`
55
+ `),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:c.string().optional().describe("SW-C short name or AUTOSAR path (runnable/C mode)"),target:c.string().optional().describe("configuration mode: module, container or element (AUTOSAR path, SHORT-NAME or partial path), e.g. 'Can', 'CanController_0'"),docs:c.boolean().optional().describe("add DOC FACTS from the ingested documents (default true)"),runnable:c.string().optional().describe("runnable short name or SYMBOL (default: all runnables)"),task:c.string().describe("the task, verbatim"),budget_tokens:c.number().int().min(500).max(200000).optional().describe("token budget (default 24000)"),use_backend:c.boolean().optional().describe("if the runnable has no local C definition, look it up with the backend trace of the selected workspace"),workspace_id:c.union([c.string(),c.number()]).optional().describe("H2Loop project id or name for use_backend"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=e.docs!==!1;if(!e.swc){if(!e.target)return"ERROR: give target (configuration change) or swc (+runnable, for C code).";let u=await y(o,["read",e.target,"--depth","3","--schema"],s.abort);if(!u.ok)return _(u);let{ok:h,engine:m,ms:g,...T}=u,k=JSON.stringify(T,null,1).split(`
56
+ `),pe=k.length>400?`${k.slice(0,400).join(`
55
57
  `)}
56
- \u2026 (${v.length-400} more lines: narrow the target)`:v.join(`
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
+ \u2026 (${k.length-400} more lines: narrow the target)`:k.join(`
59
+ `),ge=i?await J(`For this AUTOSAR configuration task: "${e.task}". The element concerned is ${e.target}. From the specifications and manuals in this knowledge base, list every constraint, default, allowed range or literal, multiplicity, dependency on other parameters or modules, and hardware limit of the target microcontroller that applies to it and to what the task changes, each with the document name and section or requirement ID.`,s.sessionID,e.workspace_id,s.abort):"(skipped: docs=false)";return{title:`autosar_build_context target ${e.target}`,output:["# CONTEXT (configuration change)",`## 1. TASK
58
60
  ${e.task}`,`## 2. PROJECT FACTS [F]: current values with @at file:line, and the param-def schema (what may be set)
59
61
  ${pe}`,`## 3. DOC FACTS [D]: from the ingested documents
60
62
  ${ge}`,`## 4. NEXT
61
63
  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
64
 
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})
65
+ `)}}let t=["build-context","--swc",e.swc,"--task",e.task,"--budget-tokens",String(e.budget_tokens??24000)];if(e.runnable)t.push("--runnable",e.runnable);let d=await y(o,t,s.abort);if(!d.ok)return _(d);let l=d.text,f=d.codeMissing??[];if(f.length&&e.use_backend){let u=[];try{let h=await N(e.workspace_id,s.abort);for(let m of f){let g=await x("/api/v1/mcp/autosar/trace",h,{query:m,limit:3},s.abort);u.push(`### backend trace for ${m} (workspace ${h})
64
66
  ${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
67
  ## 4b. RUNNABLE CODE FROM THE BACKEND (not part of the deterministic context)
66
68
  ${u.join(`
67
69
  `)}
68
- `}if(r){let u=await J(`For this AUTOSAR task: "${e.task}" in SW-C ${e.swc}${e.runnable?`, runnable ${e.runnable}`:""}. From the specifications and manuals in this knowledge base, list the requirements and constraints that apply (RTE API semantics, timing, data handling, BSW service usage), each with the document name and section or requirement ID.`,s.sessionID,e.workspace_id,s.abort);l+=`
70
+ `}if(i){let u=await J(`For this AUTOSAR task: "${e.task}" in SW-C ${e.swc}${e.runnable?`, runnable ${e.runnable}`:""}. From the specifications and manuals in this knowledge base, list the requirements and constraints that apply (RTE API semantics, timing, data handling, BSW service usage), each with the document name and section or requirement ID.`,s.sessionID,e.workspace_id,s.abort);l+=`
69
71
  ## 9. DOC FACTS [D] from the ingested documents (not part of the deterministic context)
70
72
  ${u}
71
- `}let p={swc:c.swc,runnables:c.runnables,estimatedTokens:c.estimatedTokens,budgetTokens:c.budgetTokens,reductions:c.reductions,overBudget:c.overBudget??!1,sha1:c.sha1,sections:c.sections,sources:c.manifest};return{title:`autosar_build_context ${c.swc}${c.runnables.length===1?`/${c.runnables[0]}`:""} ~${c.estimatedTokens} tok`,output:`${l}
73
+ `}let p={swc:d.swc,runnables:d.runnables,estimatedTokens:d.estimatedTokens,budgetTokens:d.budgetTokens,reductions:d.reductions,overBudget:d.overBudget??!1,sha1:d.sha1,sections:d.sections,sources:d.manifest};return{title:`autosar_build_context ${d.swc}${d.runnables.length===1?`/${d.runnables[0]}`:""} ~${d.estimatedTokens} tok`,output:`${l}
72
74
  ---
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?`
75
+ MANIFEST ${JSON.stringify(p)}`,metadata:{sha1:d.sha1,estimatedTokens:d.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:c.string().optional().describe("output dir, relative to the project or absolute; 'project' = codegen.outDir / Output. Default: scratch .hydron/codegen/out"),write_back:c.boolean().optional().describe("write assigned handle IDs into the ECUC ARXML (default true)"),binding:c.string().optional().describe("force a static-code binding (e.g. 'sip-standin'), or 'none' for generic tables only"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=["codegen"];for(let u of E(e.modules)??[])i.push("--module",u);if(e.out_dir)i.push("--out",e.out_dir);if(e.write_back===!1)i.push("--no-write-back");if(e.binding)i.push("--binding",e.binding);let t=await y(o,i,s.abort);if(!t.ok){let u=t.handleErrors??[];return S(t)+_(t)+(u.length?`
74
76
  ${u.map((h)=>` ${h}`).join(`
75
- `)}`:"")}let{modules:c,handles:l,timings:f}=n,p=[`Generated ${Object.keys(c).length} module(s) into ${n.outDir} in ${f.total_ms} ms (AUTOSAR R${n.release}):`,...Object.entries(c).map(([u,h])=>` ${u} (${h.variant}${h.binding?`, binding ${h.binding}`:", generic tables"}): ${h.files.join(", ")}; ${h.symbols} symbol(s)`+h.notes.map((m)=>`
77
+ `)}`:"")}let{modules:d,handles:l,timings:f}=t,p=[`Generated ${Object.keys(d).length} module(s) into ${t.outDir} in ${f.total_ms} ms (AUTOSAR R${t.release}):`,...Object.entries(d).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
78
  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
79
  `+l.assigned.slice(0,40).map((u)=>` ${u.path}/${u.param} = ${u.value} (hex ${he(u.value)})`).join(`
78
80
  `)+(l.changes.length?`
79
81
  ${l.changes.map((u)=>u.diff).join(`
80
- `)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(n.notes??[]).map((u)=>`NOTE: ${u}`)];return{title:`autosar_codegen ${Object.keys(c).join(", ")}`,output:S(n)+p.join(`
81
- `)}}}),autosar_codegen_diff:w({description:"Semantic diff of generated C configuration code against a reference dir (e.g. the vendor-generated Output/): compares #define names and values and the contents of every initialised table/struct element by element, plus table ordering, after normalising numbers (0x2A0u == 672), casts, parentheses and macro references. Ignores formatting, comments, banners and include order. Reports per module: matching symbols, missing (in reference only), extra (generated only), value mismatches with both values.",args:{reference_dir:d.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:d.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules: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};
82
+ `)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(t.notes??[]).map((u)=>`NOTE: ${u}`)];return{title:`autosar_codegen ${Object.keys(d).join(", ")}`,output:S(t)+p.join(`
83
+ `)}}}),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:c.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:c.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:O().describe("only these modules"),project_dir:c.string().optional().describe("project root (default: session directory)")},async execute(e,s){let o=b(s.directory,e.project_dir),i=["codegen-diff",e.reference_dir];if(e.generated_dir)i.push(e.generated_dir);for(let f of E(e.modules)??[])i.push("--module",f);let t=await y(o,i,s.abort);if(!t.ok)return _(t);let d=t.modules,l=[`Semantic diff ${t.reference} (reference) vs ${t.generated} (generated): ${JSON.stringify(t.total)}`,`Not generated (reference only): ${t.notGenerated.join(", ")||"-"}; not in reference: ${t.notInReference.join(", ")||"-"}`];for(let[f,p]of Object.entries(d)){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(t.total)}`,output:l.join(`
84
+ `)}}}),autosar_generate:a("generate"),autosar_build:a("build")}),n)}},Ke=Ye;export{Ke as Autosar};
@@ -0,0 +1,471 @@
1
+ """autosar_add_like: add a new X like an existing Y, end to end, across all ARXML (ECUC + System/SWC), or refuse.
2
+
3
+ Projects name the elements of one thing after it: a message BCM_DoorStatus is the frame BCM_DoorStatus_CanFrame,
4
+ the I-PDU, the PDU/frame triggerings, the EcuC Pdu, the CanIf TX PDU, the PduR routing path and the Com I-PDU, all
5
+ linked by references. Cloning that chain, renamed, gives a new message that is consistent with the project's own
6
+ conventions, in every file at once. The same works for a port, a runnable with its event, a Dem event, an NvM
7
+ block, a calibration parameter: whatever the template's chain is.
8
+
9
+ chain elements whose SHORT-NAME contains `like` and that are linked to each other by references
10
+ (`seed` picks the chain when several unconnected ones carry the stem)
11
+ members inside a cloned element, sub-elements whose name lacks the stem and that refer to elements outside the
12
+ chain (a message's signal mappings, an I-PDU's ComIPduSignalRefs) are the template's own content: they
13
+ are not copied (`keep_members=true` copies them)
14
+ links a list outside the chain that refers to a chain element (ECU-extract FIBEX elements, ...) gets an entry
15
+ for the clone; a single-valued slot is reported, not changed
16
+ ids ECUC *HandleId / *PduId values get the lowest unused value of that parameter
17
+ set {"ParamDefName" | "XML-TAG" | "Owner:key": value} applied to the clones (Owner = part of a clone's
18
+ SHORT-NAME or its tag); every key must match at least one value
19
+ Everything is checked (schema, every reference + DEST) and validated before/after; any new finding rolls back.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import collections
24
+ import os
25
+ import re
26
+ import uuid
27
+ from typing import Optional
28
+
29
+ from .arxml_edit import ArxmlEditor, FileTree, _ad
30
+ from .model import Project
31
+ from .xmltree import escape, line_indent
32
+
33
+ REF_TAG = re.compile(r"(?:-REF|-TREF|-IREF|^VALUE-REF)$")
34
+ REGISTRY_MIN = 12 # a holder with this many outgoing references is a list of everything, not an owner
35
+ OWNER_DEST = re.compile(r"(?:PORT-PROTOTYPE|RUNNABLE-ENTITY|COMPONENT-PROTOTYPE|SW-COMPONENT-TYPE|INTERNAL-BEHAVIOR)$")
36
+ # Handle IDs exactly as validation sees them (rules/handles.py): with param defs, an integer with SYMBOLIC-NAME-VALUE;
37
+ # without defs, by name.
38
+ from .rules.handles import NAME as HANDLE_NAME # noqa: E402
39
+
40
+
41
+ class AddLikeError(Exception):
42
+ pass
43
+
44
+
45
+ def _is_ref(node) -> bool:
46
+ """A reference to another configured/modelled element (not DEFINITION-REF, which points at the param def)."""
47
+ return bool(REF_TAG.search(node.tag)) and not node.children and node.tag != "DEFINITION-REF"
48
+
49
+
50
+ def _holder(node):
51
+ """Nearest ancestor (or self) that has a SHORT-NAME: the identifiable that owns a reference."""
52
+ n = node.parent
53
+ while n is not None and n.short_name is None:
54
+ n = n.parent
55
+ return n
56
+
57
+
58
+ class Graph:
59
+ def __init__(self, ed: ArxmlEditor, files: list):
60
+ self.ed = ed
61
+ self.trees = {}
62
+ self.where = {} # path -> (file, node)
63
+ self.path_of = {} # id(node) -> path
64
+ self.refs = [] # (file, ref node, holder path, target)
65
+ for f in files:
66
+ try:
67
+ ft = ed.load(f)
68
+ except Exception: # noqa: BLE001 -- unparseable files are left alone
69
+ continue
70
+ self.trees[f] = ft
71
+ for p, n in ft.by_path.items():
72
+ self.where.setdefault(p, (f, n))
73
+ self.path_of[id(n)] = p
74
+ for f, ft in self.trees.items():
75
+ for n in ft.root.iter():
76
+ if _is_ref(n):
77
+ t = n.text.strip()
78
+ h = _holder(n)
79
+ hp = self.path_of.get(id(h)) if h is not None else None
80
+ if t.startswith("/") and hp:
81
+ self.refs.append((f, n, hp, t))
82
+ self.referrers = collections.defaultdict(list)
83
+ self.out = collections.defaultdict(list)
84
+ for f, n, hp, t in self.refs:
85
+ self.referrers[t].append((f, n, hp))
86
+ self.out[hp].append((t, n.attrs.get("DEST", "")))
87
+
88
+ @staticmethod
89
+ def name(path: str) -> str:
90
+ return path.rsplit("/", 1)[-1]
91
+
92
+ def under(self, path: str, roots) -> bool:
93
+ return any(path == r or path.startswith(r + "/") for r in roots)
94
+
95
+
96
+ def _chain(g: Graph, pairs: list, seed: Optional[str]) -> list:
97
+ stems = [a for a, _ in pairs]
98
+ stem = pairs[-1][0] if len(pairs) == 1 else " / ".join(stems)
99
+ cands = {p for p in g.where if any(a in Graph.name(p) for a in stems)}
100
+ if not cands:
101
+ raise AddLikeError(f"no element's SHORT-NAME contains {stem!r}")
102
+ for a in stems:
103
+ if not any(a in Graph.name(p) for p in cands):
104
+ raise AddLikeError(f"no element's SHORT-NAME contains {a!r}")
105
+ adj = collections.defaultdict(set)
106
+ for f, n, hp, t in g.refs:
107
+ a = next((x for x in _ancestors(hp) if x in cands), None)
108
+ b = next((x for x in _ancestors(t) if x in cands), None)
109
+ if a and b and a != b:
110
+ adj[a].add(b)
111
+ adj[b].add(a)
112
+ for p in cands: # containment links a named child to a named parent
113
+ par = next((x for x in _ancestors(p)[1:] if x in cands), None)
114
+ if par:
115
+ adj[p].add(par)
116
+ adj[par].add(p)
117
+ comps, seen = [], set()
118
+ for p in sorted(cands):
119
+ if p in seen:
120
+ continue
121
+ comp, todo = set(), [p]
122
+ while todo:
123
+ x = todo.pop()
124
+ if x in comp:
125
+ continue
126
+ comp.add(x)
127
+ todo.extend(adj[x] - comp)
128
+ seen |= comp
129
+ comps.append(comp)
130
+ if seed:
131
+ comps = [c for c in comps if any(seed == x or x.endswith("/" + seed.strip("/")) or seed.strip("/") == Graph.name(x)
132
+ for x in c)]
133
+ if not comps:
134
+ raise AddLikeError(f"seed {seed!r} is not an element whose SHORT-NAME contains {stem!r}")
135
+ if len(stems) > 1: # the template and its named members must form ONE chain
136
+ comps = [c for c in comps if all(any(a in Graph.name(x) for x in c) for a in stems)] or comps
137
+ linked = [c for c in comps if len(c) > 1] or comps
138
+ if len(linked) > 1:
139
+ heads = ["; ".join(sorted(c)[:3]) for c in sorted(linked, key=len, reverse=True)[:6]]
140
+ raise AddLikeError(f"{len(linked)} separate chains carry {stem!r}; pass seed = one element of the one you mean: "
141
+ + " | ".join(heads))
142
+ comp = set(linked[0])
143
+ # A member of the template (named after an `also` stem, not the main one) that points at an outside element
144
+ # OWNING something (a port, runnable, component, behavior) belongs to that owner, not to the template: e.g. the
145
+ # write access of the OLD port to a data element of the cloned interface. Leave it out.
146
+ main = pairs[0][0] if len(pairs) == 1 else next(a for a, _ in pairs if a == g.main)
147
+ named = lambda x: any(a in Graph.name(x) for a in stems) # noqa: E731
148
+ mains = {p for p in comp if main in Graph.name(p)}
149
+ for p in sorted(comp):
150
+ if p in mains or any(a in mains for a in _ancestors(p)[1:]):
151
+ continue
152
+ outs = [(t, d) for hp, lst in g.out.items() if hp == p or hp.startswith(p + "/") for t, d in lst]
153
+ if any(OWNER_DEST.search(d or "") and not named(t) and not any(t == c or t.startswith(c + "/") for c in comp)
154
+ for t, d in outs):
155
+ comp.discard(p)
156
+ return sorted(p for p in comp if not any(a in comp for a in _ancestors(p)[1:])) # top-most only
157
+
158
+
159
+ def _ancestors(path: str) -> list:
160
+ segs = path.strip("/").split("/")
161
+ return ["/" + "/".join(segs[:i]) for i in range(len(segs), 0, -1)]
162
+
163
+
164
+ def _multi(project: Project, ref, wrapper) -> bool:
165
+ """Whether a reference sits in a multi-valued slot (a list the clone can leave out of)."""
166
+ if wrapper.tag.endswith("REFERENCE-VALUE"):
167
+ dr = wrapper.child("DEFINITION-REF")
168
+ d = project.defs.get(dr.text.strip()) if (dr is not None and project.defs) else None
169
+ if d is not None:
170
+ return d.upper is None or d.upper > 1
171
+ return False # without the def, assume single and keep it
172
+ return wrapper.parent is not None and wrapper.parent.tag.endswith("S")
173
+
174
+
175
+ def _wrapper(node, holder):
176
+ """The smallest element around a reference that can be repeated on its own (ECUC-REFERENCE-VALUE, *-CONDITIONAL)."""
177
+ if node.parent is not None and node.parent.tag.endswith("REFERENCE-VALUE") and \
178
+ all(c is node or c.tag == "DEFINITION-REF" for c in node.parent.children):
179
+ return node.parent # ECUC: the whole ECUC-(INSTANCE-)REFERENCE-VALUE entry
180
+ w = node
181
+ while w.parent is not None and w.parent is not holder and len(w.parent.children) == 1 and not w.parent.tag.endswith("S"):
182
+ w = w.parent
183
+ return w
184
+
185
+
186
+ def add_like(project: Project, like: str, name: str, seed: Optional[str] = None, set_values: Optional[dict] = None,
187
+ keep_members: bool = False, dry_run: bool = False, also: Optional[dict] = None) -> dict:
188
+ """also = {template member stem: new stem}, e.g. {"DrvDoorOpenSts": "SettingsAckCounter"}: those members of the
189
+ template (a signal of the message, a data element of the interface, ...) are cloned and renamed too."""
190
+ from .validate import validate
191
+ stem, new = (like or "").strip(), (name or "").strip()
192
+ if not stem or not new:
193
+ raise AddLikeError("like (the name stem of an existing element, e.g. BCM_DoorStatus) and name (the new stem) "
194
+ "are both required")
195
+ pairs = [(stem, new)] + [(str(a).strip(), str(b).strip()) for a, b in (also or {}).items()]
196
+ for a, b in pairs:
197
+ if not a or not re.fullmatch(r"[A-Za-z_]\w*", b):
198
+ raise AddLikeError(f"{a!r} -> {b!r}: the new name must be a valid SHORT-NAME")
199
+ pairs.sort(key=lambda x: len(x[0]), reverse=True) # longer stems first, so one does not eat another
200
+ ed = ArxmlEditor(project)
201
+ files = list(project.sources.config) + list(project.sources.input)
202
+ g = Graph(ed, files)
203
+ g.main = stem
204
+ chain = _chain(g, pairs, seed)
205
+ newpaths = {p: _rn(p, pairs) for p in chain}
206
+ clash = [q for q in newpaths.values() if q in g.where]
207
+ if clash:
208
+ raise AddLikeError(f"already exists: {', '.join(clash[:5])}")
209
+ chain_roots = set(chain)
210
+ in_chain = lambda t: g.under(t, chain_roots) # noqa: E731
211
+ # The template's OWN content: targets referenced only from the chain, or only from other such targets
212
+ # (a message's I-SIGNAL is referenced by its mapping and by its I-SIGNAL-TRIGGERING, which only the message's
213
+ # PDU triggering references). Shared things (a debounce class used by every Dem event) are never "own".
214
+ # Registries (an ECU extract's FIBEX-ELEMENTS, an ECUC value collection: one holder listing many elements) say
215
+ # nothing about ownership and are ignored here; they are still linked for the clones below.
216
+ registry = {hp for hp, lst in g.out.items() if len(lst) >= REGISTRY_MIN}
217
+ targets = {t for _, _, _, t in g.refs if not in_chain(t)}
218
+ exclusive: set = set()
219
+ grew = True
220
+ while grew:
221
+ grew = False
222
+ for t in targets - exclusive:
223
+ owners = [hp for _, _, hp in g.referrers[t] if hp not in registry]
224
+ if owners and all(g.under(hp, chain_roots) or g.under(hp, exclusive) for hp in owners):
225
+ exclusive.add(t)
226
+ grew = True
227
+ named = lambda p: any(a in Graph.name(p) for a, _ in pairs) # noqa: E731
228
+ notes, dropped, linked, single = [], [], [], []
229
+ before = {_dkey(d) for d in validate(project, check_generated=False)["diagnostics"]
230
+ if d["severity"] in ("error", "warning")}
231
+
232
+ # ---------- clone every chain element next to its template ----------
233
+ inserts = collections.defaultdict(list) # file -> [(end offset, bytes)]
234
+ for p in chain:
235
+ f, node = g.where[p]
236
+ ft = g.trees[f]
237
+ data = ft.data
238
+ cuts = [] # (start, end) byte spans inside the element to leave out
239
+ if not keep_members:
240
+ for d in node.iter():
241
+ if d is node:
242
+ continue
243
+ dp = g.path_of.get(id(d))
244
+ if dp and not named(dp):
245
+ outside = [t for t in _refs_below(d) if t in exclusive and not named(t)]
246
+ if outside and not any(c[0] <= d.start < c[1] for c in cuts):
247
+ cuts.append((_line_start(data, d.start), d.end))
248
+ dropped.append(f"{_rn(dp, pairs)} (the template's {d.tag} {Graph.name(dp)})")
249
+ elif _is_ref(d) and not any(c[0] <= d.start < c[1] for c in cuts):
250
+ t = d.text.strip()
251
+ if t in exclusive and not named(t):
252
+ w = _wrapper(d, _holder(d))
253
+ if not _multi(project, d, w): # a single slot (CanIfTxPduBufferRef): keep, it is shared now
254
+ notes.append(f"{_rn(g.path_of.get(id(_holder(d)), ''), pairs)}: {d.tag} still -> {t} "
255
+ "(the template's; single-valued, so the clone shares it; change it if it must not)")
256
+ elif w is not d or d.parent.tag.endswith("S"):
257
+ if not any(c[0] <= w.start < c[1] for c in cuts):
258
+ cuts.append((_line_start(data, w.start), w.end))
259
+ dropped.append(f"{d.tag} -> {t} (the template's own member)")
260
+ text = _excise(data, node.start, node.end, cuts).decode("utf-8")
261
+ text = _retext(text, pairs, in_chain)
262
+ ind = line_indent(data, node.start) or b""
263
+ inserts[f].append((node.end, ft.nl + ind + text.encode("utf-8")))
264
+
265
+ # ---------- link the clones where the template is listed ----------
266
+ for p in chain:
267
+ for f, n, hp in g.referrers.get(p, []):
268
+ if g.under(hp, chain_roots):
269
+ continue
270
+ ft = g.trees[f]
271
+ holder = _holder(n)
272
+ w = _wrapper(n, holder)
273
+ repeatable = w.parent is not None and (w.parent.tag.endswith("S") or w is not n)
274
+ if not repeatable:
275
+ single.append(f"{hp}: {n.tag} -> {p} (single-valued; not changed)")
276
+ continue
277
+ t = ft.data[w.start:w.end].decode("utf-8").replace(f">{p}<", f">{newpaths[p]}<")
278
+ t = re.sub(r'\sUUID="[^"]*"', lambda _m: f' UUID="{uuid.uuid4()}"', t)
279
+ ind = line_indent(ft.data, w.start) or b""
280
+ inserts[f].append((w.end, ft.nl + ind + t.encode("utf-8")))
281
+ linked.append(f"{hp}: {n.tag} -> {newpaths[p]}")
282
+
283
+ for f, ins in inserts.items():
284
+ data = g.trees[f].data
285
+ for off, b in sorted(ins, key=lambda x: x[0], reverse=True):
286
+ data = data[:off] + b + data[off:]
287
+ ed.files[f] = FileTree(f, data)
288
+
289
+ # ---------- handle ids + requested values ----------
290
+ created = sorted(newpaths.values())
291
+ ids = _assign_ids(ed, created)
292
+ applied = _apply_set(ed, created, set_values or {})
293
+
294
+ probs = ed.check()
295
+ changes = {f: ft.data for f, ft in ed.files.items() if ft.data != ed.original.get(f)}
296
+ res = {"like": stem, "name": new, "created": created, "linked": linked, "notCopied": dropped,
297
+ "singleValuedNotLinked": single, "ids": ids, "set": applied, "files": sorted(project.rel(f) for f in changes),
298
+ "notes": notes}
299
+ if probs:
300
+ return {**res, "ok": False, "written": False, "error": "the clone would leave broken ARXML; nothing written",
301
+ "problems": probs[:20]}
302
+ if dry_run:
303
+ return {**res, "ok": True, "written": False}
304
+ originals = {f: ed.original[f] for f in changes}
305
+ for f, b in changes.items():
306
+ with open(f, "wb") as fh:
307
+ fh.write(b)
308
+ after = validate(Project(project.root, project.sources.config, project.sources.defs), check_generated=False)
309
+ fresh = [d for d in after["diagnostics"] if d["severity"] in ("error", "warning")
310
+ and _dkey(d) not in before]
311
+ if fresh:
312
+ for f, b in originals.items():
313
+ with open(f, "wb") as fh:
314
+ fh.write(b)
315
+ return {**res, "ok": False, "written": False, "error": "validation found new problems; all changes rolled back",
316
+ "diagnostics": fresh[:20]}
317
+ return {**res, "ok": True, "written": True, "validation": after["summary"],
318
+ "next": "check each created element against the request (ecuc_read / the diff), set what is still the "
319
+ "template's (ecuc_edit / arxml_edit), add the new signals (autosar_add_signal), then regenerate "
320
+ "and build"}
321
+
322
+
323
+ def _rn(path: str, pairs, new: Optional[str] = None) -> str:
324
+ if isinstance(pairs, str):
325
+ pairs = [(pairs, new)]
326
+ out = []
327
+ for seg in path.split("/"):
328
+ for a, b in pairs:
329
+ if a in seg:
330
+ seg = seg.replace(a, b)
331
+ break
332
+ out.append(seg)
333
+ return "/".join(out)
334
+
335
+
336
+ def _refs_below(node) -> list:
337
+ return [d.text.strip() for d in node.iter() if _is_ref(d) and d.text.strip().startswith("/")]
338
+
339
+
340
+ def _line_start(data: bytes, pos: int) -> int:
341
+ if line_indent(data, pos) is not None:
342
+ nl = data.rfind(b"\n", 0, pos)
343
+ return nl if nl >= 0 else pos
344
+ return pos
345
+
346
+
347
+ def _excise(data: bytes, start: int, end: int, cuts: list) -> bytes:
348
+ out, at = [], start
349
+ for a, b in sorted(c for c in cuts if start <= c[0] and c[1] <= end):
350
+ if a < at:
351
+ continue
352
+ out.append(data[at:a])
353
+ at = b
354
+ out.append(data[at:end])
355
+ return b"".join(out)
356
+
357
+
358
+ def _retext(text: str, pairs: list, in_chain) -> str:
359
+ """Rename the stems in SHORT-NAMEs and in references into the chain; fresh UUIDs."""
360
+ text = re.sub(r"(<SHORT-NAME>)([^<]*)(</SHORT-NAME>)", lambda m: m.group(1) + _rn(m.group(2), pairs) + m.group(3), text)
361
+
362
+ def ref(m):
363
+ t = m.group(2).strip()
364
+ return m.group(1) + (_rn(t, pairs) if in_chain(t) else m.group(2)) + m.group(3)
365
+ text = re.sub(r"(<[A-Z0-9-]*(?:-REF|-TREF|-IREF|VALUE-REF)\b[^>]*>)([^<]*)(</)", ref, text)
366
+ return re.sub(r'\sUUID="[^"]*"', lambda _m: f' UUID="{uuid.uuid4()}"', text)
367
+
368
+
369
+ def _num_values(ft: FileTree, root):
370
+ """(DEFINITION-REF, def short name, VALUE node) for each ECUC numerical value below root."""
371
+ for n in root.iter():
372
+ if n.tag == "ECUC-NUMERICAL-PARAM-VALUE":
373
+ d = n.child("DEFINITION-REF")
374
+ v = n.child("VALUE")
375
+ if d is not None and v is not None:
376
+ yield d.text.strip(), d.text.strip().rsplit("/", 1)[-1], v
377
+
378
+
379
+ def _is_handle(project: Project, defref: str, name: str) -> bool:
380
+ d = project.defs.get(defref) if project.defs else None
381
+ if d is not None:
382
+ return d.kind == "INTEGER" and bool(d.symbolic_name)
383
+ return bool(HANDLE_NAME.search(name))
384
+
385
+
386
+ def _range(project: Project, defref: str) -> tuple:
387
+ d = project.defs.get(defref) if project.defs else None
388
+ lo, hi = 0, (1 << 16) - 1
389
+ try:
390
+ if d is not None and d.min not in (None, ""):
391
+ lo = int(str(d.min), 0) + (1 if d.min_open else 0)
392
+ if d is not None and d.max not in (None, ""):
393
+ hi = min(hi, int(str(d.max), 0) - (1 if d.max_open else 0))
394
+ except ValueError:
395
+ pass
396
+ return max(lo, 0), hi
397
+
398
+
399
+ def _assign_ids(ed: ArxmlEditor, created: list) -> list:
400
+ out = []
401
+ for p in created:
402
+ ft, node = ed.tree_for(p)
403
+ todo = [(dr, dn) for dr, dn, _ in _num_values(ft, node) if _is_handle(ed.p, dr, dn)]
404
+ for k, (dr, dn) in enumerate(todo):
405
+ ft, node = ed.tree_for(p) # positions move after each patch
406
+ mine = [v for r, _, v in _num_values(ft, node) if r == dr]
407
+ target = mine[min(k - sum(1 for x in todo[:k] if x[0] != dr), len(mine) - 1)] if mine else None
408
+ if target is None:
409
+ continue
410
+ used = set()
411
+ for ft2 in ed.files.values():
412
+ for r2, _, v2 in _num_values(ft2, ft2.root):
413
+ if r2 == dr and not (ft2 is ft and v2.start == target.start):
414
+ try:
415
+ used.add(int(v2.text.strip(), 0))
416
+ except ValueError:
417
+ pass
418
+ lo, hi = _range(ed.p, dr)
419
+ nid = next((i for i in range(lo, hi + 1) if i not in used), None)
420
+ if nid is None:
421
+ raise AddLikeError(f"no free {dn} value in [{lo}..{hi}]")
422
+ ed.patch(ft, target.start, target.end, f"<VALUE>{nid}</VALUE>".encode())
423
+ out.append(f"{p}/{dn} = {nid}")
424
+ return out
425
+
426
+
427
+ def _apply_set(ed: ArxmlEditor, created: list, values: dict) -> list:
428
+ applied = []
429
+ for key, value in values.items():
430
+ owner, _, k = str(key).rpartition(":")
431
+ hits = 0
432
+ for p in created:
433
+ done = 0
434
+ while True:
435
+ ft, node = ed.tree_for(p) # re-read: every patch moves the byte offsets
436
+ cands = []
437
+ for c in _value_nodes(ft, node, k):
438
+ h = _holder(c) or node
439
+ hp = next((q for q, n in ft.by_path.items() if n is h), p)
440
+ if not owner or owner in hp.rsplit("/", 1)[-1] or owner.upper() == h.tag:
441
+ cands.append((c, hp))
442
+ if done >= len(cands):
443
+ break
444
+ c, hp = cands[done]
445
+ ed.patch(ft, c.start, c.end, f"<{c.tag}>{escape(str(value))}</{c.tag}>".encode())
446
+ applied.append(f"{hp}/{k} = {value}")
447
+ done += 1
448
+ hits += 1
449
+ if not hits:
450
+ raise AddLikeError(f"set {key!r}: no ECUC parameter or element {k!r} in the cloned elements "
451
+ f"({', '.join(created[:6])}); use the parameter's definition name or the XML tag")
452
+ return applied
453
+
454
+
455
+ def _value_nodes(ft: FileTree, root, key: str) -> list:
456
+ """VALUE nodes of ECUC params named `key` and leaf elements tagged `key` below root."""
457
+ out = []
458
+ for n in root.iter():
459
+ if n.tag in ("ECUC-NUMERICAL-PARAM-VALUE", "ECUC-TEXTUAL-PARAM-VALUE"):
460
+ d, v = n.child("DEFINITION-REF"), n.child("VALUE")
461
+ if d is not None and v is not None and d.text.strip().rsplit("/", 1)[-1] == key:
462
+ out.append(v)
463
+ elif n.tag == key.upper() and not n.children and n.tag != "SHORT-NAME":
464
+ out.append(n)
465
+ return out
466
+
467
+
468
+ def _dkey(d: dict) -> tuple:
469
+ """A finding without line numbers (file.arxml:123), so one that only moved because text was inserted above it
470
+ is not taken for a new one."""
471
+ return d["rule"], d["path"], re.sub(r"(\.arxml|\.ARXML|\.dbc):\d+", r"\1", d["message"])
@@ -95,7 +95,7 @@ def add_signal(project: Project, name: str, ipdu: str, bit_size: Optional[int] =
95
95
  sib = next((m for m in members if m is not None and (m.def_ref or "").endswith("/ComSignal")), None)
96
96
  if sib is None:
97
97
  raise AddSignalError(f"{ip.name} has no ComSignal to use as template")
98
- before = {(d["rule"], d["path"], d["message"]) for d in validate(project, check_generated=False)["diagnostics"]
98
+ before = {_dkey(d) for d in validate(project, check_generated=False)["diagnostics"]
99
99
  if d["severity"] in ("error", "warning")}
100
100
  notes: list = []
101
101
 
@@ -209,7 +209,7 @@ def add_signal(project: Project, name: str, ipdu: str, bit_size: Optional[int] =
209
209
  # same inputs as `before` (explicit --defs/--config included), so only the edit's own findings count as new
210
210
  after = validate(Project(project.root, project.sources.config, project.sources.defs), check_generated=False)
211
211
  new = [d for d in after["diagnostics"] if d["severity"] in ("error", "warning")
212
- and (d["rule"], d["path"], d["message"]) not in before]
212
+ and _dkey(d) not in before]
213
213
  if new:
214
214
  for f, b in originals.items():
215
215
  with open(f, "wb") as fh:
@@ -397,3 +397,9 @@ def _dbc_line(project: Project, pdu, name, pos, size, endian, typ, notes, member
397
397
  out[f] = (text[:block_end] + line + text[block_end:]).encode()
398
398
  notes.append(f"added SG_ {name} to BO_ {m.group(1)} {m.group(2)} in {project.rel(f)}")
399
399
  return out
400
+
401
+
402
+ def _dkey(d: dict) -> tuple:
403
+ """A finding without line numbers (file.arxml:123), so one that only moved because text was inserted above it
404
+ is not taken for a new one."""
405
+ return d["rule"], d["path"], re.sub(r"(\.arxml|\.ARXML|\.dbc):\d+", r"\1", d["message"])
@@ -107,6 +107,14 @@ def main(argv=None) -> int:
107
107
  an.add_argument("--dry-run", action="store_true")
108
108
  ac = sub.add_parser("arxml-check", help="verify non-ECUC ARXML: strict schema + every reference and its DEST")
109
109
  ac.add_argument("--file", action="append", default=[], help="limit to files whose path contains this")
110
+ al = sub.add_parser("add-like", help="add a new X like an existing Y: clone its chain across all ARXML, renamed")
111
+ al.add_argument("--like", required=True, help="name stem of the template (e.g. BCM_DoorStatus)")
112
+ al.add_argument("--name", required=True, help="the new stem (e.g. BCM_SettingsAck)")
113
+ al.add_argument("--seed", help="one element of the template chain, when several chains carry the stem")
114
+ al.add_argument("--also", help='JSON {"template member stem": "new stem"}, e.g. {"DrvDoorOpenSts": "SettingsAckCounter"}')
115
+ al.add_argument("--set", dest="set_values", help='JSON {"ParamDef"|"XML-TAG"|"Owner:key": value}')
116
+ al.add_argument("--keep-members", action="store_true")
117
+ al.add_argument("--dry-run", action="store_true")
110
118
  fd = sub.add_parser("find")
111
119
  fd.add_argument("--module")
112
120
  fd.add_argument("--container-def", dest="container_def")
@@ -152,7 +160,7 @@ def main(argv=None) -> int:
152
160
  bc.add_argument("--task", required=True, help="task text, @file, or - for stdin")
153
161
  bc.add_argument("--budget-tokens", dest="budget_tokens", type=int, default=24000)
154
162
  bc.add_argument("--no-history", dest="history", action="store_false")
155
- for p in (r, e, v, d, au, so, vs, si, fd, cx, ae, an, ac, asg, cg, cd, ra, vr, bc): # allow --json after the subcommand too
163
+ for p in (r, e, v, d, au, so, vs, si, fd, cx, ae, an, ac, al, asg, cg, cd, ra, vr, bc): # allow --json after the subcommand too
156
164
  p.add_argument("--json", action="store_true", help=argparse.SUPPRESS)
157
165
  a = ap.parse_args(argv)
158
166
  t0 = time.time()
@@ -222,7 +230,7 @@ def run(a) -> dict:
222
230
  from .specids import check_ids
223
231
  return check_ids(os.path.abspath(a.root), a.ids, docs=a.docs)
224
232
  from .model import Project
225
- project = Project(a.root, config_files=a.config, def_files=a.defs, load_input=a.cmd in ("validate", "edit", "find", "crosscheck", "signal-owners", "arxml-edit", "add-signal", "arxml-check"))
233
+ project = Project(a.root, config_files=a.config, def_files=a.defs, load_input=a.cmd in ("validate", "edit", "find", "crosscheck", "signal-owners", "arxml-edit", "add-signal", "arxml-check", "add-like"))
226
234
  if a.cmd == "add-signal":
227
235
  from .add_signal import AddSignalError, add_signal
228
236
  try:
@@ -231,6 +239,18 @@ def run(a) -> dict:
231
239
  transfer_property=a.transfer_property, dry_run=a.dry_run)
232
240
  except AddSignalError as ex:
233
241
  return {"error": str(ex), "written": False}
242
+ if a.cmd == "add-like":
243
+ from .add_like import AddLikeError, add_like
244
+ try:
245
+ also = _loads(a.also) if a.also else None
246
+ sv = _loads(a.set_values) if a.set_values else None
247
+ except json.JSONDecodeError as ex:
248
+ return {"ok": False, "error": f"also/set is not valid JSON: {ex}"}
249
+ try:
250
+ return add_like(project, a.like, a.name, seed=a.seed, set_values=sv, keep_members=a.keep_members,
251
+ dry_run=a.dry_run, also=also)
252
+ except AddLikeError as ex:
253
+ return {"ok": False, "error": str(ex)}
234
254
  if a.cmd == "arxml-check":
235
255
  from .arxml_edit import arxml_check
236
256
  return arxml_check(project, a.file or None)
@@ -71,6 +71,7 @@ grounding, no tools, no exploring the project.
71
71
  | Verify ALL ARXML (ECUC rules + extract/SWC schema, references, DEST) | `ecuc_validate` (unfiltered) |
72
72
  | Edit System extract / SWC / interface XML | `arxml_edit` (DEST inferred, schema-ordered, refs checked) |
73
73
  | Add a signal end to end (ECUC + extract + DBC) | `autosar_add_signal` |
74
+ | Add a new message / port / runnable+event / Dem event / NvM block / interface **like an existing one**, in every file at once | `autosar_add_like like=<existing stem> name=<new stem> also={member: new} set={...}` |
74
75
  | What may be set/added here (types, ranges, literals, multiplicity) | `ecuc_read path=… schema=true`, or a def path `/AUTOSAR/EcucDefs/<Mod>/…` |
75
76
  | Change config | `ecuc_edit ops=[…]` (`dry_run` first for large edits) |
76
77
  | Check config | `ecuc_validate` |
@@ -123,6 +124,20 @@ Do not decide what to change from memory or from the prompt alone. Each change g
123
124
  (unvalidated edits, failing validation, unverified C, changed elements not yet checked against the documents)
124
125
  until it is resolved.
125
126
 
127
+ ## A new thing that resembles an existing one: autosar_add_like (preferred)
128
+ Most changes add something the project already has one of: a message, a port, a runnable with its timing event, a
129
+ Dem event with its DTC, an NvM block with its Fee block. Do not build those op by op. Pick the existing one most like
130
+ the new one (same direction, bus, kind), then:
131
+ 1. `autosar_add_like like=<its stem> name=<new stem> dry_run=true`: read the Created list (every file it touches)
132
+ and the "Not copied" / "single-valued" lists.
133
+ 2. Name the members you want too: `also={"DrvDoorOpenSts": "SettingsAckCounter"}` gives the new message one signal
134
+ cloned from that one.
135
+ 3. Set the values the request gives with `set` (ECUC param name, XML tag, or `Owner:key` when several clones have
136
+ it): CAN id (`IDENTIFIER`, `CanIfTxPduCanId`), lengths (`PduLength`, `FRAME-LENGTH`, `I-SIGNAL-I-PDU:LENGTH`),
137
+ period (`ComTxModeTimePeriod`), signal layout (`<sig>:ComBitPosition`, `<sig>:ComBitSize`, `START-POSITION`) ...
138
+ 4. Run it without dry_run. It validates and rolls back on any new finding. Then fix what is listed as single-valued
139
+ (e.g. the S/R-to-signal mapping of a new port) with arxml_edit, and verify as below.
140
+
126
141
  ## New ARXML file (SWC, interface, data types, extract) from nothing
127
142
  1. ONE `arxml_edit` call. Its first op creates the file:
128
143
  `{op:"new_file", file:"Input/SWC_X.arxml", packages:["/DataTypes", "/Interfaces", "/Swcs"]}` (R25-11 header and empty