@h2loop/autosar 1.5.1 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/index.js +11 -11
- package/skills/autosar/SKILL.md +5 -0
package/package.json
CHANGED
package/plugins/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{readFileSync as je}from"fs";import{isAbsolute as Ne,join as W,resolve as xe}from"path";import{tool as w}from"@kilocode/plugin";import{homedir as he}from"os";import{join as A}from"path";var pe=()=>process.env.HYDRON_TEST_HOME||he(),U=(i,t)=>process.env[i]||A(pe(),t),ge=()=>A(U("XDG_CONFIG_HOME",".config"),"hydron-cli"),me=()=>A(U("XDG_DATA_HOME",".local/share"),"hydron-cli"),be=()=>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(ge(),"server-config.json")),o=typeof t?.apiBaseUrl==="string"?t.apiBaseUrl:void 0;if(!o)throw Error("H2Loop backend URL unknown: set KILO_API_URL or sign in with `hydron auth login`.");return o.replace(/\/+$/,"")}function ye(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 we(i){let t=ye(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(me(),"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(be(),"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 we(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 _e=/(?:^|[;&|(]\s*|\bnode\s+\S*|\bnpx\s+)(?:ecuc_(?:read|edit|validate|find|crosscheck)|arxml_(?:edit|diff)|autosar_[a-z_]+)\b/m,$e='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(_e.test(o)||e)return`${$e} (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 Se=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 N(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=N(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=N(i),a=/^\s*(ERROR|Blocked|GROUND FIRST)/.test(e)||e.includes("edit rejected");if(Se.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 ve(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
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 ve(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
|
-
`)}import{existsSync as Ae}from"fs";import{dirname as ke,join as B}from"path";import{fileURLToPath as Re}from"url";var
|
|
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,Ie=["# AUTOSAR pack
|
|
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
|
|
4
|
+
`)}import{existsSync as Ae}from"fs";import{dirname as ke,join as B}from"path";import{fileURLToPath as Re}from"url";var Oe="autosar-data==0.17.0";function Ee(){let i=ke(Re(import.meta.url)),t=[B(i,"..","python"),B(i,"..","..","python")].find((o)=>Ae(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 Ce(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 x={};async function Te(){if(x.cmd!==void 0)return x.cmd;let i=process.env.AUTOSAR_PYTHON?.trim(),o=i?[[i]]:[["uv","run","--no-project","--quiet","--with",Oe,"--python",">=3.10","python"],["python3"],["python"],["py","-3"]];for(let e of o)if(await Ce(e))return x.cmd=e,e;return x.cmd=null,null}async function b(i,t,o){let e=await Te();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=Ee(),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,Ie=["# 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
7
|
Did you mean: ${i.didYouMean.join(", ")}`:"",o=i.schema?`
|
|
8
8
|
Schema errors: ${JSON.stringify(i.schema)}`:"";return`ERROR: ${i.error}${t}${o}`}function S(i){let t=i.warnings??[];return t.length?t.map((o)=>`WARNING: ${o}`).join(`
|
|
9
9
|
`)+`
|
|
@@ -21,13 +21,13 @@ ${se(u.err,80)}`:""].filter(Boolean).join(`
|
|
|
21
21
|
Rejected diff:
|
|
22
22
|
${f.map((p)=>p.diff).join(`
|
|
23
23
|
`)}`:"")}let n=r.changes??[],c=r.validation,l=[`${r.written?"Written":"Dry run (nothing written)"}: ${r.applied} op(s), ${n.length} file(s) changed.`,...(r.notes??[]).map((f)=>`NOTE: ${f}`),...n.map((f)=>f.diff)];if(c)l.push(c.validated?`Validation of touched files: ${JSON.stringify(c.summary)}`:"Validation skipped: no param defs loaded.",...I(c.diagnostics,50));return{title:`ecuc_edit ${n.map((f)=>f.file).join(", ")}`,output:S(r)+l.join(`
|
|
24
|
-
`)}}}),ecuc_validate:w({description:"Validate ALL ARXML of the project. ECUC configuration against the param defs (project .hydron/autosar.json paramDefs, auto-discovered ECUC-MODULE-DEF files, or $AUTOSAR_PARAMDEFS): multiplicity, mandatory params/containers, integer/float ranges, enum literals, booleans, string length/regex, reference targets and destination types, dangling refs, duplicate paths, unknown definitions, plus semantic rule packs (H2L-*: Com signals inside their I-PDU and non-overlapping incl. Motorola bit order, unique handle IDs) that run even without defs. System/ECU extract, SWC and interface files: strict AUTOSAR schema load and every *-REF resolves with the right DEST (H2L-ARXML-*). Returns LSP-like diagnostics "+"file:line severity rule path \u2014 message [def DEFINITION-REF]. Run after EVERY ecuc_edit / arxml_edit and before "+"autosar_generate. `files` takes files, directories or globs; omit it to validate everything (preferred). The output always lists which files/modules were loaded; a filter that matches nothing is an ERROR. If it reports nothing on a project you expect to have issues, rerun unfiltered and check the loaded-file list."+k,args:{files:
|
|
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=y(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 b(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=N(s.sessionID).changed,E=e.about?.trim()||g.join("; ");if(!E)m="\n\nDOCUMENT CHECK UNAVAILABLE: nothing was changed in this session; pass `about` with the elements/values to check.";else{let v=await J(`Check these AUTOSAR configuration elements and values against the specifications and manuals in this knowledge base: ${E}. For each one, give every constraint that applies (allowed range or literals, multiplicity, dependencies on other parameters/modules, hardware limits of the target microcontroller) with the document name and section or requirement ID, and say whether the value satisfies it.`,s.sessionID,e.workspace_id,s.abort);m=v.startsWith("UNAVAILABLE")?`
|
|
25
25
|
|
|
26
|
-
DOCUMENT CHECK UNAVAILABLE: ${v}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${
|
|
26
|
+
DOCUMENT CHECK UNAVAILABLE: ${v}`:["","","## VALIDATION 2 \u2014 against the ingested documents (soft check: the deterministic result above is the hard gate)",`Elements: ${E}`,v,"","Answer this checklist before finishing, one line per element: `<element> = <value>: OK | VIOLATED | NOT COVERED \u2014 [D#]`.","VIOLATED \u2192 fix with ecuc_edit/arxml_edit and validate again. NOT COVERED \u2192 say so; never invent a constraint.","Check every requirement ID you cite with autosar_spec_id_check."].join(`
|
|
27
27
|
`)}}return{title:`ecuc_validate ${JSON.stringify(n.summary)}`,output:S(n)+[u,...I(c,e.max??200),...h].join(`
|
|
28
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=y(s.directory,e.project_dir),r=await b(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=y(s.directory,e.project_dir),f=c.map((m)=>m.arxml).filter((m)=>!!m),[p,u]=await Promise.all([oe(l,f,s.abort),ae(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)})`:""),...ce(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
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=y(s.directory,e.project_dir),f=c.map((h)=>h.element).filter((h)=>!!h),[p,u]=await Promise.all([oe(l,f,s.abort),ae(l,f,s.abort)]);return{title:`autosar_config_lookup ${e.path}`,output:[`${c.length} match(es) for ${e.path} in workspace ${a}`,...ce(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 b(y(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:
|
|
30
|
+
`)}}}),ecuc_find:w({description:"Structured query over the ECUC configuration \u2014 use it instead of grep/read on ARXML. Filter containers by "+`module, container_def (def short-name, e.g. PduRRoutingPath, ComSignal, NvMBlockDescriptor), where ("ComIPduDirection=SEND, ComBitSize>8"; =, !=, >, <, >=, <=, ~regex), ref_to (containers that reference this path directly or through up to 2 references, e.g. all routing paths whose destination is an EcuC Pdu), and referenced_by (e.g. all ComSignals referenced by I-PDU Y). Returns AUTOSAR paths, the container's file:line (at) and its values, each with "@at:<Param>" (file:line of the VALUE element) and, for integers, "@hex:<Param>".`+k,args:{module:d.string().optional(),container_def:d.string().optional().describe("container definition short-name"),where:d.union([d.string(),d.record(d.string(),d.any())]).optional().describe("conditions on parameter values"),ref_to:d.string().optional().describe("AUTOSAR path / SHORT-NAME that the containers must reference"),referenced_by:d.string().optional().describe("container whose references define the result set"),limit:d.number().int().min(1).max(500).optional(),project_dir:d.string().optional()},async execute(e,s){let a=["find"];if(e.module)a.push("--module",e.module);if(e.container_def)a.push("--container-def",e.container_def);if(e.where)a.push("--where",typeof e.where==="string"?e.where:JSON.stringify(e.where));if(e.ref_to)a.push("--ref-to",e.ref_to);if(e.referenced_by)a.push("--referenced-by",e.referenced_by);a.push("--limit",String(e.limit??50));let r=await b(y(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 b(y(s.directory,e.project_dir),["spec-ids",...a],s.abort);if(!r.ok)return _(r);let n=r.results;return{title:`autosar_spec_id_check ${JSON.stringify(r.counts)}`,output:[`Checked ${n.length} ID(s) against ${r.docs} spec text file(s) (${r.docsOrigin}; ${r.indexedIds} IDs indexed): ${JSON.stringify(r.counts)}`,...n.map((c)=>`${c.id} ${c.status}`+(c.doc?` \u2014 ${c.doc}:${c.line}`:"")+(c.didYouMean?` (did you mean ${c.didYouMean}?)`:"")+(c.text?`
|
|
31
31
|
${c.text}`:"")),n.some((c)=>c.status!=="DEFINED")?"Do not cite IDs that are not DEFINED; state the rule without an ID instead.":""].filter(Boolean).join(`
|
|
32
32
|
`)}}}),ecuc_crosscheck:w({description:"Per-module cross-check table: runs the semantic rule packs for one module (Com, PduR, EcuC, NvM, Fee, Ea, "+"CanIf, Dem, ...) \u2014 config vs System/ECU extract (H2L-SYS), gateway routing vs extract (H2L-PDUR), NvM/Fee "+"length vs the C RAM object's sizeof (H2L-NVM), memory capacity (H2L-MEM), signal packing and handle IDs \u2014 "+"and returns, per element, the findings, plus notes on what could NOT be checked. Run it for every module present after ecuc_validate; a clean validate alone is not proof of a correct configuration."+k,args:{module:d.string().describe("module name, e.g. PduR"),project_dir:d.string().optional()},async execute(e,s){let a=await b(y(s.directory,e.project_dir),["crosscheck",e.module],s.abort);if(!a.ok)return S(a)+_(a);let r=a.rows,n=a.otherFindings??[];return{title:`ecuc_crosscheck ${e.module}: ${a.summary}`,output:[`${e.module}: ${a.summary} (element kinds: ${a.elementKinds.join(", ")||"none"})`,...r.map((c)=>`${c.element} (${c.at})
|
|
33
33
|
${c.findings.join(`
|
|
@@ -44,13 +44,13 @@ ${n.map((f)=>f.diff).join(`
|
|
|
44
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 b(y(s.directory,e.project_dir),a,s.abort);if(!r.ok)return _(r)+(r.diagnostics?.length?`
|
|
46
46
|
${I(r.diagnostics,20).join(`
|
|
47
|
-
`)}`:"");let{ok:n,engine:c,ms:l,...f}=r;return JSON.stringify(f,null,1)}}),autosar_audit:w({description:"Integration review \u2014 run this FIRST when reviewing C code that uses BSW services. Deterministically scans "+"C files (default: .hydron/autosar.json `audit` paths, else every .c in the project except generated files, "+"recognised by banner or *_Cfg/*_PBcfg/Rte* names \u2014 folder names do not matter) for Com_Send/ReceiveSignal[Group], "+"NvM_Read/WriteBlock/RestoreBlockDefaults, Dem_SetEventStatus/ReportErrorStatus, PduR_*Transmit and Rte_Write_/Rte_Read_ (resolved through the generated Output/ RTE headers), resolves every handle through the ECUC (symbolic name or raw number), and reports: H2L-API-001 raw numeric handle, -002 unknown handle, -003 direction mismatch (send on a RECEIVE I-PDU signal or receive on SEND), -004 C object width vs ComSignalType, -005 NvM NULL_PTR without a permanent RAM block (NULL_PTR WITH one is valid, SWS_NvM_00900). Each finding has file:line, evidence (configured values + AUTOSAR paths) and a spec citation; calls it cannot check are listed as unchecked, never guessed. Confirm findings with ecuc_read / autosar_trace.",args:{paths:
|
|
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=y(s.directory,e.project_dir),r=await b(a,["audit",...R(e.paths)??[]],s.abort);if(!r.ok)return S(r)+_(r);let n=(r.notes??[]).map((h)=>`NOTE: ${h}`),{findings:c,unchecked:l,scanned:f}=r,p=[`Scanned ${f.sources.length} C file(s), ${f.calls} BSW call(s): ${c.length?JSON.stringify(r.summary):"no findings"}`,...c.map((h)=>`${h.file}:${h.line} ${h.severity.toUpperCase()} ${h.rule} ${h.call}
|
|
48
48
|
${h.message}
|
|
49
49
|
evidence: ${JSON.stringify(h.evidence)}
|
|
50
50
|
spec: ${h.cite}${h.fix?`
|
|
51
51
|
fix: ${h.fix}`:""}`)];if(l.length)p.push(`Unchecked (${l.length}):`,...l.slice(0,50).map((h)=>` ${h.file}:${h.line} ${h.call} \u2014 ${h.reason}`));let u=r.unreferenced??{};for(let[h,m]of Object.entries(u))p.push(`INFO configured but never referenced in the scanned code \u2014 ${h}: ${m.count} (e.g. ${m.sample.slice(0,5).join(", ")})`);return p.push(...n),{title:`autosar_audit ${JSON.stringify(r.summary)}`,output:S(r)+p.join(`
|
|
52
|
-
`)}}}),autosar_verify_rte:w({description:"Verify Rte_* calls in C against the SW-C description (SWS_RTE naming, R25-11). Each call is mapped to its enclosing function, then to every runnable whose entry point (RUNNABLE-ENTITY SYMBOL) reaches it, and classified: OK (the runnable has the access point), NOT-ALLOWED (the API exists for the SW-C but this runnable has no dataSendPoint/dataReceivePoint/serverCallPoint/... for it), INVENTED (no such port, element, runnable, or wrong direction/semantics). For NOT-ALLOWED/INVENTED it returns ready-to-run arxml_edit ops (dry-run checked) that add the access point / port / data element. Run it after writing runnable code and never finish with a failing verify.",args:{paths:
|
|
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=y(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 b(a,["read",e.target,"--depth","3","--schema"],s.abort);if(!u.ok)return _(u);let{ok:h,engine:m,ms:g,...
|
|
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=y(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 b(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=y(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 b(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
54
|
`),ue=v.length>400?`${v.slice(0,400).join(`
|
|
55
55
|
`)}
|
|
56
56
|
\u2026 (${v.length-400} more lines: narrow the target)`:v.join(`
|
|
@@ -70,7 +70,7 @@ ${u.join(`
|
|
|
70
70
|
${u}
|
|
71
71
|
`}let p={swc:c.swc,runnables:c.runnables,estimatedTokens:c.estimatedTokens,budgetTokens:c.budgetTokens,reductions:c.reductions,overBudget:c.overBudget??!1,sha1:c.sha1,sections:c.sections,sources:c.manifest};return{title:`autosar_build_context ${c.swc}${c.runnables.length===1?`/${c.runnables[0]}`:""} ~${c.estimatedTokens} tok`,output:`${l}
|
|
72
72
|
---
|
|
73
|
-
MANIFEST ${JSON.stringify(p)}`,metadata:{sha1:c.sha1,estimatedTokens:c.estimatedTokens}}}}),autosar_codegen:w({description:"Deterministic BSW configuration code generation from the ECUC ARXML + param defs (no LLM output: the same ARXML always gives the same C). Modules: NvM, MemIf, Fee, Ea, Dem, PduR, CanIf, Port, Dio (any other configured module can be named; it then gets the generic def-driven emission only). Emits <Mip>_Cfg.h (pre-compile #defines, STD_ON/STD_OFF, <MIP>_CFG_* version macros, TPS_ECUC_02108 symbols <Mip>Conf_<ContainerDef>_<Name>), <Mip>_Cfg.c / _Lcfg.c / _PBcfg.c by each parameter's config class, const tables for multiplicity-n containers, MemMap-wrapped, SchM_<Mip>.h and <Mip>_MemMap.h. Static-code struct layouts (the SIP's NvM_BlockDescriptorType, PduR_RoutingPathType, ...) come from a binding selected by the project's headers. Missing handle IDs are assigned deterministically and written back into the ECUC ARXML in place (TPS_ECUC_02107) unless write_back=false. Writes to the scratch dir .hydron/codegen/out unless out_dir is given ('project' = the project's Output dir). Follow with autosar_codegen_diff against the existing Output/, then autosar_build.",args:{modules:
|
|
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=y(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 b(a,r,s.abort);if(!n.ok){let u=n.handleErrors??[];return S(n)+_(n)+(u.length?`
|
|
74
74
|
${u.map((h)=>` ${h}`).join(`
|
|
75
75
|
`)}`:"")}let{modules:c,handles:l,timings:f}=n,p=[`Generated ${Object.keys(c).length} module(s) into ${n.outDir} in ${f.total_ms} ms (AUTOSAR R${n.release}):`,...Object.entries(c).map(([u,h])=>` ${u} (${h.variant}${h.binding?`, binding ${h.binding}`:", generic tables"}): ${h.files.join(", ")}; ${h.symbols} symbol(s)`+h.notes.map((m)=>`
|
|
76
76
|
NOTE: ${m}`).join("")),l.assigned.length?`Assigned ${l.assigned.length} handle ID(s) (${l.writtenBack?"written back into the ECUC ARXML":"in memory only, NOT written back"}):
|
|
@@ -78,5 +78,5 @@ ${u.map((h)=>` ${h}`).join(`
|
|
|
78
78
|
`)+(l.changes.length?`
|
|
79
79
|
${l.changes.map((u)=>u.diff).join(`
|
|
80
80
|
`)}`:""):"Handle IDs: all already present in the ECUC (nothing assigned).",...(n.notes??[]).map((u)=>`NOTE: ${u}`)];return{title:`autosar_codegen ${Object.keys(c).join(", ")}`,output:S(n)+p.join(`
|
|
81
|
-
`)}}}),autosar_codegen_diff:w({description:"Semantic diff of generated C configuration code against a reference dir (e.g. the vendor-generated Output/): compares #define names and values and the contents of every initialised table/struct element by element, plus table ordering, after normalising numbers (0x2A0u == 672), casts, parentheses and macro references. Ignores formatting, comments, banners and include order. Reports per module: matching symbols, missing (in reference only), extra (generated only), value mismatches with both values.",args:{reference_dir:d.string().describe("reference code dir, e.g. Output (relative to the project or absolute)"),generated_dir:d.string().optional().describe("generated code dir (default: the autosar_codegen scratch dir)"),modules:
|
|
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=y(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 b(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
82
|
`)}}}),autosar_generate:o("generate"),autosar_build:o("build")}),t)}},Ge=We;export{Ge as Autosar};
|
package/skills/autosar/SKILL.md
CHANGED
|
@@ -8,12 +8,17 @@ description: >-
|
|
|
8
8
|
configurator / SIP. It carries the tool map (ecuc_read/ecuc_edit/ecuc_validate/arxml_diff,
|
|
9
9
|
autosar_trace/autosar_config_lookup, autosar_generate/autosar_build), the edit → validate →
|
|
10
10
|
generate → build → trace loop, and the ECUC model rules needed to edit correctly.
|
|
11
|
+
Not for greetings, small talk or questions unrelated to the AUTOSAR project: answer those directly.
|
|
11
12
|
---
|
|
12
13
|
# AUTOSAR skill — Classic Platform integration layer
|
|
13
14
|
|
|
14
15
|
You are working on an AUTOSAR Classic ECU project. The configuration is ECUC ARXML; generated C
|
|
15
16
|
in `Output/` is derived from it; in-house code in `Source/` calls the generated symbols.
|
|
16
17
|
|
|
18
|
+
Scope: everything below applies to AUTOSAR work only (a change, a review, an analysis or a question about this
|
|
19
|
+
project, its configuration/code or the AUTOSAR specs). A greeting or an unrelated question gets a direct answer: no
|
|
20
|
+
grounding, no tools, no exploring the project.
|
|
21
|
+
|
|
17
22
|
## Hard rules
|
|
18
23
|
0. **Configured values are answered with `ecuc_read`** (it accepts a SHORT-NAME or partial path) or
|
|
19
24
|
`autosar_config_lookup` — not grep/read on ARXML. A value's AUTOSAR path is its `@path`; `@def` is its
|