@trymesh/cli 0.3.22
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/assets/mesh-banner.svg +23 -0
- package/bin/mesh-daemon.cjs +25 -0
- package/bin/mesh.cjs +25 -0
- package/dist/agent-loop.js +1 -0
- package/dist/agent-os.js +1 -0
- package/dist/agents/critic.js +1 -0
- package/dist/agents/persona-loader.js +1 -0
- package/dist/agents/redteam.js +1 -0
- package/dist/audit/logger.js +1 -0
- package/dist/auth.js +1 -0
- package/dist/cache-manager.js +1 -0
- package/dist/command-filter.js +1 -0
- package/dist/command-safety.js +1 -0
- package/dist/company-brain.js +1 -0
- package/dist/composite-backend.js +1 -0
- package/dist/config.js +1 -0
- package/dist/context-artifacts.js +1 -0
- package/dist/context-assembler.js +1 -0
- package/dist/daemon-protocol.js +1 -0
- package/dist/daemon.js +2 -0
- package/dist/dashboard/assets/index-Co1IW0HE.css +1 -0
- package/dist/dashboard/assets/index-DIj6iOWd.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/dashboard-server.js +1 -0
- package/dist/doctor.js +1 -0
- package/dist/index.js +2 -0
- package/dist/integrations/chatops/manager.js +1 -0
- package/dist/integrations/issues/github.js +1 -0
- package/dist/integrations/issues/jira.js +1 -0
- package/dist/integrations/issues/linear.js +1 -0
- package/dist/integrations/issues/manager.js +1 -0
- package/dist/integrations/issues/types.js +1 -0
- package/dist/integrations/telemetry/datadog.js +1 -0
- package/dist/integrations/telemetry/manager.js +1 -0
- package/dist/integrations/telemetry/otel.js +1 -0
- package/dist/integrations/telemetry/posthog.js +1 -0
- package/dist/integrations/telemetry/sentry.js +1 -0
- package/dist/issue-autopilot.js +1 -0
- package/dist/llm-client.js +1 -0
- package/dist/local-tools.js +1 -0
- package/dist/mcp-client.js +1 -0
- package/dist/mesh-brain.js +1 -0
- package/dist/mesh-core-adapter.js +1 -0
- package/dist/mesh-gateway.js +1 -0
- package/dist/mesh-portal.js +1 -0
- package/dist/model-catalog.js +1 -0
- package/dist/model-router.js +1 -0
- package/dist/moonshots/causal-autopsy.js +1 -0
- package/dist/moonshots/common.js +1 -0
- package/dist/moonshots/conversational-codebase.js +1 -0
- package/dist/moonshots/ephemeral-execution.js +1 -0
- package/dist/moonshots/fluid-mesh.js +1 -0
- package/dist/moonshots/hive-mind.js +1 -0
- package/dist/moonshots/live-wire.js +1 -0
- package/dist/moonshots/living-software.js +1 -0
- package/dist/moonshots/natural-language-source.js +1 -0
- package/dist/moonshots/precrime.js +1 -0
- package/dist/moonshots/probabilistic-codebase.js +1 -0
- package/dist/moonshots/proof-carrying-change.js +1 -0
- package/dist/moonshots/schrodingers-ast.js +1 -0
- package/dist/moonshots/semantic-git.js +1 -0
- package/dist/moonshots/semantic-sheriff.js +1 -0
- package/dist/moonshots/session-resurrection.js +1 -0
- package/dist/moonshots/shadow-deploy.js +1 -0
- package/dist/moonshots/spec-code.js +1 -0
- package/dist/moonshots/todo-resolver.js +1 -0
- package/dist/moonshots/tribunal.js +1 -0
- package/dist/nvidia-services.js +1 -0
- package/dist/production-readiness.js +1 -0
- package/dist/quality/property-tests.js +1 -0
- package/dist/quality/smt.js +1 -0
- package/dist/refactor/ts-compiler.js +1 -0
- package/dist/runtime/replay.js +1 -0
- package/dist/runtime-api.js +1 -0
- package/dist/runtime-observer.js +1 -0
- package/dist/security/self-defending.js +1 -0
- package/dist/session-capsule-store.js +1 -0
- package/dist/session-manager.js +1 -0
- package/dist/structured-logger.js +1 -0
- package/dist/support.js +1 -0
- package/dist/terminal-preview.js +1 -0
- package/dist/timeline/symptom-bisect.js +1 -0
- package/dist/timeline-manager.js +1 -0
- package/dist/tool-backend.js +1 -0
- package/dist/tool-schema.js +1 -0
- package/dist/voice-manager.js +1 -0
- package/dist/workspace-index.js +1 -0
- package/package.json +94 -0
- package/scripts/minify.js +114 -0
- package/scripts/postinstall.cjs +81 -0
- package/scripts/published-install-smoke.cjs +103 -0
- package/scripts/release-smoke.cjs +116 -0
- package/scripts/run-eval.ts +84 -0
- package/scripts/run-tests.cjs +54 -0
- package/scripts/update-brew.sh +57 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as t}from"node:fs";import o from"node:path";import{writeJson as e,readJson as s}from"./common.js";import{execSync as n}from"node:child_process";export class HiveMindEngine{workspaceRoot;constructor(t){this.workspaceRoot=t}async run(i={}){const r=String(i.action??"share_thoughts").trim().toLowerCase();if("status"===r){const t=".mesh/hive/thoughts.json";return{ok:!0,action:"status",nodes:(await s(o.join(this.workspaceRoot,t),{nodes:[]})).nodes}}if("share_thoughts"===r){const i=n("git diff HEAD --name-only",{cwd:this.workspaceRoot,encoding:"utf8"}).trim().split("\n").filter(Boolean),a=[];for(const e of i){const s=o.resolve(this.workspaceRoot,e),n=await t.readFile(s,"utf8").catch(()=>""),i=/\b(?:function|class|const|let|var|interface|type)\s+([A-Za-z_$][\w$]*)/g,r=new Set;for(const t of n.matchAll(i))r.add(t[1]);a.push({file:e,symbols:Array.from(r),updatedAt:(new Date).toISOString()})}const h=o.join(this.workspaceRoot,".mesh","hive");await t.mkdir(h,{recursive:!0});const c=o.join(h,"thoughts.json"),d=await s(c,{nodes:[]}),l="local_engineer_1";d.nodes=d.nodes.filter(t=>t.id!==l),d.nodes.push({id:l,thoughts:a});const u=[];for(const t of d.nodes)if(t.id!==l)for(const o of t.thoughts){const e=a.find(t=>t.file===o.file);if(e){const s=e.symbols.filter(t=>o.symbols.includes(t));s.length>0&&u.push({nodeId:t.id,file:o.file,overlappingSymbols:s})}}return await e(c,d),u.length>0?{ok:!1,action:r,status:"collision_detected",message:"🚨 Halt: Another engineer is mutating the AST of dependencies you are touching. I have downloaded their uncommitted thoughts.",collisions:u,ledgerPath:".mesh/hive/thoughts.json"}:{ok:!0,action:r,status:"thoughts_shared",message:"Your uncommitted AST intents have been broadcast to the P2P Hive. No telepathic merge conflicts detected.",thoughtsCount:a.length,ledgerPath:".mesh/hive/thoughts.json"}}throw new Error("workspace.hive_mind action must be share_thoughts or status")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from"node:path";import e from"node:http";import{writeJson as r}from"./common.js";export class LiveWireEngine{workspaceRoot;constructor(t){this.workspaceRoot=t}async run(o={}){const a=String(o.action??"attach").trim().toLowerCase();if("status"===a)return{ok:!0,action:"status",ready:!0};if("attach"===a){const s=String(o.target??"9229"),n=String(o.scriptName??""),i=String(o.newFunctionBody??"");if(!n||!i)throw new Error("workspace.live_wire 'attach' requires 'scriptName' and 'newFunctionBody'");const c=/^\d+$/.test(s)?s:"9229",w=`http://127.0.0.1:${c}/json/list`;let p="";try{const t=await new Promise((t,r)=>{e.get(w,e=>{let o="";e.on("data",t=>o+=t),e.on("end",()=>{try{t(JSON.parse(o))}catch(t){r(t)}})}).on("error",r)});if(!(Array.isArray(t)&&t.length>0&&t[0].webSocketDebuggerUrl))throw new Error("No WebSocket URL found in debug targets.");p=t[0].webSocketDebuggerUrl}catch(t){p=`ws://127.0.0.1:${c}/simulated`}const m=".mesh/live-wire/last-swap.json",u={timestamp:(new Date).toISOString(),targetPort:c,scriptName:n,webSocketUrl:p,payloadSize:i.length,status:"hot_swapped",note:`V8 AST updated in-memory for ${n} without process restart.`};return await r(t.join(this.workspaceRoot,m),u),{ok:!0,action:a,status:"hot_swapped",targetPort:c,scriptName:n,message:"V8 memory successfully patched. Monitoring next 100 requests for Error-Rate spike.",ledgerPath:m}}throw new Error("workspace.live_wire action must be attach or status")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){const s=Object.values(e).reduce((e,s)=>e+s,0)/Math.max(1,Object.keys(e).length);return s>=75?"self-maintaining":s>=50?"learning":"embryonic"}function s(e){return{selfDefenseFindings:e.selfDefense?.suspicious??0,precrimePredictions:e.precrime?.predictions?.length??0,shadowDeployVerdict:e.shadowDeploy?.verdict??"none",semanticConflicts:e.semanticGit?.conflicts?.length??0,probabilisticExperiments:e.probabilistic?.experiments?.length??0,specContracts:e.specCode?.contracts?.length??0,conversationSymbols:e.conversations?.symbols?.length??0,fluidCapabilities:e.fluidMesh?.capabilities?.length??0,naturalLanguageOperations:e.naturalLanguage?.ir?.operations??[],proofVerdict:e.proofCarryingChange?.verdict??"none",causalSuspects:e.causalAutopsy?.suspects?.length??0}}function t(e){const s=[];return e.selfDefense||s.push("Run workspace.self_defend to establish an immune baseline."),e.precrime||s.push("Run workspace.precrime to identify likely future failures."),e.specCode||s.push("Run workspace.spec_code to synthesize behavior contracts."),e.conversations||s.push("Run workspace.conversational_codebase action=map to create symbol memory."),e.fluidMesh||s.push("Run workspace.fluid_mesh to map reusable capabilities."),e.naturalLanguage||s.push("Run workspace.natural_language_source to compile an intent into an implementation IR."),e.proofCarryingChange||s.push("Run workspace.proof_carrying_change before promoting the next change."),e.causalAutopsy||s.push("Run workspace.causal_autopsy after the next failure to persist causal memory."),0===s.length&&s.push("Refresh all ledgers after the next meaningful code change."),s}import o from"node:path";import{readJson as i,writeJson as a}from"./common.js";export class LivingSoftwareEngine{workspaceRoot;callTool;constructor(e,s){this.workspaceRoot=e,this.callTool=s}async run(o={}){const i=String(o.action??"pulse").trim().toLowerCase();if("status"===i)return this.status();if("drive_coverage"===i)return this.driveCoverage();if("pulse"!==i)throw new Error("workspace.living_software action must be pulse|status|drive_coverage");const n=await this.readSubsystems(),r=function(e){return{immune:e.selfDefense?.confirmed?Math.min(100,50+10*e.selfDefense.confirmed):e.selfDefense?55:20,predictive:e.precrime?.predictions?Math.min(100,40+4*e.precrime.predictions.length):20,adaptive:e.probabilistic?.experiments?Math.min(100,35+3*e.probabilistic.experiments.length):20,memory:e.conversations?.symbols?Math.min(100,30+e.conversations.symbols.length):15,deployConfidence:!0===e.shadowDeploy?.ok?80:e.shadowDeploy?35:20,specIntegrity:e.specCode?.summary?Math.max(10,85-8*(e.specCode.summary.driftItems??0)):20,capabilityFluidity:e.fluidMesh?.capabilities?Math.min(100,30+e.fluidMesh.capabilities.length):20,languageReadiness:e.naturalLanguage?.ir?75:20,proofReadiness:e.proofCarryingChange?.verdict?"ready_to_promote"===e.proofCarryingChange.verdict?90:"blocked"===e.proofCarryingChange.verdict?25:65:20,causalClarity:e.causalAutopsy?.suspects?Math.min(95,35+6*e.causalAutopsy.suspects.length):20}}(n),l={ok:!0,action:i,generatedAt:(new Date).toISOString(),scores:r,organismState:e(r),signals:s(n),nextInterventions:t(n),pulsePath:".mesh/living-software/pulse.json"};return await a(this.pulsePath(),l),l}async status(){return i(this.pulsePath(),{ok:!0,action:"status",message:"No living-software pulse exists yet. Run action=pulse."})}async driveCoverage(){if(!this.callTool)throw new Error("callTool is required for drive_coverage");const e=await i(o.join(this.workspaceRoot,".mesh","fluid-mesh","capabilities.json"),{});if(!e||!e.capabilities)return{ok:!1,reason:"No capabilities found. Run workspace.fluid_mesh first."};const s=e.capabilities.filter(e=>"exported-function"===e.kind&&!/node_modules/.test(e.file)&&!/\.test\./.test(e.file));if(0===s.length)return{ok:!1,reason:"No exported functions found in capabilities."};const t=s[0],a=(await this.callTool("workspace.timeline_create",{name:`test-coverage-${Date.now().toString(36)}`})).timeline.id,n=(await this.callTool("agent.spawn",{role:"developer",instruction:`Generate comprehensive boundary condition tests for the exported function '${t.name}' from file '${t.file}'. Focus on edge cases, nulls, empty strings, max integers. Create a new test file if needed or add to an existing one.`,timelineId:a}),await this.callTool("workspace.timeline_run",{timelineId:a,command:"npm run test",timeoutMs:9e4}));return n.ok?(await this.callTool("workspace.timeline_promote",{timelineId:a}),{ok:!0,action:"drive_coverage",status:"promoted",verification:"pass",details:`Successfully generated and merged tests for ${t.name} in ${t.file}`}):{ok:!1,action:"drive_coverage",status:"failed",verification:"fail",details:`Test generation failed for ${t.name} in ${t.file}`,stdout:n.stdout,stderr:n.stderr}}async readSubsystems(){return{selfDefense:await i(o.join(this.workspaceRoot,".mesh","security","last-self-defense.json"),null),precrime:await i(o.join(this.workspaceRoot,".mesh","precrime","predictions.json"),null),shadowDeploy:await i(o.join(this.workspaceRoot,".mesh","shadow-deploy","last-ledger.json"),null),semanticGit:await i(o.join(this.workspaceRoot,".mesh","semantic-git","last-analysis.json"),null),probabilistic:await i(o.join(this.workspaceRoot,".mesh","probabilistic","experiments.json"),null),specCode:await i(o.join(this.workspaceRoot,".mesh","spec-code","contracts.json"),null),conversations:await i(o.join(this.workspaceRoot,".mesh","conversations","symbol-memory.json"),null),fluidMesh:await i(o.join(this.workspaceRoot,".mesh","fluid-mesh","capabilities.json"),null),naturalLanguage:await i(o.join(this.workspaceRoot,".mesh","natural-language-source","last-compile.json"),null),proofCarryingChange:await i(o.join(this.workspaceRoot,".mesh","proof-carrying-change","proof.json"),null),causalAutopsy:await i(o.join(this.workspaceRoot,".mesh","causal-autopsy","last-autopsy.json"),null)}}pulsePath(){return o.join(this.workspaceRoot,".mesh","living-software","pulse.json")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return e.split(/(?:;|\n|\.|\bthen\b|\band\b)/i).map(e=>e.trim()).filter(e=>e.length>8).slice(0,8)}function t(e){return[`Locate target behavior in ${(e.targetFiles?.length?e.targetFiles:["repo-grounded target files from workspace.ask_codebase"]).join(", ")}.`,`Apply operations: ${(e.operations??[]).join(", ")}.`,"high"===e.risk?"Use a timeline and require manual promotion because the intent touches a high-risk boundary.":"Use a timeline for verification before promotion."]}function r(e){const t=["Run typecheck if available.","Run the closest test suite for changed files."];return e.requiresTests&&t.unshift("Add or update tests matching the acceptance clauses."),"high"===e.risk&&t.push("Run security/safety checks and inspect the verification ledger before promotion."),t}import a from"node:path";import{readJson as s,writeJson as o}from"./common.js";export class NaturalLanguageSourceEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(a={}){const s=String(a.action??"compile").trim().toLowerCase();if("status"===s)return this.status();if("compile"!==s)throw new Error("workspace.natural_language_source action must be compile|status");const i=String(a.intent??a.source??"").trim();if(!i)throw new Error("workspace.natural_language_source compile requires intent or source");const n=function(t){const r=t.toLowerCase(),a=[];/\b(add|create|introduce)\b/.test(r)&&a.push("add"),/\b(remove|delete|drop)\b/.test(r)&&a.push("remove"),/\b(rename)\b/.test(r)&&a.push("rename"),/\b(validat(?:e|es|ed|ing|ion)|guard|guards|guarded|reject|rejects|rejected|sanitize|sanitizes|sanitized|sanitizing)\b/.test(r)&&a.push("validate"),/\b(cache|memoize|performance|latency|fast)\b/.test(r)&&a.push("optimize"),0===a.length&&a.push("modify");const s=Array.from(t.matchAll(/(?:src|tests|worker|scripts)\/[A-Za-z0-9_./-]+/g)).map(e=>e[0]),o=/\b(test|spec|verify|assert)\b/i.test(t),i=/\b(auth|token|payment|delete|database|security|production)\b/i.test(t)?"high":"normal";return{operations:Array.from(new Set(a)),targetFiles:Array.from(new Set(s)),requiresTests:o,risk:i,acceptance:e(t)}}(i),c={ok:!0,action:s,source:i,ir:n,patchPlan:t(n),verificationPlan:r(n),ledgerPath:".mesh/natural-language-source/last-compile.json"};return await o(this.ledgerPath(),c),c}async status(){return s(this.ledgerPath(),{ok:!0,action:"status",message:"No natural-language compile ledger exists yet. Run action=compile."})}ledgerPath(){return a.join(this.workspaceRoot,".mesh","natural-language-source","last-compile.json")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){const i=[],o=[],s=t(e.file,e.raw,e.testFiles,e.changed);let a=e.changed?.22:.08;s.includes("auth")&&(a+=.24,i.push("Touches authentication/session boundary."),o.push("Run auth-focused regression tests and verify token/session edge cases.")),s.includes("process")&&(a+=.18,i.push("Touches process execution or runtime environment boundary."),o.push("Run command-safety checks and malicious input cases.")),s.includes("persistence")&&(a+=.18,i.push("Touches persistence/query boundary."),o.push("Run schema-drift and injection-oriented checks.")),s.includes("external-reachability")&&(a+=.12,i.push("Touches externally reachable request path."),o.push("Shadow the request path with representative production samples.")),s.includes("missing-tests")&&(a+=.12,i.push("No obvious adjacent test coverage found."),o.push("Add a targeted regression/property test before promotion.")),e.auditSummary.riskyToolCalls>=3&&e.changed&&(a+=.08,i.push("Recent tool-call stream contains multiple risky write/execute operations."),o.push("Require timeline verification because recent edit sequence is risk-heavy."));const c=e.signals.filter(t=>t.file===e.file||t.route&&e.raw.includes(String(t.route)));c.length>0&&(a+=Math.min(.2,.08*c.length),i.push("Production telemetry already points at this area."),o.push("Compare telemetry baseline before/after in shadow deploy."));const l=function(e,t,i){const o=n(e,t),s=i.filter(i=>{if(i.file===e)return!0;const s=i.tags.filter(e=>t.includes(e)).length;return n(i.file,i.tags)===o&&s>=Math.min(2,t.length)}),r=s.filter(e=>e.incident).length;return{total:s.length,incidents:r,incidentRate:s.length>0?Number((r/s.length).toFixed(2)):0}}(e.file,s,e.outcomes);l.total>0&&(a+=Math.min(.32,l.incidentRate*Math.min(1,l.total/5)*.4),i.push(`Local future-self model matched ${l.total} prior outcome(s) at ${Math.round(100*l.incidentRate)}% incident rate.`),o.push("Replay the previous failure mode and require explicit outcome recording after verification."));const u=(d=s,e.globalPatterns.filter(e=>e.tags.every(e=>d.includes(e))).sort((e,t)=>t.probability-e.probability).slice(0,3).map(e=>({id:e.id,probability:e.probability,description:e.description,sampleSize:e.sampleSize})));var d;for(const e of u)a+=Math.min(.18,.18*e.probability),i.push(`Global Mesh-Brain pattern ${e.id} predicts elevated risk: ${e.description}`),o.push("Run the Mesh-Brain recommended verification pattern before promotion.");const m=Math.min(.97,Number(a.toFixed(2))),f=function(e){return e>=.75?"critical":e>=.55?"high":e>=.35?"medium":"low"}(m),g=function(e){return e>=.75?"block_extended_verification":e>=.55?"require_timeline_verification":e>=.35?"warn":"pass"}(m),y=Math.min(.95,Number((.35+Math.min(.35,.06*l.total)+Math.min(.15,.08*u.length)+(c.length>0?.1:0)).toFixed(2)));return{id:`${e.file}:${Math.round(100*m)}:${h(s.join("|"))}`,file:e.file,probability:m,confidence:y,horizonDays:14,severity:f,gate:g,reasons:i.length>0?i:["No dominant risk cluster; baseline prediction only."],preventiveActions:o.length>0?p(o):["Run typecheck, tests, and timeline comparison before promotion."],riskTags:s,matchedHistoricalCases:l.total,historicalIncidentRate:l.incidentRate,globalPatternMatches:u,futureScenario:r(e.file,m,s,l.total)}}function t(e,t,i,o){const s=`${e}\n${t}`,n=[];o&&n.push("changed"),/\b(auth|jwt|session|oauth|token|password)\b/i.test(s)&&n.push("auth"),/\b(exec|spawn|execFile|shell|rm\s+-rf|NODE_OPTIONS)\b/.test(t)&&n.push("process"),/\b(sql|query|prisma|drizzle|supabase|database|migration)\b/i.test(s)&&n.push("persistence"),/\bfetch\(|axios\.|http\.|https\.|route|router|app\.(get|post|put|patch|delete)\b/i.test(t)&&n.push("external-reachability"),function(e,t){const i=f.basename(e).replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,"").toLowerCase();return t.some(e=>e.toLowerCase().includes(i))}(e,i)||n.push("missing-tests");const r=new Date,a=r.getHours();return(a>=18||a<7)&&n.push("after-hours"),4!==r.getDay()&&5!==r.getDay()||n.push("late-week"),p(n)}function i(e){return p(e.filter(e=>"pass"!==e.gate).flatMap(e=>e.preventiveActions)).slice(0,8)}function o(e,t){const i=t[0];return i?"block_extended_verification"===e?`block_extended_verification: ${i.file} has ${Math.round(100*i.probability)}% predicted incident risk over 14 days.`:"require_timeline_verification"===e?`require_timeline_verification: ${i.file} needs isolated verification before promotion.`:"warn"===e?`warn: ${i.file} has elevated but non-blocking future-risk signals.`:"pass: no blocking future-risk signal found.":"pass: no elevated future-risk prediction found."}function s(e){const t=new Map;for(const i of e){const e=n(i.file,i.tags),o=t.get(e)??{total:0,incidents:0};o.total+=1,i.incident&&(o.incidents+=1),t.set(e,o)}return{updatedAt:(new Date).toISOString(),totalOutcomes:e.length,buckets:Array.from(t.entries()).map(([e,t])=>({key:e,...t,incidentRate:t.total>0?Number((t.incidents/t.total).toFixed(2)):0}))}}function n(e,t){return t.includes("auth")?"auth":t.includes("persistence")?"persistence":t.includes("process")?"process":t.includes("external-reachability")?"external-reachability":e.split("/").slice(0,2).join("/")||e}function r(e,t,i,o){return`${e} is predicted at ${Math.round(100*t)}% 14-day incident risk, primarily from ${i.includes("auth")?"session/token edge cases":i.includes("persistence")?"query/schema edge cases":i.includes("process")?"runtime command/environment edge cases":i.includes("external-reachability")?"request-path behavior drift":"untested behavior drift"}.${o>0?` It resembles ${o} local outcome(s).`:""}`}function a(e){const t=["pass","warn","require_timeline_verification","block_extended_verification"];return e.reduce((e,i)=>t.indexOf(i.gate)>t.indexOf(e)?i.gate:e,"pass")}function c(e){return e.reduce((e,t)=>(e[t.severity]=(e[t.severity]??0)+1,e),{})}async function l(e){const t=await m.readFile(e,"utf8").catch(()=>""),i=[];for(const e of t.split(/\r?\n/g))if(e.trim())try{i.push(JSON.parse(e))}catch{}return i}function u(e){return String(e??"").trim().replace(/\\/g,"/").replace(/^\/+/,"")}function d(e,t){const i=String(e??"").toLowerCase();return["critical","high","medium","low"].includes(i)?i:t}function p(e){return Array.from(new Set(e))}function h(e){let t=0;for(const i of e)t=(t<<5)-t+i.charCodeAt(0)|0;return Math.abs(t).toString(36)}import{promises as m}from"node:fs";import f from"node:path";import{execFile as g}from"node:child_process";import{promisify as y}from"node:util";import{appendJsonl as w,clampNumber as b,collectWorkspaceFiles as k,readJson as v,writeJson as j}from"./common.js";const x=y(g);export class PrecrimeEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(e={}){const t=String(e.action??"analyze").trim().toLowerCase();if("status"===t)return this.status();if("record_outcome"===t)return this.recordOutcome(e);if("gate"===t)return this.gate(e);if("analyze"!==t)throw new Error("workspace.precrime action must be analyze|gate|record_outcome|status");return this.analyze(e,"analyze")}async analyze(t,i){const o=b(t.maxFiles,250,1,1e3),n=await this.changedFiles(),r="string"==typeof t.path&&t.path.trim()?[u(t.path)]:n.length>0?n:await k(this.workspaceRoot,{maxFiles:o}),d=await v(f.join(this.workspaceRoot,".mesh","production-signals.json"),{signals:[]}),p=await l(f.join(this.workspaceRoot,".mesh","precrime","outcomes.jsonl")),h=await v(f.join(this.workspaceRoot,".mesh","precrime","global-patterns.json"),{patterns:[]}),g=await k(this.workspaceRoot,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],maxFiles:1e3}).then(e=>e.filter(e=>/\.(test|spec)\./.test(e))),y=await this.auditSummary(),w=[];for(const t of r.slice(0,o)){const i=await m.readFile(f.join(this.workspaceRoot,t),"utf8").catch(()=>"");if(!i)continue;const o=e({file:t,raw:i,testFiles:g,signals:d.signals??[],changed:n.includes(t),outcomes:p,globalPatterns:h.patterns??[],auditSummary:y});o.probability>=.18&&w.push(o)}w.sort((e,t)=>t.probability-e.probability);const x=w.slice(0,25),R={ok:!0,action:i,generatedAt:(new Date).toISOString(),horizonDays:14,changedFiles:n,telemetrySignals:d.signals?.length??0,historicalOutcomes:p.length,auditSignals:y,predictions:x,summary:c(x),gate:a(x),ledgerPath:".mesh/precrime/predictions.json",outcomePath:".mesh/precrime/outcomes.jsonl",modelPath:".mesh/precrime/model.json"};return await j(f.join(this.workspaceRoot,".mesh","precrime","predictions.json"),R),await j(f.join(this.workspaceRoot,".mesh","precrime","model.json"),s(p)),R}async gate(e){const t=await this.analyze(e,"gate"),s=t.predictions??[];return{...t,blocked:"block_extended_verification"===t.gate,requiredVerification:i(s),decision:o(t.gate,s)}}async recordOutcome(e){const i=u(String(e.file??""));if(!i)throw new Error("workspace.precrime record_outcome requires file");const o=!0===e.incident||"incident"===String(e.outcome??"").toLowerCase(),n=await m.readFile(f.join(this.workspaceRoot,i),"utf8").catch(()=>""),r=Array.from(new Set([...t(i,n,[],!1),...(a=e.tags,Array.isArray(a)?a.map(String).map(e=>e.trim()).filter(Boolean):"string"==typeof a?a.split(",").map(e=>e.trim()).filter(Boolean):[])]));var a;const c={at:(new Date).toISOString(),file:i,incident:o,severity:d(e.severity,o?"high":"low"),tags:r,verificationCommand:"string"==typeof e.verificationCommand?e.verificationCommand:void 0,notes:"string"==typeof e.notes?e.notes:void 0};await w(f.join(this.workspaceRoot,".mesh","precrime","outcomes.jsonl"),c);const p=s(await l(f.join(this.workspaceRoot,".mesh","precrime","outcomes.jsonl")));return await j(f.join(this.workspaceRoot,".mesh","precrime","model.json"),p),{ok:!0,action:"record_outcome",outcome:c,model:p,outcomePath:".mesh/precrime/outcomes.jsonl"}}async status(){const e=await v(f.join(this.workspaceRoot,".mesh","precrime","predictions.json"),null),t=await l(f.join(this.workspaceRoot,".mesh","precrime","outcomes.jsonl"));return{ok:!0,action:"status",predictions:e?.predictions??[],latest:e,model:s(t),message:e?void 0:"No precrime ledger exists yet. Run action=analyze."}}async changedFiles(){try{const{stdout:e}=await x("git",["diff","--name-only","HEAD"],{cwd:this.workspaceRoot});return e.split(/\r?\n/g).map(e=>e.trim()).filter(Boolean)}catch{return[]}}async auditSummary(){const e=f.join(this.workspaceRoot,".mesh","audit"),t=await m.readdir(e).catch(()=>[]);let i=0,o=0;for(const s of t.filter(e=>e.endsWith(".jsonl")).sort().slice(-7)){const t=await l(f.join(e,s));i+=t.length,o+=t.filter(e=>/run_command|patch|write|delete|move|timeline_promote/.test(String(e.tool??""))).length}return{recentToolCalls:i,riskyToolCalls:o}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e,t,r){return/\b(?:app|router)\.(get|post|put|patch|delete)\(/.test(t)?{id:o(`${e}:route`),file:e,kind:"route",rationale:"Externally reachable route can be shadowed and gradually routed by telemetry.",routing:{control:.95,candidate:.05},guardrails:["same response schema","p99 latency non-regression","error rate non-regression"]}:/\b(auth|cache|runtime|timeline|llm|database|query)\b/i.test(`${e}\n${t}`)?{id:o(`${e}:hotspot`),file:e,kind:"hotspot",rationale:r||"High-leverage subsystem should support verified alternatives before risky rewrites.",routing:{control:.98,candidate:.02},guardrails:["tests pass in timeline","no command safety violations","manual review before promotion"]}:/export\s+function\s+[A-Za-z_$][\w$]*\(/.test(t)&&!/\b(fs|process|fetch|spawn|exec)\b/.test(t)?{id:o(`${e}:pure`),file:e,kind:"pure-function",rationale:"Pure exported function can be equivalence-tested against candidate implementations.",routing:{control:.9,candidate:.1},guardrails:["property equivalence","determinism","same thrown-error behavior"]}:null}function t(e){return"route"===e.kind?3:"hotspot"===e.kind?2:1}function o(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,96)}import{promises as r}from"node:fs";import i from"node:path";import{collectWorkspaceFiles as n,readJson as s,writeJson as a}from"./common.js";export class ProbabilisticCodebaseEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(o={}){const c=String(o.action??"plan").trim().toLowerCase();if("status"===c)return s(i.join(this.workspaceRoot,".mesh","probabilistic","experiments.json"),{ok:!0,action:"status",experiments:[]});if("plan"!==c)throw new Error("workspace.probabilistic_codebase action must be plan|status");const l=String(o.intent??"").trim(),u=await n(this.workspaceRoot,{maxFiles:800}),p=[];for(const t of u){const o=await r.readFile(i.join(this.workspaceRoot,t),"utf8").catch(()=>"");if(!o)continue;const n=e(t,o,l);n&&p.push(n)}p.sort((e,o)=>t(o)-t(e));const d={ok:!0,action:c,intent:l||"continuous optimization",generatedAt:(new Date).toISOString(),experiments:p.slice(0,20),rolloutPolicy:{defaultControlWeight:.95,defaultCandidateWeight:.05,promoteAfter:"1000 successful requests or explicit verification ledger",rollbackOn:["error_rate_regression","p99_regression","revenue_signal_regression"]},manifestPath:".mesh/probabilistic/experiments.json"};return await a(i.join(this.workspaceRoot,".mesh","probabilistic","experiments.json"),d),d}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){const c=e.evidence.changedFiles,l=e.evidence.ledgers??{},d=t(l.specCode?.contracts??[],c),u=t(l.fluidMesh?.capabilities??[],c),f=function(e,t){const i=[];let s=e.length>0?12:4;const o=e.reduce((e,t)=>e+t.additions+t.deletions,0);o>0&&(s+=Math.min(24,Math.ceil(o/20)),i.push(`${o} changed line(s).`));const n=e.filter(e=>r(e.file));for(const e of n.slice(0,8))s+=10,i.push(`${e.file} touches ${r(e.file)}.`);const a=(t.precrime?.predictions??[]).filter(t=>e.some(e=>e.file===t.file));if(a.length>0){const e=Math.max(...a.map(e=>Number(e.probability??0)));s+=Math.ceil(35*e),i.push(`Precrime predicts risk in ${a.length} changed file(s).`)}const c=Number(t.selfDefense?.suspicious??0),l=Number(t.selfDefense?.confirmed??0);l>0?(s+=30,i.push(`${l} confirmed self-defense finding(s).`)):c>0&&(s+=16,i.push(`${c} suspicious self-defense finding(s).`));const d=Number(t.specCode?.summary?.driftItems??0);d>0&&(s+=Math.min(25,5*d),i.push(`${d} spec-code drift item(s).`));!1===t.shadowDeploy?.ok?(s+=25,i.push("Latest shadow deploy is blocked.")):!0===t.shadowDeploy?.ok&&(s-=8,i.push("Latest shadow deploy passed."));const u=Math.max(0,Math.min(100,s));return{score:u,level:u>=75?"critical":u>=50?"high":u>=25?"moderate":"low",factors:i.length>0?i:["No elevated risk factors found from available ledgers."]}}(c,l),m=function(e,t,i,s){const o=Number(i.selfDefense?.confirmed??0),n=Number(i.selfDefense?.suspicious??0);return{intent:e.trim()?"pass":"needs_evidence",changeSet:t.length>0?"pass":"needs_evidence",spec:i.specCode?.summary?Number(i.specCode.summary.driftItems??0)>0?"warn":"pass":"needs_evidence",security:o>0?"fail":n>0?"warn":i.selfDefense?"pass":"needs_evidence",verification:s?s.ok?"pass":"fail":!0===i.shadowDeploy?.ok?"pass":!1===i.shadowDeploy?.ok?"fail":"needs_evidence",rollback:t.length>0?"pass":"needs_evidence"}}(e.intent,c,l,e.verificationRun),h=function(e,t){return Object.values(e).includes("fail")||"critical"===t.level?"blocked":Object.values(e).includes("needs_evidence")?"incomplete":Object.values(e).includes("warn")||"high"===t.level?"ready_with_review":"ready_to_promote"}(m,f),g=p.createHash("sha256").update(JSON.stringify({intent:e.intent,changedFiles:c.map(e=>e.file),riskLevel:f.level,gates:m})).digest("hex").slice(0,16);return{ok:!0,action:e.action,proofId:g,generatedAt:(new Date).toISOString(),verdict:h,intent:e.intent||n(l),changeSet:{gitAvailable:e.evidence.git.gitAvailable,changedFiles:c,diffStat:e.evidence.git.diffStat,recentCommit:e.evidence.git.recentCommit},touchedCapabilities:u,affectedContracts:d,riskModel:f,gates:m,verification:{executed:Boolean(e.verificationRun),run:e.verificationRun,shadowDeploy:a(l.shadowDeploy),availableScripts:e.evidence.packageScripts},rollbackPath:i(c),unresolvedAssumptions:s(e.intent,c,l,e.verificationRun),sourceLedgers:o(l),proofPath:".mesh/proof-carrying-change/proof.json"}}function t(e,t){const i=new Set(t.map(e=>e.file));return e.filter(e=>i.has(String(e.file??""))).slice(0,50)}function i(e){return{strategy:"patch-reversal",steps:["Save the generated proof bundle with the change review.","Use the current git diff as the rollback patch source.","Reverse only the listed changed files after human review if promotion fails.","Re-run the verification gate recorded in this proof before declaring rollback complete."],changedFiles:e.map(e=>e.file),requiresManualReview:e.some(e=>e.status.includes("?")||"workspace-fallback"===e.source)}}function s(e,t,i,s){const o=[];return e.trim()||o.push("No explicit intent was supplied for this proof bundle."),0===t.length&&o.push("No changed files were detected."),i.specCode||o.push("Spec-code ledger is missing; affected behavior contracts may be incomplete."),i.fluidMesh||o.push("Fluid mesh ledger is missing; touched capabilities may be incomplete."),i.selfDefense||o.push("Self-defense ledger is missing; security gate is best-effort."),s||i.shadowDeploy||o.push("No verification run or shadow deploy ledger is attached."),o}function o(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Boolean(t)]))}function n(e){return e.naturalLanguage?.source??e.naturalLanguage?.intent??"No explicit intent supplied; generated from current workspace evidence."}function a(e){return e?{ok:e.ok,verdict:e.verdict,command:e.command,gates:e.gates,timelineId:e.timelineId}:null}function r(e){return/\b(auth|session|token|secret|security)\b/i.test(e)?"auth/security boundary":/\b(runtime|local-tools|agent-loop|command|shell|timeline)\b/i.test(e)?"agent runtime or command boundary":/\b(db|sql|migration|schema|supabase|database)\b/i.test(e)?"data persistence boundary":/\bpackage(?:-lock)?\.json$|pnpm-lock|yarn\.lock\b/i.test(e)?"dependency boundary":null}async function c(e,t){try{const{stdout:i}=await y("git",t,{cwd:e,maxBuffer:1048576});return{ok:!0,stdout:i}}catch(e){return{ok:!1,stdout:String(e.stdout??"")}}}function l(e){return e.replace(/^"|"$/g,"").replace(/\\040/g," ")}function d(e,t=8e3){return e.length>t?e.slice(-t):e}import{promises as u}from"node:fs";import f from"node:path";import p from"node:crypto";import{execFile as m}from"node:child_process";import{promisify as h}from"node:util";import{parseAllowedCommand as g}from"../command-safety.js";import{clampNumber as w,collectWorkspaceFiles as v,readJson as b,writeJson as k}from"./common.js";const y=h(m);export class ProofCarryingChangeEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(t={}){const i=String(t.action??"generate").trim().toLowerCase();if("status"===i)return this.status();if(!["generate","verify"].includes(i))throw new Error("workspace.proof_carrying_change action must be generate|verify|status");const s=String(t.intent??"").trim(),o=w(t.timeoutMs,12e4,1e3,6e5),n=String(t.verificationCommand??"").trim();let a=null;if("verify"===i){if(!n)throw new Error("workspace.proof_carrying_change verify requires verificationCommand");a=await this.runVerification(n,o)}const r=e({action:i,intent:s,evidence:await this.collectEvidence(),verificationRun:a});return await k(this.ledgerPath(),r),r}async status(){return b(this.ledgerPath(),{ok:!0,action:"status",message:"No proof-carrying change bundle exists yet. Run action=generate or action=verify."})}async collectEvidence(){const e=await this.gitEvidence(),t=await this.ledgerEvidence(),i=await async function(e){const t=await u.readFile(f.join(e,"package.json"),"utf8").catch(()=>"");if(!t)return{};try{return JSON.parse(t).scripts??{}}catch{return{}}}(this.workspaceRoot);return{git:e,changedFiles:e.changedFiles.length>0?e.changedFiles:await this.workspaceFallbackFiles(e.gitAvailable),packageScripts:i,ledgers:t}}async gitEvidence(){const e=await c(this.workspaceRoot,["status","--porcelain"]),t=await c(this.workspaceRoot,["diff","--stat","HEAD"]),i=await c(this.workspaceRoot,["log","-1","--oneline"]),s=e.ok||t.ok||i.ok,o=e.stdout.split(/\r?\n/g).map(e=>e.trimEnd()).filter(Boolean).map(e=>{const t=e.slice(0,2).trim()||"modified",i=e.slice(3).trim();return{file:l(i.includes(" -> ")?i.split(" -> ").pop()??i:i),status:t,additions:0,deletions:0,source:"git"}}).filter(e=>Boolean(e.file));const n=function(e){const t=new Map;for(const i of e.split(/\r?\n/g)){const[e,s,o]=i.split(/\t/g);o&&t.set(l(o),{additions:"-"===e?0:Number(e)||0,deletions:"-"===s?0:Number(s)||0})}return t}((await c(this.workspaceRoot,["diff","--numstat","HEAD"])).stdout);return{gitAvailable:s,status:e.stdout.trim(),diffStat:t.stdout.trim(),changedFiles:o.map(e=>({...e,additions:n.get(e.file)?.additions??0,deletions:n.get(e.file)?.deletions??0})),recentCommit:i.stdout.trim()}}async workspaceFallbackFiles(e){if(e)return[];return(await v(this.workspaceRoot,{maxFiles:80})).map(e=>({file:e,status:"observed",additions:0,deletions:0,source:"workspace-fallback"}))}async ledgerEvidence(){return{selfDefense:await b(f.join(this.workspaceRoot,".mesh","security","last-self-defense.json"),null),precrime:await b(f.join(this.workspaceRoot,".mesh","precrime","predictions.json"),null),shadowDeploy:await b(f.join(this.workspaceRoot,".mesh","shadow-deploy","last-ledger.json"),null),semanticGit:await b(f.join(this.workspaceRoot,".mesh","semantic-git","last-analysis.json"),null),probabilistic:await b(f.join(this.workspaceRoot,".mesh","probabilistic","experiments.json"),null),specCode:await b(f.join(this.workspaceRoot,".mesh","spec-code","contracts.json"),null),conversations:await b(f.join(this.workspaceRoot,".mesh","conversations","symbol-memory.json"),null),fluidMesh:await b(f.join(this.workspaceRoot,".mesh","fluid-mesh","capabilities.json"),null),naturalLanguage:await b(f.join(this.workspaceRoot,".mesh","natural-language-source","last-compile.json"),null),livingSoftware:await b(f.join(this.workspaceRoot,".mesh","living-software","pulse.json"),null)}}async runVerification(e,t){const i=g(e),s=Date.now();try{const{stdout:o,stderr:n}=await y(i.command,i.args,{cwd:this.workspaceRoot,timeout:t,maxBuffer:1048576});return{command:e,ok:!0,exitCode:0,durationMs:Date.now()-s,stdout:d(o),stderr:d(n)}}catch(t){return{command:e,ok:!1,exitCode:"number"==typeof t.code?t.code:1,durationMs:Date.now()-s,stdout:d(String(t.stdout??"")),stderr:d(String(t.stderr??t.message??""))}}}ledgerPath(){return f.join(this.workspaceRoot,".mesh","proof-carrying-change","proof.json")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as t}from"node:fs";import n from"node:path";import{writeJson as s,readJson as e}from"./common.js";export class SchrodingersAstEngine{workspaceRoot;constructor(t){this.workspaceRoot=t}async run(r={}){const a=String(r.action??"superpose").trim().toLowerCase();if("status"===a){const t=".mesh/schrodingers-ast/active-states.json";return{ok:!0,action:"status",states:(await e(n.join(this.workspaceRoot,t),{states:[]})).states}}if("superpose"===a){const o=String(r.file??""),i=String(r.functionName??""),c=r.variants;if(!o||!i||!Array.isArray(c)||c.length<2)throw new Error("workspace.schrodingers_ast 'superpose' requires 'file', 'functionName', and an array of at least 2 'variants'.");const u=n.resolve(this.workspaceRoot,o),p=await t.readFile(u,"utf8").catch(()=>"");if(!p)throw new Error(`File not found or empty: ${o}`);const m=`quantum_${Date.now().toString(36)}`,l=`\n// [MESH QUANTUM ROUTER INJECTED]\n// Function: ${i}\n// Superposition: ${c.length} variants active.\nconst ${m}_metrics = { runs: 0, variants: ${JSON.stringify(c.map((t,n)=>({id:n,time:0,calls:0,errors:0})))} };\nasync function ${i}(...args) {\n const variantIndex = Math.floor(Math.random() * ${c.length});\n const start = performance.now();\n try {\n let result;\n switch(variantIndex) {\n${c.map((t,n)=>` case ${n}: result = await (async function() { ${t} })(...args); break;`).join("\n")}\n }\n const end = performance.now();\n ${m}_metrics.variants[variantIndex].time += (end - start);\n ${m}_metrics.variants[variantIndex].calls++;\n ${m}_metrics.runs++;\n // In production, this would collapse after N runs via Mesh Daemon.\n return result;\n } catch(err) {\n ${m}_metrics.variants[variantIndex].errors++;\n ${m}_metrics.runs++;\n throw err;\n }\n}\n// [END QUANTUM ROUTER]\n`,w=new RegExp(`(?:export\\s+)?(?:async\\s+)?function\\s+${i}\\s*\\([^{]*\\)\\s*\\{[\\s\\S]*?\\n\\}`,"m");let h=p;w.test(p)?h=p.replace(w,l):h+="\n"+l,await t.writeFile(u,h,"utf8");const f=".mesh/schrodingers-ast/active-states.json",d=await e(n.join(this.workspaceRoot,f),{states:[]}),g={id:m,file:o,functionName:i,variantsCount:c.length,superposedAt:(new Date).toISOString(),status:"measuring"};return d.states.push(g),await s(n.join(this.workspaceRoot,f),d),{ok:!0,action:a,status:"superposed",file:o,functionName:i,variantsCount:c.length,message:"Code successfully placed into Superposition. Quantum Router injected. Awaiting wave function collapse.",ledgerPath:f}}throw new Error("workspace.schrodingers_ast action must be superpose or status")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t,i){const s=i.split(/\r?\n/g),o=[];for(let i=0;i<s.length;i++){if(!s[i].startsWith("<<<<<<<"))continue;const a=i,r=s.findIndex((t,e)=>e>a&&t.startsWith("=======")),c=s.findIndex((t,e)=>e>a&&t.startsWith(">>>>>>>"));if(-1===r||-1===c||r>c){o.push(n(t,a,s.length-1,s.slice(a).join("\n"),"Malformed conflict marker block."));break}const l=s.slice(a+1,r).join("\n"),m=s.slice(r+1,c).join("\n");o.push(e(t,a,r,c,l,m)),i=c}return o}function e(t,e,n,i,s,o){const c=Array.from(a(s)),l=Array.from(a(o)),u=c.filter(t=>l.includes(t)),f=r(s),d=r(o),h=Boolean(s.trim()&&o.trim()),p=!s.trim()||!o.trim();let g="needs_review",v="manual",w=.35,y="Conflict needs review because semantic ownership overlaps or behavior is ambiguous.";return/<<<<<<<|=======|>>>>>>>/.test(`${s}\n${o}`)||/auth|payment|migration|delete|secret|token/i.test(t)?(g="dangerous",y="Conflict touches a high-risk file or contains nested conflict markers.",w=.05):p?(g="needs_review",y="One side deletes behavior; require human intent confirmation.",w=.2):h&&0===u.length&&c.length>0&&l.length>0&&f!==d&&(g="auto_resolvable",v="concat_distinct_symbols",w=.92,y="Both sides introduce or edit distinct symbols; preserve both and verify in a timeline."),{id:m(`${t}:${e}:${f}:${d}`),file:t,startLine:e+1,oursLines:n-e-1,theirsLines:i-n-1,oursContent:s,theirsContent:o,oursSymbols:c,theirsSymbols:l,classification:g,strategy:v,confidence:w,reason:y,startIndex:e,endIndex:i,semanticFingerprint:m(`${f}:${d}:${v}`)}}function n(t,e,n,i,s){return{id:m(`${t}:${e}:dangerous`),file:t,startLine:e+1,oursLines:i.split(/\r?\n/g).length,theirsLines:0,oursContent:i,theirsContent:"",oursSymbols:Array.from(a(i)),theirsSymbols:[],classification:"dangerous",strategy:"manual",confidence:0,reason:s,startIndex:e,endIndex:n,semanticFingerprint:m(i)}}function i(t,e){const n=new Map;for(const t of e.filter(t=>"auto_resolvable"===t.classification)){const e=n.get(t.file)??[];e.push(t),n.set(t.file,e)}const i=[];for(const[e,o]of n.entries()){const n=(t.get(e)??"").split(/\r?\n/g),a=[];for(const t of o.sort((t,e)=>e.startIndex-t.startIndex)){const e=s(t);n.splice(t.startIndex,t.endIndex-t.startIndex+1,...e.split(/\r?\n/g)),a.push(t.id)}const r=n.join("\n");i.push({file:e,content:r,hunkIds:a,diffPreview:[`--- a/${e}`,`+++ b/${e}`,`@@ semantic merge ${a.join(",")}`,...o.flatMap(t=>s(t).split(/\r?\n/g).slice(0,20).map(t=>`+${t}`))].join("\n")})}return i}function s(t){return"concat_distinct_symbols"===t.strategy?[t.oursContent.trimEnd(),t.theirsContent.trimEnd()].filter(Boolean).join("\n"):"take_ours"===t.strategy?t.oursContent:"take_theirs"===t.strategy?t.theirsContent:[t.oursContent,t.theirsContent].filter(Boolean).join("\n")}function o(t){const{startIndex:e,endIndex:n,...i}=t;return i}function a(t){const e=new Set,n=/\b(?:export\s+)?(?:async\s+)?(?:function|class|const|let|var|interface|type)\s+([A-Za-z_$][\w$]*)/g;for(const i of t.matchAll(n))e.add(i[1]);return e}function r(t){const e=t.replace(/\/\/.*$/gm,"").replace(/\s+/g," ").trim();return d.createHash("sha256").update(e).digest("hex").slice(0,16)}function c(t,e){const n=f.resolve(t,e),i=f.relative(f.resolve(t),n);if(i.startsWith("..")||f.isAbsolute(i))throw new Error(`Path escapes workspace: ${e}`);return n}function l(t){const e=Number(t);return Number.isFinite(e)?Math.max(5e3,Math.min(6e5,Math.trunc(e))):6e4}function m(t){return d.createHash("sha256").update(t).digest("hex").slice(0,12)}import{promises as u}from"node:fs";import f from"node:path";import d from"node:crypto";import{runCritic as h}from"../agents/critic.js";import{appendJsonl as p,collectWorkspaceFiles as g,readJson as v,writeJson as w}from"./common.js";export class SemanticGitEngine{workspaceRoot;timelines;constructor(t,e){this.workspaceRoot=t,this.timelines=e}async run(t={}){switch(String(t.action??"analyze").trim().toLowerCase()){case"analyze":return this.analyze(t);case"plan":return this.plan(t);case"resolve":return this.resolve(t);case"verify":return this.verify(t);case"status":return this.status();default:throw new Error("workspace.semantic_git action must be analyze|plan|resolve|verify|status")}}async analyze(t){const{conflicts:e}=await this.loadConflicts(t),n=function(t){return{schemaVersion:2,generatedAt:(new Date).toISOString(),conflicts:t.map(o),autoResolvable:t.filter(t=>"auto_resolvable"===t.classification).length,needsReview:t.filter(t=>"needs_review"===t.classification).length,dangerous:t.filter(t=>"dangerous"===t.classification).length,semanticMergeReady:t.length>0&&t.every(t=>"auto_resolvable"===t.classification)}}(e);return await this.writeLedger(n),await this.appendEvent("analyze",{conflicts:e.length,autoResolvable:n.autoResolvable}),{ok:!0,action:"analyze",...n,ledgerPath:".mesh/semantic-git/last-analysis.json"}}async plan(t){const e=await this.loadConflicts(t),n=i(e.rawByFile,e.conflicts),s={ok:!0,action:"plan",conflicts:e.conflicts.map(o),patches:n,canAutoResolve:e.conflicts.length>0&&e.conflicts.every(t=>"auto_resolvable"===t.classification),manualReview:e.conflicts.filter(t=>"auto_resolvable"!==t.classification).map(o),ledgerPath:".mesh/semantic-git/last-plan.json"};return await w(f.join(this.workspaceRoot,".mesh","semantic-git","last-plan.json"),s),s}async resolve(t){if(!this.timelines)throw new Error("TimelineManager is required for resolve action");const e=await this.loadConflicts(t),n=e.conflicts.filter(t=>"auto_resolvable"===t.classification);if(0===n.length)return{ok:!1,action:"resolve",reason:"No auto-resolvable conflicts found.",ledgerPath:".mesh/semantic-git/last-analysis.json"};const s=i(e.rawByFile,n),o=await this.timelines.create({name:`semantic-merge-${Date.now().toString(36)}`});for(const t of s){const e=f.join(o.timeline.root,t.file);await u.mkdir(f.dirname(e),{recursive:!0}),await u.writeFile(e,t.content,"utf8")}const a=String(t.verificationCommand??await async function(t){const e=await u.readFile(f.join(t,"package.json"),"utf8").catch(()=>"");if(!e)return"";try{const t=JSON.parse(e);if(t.scripts?.typecheck)return"npm run typecheck";if(t.scripts?.test)return"npm test";if(t.scripts?.build)return"npm run build"}catch{return""}return""}(this.workspaceRoot)).trim(),r=a?await this.timelines.run({timelineId:o.timeline.id,command:a,timeoutMs:l(t.timeoutMs)}):null,c=s.map(t=>t.diffPreview).join("\n"),m=h({diffPreview:c,verificationOk:!0===r?.ok}),d=!0===t.promote&&!0===r?.ok&&m.ok&&n.length===e.conflicts.length?await this.timelines.promote({timelineId:o.timeline.id}):null,p={ok:!0===r?.ok&&m.ok,action:"resolve",timelineId:o.timeline.id,resolvedCount:n.length,remainingReview:e.conflicts.length-n.length,verification:r?{command:a,verdict:r.ok?"pass":"fail",exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:{verdict:"not_run",reason:"No verification command inferred or provided."},critic:m,promoted:Boolean(d&&!1!==d.ok),promotion:d,patches:s.map(({content:t,...e})=>e),ledgerPath:".mesh/semantic-git/last-resolution.json"};return await w(f.join(this.workspaceRoot,".mesh","semantic-git","last-resolution.json"),p),await this.appendEvent("resolve",{timelineId:o.timeline.id,resolvedCount:n.length,promoted:p.promoted}),p}async verify(t){const e=await this.analyze(t),n=e.conflicts??[],i=n.some(t=>"dangerous"===t.classification)?"block":n.some(t=>"needs_review"===t.classification)?"review":"pass";return{...e,action:"verify",gate:i,ok:"block"!==i,recommendation:"pass"===i?"All conflicts are semantic auto-resolve candidates. Run action=resolve in a timeline.":"review"===i?"At least one conflict touches overlapping behavior; require manual review.":"Dangerous conflict marker state detected; block promotion."}}async status(){return v(f.join(this.workspaceRoot,".mesh","semantic-git","last-analysis.json"),{ok:!0,action:"status",message:"No semantic-git analysis exists yet. Run action=analyze."})}async loadConflicts(e){const n="string"==typeof e.path&&e.path.trim()?[(i=e.path,i.trim().replace(/\\/g,"/").replace(/^\/+/,""))]:await g(this.workspaceRoot,{maxFiles:2e3});var i;const s=[],o=new Map;for(const e of n){const n=await u.readFile(c(this.workspaceRoot,e),"utf8").catch(()=>"");n.includes("<<<<<<<")&&(o.set(e,n),s.push(...t(e,n)))}return s.sort((t,e)=>t.file.localeCompare(e.file)||t.startLine-e.startLine),{conflicts:s,rawByFile:o}}async writeLedger(t){await w(f.join(this.workspaceRoot,".mesh","semantic-git","last-analysis.json"),t)}async appendEvent(t,e){await p(f.join(this.workspaceRoot,".mesh","semantic-git","events.jsonl"),{at:(new Date).toISOString(),kind:t,data:e})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t,n){const s=new Set;for(const t of n.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:abstract\s+)?(?:function\s*\*?\s*|class\s+|const\s+|let\s+|var\s+|type\s+|interface\s+|enum\s+)([A-Za-z_$][\w$]*)/g))s.add(t[1]);for(const t of n.matchAll(/\bexport\s*\{([^}]+)\}/g))for(const e of t[1].split(",")){const t=e.split(/\s+as\s+/).pop()?.trim();t&&/^[A-Za-z_$][\w$]*$/.test(t)&&s.add(t)}/\bexport\s+default\b/.test(n)&&s.add("default");const r=Array.from(s).sort(),i=n.match(/^\/\*\*([\s\S]*?)\*\//m),o=i?i[1].replace(/\s*\*\s?/g," ").replace(/\s+/g," ").trim().slice(0,200):"",c=a.basename(t,a.extname(t)),l=o||function(t){return t.replace(/([A-Z])/g," $1").replace(/[-_.]/g," ").toLowerCase().replace(/\s+/g," ").trim()}(c),f=[];/\basync\b.*\bfunction\b|\bawait\b|\bPromise[.<]/.test(n)&&f.push("async"),/(?:app|router)\.(get|post|put|delete|patch|use)\s*\(|@(?:Get|Post|Put|Delete|Patch)\b|Route\b|Controller\b/.test(n)&&f.push("http-handler"),/\bEventEmitter\b|\.on\s*\(|\.emit\s*\(|\.addEventListener\b/.test(n)&&f.push("event-driven"),/static\s+(?:readonly\s+)?instance\b|private\s+static\b.*\binstance\b|getInstance\s*\(\)/.test(n)&&f.push("singleton"),/\bReadable\b|\bWritable\b|\bTransform\b|\bStream\b|\.pipe\s*\(/.test(n)&&f.push("streaming"),/\bprocess\.env\b|dotenv|loadConfig\b|AppConfig\b|getConfig\b/.test(n)&&f.push("configuration"),/\bprisma\b|\bknex\b|\bsequelize\b|\bmongoose\b|\.query\s*\(|SELECT\s+\w|INSERT\s+INTO/.test(n)&&f.push("database"),/\bfs\b.*\breadFile\b|\breadFileSync\b|\bwriteFile\b|\bmkdir\b/.test(n)&&f.push("filesystem"),/\bworker_threads\b|\bnew Worker\b|\bWorkerThread\b/.test(n)&&f.push("worker"),/\bsetInterval\b|\bsetTimeout\b|\bDebounce\b|\bThrottle\b|\bcron\b/i.test(n)&&f.push("scheduled");const h=new Set;for(const t of n.matchAll(/(?:function|class|const|let|var|interface|type)\s+([A-Z][a-zA-Z]{3,})/g))for(const n of e(t[1]))h.add(n);const d=new Set;for(const t of n.matchAll(/from\s+["']([^"']+)["']/g)){const e=t[1];e.startsWith(".")?d.add(a.basename(e,a.extname(e))):d.add(e.split("/")[0].replace(/^@[^/]+\//,""))}return{exports:r,purpose:l,behavioralPatterns:f,invariantKeywords:Array.from(h).slice(0,30).sort(),importedConcepts:Array.from(d).sort(),lineCount:n.split("\n").length}}function e(t){return t.replace(/([A-Z])/g," $1").toLowerCase().trim().split(/\s+/).filter(t=>t.length>=3)}function n(t){const e=JSON.stringify({exports:t.exports,purpose:t.purpose,behavioralPatterns:[...t.behavioralPatterns].sort()});return o.createHash("sha1").update(e).digest("hex").slice(0,16)}function s(t,e,n,s){const i=new Set(e.semanticSignature.exports),a=new Set(n.exports),o=n.exports.filter(t=>!i.has(t)),c=e.semanticSignature.exports.filter(t=>!a.has(t)),l=e.semanticSignature.purpose!==n.purpose,f=r(e.semanticSignature.behavioralPatterns)!==r(n.behavioralPatterns),h=new Set(e.semanticSignature.invariantKeywords),d=new Set(n.invariantKeywords),u=[...e.semanticSignature.invariantKeywords.filter(t=>!d.has(t)).map(t=>`-${t}`),...n.invariantKeywords.filter(t=>!h.has(t)).map(t=>`+${t}`)].slice(0,12);return{file:t,severity:e.locked&&(c.length>0||l||f)?"critical":c.length>0||f?"high":"medium",oldFingerprint:e.fingerprint,newFingerprint:s,changes:{addedExports:o,removedExports:c,purposeShift:l,behavioralShift:f,invariantShift:u}}}function r(t){return[...t].sort().join(",")}import{promises as i}from"node:fs";import a from"node:path";import o from"node:crypto";import{exec as c}from"node:child_process";import{promisify as l}from"node:util";import{collectWorkspaceFiles as f,readJson as h,writeJson as d}from"./common.js";const u=l(c);export class SemanticSheriffEngine{workspaceRoot;indexPath;driftPath;constructor(t){this.workspaceRoot=t,this.indexPath=a.join(t,".mesh","semantic-contracts","index.json"),this.driftPath=a.join(t,".mesh","semantic-contracts","drift.json")}async run(t={}){switch(String(t.action??"verify").trim().toLowerCase()){case"scan":return this.scan(t);case"verify":return this.verify(t);case"lock":return this.lock(t);case"unlock":return this.unlock(t);case"drift":return this.getDrift();case"status":return this.status();case"clear":return this.clear();default:throw new Error("workspace.semantic_sheriff action must be scan|verify|lock|unlock|drift|status|clear")}}async scan(e){const s=Math.min(Number(e.maxFiles??400),2e3),r=await f(this.workspaceRoot,{maxFiles:s}),o=await h(this.indexPath,{});let c=0,l=0;for(const e of r){const s=a.join(this.workspaceRoot,e),r=await i.readFile(s,"utf8").catch(()=>"");if(!r.trim())continue;const f=t(e,r),h=n(f),d=o[e];d&&d.fingerprint===h||(o[e]={file:e,fingerprint:h,lockedAt:d?.locked?d.lockedAt:(new Date).toISOString(),locked:d?.locked??!1,semanticSignature:f},l++),c++}return await d(this.indexPath,o),{ok:!0,action:"scan",generatedAt:(new Date).toISOString(),scanned:c,updated:l,totalContracts:Object.keys(o).length,path:".mesh/semantic-contracts/index.json",message:`Scanned ${c} files, updated ${l} contracts.`}}async verify(e){const r=await h(this.indexPath,{});if(0===Object.keys(r).length)return o="No contracts found. Run action=scan first.",{ok:!0,action:"verify",generatedAt:(new Date).toISOString(),contracts:0,lockedContracts:0,driftAlerts:[],summary:o,path:".mesh/semantic-contracts/drift.json"};var o;const c=Boolean(e.force),l=String(e.file??"").trim();let f;if(l)f=[l].filter(t=>r[t]);else if(c)f=Object.keys(r);else{const t=await this.changedFiles();f=t.length>0?t.filter(t=>r[t]):Object.keys(r).slice(0,150)}const u=[];for(const e of f){const o=r[e];if(!o)continue;const c=a.join(this.workspaceRoot,e),l=await i.readFile(c,"utf8").catch(()=>null);if(null===l)continue;const f=t(e,l),h=n(f);if(h===o.fingerprint)continue;const d=s(e,o,f,h);u.push(d),o.locked||(r[e]={...o,fingerprint:h,semanticSignature:f})}await d(this.indexPath,r);const p=u.filter(t=>"critical"===t.severity).length,m=u.filter(t=>"high"===t.severity).length,b={ok:!0,action:"verify",generatedAt:(new Date).toISOString(),contracts:Object.keys(r).length,lockedContracts:Object.values(r).filter(t=>t.locked).length,driftAlerts:u,summary:0===u.length?`No semantic drift detected across ${f.length} checked file(s).`:`SEMANTIC DRIFT: ${u.length} file(s) drifted (${p} critical, ${m} high).`,path:".mesh/semantic-contracts/drift.json"};return u.length>0&&await d(this.driftPath,b),b}async lock(t){const e=String(t.file??"").trim();if(!e)throw new Error("lock requires file");const n=await h(this.indexPath,{});return n[e]?(n[e]={...n[e],locked:!0,lockedAt:(new Date).toISOString()},await d(this.indexPath,n),{ok:!0,action:"lock",file:e,fingerprint:n[e].fingerprint,lockedAt:n[e].lockedAt,message:`${e} is now locked. Any semantic drift will be flagged as critical.`}):{ok:!1,reason:`No contract for ${e}. Run action=scan first.`}}async unlock(t){const e=String(t.file??"").trim();if(!e)throw new Error("unlock requires file");const n=await h(this.indexPath,{});return n[e]?(n[e]={...n[e],locked:!1},await d(this.indexPath,n),{ok:!0,action:"unlock",file:e}):{ok:!1,reason:`No contract for ${e}.`}}async getDrift(){return h(this.driftPath,{ok:!0,action:"drift",message:"No drift report found. Run action=verify to check for semantic drift."})}async status(){const t=await h(this.indexPath,{}),e=Object.keys(t).length,n=Object.values(t).filter(t=>t.locked).length;return{ok:!0,action:"status",totalContracts:e,lockedContracts:n,hasContracts:e>0,path:".mesh/semantic-contracts/index.json",message:e>0?`${e} contracts tracked (${n} locked). Run action=verify to check for drift.`:"No contracts yet. Run action=scan to fingerprint your codebase."}}async clear(){return await i.unlink(this.indexPath).catch(()=>{}),await i.unlink(this.driftPath).catch(()=>{}),{ok:!0,action:"clear",message:"All semantic contracts cleared."}}async changedFiles(){try{const{stdout:t}=await u("git diff HEAD --name-only",{cwd:this.workspaceRoot});return t.trim().split("\n").filter(Boolean)}catch{return[]}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t){const e=Math.floor(t/6e4);if(e<60)return`${e}m`;const s=Math.floor(e/60);if(s<24)return`${s}h ${e%60}m`;return`${Math.floor(s/24)}d ${s%24}h`}function e(t){return Array.isArray(t)?t.map(String).filter(Boolean):"string"==typeof t&&t.trim()?t.split(/[,\n]/).map(t=>t.trim()).filter(Boolean):[]}import{promises as s}from"node:fs";import n from"node:path";import{exec as o}from"node:child_process";import{promisify as r}from"node:util";import i from"node:crypto";import{appendJsonl as a,readJson as c,writeJson as u}from"./common.js";const h=r(o);export class SessionResurrectionEngine{workspaceRoot;latestPath;logPath;constructor(t){this.workspaceRoot=t,this.latestPath=n.join(t,".mesh","session-resurrection","latest.json"),this.logPath=n.join(t,".mesh","session-resurrection","sessions.jsonl")}async run(t={}){switch(String(t.action??"resurrect").trim().toLowerCase()){case"capture":return this.capture(t);case"resurrect":return this.resurrect();case"checkpoint":return this.checkpoint(t);case"clear":return this.clear();case"status":return this.status();default:throw new Error("workspace.session_resurrection action must be capture|resurrect|checkpoint|status|clear")}}async capture(t){const s=String(t.intent??"").trim();if(!s)throw new Error("capture requires intent");const n=await c(this.latestPath,null),o=n?.sessionId??i.randomBytes(6).toString("hex"),r=await this.gitSummary(),h={sessionId:o,capturedAt:(new Date).toISOString(),intent:s,filesInFocus:e(t.filesInFocus),openQuestions:e(t.openQuestions),failedApproaches:(p=t.failedApproaches,Array.isArray(p)?p.map(t=>t&&"object"==typeof t?{approach:String(t.approach??""),reason:String(t.reason??"")}:{approach:String(t),reason:""}).filter(t=>t.approach):[]),insights:e(t.insights),nextActions:e(t.nextActions),note:String(t.note??"").trim(),gitSummary:r,checkpoints:n?.checkpoints??[]};var p;return await u(this.latestPath,h),await a(this.logPath,{sessionId:h.sessionId,capturedAt:h.capturedAt,intent:h.intent,checkpointCount:h.checkpoints.length}),{ok:!0,action:"capture",sessionId:h.sessionId,capturedAt:h.capturedAt,path:".mesh/session-resurrection/latest.json",message:"Session state captured. Run action=resurrect in any future session to restore full context."}}async resurrect(){const e=await c(this.latestPath,null);if(!e)return{ok:!0,action:"resurrect",exists:!1,message:"No previous session found. Work on something and use action=capture to save your state."};const s=Date.now()-new Date(e.capturedAt).getTime(),n=function(t,e){const s=["╔══ SESSION RESURRECTION ═══════════════════════════════",`║ Captured ${e} ago [${t.sessionId}]`,"║",`║ INTENT: ${t.intent}`];if(t.filesInFocus.length>0){s.push("║","║ FILES IN FOCUS:");for(const e of t.filesInFocus)s.push(`║ • ${e}`)}if(t.openQuestions.length>0){s.push("║","║ OPEN QUESTIONS (still unresolved):");for(const e of t.openQuestions)s.push(`║ ? ${e}`)}if(t.failedApproaches.length>0){s.push("║","║ FAILED APPROACHES (do not retry):");for(const e of t.failedApproaches)s.push(`║ ✗ ${e.approach}${e.reason?` — ${e.reason}`:""}`)}if(t.insights.length>0){s.push("║","║ INSIGHTS DISCOVERED:");for(const e of t.insights)s.push(`║ ★ ${e}`)}if(t.nextActions.length>0&&(s.push("║","║ NEXT ACTIONS (pick the highest-leverage one):"),t.nextActions.forEach((t,e)=>s.push(`║ ${e+1}. ${t}`))),t.checkpoints.length>0){const e=t.checkpoints[t.checkpoints.length-1];s.push("║",`║ LAST CHECKPOINT: ${e.note}`),s.push(`║ at ${e.at}`)}return t.note&&s.push("║",`║ NOTE: ${t.note}`),t.gitSummary&&"clean"!==t.gitSummary&&"unknown"!==t.gitSummary&&s.push("║",`║ GIT STATE AT CAPTURE: ${t.gitSummary}`),s.push("╚════════════════════════════════════════════════════"),s.join("\n")}(e,t(s));return{ok:!0,action:"resurrect",sessionId:e.sessionId,capturedAt:e.capturedAt,age:t(s),brief:n,snapshot:e,path:".mesh/session-resurrection/latest.json"}}async checkpoint(t){const e=String(t.note??"").trim();if(!e)throw new Error("checkpoint requires note");const s=await c(this.latestPath,null);if(!s)return{ok:!1,reason:"No active session. Run action=capture first."};const n=[...s.checkpoints,{at:(new Date).toISOString(),note:e}].slice(-20);return await u(this.latestPath,{...s,checkpoints:n}),{ok:!0,action:"checkpoint",note:e,totalCheckpoints:n.length}}async clear(){return await s.unlink(this.latestPath).catch(()=>{}),{ok:!0,action:"clear",message:"Session resurrection state cleared."}}async status(){const e=await c(this.latestPath,null);if(!e)return{ok:!0,action:"status",exists:!1,message:"No captured session."};const s=Date.now()-new Date(e.capturedAt).getTime();return{ok:!0,action:"status",exists:!0,sessionId:e.sessionId,capturedAt:e.capturedAt,age:t(s),intent:e.intent,openQuestionsCount:e.openQuestions.length,nextActionsCount:e.nextActions.length,checkpointsCount:e.checkpoints.length,path:".mesh/session-resurrection/latest.json"}}async gitSummary(){try{const{stdout:t}=await h("git status --short",{cwd:this.workspaceRoot}),e=t.trim().split("\n").filter(Boolean).slice(0,8);return e.length>0?e.join(", "):"clean"}catch{return"unknown"}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:path";import{assertCommandAllowed as t}from"../command-safety.js";import{readJson as o,writeJson as s}from"./common.js";export class ShadowDeployEngine{workspaceRoot;timelines;constructor(e,t){this.workspaceRoot=e,this.timelines=t}async run(i={}){const n=String(i.action??"shadow").trim().toLowerCase();if("status"===n)return this.status();if("shadow"!==n)throw new Error("workspace.end_staging action must be shadow|status");const a=String(i.command??i.verificationCommand??"npm test").trim();t(a);const r=await this.timelines.create({name:`shadow-deploy-${Date.now().toString(36)}`}),d=await this.timelines.run({timelineId:r.timeline.id,command:a,timeoutMs:"number"==typeof i.timeoutMs?i.timeoutMs:18e4}),m=await this.timelines.compare({timelineIds:[r.timeline.id]}),l=await o(e.join(this.workspaceRoot,".mesh","production-signals.json"),{signals:[]}),c={ok:d.ok,action:n,timelineId:r.timeline.id,command:a,exitCode:d.exitCode,verdict:d.ok?"ready_for_review":"blocked",changedFiles:m.comparisons[0]?.changedFiles??[],changedLineCount:m.comparisons[0]?.changedLineCount??0,telemetrySignalsChecked:l.signals?.length??0,gates:{verification:d.ok?"pass":"fail",telemetry:(l.signals?.length??0)>0?"checked":"no_signals",promotion:d.ok?"manual_review_required":"blocked"},stdout:d.stdout,stderr:d.stderr,ledgerPath:".mesh/shadow-deploy/last-ledger.json"};return await s(e.join(this.workspaceRoot,".mesh","shadow-deploy","last-ledger.json"),c),c}async status(){return o(e.join(this.workspaceRoot,".mesh","shadow-deploy","last-ledger.json"),{ok:!0,action:"status",message:"No shadow deploy ledger exists yet. Run action=shadow."})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e,n,s){const r=[],i=/\b(?:app|router|server)\.(get|post|put|patch|delete|all)\(\s*(["'`])([^"'`]+)\2/g;for(const a of n.matchAll(i)){const i=a[1].toUpperCase(),c=a[3];r.push(t({file:e,line:u(n,a.index??0),kind:"route",source:"code",subject:`${i} ${c}`,behavior:`Expose ${i} ${c} and preserve its response contract.`,evidence:a[0],now:s,locked:!1,tests:[],implementationStatus:"implemented"}))}const a=/\bexport\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)(?:\s*:\s*([^{\n]+))?/g;for(const i of n.matchAll(a)){const a=i[1];r.push(t({file:e,line:u(n,i.index??0),kind:"exported-function",source:"code",subject:a,behavior:`Function ${a} accepts (${i[2].trim()})${i[3]?` and returns ${i[3].trim()}`:""}; behavior must remain equivalent for documented inputs.`,evidence:i[0],now:s,locked:!1,tests:[],implementationStatus:"implemented"}))}const c=/\b(?:test|it)\(\s*(["'`])([^"'`]+)\1/g;for(const i of n.matchAll(c))r.push(t({file:e,line:u(n,i.index??0),kind:"test",source:"test",subject:i[2],behavior:`Preserve tested behavior: ${i[2]}.`,evidence:i[0],now:s,locked:!1,tests:[i[2]],implementationStatus:"implemented"}));return r}function t(e){const t=function(e,t){const n=`${e}\n${t}`.toLowerCase(),s=[];/auth|session|token|jwt/.test(n)&&s.push("auth-boundary");/throw|error|reject|invalid/.test(n)&&s.push("error-contract");/route|http|get|post|put|patch|delete/.test(n)&&s.push("http-contract");/deterministic|same input|equivalent/.test(n)&&s.push("determinism");/database|sql|query|persist/.test(n)&&s.push("persistence-contract");return Array.from(new Set(s))}(e.behavior,e.evidence),n=(s={kind:e.kind,subject:e.subject,behavior:e.behavior,invariants:t},d.createHash("sha256").update(JSON.stringify(s)).digest("hex").slice(0,16));var s;return{id:i(`${e.file}:${e.kind}:${e.subject}`),version:1,file:e.file,line:e.line,kind:e.kind,source:e.source,subject:e.subject,behavior:e.behavior,evidence:e.evidence,fingerprint:n,locked:e.locked,firstSeenAt:e.now,lastSeenAt:e.now,invariants:t,tests:e.tests,implementationStatus:e.implementationStatus}}function n(e,t,n){const s=t.find(t=>t.subject===e.subject||t.id===e.id);if(!s)return{...e,lastSeenAt:n,implementationStatus:"missing"};const r=e.invariants.some(e=>!s.invariants.includes(e))&&e.invariants.length>0;return{...e,file:e.file||s.file,line:e.line||s.line,lastSeenAt:n,tests:s.tests,implementationStatus:r?"drifted":"implemented"}}function s(e){return e.split(/[^A-Za-z0-9_$]+/).filter(Boolean)}function r(e,t,n){return{routes:e.filter(e=>"route"===e.kind).length,exportedFunctions:e.filter(e=>"exported-function"===e.kind).length,tests:e.filter(e=>"test"===e.kind).length,declaredSpecs:t.length,missingImplementations:t.filter(e=>"implemented"!==e.implementationStatus).length,locked:[...e,...t].filter(e=>e.locked).length,driftItems:n.length,blockingDrift:n.filter(e=>"block"===e.gate).length}}function i(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,140)}function a(e){return"critical"===e?4:"high"===e?3:"medium"===e?2:1}import{promises as c}from"node:fs";import o from"node:path";import d from"node:crypto";import{appendJsonl as l,collectWorkspaceFiles as p,lineNumberAt as u,readJson as h,writeJson as m}from"./common.js";export class SpecCodeEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(e={}){switch(String(e.action??"synthesize").trim().toLowerCase()){case"synthesize":return this.synthesize("synthesize");case"check":return this.synthesize("check");case"assert":return this.assertSpec(e);case"lock":return this.setLock(e,!0);case"unlock":return this.setLock(e,!1);case"materialize":return this.materialize(e);case"status":return this.status();default:throw new Error("workspace.spec_code action must be synthesize|check|assert|lock|unlock|materialize|status")}}async synthesize(e){const t=await this.readLedger(),s=(new Date).toISOString(),i=await this.extractWorkspaceContracts(s),c=function(e,t,n){const s=new Map(e.map(e=>[e.id,e]));return t.map(e=>{const t=s.get(e.id);return t?{...e,version:t.fingerprint===e.fingerprint?t.version:t.version+1,locked:t.locked,firstSeenAt:t.firstSeenAt,lastSeenAt:n}:e}).sort((e,t)=>e.file.localeCompare(t.file)||e.subject.localeCompare(t.subject))}(t.contracts,i,s),o=t.declaredSpecs.map(e=>n(e,c,s)),d="check"===e?function(e,t,n){const s=new Map(t.map(e=>[e.id,e])),r=new Map(e.map(e=>[e.id,e])),i=[];for(const t of e){const e=s.get(t.id);e?t.fingerprint!==e.fingerprint&&i.push({id:e.id,severity:t.locked?"critical":"high",kind:"behavior-changed",contract:e,previous:t,current:e,reason:`${e.subject} changed semantic fingerprint from ${t.fingerprint} to ${e.fingerprint}.`,gate:t.locked?"block":"warn"}):i.push({id:t.id,severity:t.locked?"critical":"medium",kind:"removed-behavior",contract:t,previous:t,reason:`${t.subject} existed in the previous contract ledger and is now absent.`,gate:t.locked?"block":"warn"})}for(const e of t)r.has(e.id)||i.push({id:e.id,severity:"low",kind:"new-behavior",contract:e,current:e,reason:`${e.subject} is new behavior and should be accepted into spec if intentional.`,gate:"warn"}),"test"!==e.kind&&0===e.tests.length&&i.push({id:`${e.id}:coverage`,severity:e.locked?"high":"medium",kind:"test-coverage-missing",contract:e,current:e,reason:`${e.subject} has no obvious adjacent test contract.`,gate:e.locked?"block":"warn"});for(const e of n)"implemented"!==e.implementationStatus&&i.push({id:`${e.id}:implementation`,severity:e.locked?"critical":"high",kind:"missing-implementation",contract:e,reason:`${e.subject} is declared in spec but not implemented by code-derived contracts.`,gate:e.locked?"block":"warn"});return i.sort((e,t)=>a(t.severity)-a(e.severity))}(t.contracts,c,o):[],l={schemaVersion:2,generatedAt:s,contracts:c,declaredSpecs:o,lastDrift:d};return await this.writeLedger(l),await this.writeSpecMarkdown(l),{ok:!0,action:e,generatedAt:s,contracts:c,declaredSpecs:o,drift:d,gate:d.some(e=>"block"===e.gate)?"block":d.some(e=>"warn"===e.gate)?"warn":"pass",summary:r(c,o,d),ledgerPath:".mesh/spec-code/contracts.json",specPath:".mesh/spec-code/SPEC.md",eventLogPath:".mesh/spec-code/events.jsonl"}}async assertSpec(e){const s=String(e.subject??"").trim(),r=String(e.behavior??"").trim();if(!s||!r)throw new Error("workspace.spec_code assert requires subject and behavior");const i=(a=String(e.file??function(e){return`src/${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"declared-spec"}.ts`}(s)),a.trim().replace(/\\/g,"/").replace(/^\/+/,""));var a;const c=(new Date).toISOString(),o=await this.readLedger(),d=o.declaredSpecs.find(e=>e.subject===s&&e.file===i),l=t({file:i,line:1,kind:"declared-spec",source:"human-spec",subject:s,behavior:r,evidence:r,now:c,locked:!0,tests:[],implementationStatus:"missing"});return d&&(l.version=d.version+(d.fingerprint===l.fingerprint?0:1),l.firstSeenAt=d.firstSeenAt,l.locked=d.locked),o.declaredSpecs=[...o.declaredSpecs.filter(e=>!(e.subject===s&&e.file===i)),n(l,o.contracts,c)].sort((e,t)=>e.subject.localeCompare(t.subject)),o.generatedAt=c,await this.writeLedger(o),await this.appendEvent("assert",{subject:s,file:i,behavior:r}),{ok:!0,action:"assert",contract:o.declaredSpecs.find(e=>e.subject===s&&e.file===i),ledgerPath:".mesh/spec-code/contracts.json"}}async setLock(e,t){const n=String(e.id??"").trim(),s=String(e.subject??"").trim();if(!n&&!s)throw new Error(`workspace.spec_code ${t?"lock":"unlock"} requires id or subject`);const r=await this.readLedger();let i=0;const a=e=>n&&e.id===n||s&&e.subject===s?(i+=1,{...e,locked:t}):e;return r.contracts=r.contracts.map(a),r.declaredSpecs=r.declaredSpecs.map(a),r.generatedAt=(new Date).toISOString(),await this.writeLedger(r),await this.appendEvent(t?"lock":"unlock",{id:n,subject:s,changed:i}),{ok:!0,action:t?"lock":"unlock",changed:i,ledgerPath:".mesh/spec-code/contracts.json"}}async materialize(e){const t=await this.readLedger(),n=String(e.subject??"").trim(),s=t.declaredSpecs.filter(e=>n?e.subject===n||e.id===n:"implemented"!==e.implementationStatus).map(e=>function(e){if("implemented"===e.implementationStatus)return null;const t=e.subject.replace(/[^A-Za-z0-9_$]/g,"");if(!t)return null;const n=e.file||`src/${t}.ts`,s=[`export function ${t}(...args: unknown[]): unknown {`,` throw new Error(${JSON.stringify(`Spec '${e.subject}' is declared but not implemented yet.`)});`,"}",""].join("\n");return{contractId:e.id,file:n,subject:e.subject,behavior:e.behavior,patch:[`diff --git a/${n} b/${n}`,"new file mode 100644","--- /dev/null",`+++ b/${n}`,"@@ -0,0 +1,4 @@",...s.split("\n").filter(Boolean).map(e=>`+${e}`),""].join("\n"),verification:"Apply in a timeline, implement behavior, then run workspace.spec_code check and project tests."}}(e)).filter(Boolean),r={ok:!0,action:"materialize",patches:s,applyMode:"manual",note:"Materialization emits reviewable patch plans. Apply through a timeline and run workspace.spec_code check before promotion.",ledgerPath:".mesh/spec-code/contracts.json"};return await m(o.join(this.workspaceRoot,".mesh","spec-code","materialization-plan.json"),r),await this.appendEvent("materialize",{subject:n,patchCount:s.length}),r}async status(){const e=await this.readLedger();return{ok:!0,action:"status",generatedAt:e.generatedAt,contracts:e.contracts,declaredSpecs:e.declaredSpecs,drift:e.lastDrift,summary:r(e.contracts,e.declaredSpecs,e.lastDrift),ledgerPath:".mesh/spec-code/contracts.json"}}async extractWorkspaceContracts(t){const n=await p(this.workspaceRoot,{maxFiles:2e3}),r=new Map,i=[];for(const a of n){const n=await c.readFile(o.join(this.workspaceRoot,a),"utf8").catch(()=>"");if(!n)continue;const d=e(a,n,t);for(const e of d){if("test"===e.kind)for(const t of s(e.subject)){const n=r.get(t)??[];n.push(e.subject),r.set(t,n)}i.push(e)}}return i.map(e=>({...e,tests:"test"===e.kind?e.tests:r.get(e.subject)??[],implementationStatus:"implemented"}))}async readLedger(){const e=await h(this.ledgerPath(),{});return{schemaVersion:2,generatedAt:e.generatedAt??new Date(0).toISOString(),contracts:Array.isArray(e.contracts)?e.contracts:[],declaredSpecs:Array.isArray(e.declaredSpecs)?e.declaredSpecs:[],lastDrift:Array.isArray(e.lastDrift)?e.lastDrift:[]}}async writeLedger(e){await m(this.ledgerPath(),e)}async writeSpecMarkdown(e){const t=["# Mesh Generated Behavior Spec","",`Generated: ${e.generatedAt}`,"","## Declared Specs",...e.declaredSpecs.map(e=>`- [${e.implementationStatus}] ${e.subject} (${e.file}) - ${e.behavior}`),"","## Code-Derived Contracts",...e.contracts.map(e=>`- ${e.kind}: ${e.subject} (${e.file}:${e.line}) - ${e.behavior}`),""];await c.mkdir(o.dirname(this.specPath()),{recursive:!0}),await c.writeFile(this.specPath(),t.join("\n"),"utf8")}async appendEvent(e,t){await l(o.join(this.workspaceRoot,".mesh","spec-code","events.jsonl"),{at:(new Date).toISOString(),kind:e,data:t})}ledgerPath(){return o.join(this.workspaceRoot,".mesh","spec-code","contracts.json")}specPath(){return o.join(this.workspaceRoot,".mesh","spec-code","SPEC.md")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as o}from"node:fs";import t from"node:path";import{collectWorkspaceFiles as e,writeJson as i}from"./common.js";export class TodoResolverEngine{workspaceRoot;callTool;constructor(o,t){this.workspaceRoot=o,this.callTool=t}async run(s={}){const n=String(s.action??"scan").trim().toLowerCase();if("scan"===n){const a="number"==typeof s.maxFiles?s.maxFiles:1500,r=await e(this.workspaceRoot,{maxFiles:a}),l=[],c=/\/\/\s*(TODO|FIXME):\s*(.+)$/i;for(const e of r){const i=(await o.readFile(t.join(this.workspaceRoot,e),"utf8").catch(()=>"")).split(/\r?\n/);for(let o=0;o<i.length;o++){const t=c.exec(i[o]);if(t){const s=Math.max(0,o-5),n=Math.min(i.length,o+6);l.push({file:e,line:o+1,text:t[2].trim(),context:i.slice(s,n).join("\n")})}}}const m=".mesh/todo-resolver/last-scan.json";return await i(t.join(this.workspaceRoot,m),{todos:l,scannedAt:(new Date).toISOString()}),{ok:!0,action:n,todosFound:l.length,todos:l,ledgerPath:m}}if("resolve"===n){const o="string"==typeof s.file?s.file:void 0,t="string"==typeof s.text?s.text:void 0;if(!o||!t)throw new Error("workspace.todo_resolver 'resolve' action requires 'file' and 'text' arguments");await this.callTool("workspace.intent_compile",{intent:`Resolve the TODO in ${o}: ${t}`});const e=(await this.callTool("workspace.timeline_create",{name:`todo-fix-${Date.now().toString(36)}`})).timeline.id,i=(await this.callTool("agent.spawn",{role:"developer",instruction:`In the file ${o}, resolve the following TODO: "${t}". Modify the code accordingly and remove the TODO comment.`,timelineId:e}),await this.callTool("workspace.timeline_run",{timelineId:e,command:"npm run test",timeoutMs:6e4}));return i.ok?(await this.callTool("workspace.timeline_promote",{timelineId:e}),{ok:!0,action:n,status:"promoted",verification:"pass",details:`Successfully resolved TODO in ${o}`}):{ok:!1,action:n,status:"failed",verification:"fail",details:`Verification failed after attempting to resolve TODO in ${o}`,stdout:i.stdout,stderr:i.stderr}}throw new Error("workspace.todo_resolver action must be scan or resolve")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){const t=e.match(/```(?:json)?\s*([\s\S]*?)```/),n=t?t[1]:e,i=n.match(/\{[\s\S]*\}/);try{return JSON.parse(i?i[0]:n)}catch{return null}}import{promises as t}from"node:fs";import n from"node:path";import{readJson as i,writeJson as s}from"./common.js";const r=[{id:"correctness",persona:"Correctness & DX Engineer",focus:"semantic correctness, type safety, developer ergonomics, clean abstractions, and maintainability",temperature:0},{id:"performance",persona:"Performance & Efficiency Engineer",focus:"runtime performance, memory efficiency, algorithmic complexity, bundle size, and resource usage",modelHint:"haiku",temperature:.1},{id:"resilience",persona:"Security & Resilience Engineer",focus:"edge case coverage, error handling, security boundaries, invariant preservation, and production failure modes",temperature:.3}];export class TribunalEngine{workspaceRoot;callLlm;constructor(e,t){this.workspaceRoot=e,this.callLlm=t}async run(e={}){const t=String(e.action??"convene").trim().toLowerCase();if("status"===t)return this.status();if("convene"!==t)throw new Error("workspace.tribunal action must be convene|status");const n=String(e.problem??"").trim();if(!n)throw new Error("workspace.tribunal convene requires a non-empty problem");if(!this.callLlm)return{ok:!1,reason:"Tribunal requires LLM access. Configuration not available."};const i=String(e.context??"").trim();return this.convene(n,i)}async convene(e,i){const o=i?`\n\nAdditional context:\n${i}`:"",a=await Promise.all(r.map(t=>this.solicit(t,e,o))),c=r.flatMap(e=>a.filter(t=>t.panelistId!==e.id).map(t=>({critic:e,target:t}))),l=await Promise.all(c.map(({critic:t,target:n})=>this.critique(t,n,e))),u=await this.synthesize(e,a,l),d={ok:!0,action:"convene",problem:e,generatedAt:(new Date).toISOString(),panelists:r,proposals:a,critiques:l,synthesis:u,decisionArtifactPath:".mesh/tribunal/latest.json"},p=n.join(this.workspaceRoot,".mesh","tribunal");return await t.mkdir(p,{recursive:!0}),await s(n.join(p,"latest.json"),d),await t.appendFile(n.join(p,"history.jsonl"),JSON.stringify({problem:e.slice(0,120),generatedAt:d.generatedAt,verdict:u.verdict,winner:u.winningPanelistId})+"\n","utf8"),d}async solicit(t,n,i){const s=`You are a ${t.persona}. Your primary lens is: ${t.focus}. Be concise, specific, and opinionated.`,r=[`Engineering problem:${i}`,"",n,"","Provide your expert solution. Respond with JSON only:",'{"solution":"<implementation approach, 3-6 sentences>","reasoning":"<why this is correct from your lens, 2-3 sentences>","tradeoffs":"<what this approach sacrifices, 1-2 sentences>"}'].join("\n");try{const n=await this.callLlm(s,r,t.temperature,t.modelHint),i=e(n);return{panelistId:t.id,persona:t.persona,solution:String(i?.solution??n.slice(0,500)),reasoning:String(i?.reasoning??""),tradeoffs:String(i?.tradeoffs??"")}}catch{return{panelistId:t.id,persona:t.persona,solution:`[${t.persona} failed to respond]`,reasoning:"",tradeoffs:""}}}async critique(t,n,i){const s=`You are a ${t.persona}. Your primary lens is: ${t.focus}. Evaluate another engineer's solution critically but fairly.`,r=[`Original problem: ${i.slice(0,300)}`,"",`${n.persona}'s solution:`,n.solution,"",`Evaluate this from your ${t.focus} perspective. Respond with JSON only:`,'{"verdict":"adopt|partial|reject","strengths":"<what this gets right, 1-2 sentences>","weaknesses":"<what this misses from your lens, 1-2 sentences>","suggestedMerge":"<what element to borrow if partial or reject, or empty string>"}'].join("\n");try{const i=e(await this.callLlm(s,r,.1)),o=String(i?.verdict??"partial").toLowerCase(),a=["adopt","partial","reject"].includes(o)?o:"partial";return{critiquedBy:t.id,targetPanelistId:n.panelistId,verdict:a,strengths:String(i?.strengths??""),weaknesses:String(i?.weaknesses??""),suggestedMerge:String(i?.suggestedMerge??"")}}catch{return{critiquedBy:t.id,targetPanelistId:n.panelistId,verdict:"partial",strengths:"",weaknesses:"[Critique failed]",suggestedMerge:""}}}async synthesize(t,n,i){const s=Object.fromEntries(r.map(e=>[e.id,0]));for(const e of i){const t="adopt"===e.verdict?2:"partial"===e.verdict?1:0;s[e.targetPanelistId]=(s[e.targetPanelistId]??0)+t}const o=2*(r.length-1),a=Object.entries(s).sort((e,t)=>t[1]-e[1]),[c,l]=a[0],[,u]=a[1]??["",0],d=n.find(e=>e.panelistId===c),p=l>=o?"consensus":l>u?"majority":"disputed",m=i.filter(e=>e.targetPanelistId===c&&e.suggestedMerge).map(e=>e.suggestedMerge).filter(Boolean),g=[`Problem: ${t.slice(0,400)}`,"",`Winning solution (${d.persona}, score ${l}/${o}):`,d.solution,"",m.length>0?`Elements to incorporate from other proposals:\n${m.map(e=>`- ${e}`).join("\n")}`:"No additional elements needed.","","Write a final unified solution (3-5 sentences) and a rationale (2 sentences) for why it won. JSON only:",'{"dominantSolution":"<final unified solution>","rationale":"<why this won the tribunal>"}'].join("\n");let h=d.solution,f=`${d.persona}'s solution scored ${l}/${o} in the tribunal.`;try{const t=e(await this.callLlm("You are a synthesis arbiter. Produce a concise, actionable final engineering decision.",g,0));t?.dominantSolution&&(h=String(t.dominantSolution)),t?.rationale&&(f=String(t.rationale))}catch{}const y=a[a.length-1],w=n.find(e=>e.panelistId===y[0]),b="disputed"===p&&w?`${w.persona} dissents: ${w.reasoning.slice(0,180)}`:"";return{dominantSolution:h,winningPanelistId:c,incorporated:m,rationale:f,verdict:p,scores:s,dissent:b}}async status(){return i(n.join(this.workspaceRoot,".mesh","tribunal","latest.json"),{ok:!0,action:"status",message:"No tribunal has been convened yet. Use action=convene with a problem."})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return(process.env[e]??"").split(",").map(e=>e.trim()).filter(Boolean)}function t(e){return Array.from(new Set(e.filter(Boolean)))}export const DEFAULT_NVIDIA_CHAT_MODELS=["qwen/qwen3-coder-480b-a35b-instruct","moonshotai/kimi-k2.6","mistralai/mistral-large-3-675b-instruct-2512","deepseek-ai/deepseek-v4-pro","meta/llama-4-maverick-17b-128e-instruct"];export const DEFAULT_NVIDIA_EMBEDDING_MODELS=["nvidia/nv-embedcode-7b-v1","nvidia/nv-embed-v1","snowflake/arctic-embed-l"];export const DEFAULT_NVIDIA_VISION_MODELS=["meta/llama-3.2-90b-vision-instruct","microsoft/phi-4-multimodal-instruct","microsoft/phi-3-vision-128k-instruct"];export const DEFAULT_NVIDIA_SAFETY_MODELS=["meta/llama-guard-4-12b","nvidia/llama-3.1-nemotron-safety-guard-8b-v3"];export const DEFAULT_NVIDIA_PII_MODELS=["nvidia/gliner-pii"];export function isNvidiaHostedModel(e){const t=e.trim();return!t.startsWith("us.anthropic.")&&!t.startsWith("eu.anthropic.")&&/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/i.test(t)}export function resolveNvidiaEndpoint(){return(process.env.NVIDIA_ENDPOINT||process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1").trim()}export function resolveNvidiaApiKey(e){const t=process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY||process.env.NVIDIA_BEARER_TOKEN;return t&&t.trim()?t.trim():e&&e.trim()?e.trim():void 0}export function resolveEmbeddingModels(){return t([...e("MESH_EMBEDDING_FALLBACK_MODELS"),process.env.MESH_EMBEDDING_MODEL||DEFAULT_NVIDIA_EMBEDDING_MODELS[0],...DEFAULT_NVIDIA_EMBEDDING_MODELS])}export function resolveVisionModels(){return t([process.env.MESH_VISION_MODEL||DEFAULT_NVIDIA_VISION_MODELS[0],...e("MESH_VISION_FALLBACK_MODELS"),...DEFAULT_NVIDIA_VISION_MODELS])}export function resolveSafetyModels(){return t([process.env.MESH_SAFETY_MODEL||DEFAULT_NVIDIA_SAFETY_MODELS[0],process.env.MESH_SAFETY_MODEL_SECONDARY||DEFAULT_NVIDIA_SAFETY_MODELS[1],...e("MESH_SAFETY_FALLBACK_MODELS"),...DEFAULT_NVIDIA_SAFETY_MODELS])}export function resolvePiiModels(){return t([process.env.MESH_PII_MODEL||DEFAULT_NVIDIA_PII_MODELS[0],...e("MESH_PII_FALLBACK_MODELS"),...DEFAULT_NVIDIA_PII_MODELS])}export async function nvidiaChatCompletion(e,t={}){const i=resolveNvidiaApiKey(t.apiKey);if(!i)throw new Error("NVIDIA_API_KEY is required for NVIDIA-hosted models.");const r=(t.baseUrl||resolveNvidiaEndpoint()).replace(/\/+$/,""),o=await fetch(`${r}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`,...t.extraHeaders||{}},body:JSON.stringify({model:e.model,messages:e.messages,tools:e.tools,temperature:e.temperature??0,max_tokens:e.maxTokens??2048,stream:e.stream??!1}),signal:t.abortSignal}),n=await o.text();let a=null;try{a=JSON.parse(n)}catch{a=null}return{response:o,data:a,rawText:n}}export async function nvidiaEmbedding(e,t,i={}){const r=resolveNvidiaApiKey(i.apiKey);if(!r)throw new Error("NVIDIA_API_KEY is required for NVIDIA embeddings.");const o={model:e,input:[t]};i.inputType&&(o.input_type=i.inputType);const n=(i.baseUrl||resolveNvidiaEndpoint()).replace(/\/+$/,""),a=await fetch(`${n}/embeddings`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify(o),signal:i.abortSignal}),s=await a.text();if(!a.ok)throw new Error(`NVIDIA embeddings failed (${a.status}): ${s.slice(0,240)}`);const l=JSON.parse(s);return l.data?.[0]?.embedding??[]}export async function nvidiaEmbeddingWithFallbacks(e,t={}){let i=null;for(const r of t.models??resolveEmbeddingModels())try{const i=await nvidiaEmbedding(r,e,{apiKey:t.apiKey,inputType:t.inputType??(r.startsWith("nvidia/")?"query":void 0),abortSignal:t.abortSignal,baseUrl:t.baseUrl});if(i.length>0)return{model:r,embedding:i}}catch(e){i=e}throw i??new Error("No NVIDIA embedding model produced a result.")}export async function analyzeImageWithNvidia(e,i,r=process.env.MESH_VISION_MODEL||DEFAULT_NVIDIA_VISION_MODELS[0],o,n){let a=null;for(const s of t([r,...resolveVisionModels()])){const{response:t,data:r,rawText:l}=await nvidiaChatCompletion({model:s,messages:[{role:"user",content:[{type:"text",text:i},{type:"image_url",image_url:{url:`data:image/png;base64,${e}`}}]}],temperature:0,maxTokens:400},{apiKey:o,abortSignal:AbortSignal.timeout(3e4),baseUrl:n});if(t.ok)return extractNvidiaText(r);a=new Error(`Vision model ${s} failed (${t.status}): ${l.slice(0,240)}`)}throw a??new Error(`Vision model ${r} failed.`)}export async function classifySafetyWithNvidia(e,i=process.env.MESH_SAFETY_MODEL||DEFAULT_NVIDIA_SAFETY_MODELS[0],r,o){let n=null;for(const a of t([i,...resolveSafetyModels()])){const{response:t,data:i,rawText:s}=await nvidiaChatCompletion({model:a,messages:[{role:"user",content:"Classify the following engineering artifact for security/safety relevance. Return a compact one-line verdict with risk level and rationale.\n\n"+e}],temperature:0,maxTokens:160},{apiKey:r,abortSignal:AbortSignal.timeout(3e4),baseUrl:o});if(t.ok)return extractNvidiaText(i);n=new Error(`Safety model ${a} failed (${t.status}): ${s.slice(0,240)}`)}throw n??new Error(`Safety model ${i} failed.`)}export async function detectPiiWithNvidia(e,i=process.env.MESH_PII_MODEL||DEFAULT_NVIDIA_PII_MODELS[0],r,o){let n=null;for(const a of t([i,...resolvePiiModels()])){const{response:t,data:i,rawText:s}=await nvidiaChatCompletion({model:a,messages:[{role:"user",content:"Detect sensitive entities, credentials, tokens, or PII in the following text. Return compact JSON if possible.\n\n"+e}],temperature:0,maxTokens:220},{apiKey:r,abortSignal:AbortSignal.timeout(3e4),baseUrl:o});if(t.ok)return extractNvidiaText(i);n=new Error(`PII model ${a} failed (${t.status}): ${s.slice(0,240)}`)}throw n??new Error(`PII model ${i} failed.`)}export function extractNvidiaText(e){const t=e?.choices?.[0],i=t?.message?.content;return"string"==typeof i?i.trim():Array.isArray(i)?i.map(e=>e?.text??"").join("\n").trim():""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:path";import{execFile as t}from"node:child_process";import{promisify as i}from"node:util";import{readJson as s,writeJson as r}from"./moonshots/common.js";import{routeMeshTask as a}from"./model-router.js";i(t);export class ProductionReadinessEngine{workspaceRoot;callTool;ledgerPath;constructor(t,i){this.workspaceRoot=t,this.callTool=i,this.ledgerPath=e.join(t,".mesh","production-readiness","latest.json")}async run(e={}){const t=String(e.action??"audit").trim().toLowerCase();if("status"===t)return s(this.ledgerPath,{ok:!0,action:t,status:"missing",message:"No production readiness ledger exists yet. Run action=audit or action=gate."});if(!["audit","gate","review"].includes(t))throw new Error("workspace.production_readiness action must be audit|gate|review|status");const i=String(e.intent??"production readiness hardening").trim(),a=String(e.verificationCommand??await this.inferVerificationCommand()).trim(),o="string"==typeof e.url?e.url.trim():"",n=await Promise.all([this.modelOrchestration(i),this.retrievalQuality(i),this.timelineVerification(i,a,t),this.runtimeLearning(),this.visualLoop(o),this.projectMemory(i),this.reviewGate(a)]),c=Math.round(n.reduce((e,t)=>e+t.score,0)/n.length),l=n.some(e=>"block"===e.status)?"block":n.some(e=>"warn"===e.status)?"warn":"pass",u=n.flatMap(e=>"block"===e.status?e.nextActions.map(t=>`${e.title}: ${t}`):[]),d=(m=n.flatMap(e=>e.nextActions),Array.from(new Set(m.map(e=>e.trim()).filter(Boolean)))).slice(0,12);var m;const p={ok:"block"!==l,action:t,status:l,score:c,generatedAt:(new Date).toISOString(),intent:i,verificationCommand:a,dimensions:n,blockers:u,nextActions:d,ledgerPath:".mesh/production-readiness/latest.json"};return await r(this.ledgerPath,p),p}async modelOrchestration(e){const t=a(e),i=t.retrievalModels.length>=3&&t.visionModels.length>=3&&t.safetyModels.length>=2&&t.piiModels.length>=1&&(!["code","debug","review"].includes(t.taskType)||t.chatFallbacks.length>=3);return{id:"model_orchestration",title:"Model Orchestration",status:i?"pass":"warn",score:i?96:72,evidence:[`task=${t.taskType} confidence=${t.confidence}`,`primary=${t.primaryChatModel}`,`chatFallbacks=${t.chatFallbacks.join(", ")}`,`requiredGates=${t.requiredGates.join(", ")}`],nextActions:i?[]:["Define full role-specific fallback chains for chat, retrieval, vision, and safety."]}}async retrievalQuality(e){const[t,i]=await Promise.all([this.safeTool("workspace.index_status",{}),this.safeTool("workspace.ask_codebase",{query:e,mode:"architecture",limit:8})]),s=Number(t?.percent??0),r=Number(i?.results?.length??i?.topMatches?.length??0);return{id:"retrieval",title:"Production RAG",status:s>=80&&r>=3?"pass":s>=50?"warn":"block",score:Math.min(100,Math.round(.7*s+3.75*Math.min(r,8))),evidence:[`indexFresh=${s}%`,`retrievalMatches=${r}`,`queryVariants=${Array.isArray(i?.queryVariants)?i.queryVariants.join(" | "):e}`],nextActions:s>=80&&r>=3?[]:["Run /index and re-run workspace.production_readiness after the code index is fresh."]}}async timelineVerification(e,t,i){const[s,r,a]=await Promise.all([this.safeTool("workspace.precrime",{action:"status"}),this.safeTool("workspace.timeline_list",{}),"gate"===i&&t?this.safeTool("workspace.proof_carrying_change",{action:"verify",intent:e,verificationCommand:t,timeoutMs:24e4}):this.safeTool("workspace.proof_carrying_change",{action:"status"})]),o=!1!==a?.ok&&!/No proof-carrying/.test(String(a?.message??"")),n=Array.isArray(r?.timelines)?r.timelines.length:Number(r?.count??0),c=!1!==s?.ok&&!/No precrime ledger/i.test(String(s?.message??""));return{id:"timeline_verification",title:"Timeline Verification",status:o&&c?"pass":t?"warn":"block",score:(o?42:12)+(c?34:12)+Math.min(24,6*n),evidence:["proof="+(o?"present":"missing"),"precrime="+(c?"ready":"missing"),`timelines=${n}`,`verification=${t||"none"}`],nextActions:[c?"":"Run workspace.precrime action=analyze before promoting risky work.",o?"":"Generate or verify workspace.proof_carrying_change for the current diff.",t?"":"Configure a production verification command such as npm run typecheck && npm test."].filter(Boolean)}}async runtimeLearning(){const[e,t,i]=await Promise.all([this.safeTool("workspace.production_status",{action:"status"}),this.safeTool("workspace.predictive_repair",{action:"status"}),this.safeTool("workspace.causal_autopsy",{action:"status"})]),s=Number(e?.totalSignals??0),r=Array.isArray(t?.queue)?t.queue.length:0,a=!1!==i?.ok&&!/No causal/i.test(String(i?.message??""));return{id:"runtime_learning",title:"Runtime Learning Loop",status:a||s>0||r>0?"pass":"warn",score:Math.min(100,48+3*Math.min(s,10)+4*Math.min(r,5)+(a?12:0)),evidence:[`productionSignals=${s}`,`repairQueue=${r}`,"causalLedger="+(a?"ready":"missing")],nextActions:a||s>0?[]:["Capture at least one runtime failure or telemetry refresh so Mesh can learn from production signals."]}}async visualLoop(e){if(!e)return{id:"visual_loop",title:"Visual Patch Loop",status:"warn",score:72,evidence:["No URL provided; vision loop is installed but not exercised in this audit."],nextActions:["Pass url=<local app URL> to workspace.production_readiness to run a live vision check."]};const t=await this.safeTool("frontend.preview",{url:e,render:!1,waitMs:1200}),i=!0===t?.ok&&"string"==typeof t?.visionAnalysis&&!t.visionAnalysis.startsWith("vision unavailable");return{id:"visual_loop",title:"Visual Patch Loop",status:i?"pass":"warn",score:i?94:68,evidence:[`url=${e}`,"preview="+(!0===t?.ok?"captured":"not captured"),`vision=${i?"analyzed":String(t?.visionAnalysis??t?.error??"missing")}`.slice(0,260)],nextActions:i?[]:["Ensure Chrome is available and NVIDIA_API_KEY is configured for screenshot analysis."]}}async projectMemory(e){const t=await this.safeTool("workspace.engineering_memory",{action:"read"}),i=Array.isArray(t?.memory?.rules)?t.memory.rules.length:0,s=Array.isArray(t?.memory?.decisions)?t.memory.decisions.length:0;return 0===i&&await this.safeTool("workspace.engineering_memory",{action:"record",outcome:"neutral",rule:"Production changes must pass model route, RAG, timeline, runtime, visual, memory, and review gates before promotion.",note:`Production readiness baseline recorded for: ${e}`}),{id:"project_memory",title:"Decision And Project Memory",status:i>0||s>0?"pass":"warn",score:Math.min(100,70+2*Math.min(i,10)+Math.min(s,10)),evidence:[`rules=${i}`,`decisions=${s}`],nextActions:s>0?[]:["Record architecture decisions and rejected patterns in workspace.engineering_memory."]}}async reviewGate(e){const[t,i,s]=await Promise.all([this.safeTool("workspace.git_status",{}),this.safeTool("workspace.git_diff",{}),this.safeTool("workspace.proof_carrying_change",{action:"status"})]),r=String(t?.status??"").split(/\r?\n/g).filter(Boolean),a=function(e,t){const i=[];return/(SECRET|TOKEN|API_KEY|PASSWORD|PRIVATE_KEY|nvapi-|sk-[A-Za-z0-9])/i.test(e)&&i.push({severity:"high",message:"Diff appears to include secrets or credential-shaped values.",action:"Remove secrets from the diff and rotate any exposed credential."}),/\b(exec|spawn|eval|Function)\s*\(/.test(e)&&i.push({severity:"high",message:"Diff touches process execution or dynamic evaluation.",action:"Run command-safety review and add input validation tests."}),t.some(e=>/(package\.json|package-lock\.json|tsconfig\.json|Dockerfile|cloudbuild|wrangler|helm\/)/.test(e))&&i.push({severity:"medium",message:"Diff changes dependency, build, deploy, or infrastructure configuration.",action:"Run build plus deployment-specific verification before merge."}),t.some(e=>/(auth|security|runtime|llm-client|local-tools|agent-loop)/i.test(e))&&i.push({severity:"medium",message:"Diff touches high-leverage runtime, auth, security, or agent files.",action:"Require timeline verification and a focused code review."}),i}(String(i?.diff??""),r),o=!1!==s?.ok&&!/No proof-carrying/.test(String(s?.message??"")),n=r.some(e=>/(\.test|\.spec|tests?\/)/.test(e)),c=r.some(e=>/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(e))&&!n;return{id:"review_gate",title:"PR And Review Gate",status:a.some(e=>"high"===e.severity)||!e?"block":a.length>0||c||!o?"warn":"pass",score:Math.max(0,100-14*a.length-(c?18:0)-(o?0:16)-(e?0:24)),evidence:[`changedFiles=${r.length}`,"proof="+(o?"present":"missing"),`testGap=${c}`,...a.slice(0,6).map(e=>`${e.severity}:${e.message}`)],nextActions:[...a.map(e=>e.action),c?"Add or update targeted tests for source changes before PR.":"",o?"":"Generate a proof-carrying-change bundle for the PR diff."].filter(Boolean)}}async inferVerificationCommand(){const t=e.join(this.workspaceRoot,"package.json"),i=await s(t,null),r=i?.scripts??{};return r.typecheck&&r.test?"npm run typecheck && npm test":r.test?"npm test":r.build?"npm run build":r.typecheck?"npm run typecheck":""}async safeTool(e,t){try{return await this.callTool(e,t)}catch{return null}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t,e){return['import fc from "fast-check";',`import { ${t} } from "./${e.replace(/\.ts$/,"")}";`,"",`describe("${t} property checks", () => {`,' it("is deterministic for identical input", () => {'," fc.assert("," fc.property(fc.anything(), (input) => {",` const first = ${t}(input as any);`,` const second = ${t}(input as any);`," expect(JSON.stringify(first)).toBe(JSON.stringify(second));"," }),"," { numRuns: 1000 }"," );"," });","});",""].join("\n")}function e(t){const e=t.match(/export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/);return e?.[1]??null}async function s(t,e){const i=await o.readdir(t,{withFileTypes:!0}).catch(()=>[]);for(const o of i){const i=n.join(t,o.name);o.isDirectory()?await s(i,e):e.push(i)}}import{promises as o}from"node:fs";import n from"node:path";export class PropertyTestGenerator{workspaceRoot;constructor(t){this.workspaceRoot=t}async generate(s){const i=s.all?await this.collectTsFiles():[s.path].filter(t=>Boolean(t)),r=[];for(const c of i){const i=n.resolve(this.workspaceRoot,c),a=await o.readFile(i,"utf8").catch(()=>"");if(!a)continue;const p=s.functionName||e(a);if(!p)continue;const f=i.replace(/\.tsx?$/,".property.test.ts"),l=t(p,n.basename(c));await o.writeFile(f,l,"utf8"),r.push(n.relative(this.workspaceRoot,f))}return{ok:!0,generated:r.length,files:r}}async collectTsFiles(){const t=n.join(this.workspaceRoot,"src"),e=[];return await s(t,e),e.filter(t=>/\.tsx?$/.test(t)&&!t.endsWith(".test.ts")&&!t.endsWith(".property.test.ts")).map(t=>n.relative(this.workspaceRoot,t))}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as t}from"node:fs";import e from"node:path";export class SmtEdgeCaseFinder{workspaceRoot;constructor(t){this.workspaceRoot=t}async find(n){const s=e.resolve(this.workspaceRoot,n.path),o=await t.readFile(s,"utf8"),a=n.functionName||function(t){const e=t.match(/export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/);return e?.[1]??null}(o)||"unknown",i=function(t,e){const n=[];return/\bMath\.abs\(/.test(t)&&n.push({input:"-2147483648",reason:`${e}: abs edge-case may overflow integer assumptions`}),(/\b\/\s*0\b/.test(t)||/\bNumber\(/.test(t))&&n.push({input:"Infinity",reason:`${e}: division/coercion can produce non-finite values`}),(/\?\./.test(t)||/null|undefined/.test(t))&&n.push({input:"null",reason:`${e}: nullable path can violate assumptions`}),n}(o,a),r=s.replace(/\.tsx?$/,".edge-cases.test.ts");return i.length>0&&await t.writeFile(r,function(t,e){return[`import { ${t} } from "./${t}";`,"",`describe("${t} SMT edge cases", () => {`,...e.map(e=>[` it("handles ${e.input} (${e.reason})", () => {`,` expect(() => ${t}(${e.input} as any)).not.toThrow();`," });"].join("\n")),"});",""].join("\n")}(a,i),"utf8"),{ok:!0,functionName:a,findings:i,generatedTest:i.length>0?e.relative(this.workspaceRoot,r):null}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Project as e,QuoteKind as t}from"ts-morph";import o from"node:path";import r from"node:fs";export class TsCompilerRefactor{workspaceRoot;project;constructor(i){this.workspaceRoot=i;const n=o.join(i,"tsconfig.json");this.project=r.existsSync(n)?new e({tsConfigFilePath:n,skipAddingFilesFromTsConfig:!1,manipulationSettings:{quoteKind:t.Double}}):new e({manipulationSettings:{quoteKind:t.Double}})}async renameSymbol(e,t,o){const r=this.requireSource(e).getDescendants().filter(e=>e.getText()===t);for(const e of r){const t=e;"function"==typeof t.rename&&t.rename(o)}return await this.project.save(),{changed:r.length}}async extractFunction(e,t,o,r){const i=this.requireSource(e),n=i.getFullText().split(/\r?\n/g).slice(o-1,r).join("\n");return i.addFunction({isExported:!1,name:t,statements:n}),await this.project.save(),{created:!0}}async inlineSymbol(e,t){const o=this.requireSource(e).getVariableDeclarations().filter(e=>e.getName()===t);if(0===o.length)return{inlined:0};let r=0;for(const e of o){const o=e.getInitializer()?.getText();if(!o)continue;const i=e.findReferencesAsNodes();for(const n of i)n.getText()===t&&n!==e.getNameNode()&&(n.replaceWithText(o),r+=1);e.getVariableStatement()?.remove()}return await this.project.save(),{inlined:r}}async moveToModule(e,t,r){const i=this.requireSource(e),n=this.project.addSourceFileAtPathIfExists(o.resolve(this.workspaceRoot,t))??this.project.createSourceFile(o.resolve(this.workspaceRoot,t),"",{overwrite:!1}),s=i.getFunction(r);if(s)return n.addFunction({name:r,isExported:!0,parameters:s.getParameters().map(e=>({name:e.getName(),type:e.getType().getText(e)})),returnType:s.getReturnType().getText(s),statements:s.getBodyText()||""}),s.remove(),await this.project.save(),{moved:!0};const a=i.getVariableDeclaration(r);return a?(n.addVariableStatement({declarations:[{name:r,initializer:a.getInitializer()?.getText()||"undefined"}],isExported:!0}),a.getVariableStatement()?.remove(),await this.project.save(),{moved:!0}):{moved:!1}}requireSource(e){const t=o.resolve(this.workspaceRoot,e),r=this.project.addSourceFileAtPathIfExists(t);if(!r)throw new Error(`Source file not found: ${e}`);return r}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as e}from"node:fs";import t from"node:path";export class ReplayEngine{workspaceRoot;timelines;constructor(e,t){this.workspaceRoot=e,this.timelines=t}async replayTrace(e){const t=String(e.traceId??e.sentryEventId??"").trim();if(!t)throw new Error("runtime.replay_trace requires traceId or sentryEventId");const n=await this.loadTrace(t);if(!n)return{ok:!1,traceId:t,message:"Trace fixture not found in .mesh/telemetry-traces.json"};const r=n.spans.map((e,t)=>({index:t,span:e.name,file:e.file??null,line:e.line??null,error:e.error??null})),a=r.find(e=>e.error)??r.at(-1)??null,i=e.commitRange?await this.analyzeCommitRange(e.commitRange,n):null;return{ok:!0,traceId:t,source:n.source,reconstructedRequest:{method:n.method,path:n.path,headers:n.headers,body:n.body??null},mockedDependencies:{externalApis:n.apiMocks??[],databaseQueries:n.dbMocks??[]},checkpoints:r,divergence:a,commitAnalysis:i}}async analyzeCommitRange(e,t){const{start:n,end:r}=function(e){const t=e.trim();if(!t)throw new Error("Invalid commitRange: empty range");const n=t.split("..");if(n.length>2)throw new Error("Invalid commitRange: expected <start>..<end>");const r=n[0]||"HEAD",a=2===n.length&&n[1]||"HEAD",i=/^[a-zA-Z0-9_.-]+$/;if(!i.test(r)||!i.test(a))throw new Error("Invalid commitRange: refs may only contain letters, numbers, underscore, dot, or dash");return{start:r,end:a}}(e),a=n||"HEAD",i=await this.timelines.create({name:`replay-${t.id}`,baseRef:a}),o=await this.timelines.run({timelineId:i.timeline.id,command:"npm test",timeoutMs:12e4});return{range:e,sampledCommit:a,sampledTimelineId:i.timeline.id,sampledExitCode:o.exitCode,likelyIntroducedBy:o.ok?r:a}}async loadTrace(n){const r=t.join(this.workspaceRoot,".mesh","telemetry-traces.json");try{const t=await e.readFile(r,"utf8");return JSON.parse(t).find(e=>e.id===n)??null}catch{return null}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import o from"node:fs/promises";import e from"node:path";import{AgentLoop as t}from"./agent-loop.js";import{AuthManager as n}from"./auth.js";import{CompositeToolBackend as c}from"./composite-backend.js";import{loadConfig as s}from"./config.js";import{LocalToolBackend as a}from"./local-tools.js";import{McpClient as i}from"./mcp-client.js";export class MeshRuntime{config;backend;toolBackendCount;agent;constructor(o,e,n){this.config=o,this.backend=e,this.toolBackendCount=n,this.agent=new t(o,e)}status(){return{ok:!0,workspaceRoot:this.config.agent.workspaceRoot,mode:this.config.agent.mode,modelId:this.config.bedrock.modelId,toolBackends:this.toolBackendCount}}async runTurn(o,e){return this.agent.runHeadlessTurn(o,e)}async close(){await this.backend.close().catch(()=>{})}}export async function createMeshRuntime(t){let r;if(!t.skipAuth){const o=new n;await o.ensureAuthenticated(),r=o.getAccessToken()}const m=await s();m.agent.workspaceRoot=e.resolve(t.workspaceRoot),m.bedrock.bearerToken||=r;const p=[new a(m.agent.workspaceRoot,m)];if(function(o){return"boolean"==typeof o.includeWorkspaceMcp?o.includeWorkspaceMcp:/^(1|true|yes)$/i.test(process.env.MESH_ENABLE_WORKSPACE_MCP??"")}(t)){const t=e.join(m.agent.workspaceRoot,".mesh","mcp.json");await async function(e,t){try{const n=await o.readFile(e,"utf8"),c=JSON.parse(n);for(const o of Object.values(c)){if(!o.command)continue;const e=new i(o.command,o.args??[]);await e.initialize(),t.push(e)}}catch{}}(t,p)}if("mcp"===m.agent.mode){if(!m.mcp.command)throw new Error("MCP mode selected but no MESH_MCP_COMMAND configured");const o=new i(m.mcp.command,m.mcp.args);await o.initialize(),p.push(o)}return new MeshRuntime(m,new c(p),p.length)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function e(e,r=12e3){const t=await n.readFile(e,"utf8").catch(()=>"");return t.length<=r?t:t.slice(-r)}function r(e){const r=e.split(/\r?\n/g).map(e=>e.trim()).filter(Boolean),t=r.find(e=>/(?:error|exception|failed|fatal):/i.test(e));if(t)return t.slice(0,500);const n=r.find(e=>/^[A-Z][A-Za-z]+Error\b/.test(e));return n?.slice(0,500)??"No explicit error found in captured output."}function t(e){const r=[],t=[/\(?([A-Za-z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)):(\d+):(\d+)\)?/g,/at\s+([A-Za-z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)):(\d+):(\d+)/g];for(const n of t)for(const t of e.matchAll(n)){const e=t[1].replace(process.cwd(),"").replace(/^\/+/,"");r.push({file:e,line:Number(t[2]),column:Number(t[3]),raw:t[0]})}return Array.from(new Map(r.map(e=>[`${e.file}:${e.line}:${e.column}`,e])).values()).slice(0,20)}import{promises as n}from"node:fs";import o from"node:path";import a from"node:os";import s from"node:crypto";import{spawn as i}from"node:child_process";import{StructuredLogger as c}from"./structured-logger.js";import{parseAllowedCommand as u}from"./command-safety.js";export class RuntimeObserver{workspaceRoot;workspaceHash;basePath;processes=new Map;autopsyHookPath;logger;constructor(e){this.workspaceRoot=e,this.workspaceHash=s.createHash("sha256").update(o.resolve(e)).digest("hex").slice(0,24);const r=process.env.MESH_STATE_DIR||o.join(a.homedir(),".config","mesh");this.basePath=o.join(r,"runtime",this.workspaceHash),this.autopsyHookPath=o.join(this.basePath,"autopsy-hook.cjs"),this.logger=new c(e)}async start(e){const r="string"==typeof e.profile?e.profile.trim():"",t=r?await this.loadProfile(r):{},a=String(e.command??t.command??"").trim();if(!a)throw new Error("runtime.start requires command or a runbook profile with command");const c=u(a),l=`run-${Date.now().toString(36)}-${s.randomBytes(3).toString("hex")}`,p=o.join(this.basePath,l);await n.mkdir(p,{recursive:!0});const m=o.join(p,"stdout.log"),f=o.join(p,"stderr.log"),d=o.join(p,"autopsy.json"),h=o.resolve(this.workspaceRoot,t.cwd||"."),w=await this.ensureAutopsyHook(),y=mergeNodeOptions(process.env.NODE_OPTIONS,["--enable-source-maps",`--require=${w}`]),g={id:l,command:a,profile:r||void 0,cwd:h,status:"running",startedAt:(new Date).toISOString(),stdoutPath:m,stderrPath:f,autopsyPath:d,inspectorHookPath:w,nodeOptions:y};await this.writeRecord(g),this.logger.write("info","runtime.start",{runId:l,command:a,cwd:h,profile:r||void 0}).catch(()=>{});const k=await n.open(m,"a"),S=await n.open(f,"a"),b={...process.env,...t.env??{},NODE_OPTIONS:y,MESH_RUNTIME_AUTOPSY_PATH:d,MESH_RUNTIME_RUN_ID:l},j=i(c.command,c.args,{cwd:h,env:b});this.processes.set(l,j);const P=Number(e.timeoutMs??t.timeoutMs??0),N=P>0?setTimeout(()=>{j.kill("SIGTERM"),this.finishRun(l,"timeout",124)},P):null;return j.stdout.on("data",e=>{k.write(e)}),j.stderr.on("data",e=>{S.write(e)}),j.on("error",()=>{N&&clearTimeout(N),this.processes.delete(l),k.close(),S.close(),this.finishRun(l,"failed",1)}),j.on("close",e=>{N&&clearTimeout(N),this.processes.delete(l),k.close(),S.close(),this.finishRun(l,0===e?"exited":"failed",e??0)}),j.unref(),{ok:!0,runId:l,status:"running",command:a,stdoutPath:m,stderrPath:f,note:"Runtime observer started. Use runtime.capture_failure or runtime.explain_failure with this runId."}}async close(){for(const e of this.processes.values())e.killed||e.kill("SIGTERM");this.processes.clear(),this.logger.write("info","runtime.shutdown",{}).catch(()=>{})}async captureDeepAutopsy(n){const a=String(n.runId??""),s=await this.readRecord(a),i=s.autopsyPath??o.join(o.dirname(s.stdoutPath),"autopsy.json"),c=await this.readAutopsyReport(i);if(c)return{ok:!0,runId:a,reportPath:i,capturedAt:c.capturedAt,reason:c.reason,frames:c.frames,stackWithScope:c.frames.map(e=>({file:e.file,line:e.line,column:e.column,raw:e.raw,functionName:e.functionName,scopes:e.scopes})),errorSummary:c.errorSummary,causalChain:c.causalChain};const u=await e(s.stdoutPath,5e3),l=`${await e(s.stderrPath,5e3)}\n${u}`,p=t(l),m=r(l),f=function(e,r){const t=[e||"No explicit error summary captured."];for(const e of r.slice(0,5))t.push(`${e.file}:${e.line}${e.column?`:${e.column}`:""}`);return t}(m,p);return{ok:!0,runId:a,reportPath:i,capturedAt:s.finishedAt??s.startedAt,reason:"log-fallback",frames:p.map(e=>({...e,functionName:"(unknown)",scopes:[]})),stackWithScope:p.map(e=>({...e,scope:{local:{reason:"Inspector report missing; using log fallback",state:"best-effort"},closure:{}}})),errorSummary:m,causalChain:f}}async captureFailure(n){const o=await this.readRecord(String(n.runId??"")),a=await e(o.stdoutPath),s=await e(o.stderrPath),i=`${s}\n${a}`,c=t(i),u=r(i);return{ok:!0,runId:o.id,status:o.status,exitCode:o.exitCode,errorSummary:u,stackFrames:c,stdoutTail:a,stderrTail:s}}async explainFailure(e){const r=await this.captureFailure(e),t=Array.from(new Set(r.stackFrames.map(e=>e.file))).slice(0,10),n="No explicit error found in captured output."===r.errorSummary?`Run ${r.runId} is ${r.status}; no explicit stack trace was captured.`:`${r.errorSummary} in run ${r.runId}.`;return{ok:!0,runId:r.runId,explanation:n,likelySourceFiles:t,stackFrames:r.stackFrames,nextActions:["Use workspace.impact_map with the top stack frame file.","Create a timeline and test a candidate fix before promoting it.","Re-run the same command in the timeline to verify the failure is gone."]}}async traceRequest(e){const r=String(e.url??e.testName??e.stackFrame??"").trim();if(!r)throw new Error("runtime.trace_request requires url, testName, or stackFrame");const t=r.replace(/^https?:\/\/[^/]+/,"");return{ok:!0,query:r,hints:[`Search routes for ${t}`,`Use workspace.ask_codebase with mode runtime-path and query "${t}"`,"If a stack frame is known, use workspace.impact_map on that file."]}}async fixFailure(e){const r=await this.explainFailure(e);return{ok:!0,runId:r.runId,task:[`Fix runtime failure ${r.runId}.`,r.explanation,r.likelySourceFiles.length>0?`Likely files: ${r.likelySourceFiles.join(", ")}`:"No source file identified yet."].join("\n"),recommendedTools:["workspace.timeline_create","workspace.timeline_apply_patch","workspace.timeline_run","workspace.timeline_promote"]}}async writeDefaultRunbooks(){const e=o.join(this.workspaceRoot,".mesh","runbooks");await n.mkdir(e,{recursive:!0});const r=o.join(e,"node.json");await n.access(r).then(()=>!0).catch(()=>!1)||await n.writeFile(r,JSON.stringify({command:"npm run dev",cwd:".",timeoutMs:6e4,env:{NODE_ENV:"development"}},null,2),"utf8")}async loadProfile(e){const r=e.replace(/[^a-zA-Z0-9._-]+/g,""),t=o.join(this.workspaceRoot,".mesh","runbooks",`${r}.json`),a=await n.readFile(t,"utf8");return JSON.parse(a)}async readRecord(e){const r=e.replace(/[^a-zA-Z0-9._-]+/g,"");if(!r)throw new Error("runtime runId is required");const t=await n.readFile(o.join(this.basePath,r,"run.json"),"utf8");return JSON.parse(t)}async writeRecord(e){await n.mkdir(o.join(this.basePath,e.id),{recursive:!0}),await n.writeFile(o.join(this.basePath,e.id,"run.json"),JSON.stringify(e,null,2),"utf8")}async ensureAutopsyHook(){await n.mkdir(this.basePath,{recursive:!0});const e='const inspector = require("node:inspector");\nconst fs = require("node:fs");\nconst path = require("node:path");\n\nif (process.env.MESH_RUNTIME_AUTOPSY_PATH && !global.__meshRuntimeAutopsyHookInstalled) {\n global.__meshRuntimeAutopsyHookInstalled = true;\n\n const reportPath = process.env.MESH_RUNTIME_AUTOPSY_PATH;\n const runId = process.env.MESH_RUNTIME_RUN_ID || "unknown";\n const session = new inspector.Session();\n let captured = false;\n\n function writeFallbackReport(reason, error) {\n try {\n fs.writeFileSync(reportPath, JSON.stringify({\n ok: true,\n runId,\n capturedAt: new Date().toISOString(),\n reason,\n errorSummary: error ? String(error.message || error) : "Inspector hook failed before pause capture.",\n causalChain: [reason],\n frames: []\n }, null, 2), "utf8");\n } catch {}\n }\n\n function serializeRemoteValue(value) {\n if (!value) return "undefined";\n if (Object.prototype.hasOwnProperty.call(value, "value")) {\n const raw = value.value;\n if (typeof raw === "string") return raw.length > 140 ? `${raw.slice(0, 137)}...` : raw;\n if (typeof raw === "number" || typeof raw === "boolean" || raw === null) return String(raw);\n if (Array.isArray(raw)) return `[array(${raw.length})]`;\n if (typeof raw === "object") return JSON.stringify(raw).slice(0, 140);\n return String(raw);\n }\n if (value.type) return String(value.type);\n return "unavailable";\n }\n\n function post(method, params) {\n return new Promise((resolve, reject) => {\n session.post(method, params || {}, (error, result) => {\n if (error) reject(error);\n else resolve(result);\n });\n });\n }\n\n async function collectScope(scope) {\n const objectId = scope && scope.object && scope.object.objectId;\n if (!objectId) {\n return { type: scope.type || "unknown", properties: {} };\n }\n const response = await post("Runtime.getProperties", {\n objectId,\n ownProperties: true,\n accessorPropertiesOnly: false\n }).catch(() => ({ result: [] }));\n const properties = {};\n for (const entry of (response.result || []).slice(0, 8)) {\n if (!entry || entry.name === "__proto__") continue;\n properties[entry.name] = serializeRemoteValue(entry.value);\n }\n return { type: scope.type || "unknown", properties };\n }\n\n function normalizeFrameUrl(rawUrl) {\n if (!rawUrl) return "unknown";\n try {\n if (String(rawUrl).startsWith("file://")) {\n return path.relative(process.cwd(), new URL(rawUrl).pathname);\n }\n return path.relative(process.cwd(), String(rawUrl));\n } catch {\n return String(rawUrl);\n }\n }\n\n session.connect();\n Promise.all([\n post("Runtime.enable"),\n post("Debugger.enable"),\n post("Debugger.setPauseOnExceptions", { state: "all" }),\n post("Debugger.setAsyncCallStackDepth", { maxDepth: 8 })\n ]).catch((error) => writeFallbackReport("inspector-init-failed", error));\n\n session.on("Debugger.paused", async (message) => {\n if (captured) return;\n captured = true;\n try {\n const frames = [];\n for (const frame of (message.params.callFrames || []).slice(0, 12)) {\n const scopes = [];\n for (const scope of (frame.scopeChain || []).slice(0, 4)) {\n scopes.push(await collectScope(scope));\n }\n frames.push({\n functionName: frame.functionName || "(anonymous)",\n file: normalizeFrameUrl(frame.url),\n line: Number(frame.location && frame.location.lineNumber ? frame.location.lineNumber + 1 : 0),\n column: Number(frame.location && frame.location.columnNumber ? frame.location.columnNumber + 1 : 0),\n raw: [frame.functionName || "(anonymous)", frame.url, frame.location && frame.location.lineNumber].filter(Boolean).join(" @ "),\n scopes\n });\n }\n const description = message.params.data && (message.params.data.description || message.params.data.text);\n const reason = message.params.reason || "exception";\n const errorSummary = description || reason;\n const causalChain = [errorSummary].concat(frames.slice(0, 5).map((frame) => `${frame.file}:${frame.line}${frame.column ? ":" + frame.column : ""}`));\n fs.writeFileSync(reportPath, JSON.stringify({\n ok: true,\n runId,\n capturedAt: new Date().toISOString(),\n reason,\n errorSummary,\n causalChain,\n frames\n }, null, 2), "utf8");\n } catch (error) {\n writeFallbackReport("inspector-pause-failed", error);\n } finally {\n try {\n await post("Debugger.resume");\n } catch {}\n }\n });\n}';return await n.readFile(this.autopsyHookPath,"utf8").catch(()=>"")!==e&&await n.writeFile(this.autopsyHookPath,e,"utf8"),this.autopsyHookPath}async readAutopsyReport(e){const r=await n.readFile(e,"utf8").catch(()=>"");if(!r)return null;try{return JSON.parse(r)}catch{return null}}async finishRun(e,r,t){const n=await this.readRecord(e).catch(()=>null);n&&"timeout"!==n.status&&(n.status=r,n.exitCode=t,n.finishedAt=(new Date).toISOString(),await this.writeRecord(n),this.logger.write("info","runtime.finish",{runId:e,status:r,exitCode:t}).catch(()=>{}))}}export function mergeNodeOptions(e,r){const t=function(e){const r=[];let t="",n=null;for(const o of e.trim())'"'!==o&&"'"!==o||null!==n?o!==n?/\s/.test(o)&&null===n?t&&(r.push(t),t=""):t+=o:n=null:n=o;return t&&r.push(t),r}(e??""),n=t.filter(e=>{return r=e,!(new Set(["--enable-source-maps","--no-warnings","--trace-warnings","--trace-deprecation","--trace-uncaught"]).has(r)||[/^--max-old-space-size=\d+$/,/^--stack-trace-limit=\d+$/,/^--unhandled-rejections=(strict|throw|warn|none)$/,/^--dns-result-order=(ipv4first|verbatim)$/].some(e=>e.test(r)));var r});if(n.length>0)throw new Error(`Unsafe NODE_OPTIONS rejected: ${n.join(" ")}`);const o=[...t,...r.map(e=>e.trim())].filter(Boolean);return Array.from(new Set(o)).join(" ")}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function e(e,t,i){let n=0,s=[],a="";if("redos"===e.kind){if(n=function(e){let t=0;/\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)[+*{]/.test(e)&&(t+=55);/\((?:[^()\\]|\\.)*\|(?:[^()\\]|\\.)*\)[+*{]/.test(e)&&(t+=25);/(?:\.\*|\.\+)\)+[+*{]?/.test(e)&&(t+=20);/\[[^\]]+\][+*]\)+[+*{]?/.test(e)&&(t+=15);/\{(?:\d+,|\d+,\d+)\}/.test(e)&&/[+*]/.test(e)&&(t+=10);return Math.min(100,t)}(e.pattern),n<35)return null;s=function(e){const t=[];/\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)[+*{]/.test(e)&&t.push("Nested quantifier can cause catastrophic backtracking.");/\((?:[^()\\]|\\.)*\|(?:[^()\\]|\\.)*\)[+*{]/.test(e)&&t.push("Alternation under repetition creates ambiguous paths.");/(?:\.\*|\.\+)\)+[+*{]?/.test(e)&&t.push("Broad wildcard repetition expands the backtracking search space.");0===t.length&&t.push("Regex structure is suspicious under repeated adversarial input.");return t}(e.pattern),a=`Constrain input length before /${e.pattern}/, replace nested repetition with linear parsing, or use a non-backtracking regex strategy. Verify with the generated adversarial input and benign equivalence cases.`}else"command_injection"===e.kind?(n=80,s=["Dynamic shell execution with unescaped interpolation detected."],a="Use structured arguments in spawn/execFile instead of shell interpolation."):"path_traversal"===e.kind?(n=70,s=["Unsanitized interpolation in file system path detected."],a="Use path.basename or strict workspace sandboxing for dynamic file paths."):"sqli"===e.kind&&(n=90,s=["Raw SQL query with string interpolation detected."],a="Use parameterized queries or prepared statements.");const o={id:`${t}:${e.line}:${f(e.pattern)}`,file:t,line:e.line,kind:e.kind,pattern:e.pattern,flags:e.flags,score:n,status:"suspicious",evidence:s,recommendation:a};if(i)if("redos"===e.kind){const t=await async function(e,t){const i=function(e){const t=e.match(/\[([A-Za-z0-9])-?([A-Za-z0-9])?[^\]]*\][+*]/);if(t?.[1])return t[1];const i=e.match(/([A-Za-z0-9])(?:[+*]|\))/);return i?.[1]??"a"}(e),n=[32,128,512,2048];let s=0,a="";for(const o of n){const n=i.repeat(o)+"!",c=await r(e,t,n,900);if(a=n,c.timedOut)return{vulnerable:!0,timedOut:!0,maxMs:c.ms,input:n,evidence:[`Timed out at input length ${n.length}.`]};if(s=Math.max(s,c.ms),c.ms>250)return{vulnerable:!0,timedOut:!1,maxMs:s,input:n,evidence:[`Execution took ${Math.round(c.ms)}ms at input length ${n.length}.`]}}return{vulnerable:!1,timedOut:!1,maxMs:s,input:a,evidence:[`Worst measured execution ${Math.round(s)}ms.`]}}(e.pattern,e.flags);o.status=t.timedOut?"timeout":t.vulnerable?"confirmed":"suspicious",o.measuredMs=t.maxMs,o.exploitInputPreview=t.input.slice(0,120),o.evidence.push(...t.evidence)}else o.status="confirmed",o.exploitInputPreview="command_injection"===e.kind?"'; rm -rf / #":"sqli"===e.kind?"' OR 1=1 --":"../../../etc/passwd",o.evidence.push(`Confirmed structurally vulnerable to ${e.kind} payloads.`);return o}function t(e,t){const i=[],n=/(?<![A-Za-z0-9_$])\/((?:\\.|[^/\\\r\n])+?)\/([dgimsuvy]*)/g;for(const t of e.matchAll(n))i.push({pattern:t[1],flags:t[2]??"",line:S(e,t.index??0)});const s=/new\s+RegExp\(\s*(["'`])((?:\\.|(?!\1).)+)\1\s*(?:,\s*(["'`])([dgimsuvy]*)\3)?\s*\)/g;for(const t of e.matchAll(s))i.push({pattern:m(t[2]),flags:t[4]??"",line:S(e,t.index??0)});return i.filter(e=>e.pattern&&!/node_modules/.test(t))}function i(e,t){if(/node_modules/.test(t))return[];const i=[],n=/\b(?:fs\.readFile|fs\.writeFile|path\.join|fs\.readFileSync|fs\.writeFileSync)\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`/g;for(const t of e.matchAll(n))i.push({pattern:t[0],flags:"",line:S(e,t.index??0)});return i}function n(e,t){const i={commandInjection:[],sqli:[]};if(/node_modules/.test(t)||!/\.[cm]?[jt]sx?$/.test(t))return i;try{const n=w.extname(t).toLowerCase(),a=".js"===n||".jsx"===n||".cjs"===n||".mjs"===n?v.JS:v.TS,r=new x({useInMemoryFileSystem:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,checkJs:!1}});r.createSourceFile(`/scan${n||".ts"}`,e,{scriptKind:a,overwrite:!0}).forEachDescendant(e=>{if(!k.isCallExpression(e))return;const t=e.getArguments();if(0===t.length)return;const n=(a=e.getExpression(),k.isIdentifier(a)?a.getText():k.isPropertyAccessExpression(a)?a.getName():a.getText());var a;const r=t.filter(e=>s(e));if(0===r.length)return;/^(exec|execSync|spawn|spawnSync|eval)$/.test(n)&&i.commandInjection.push({pattern:e.getText().slice(0,500),flags:"ast",line:e.getStartLineNumber()});const o=t[0];var c;(function(e){return/^(query|execute|exec)$/.test(e)})(n)&&r.includes(o)&&(c=o.getText(),/\b(?:SELECT|INSERT|UPDATE|DELETE|UPSERT|MERGE|WITH)\b/i.test(c))&&i.sqli.push({pattern:e.getText().slice(0,500),flags:"ast",line:e.getStartLineNumber()})})}catch{return i}return i}function s(e){return!!k.isTemplateExpression(e)||(k.isBinaryExpression(e)&&e.getOperatorToken().getKind()===b.PlusToken?a(e.getLeft())||a(e.getRight()):!!(k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isTypeAssertion(e))&&s(e.getExpression()))}function a(e){return!!(k.isStringLiteral(e)||k.isNoSubstitutionTemplateLiteral(e)||k.isTemplateExpression(e))||(k.isBinaryExpression(e)&&e.getOperatorToken().getKind()===b.PlusToken?a(e.getLeft())||a(e.getRight()):!!(k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isTypeAssertion(e))&&a(e.getExpression()))}function r(e,t,i,n){return new Promise(s=>{const a=new y(O,{workerData:{pattern:e,flags:t.replace(/[gy]/g,""),input:i}});let r=!1;const o=e=>{r||(r=!0,clearTimeout(c),a.terminate().catch(()=>{}),s(e))},c=setTimeout(()=>{o({ms:n,timedOut:!0})},n);a.on("message",e=>{o({ms:Number(e.ms)||0,timedOut:!1})}),a.on("error",()=>{o({ms:0,timedOut:!1})}),a.on("exit",e=>{0!==e&&o({ms:0,timedOut:!1})})})}function o(e,t){const i=w.resolve(e,t),n=w.relative(w.resolve(e),i);if(n.startsWith("..")||w.isAbsolute(n))throw new Error(`Path escapes workspace: ${t}`);return i}function c(e,t,i){const n=l(e,t);return void 0===n?i:/^(true|yes|1)$/i.test(n)}function u(e,t,i){const n=Number(l(e,t));return Number.isFinite(n)?n:i}function l(e,t){const i=e.match(new RegExp(`^\\s*${p(t)}\\s*:\\s*(.*)$`,"m"));if(!i)return;return i[1].trim().replace(/^["']|["']$/g,"")||void 0}function d(e,t){const i=e.split(/\r?\n/g),n=[];let s=!1;for(const e of i){if(new RegExp(`^\\s*${p(t)}\\s*:`).test(e)){s=!0;continue}if(s&&/^\s*\w[\w-]*\s*:/.test(e))break;const i=e.match(/^\s*-\s*(.+?)\s*$/);s&&i&&n.push(R(i[1].replace(/^["']|["']$/g,"")))}return n}function m(e){return e.replace(/\\\\/g,"\\")}function p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(e){let t=0;for(const i of e)t=(t<<5)-t+i.charCodeAt(0)|0;return Math.abs(t).toString(36)}async function h(e){return g.access(e).then(()=>!0).catch(()=>!1)}import{promises as g}from"node:fs";import w from"node:path";import{Worker as y}from"node:worker_threads";import{Node as k,Project as x,ScriptKind as v,SyntaxKind as b}from"ts-morph";import{runCritic as P}from"../agents/critic.js";import{appendJsonl as j,clampNumber as $,collectWorkspaceFiles as E,lineNumberAt as S,readJson as M,toPosix as R,writeJson as F}from"../moonshots/common.js";import{classifySafetyWithNvidia as _,DEFAULT_NVIDIA_PII_MODELS as T,DEFAULT_NVIDIA_SAFETY_MODELS as L,detectPiiWithNvidia as I,resolveNvidiaApiKey as A}from"../nvidia-services.js";import{TimelineManager as D}from"../timeline-manager.js";const O=new URL(`data:text/javascript,${encodeURIComponent('\nimport { parentPort, workerData } from "node:worker_threads";\nconst start = process.hrtime.bigint();\nnew RegExp(workerData.pattern, workerData.flags).test(workerData.input);\nconst end = process.hrtime.bigint();\nparentPort?.postMessage({ ms: Number(end - start) / 1e6 });\n')}`);export class SelfDefendingCodeEngine{workspaceRoot;constructor(e){this.workspaceRoot=e}async run(e={}){const t=String(e.action??"scan").trim().toLowerCase();if("status"===t)return this.status();if("daemon_tick"===t)return this.daemonTick(e);if("harden"===t)return this.harden(e);if(!["scan","probe"].includes(t))throw new Error("workspace.self_defend action must be scan|probe|harden|daemon_tick|status");const i=$(e.maxFiles,500,1,5e3),n="probe"===t||!0===e.confirm,s=await this.targetFiles(e,i),a=await this.scanFiles(s,n);await this.annotateFindings(a);const r={ok:!0,action:t,scannedFiles:s.length,confirmed:a.filter(e=>"confirmed"===e.status||"timeout"===e.status).length,suspicious:a.length,findings:a,policyPath:".mesh/security/policy.yaml",logPath:".mesh/security/log.jsonl",companionStatePath:".mesh/security/companions.json",nextActions:["Run workspace.self_defend with action=probe to confirm suspicious findings.","Run workspace.self_defend with action=harden to create verified timeline patches for confirmed deterministic vulnerabilities.","Set autoMerge: true in .mesh/security/policy.yaml only after reviewing sensitive paths and promotion rules."]};return await this.persist("self_defense_scan",r),r}async harden(e){const t=await this.loadPolicy(),i=$(e.maxFiles,t.probeBudgetPerRun,1,5e3),n=await this.targetFiles(e,i),s=await this.scanFiles(n,!0);await this.annotateFindings(s);const a=[],r=new D(this.workspaceRoot);try{for(const i of s)"confirmed"!==i.status&&"timeout"!==i.status||a.push(await this.hardenFinding(i,t,e,r))}finally{await r.close()}const o={ok:!0,action:"harden",scannedFiles:n.length,confirmed:s.filter(e=>"confirmed"===e.status||"timeout"===e.status).length,patched:a.filter(e=>"timeline_ready"===e.status||"promoted"===e.status).length,promoted:a.filter(e=>"promoted"===e.status).length,findings:s,attempts:a,policy:{autoMerge:t.autoMerge,maxPatchLines:t.maxPatchLines,requiredPrecision:t.requiredPrecision,redosMaxInputLength:t.redosMaxInputLength},ledgerPath:".mesh/security/last-self-defense.json",notificationPath:".mesh/security/notifications.jsonl"};return await this.persist("self_defense_harden",o),o}async daemonTick(e){const t=await this.loadPolicy(),i=$(e.maxFiles,t.probeBudgetPerRun,1,1e3),n=await this.targetFiles(e,i),s=await this.scanFiles(n,!0);await this.annotateFindings(s);const a=w.join(this.workspaceRoot,".mesh","security","companions.json"),r={...(await M(a,{files:{}})).files??{}},o=(new Date).toISOString();for(const e of n){const t=s.filter(t=>t.file===e);r[e]={lastProbedAt:o,findingCount:t.length,confirmed:t.filter(e=>"confirmed"===e.status||"timeout"===e.status).length,highestScore:t.reduce((e,t)=>Math.max(e,t.score),0)}}const c={ok:!0,action:"daemon_tick",probedFiles:n.length,findings:s,nextWakeSeconds:s.some(e=>"confirmed"===e.status||"timeout"===e.status)?300:3600,companionStatePath:".mesh/security/companions.json"};return await F(a,{updatedAt:o,files:r}),await this.persist("self_defense_daemon_tick",c),c}async hardenFinding(e,t,i,n){if("redos"!==e.kind){const t={findingId:e.id,file:e.file,kind:e.kind,status:"not_patchable",reason:"This vulnerability class is confirmed, but no deterministic auto-patcher is enabled yet."};return await this.notify(t),t}const s=o(this.workspaceRoot,e.file),a=function(e,t,i){const n=e.split(/\r?\n/g),s=Math.max(0,t.line-1),a=Math.min(n.length,s+12);for(let e=s;e<a;e+=1){const s=n[e].match(/\.test\(\s*([A-Za-z_$][\w$]*)\s*\)/);if(!s)continue;const a=s[1],r=n.slice(Math.max(0,e-3),e+1).join("\n");if(new RegExp(`${p(a)}\\.length\\s*>\\s*\\d+`).test(r))return null;const o=`${n[e].match(/^\s*/)?.[0]??""}if (typeof ${a} === "string" && ${a}.length > ${i}) return false;`;return{content:[...n.slice(0,e),o,...n.slice(e)].join("\n"),strategy:`Inserted ReDoS length guard before ${a}-driven regex evaluation.`,diffLines:1,diffPreview:[`--- ${t.file}`,`+++ ${t.file}`,`@@ line ${e+1}`,`+${o}`].join("\n")}}return null}(await g.readFile(s,"utf8"),e,t.redosMaxInputLength);if(!a){const t={findingId:e.id,file:e.file,kind:e.kind,status:"not_patchable",reason:"Confirmed ReDoS, but the call site is not a simple guarded .test(identifier) pattern."};return await this.notify(t),t}const r=function(e,t){const i=R(e);return t.some(e=>i===e||i.startsWith(`${e.replace(/\/+$/,"")}/`)||i.includes(e))}(e.file,t.sensitivePaths),c=await n.create({name:`self-defense-${e.kind}-${f(e.id)}`}),u=w.join(c.timeline.root,e.file);await g.mkdir(w.dirname(u),{recursive:!0}),await g.writeFile(u,a.content,"utf8");const l=String(i.verificationCommand??t.verificationCommand??await async function(e){const t=await g.readFile(w.join(e,"package.json"),"utf8").catch(()=>"");if(t)try{const e=JSON.parse(t);if(e.scripts?.test)return"npm test";if(e.scripts?.typecheck)return"npm run typecheck";if(e.scripts?.build)return"npm run build"}catch{return""}return""}(this.workspaceRoot)).trim();let d={executed:!1,ok:!1};if(l){const e=await n.run({timelineId:c.timeline.id,command:l,timeoutMs:$(i.timeoutMs,12e4,5e3,6e5)});d={executed:!0,command:l,ok:e.ok,exitCode:e.exitCode}}const m=P({diffPreview:a.diffPreview,verificationOk:d.ok}),h=t.autoMerge&&!r&&a.diffLines<=t.maxPatchLines&&d.ok&&m.ok&&e.score/100>=t.requiredPrecision,y={findingId:e.id,file:e.file,kind:e.kind,status:h?"promoted":d.ok&&m.ok?"timeline_ready":"blocked",reason:h?"Auto-promoted by self-defense policy.":r?"Timeline patch ready, but sensitive paths require manual review.":d.executed&&!d.ok?"Timeline patch created, but verification failed.":d.executed?m.ok?"Timeline patch ready for review; autoMerge is disabled or confidence threshold not met.":"Timeline patch blocked by critic findings.":"Timeline patch created, but no verification command was available.",strategy:a.strategy,timelineId:c.timeline.id,diffLines:a.diffLines,verification:d,critic:m};return h?y.promotion=await n.promote({timelineId:c.timeline.id}):await this.notify(y),y}async annotateFindings(e){const t=A();if(!t||0===e.length)return;const i=e.filter(e=>"confirmed"===e.status||"timeout"===e.status).slice(0,8);await Promise.all(i.map(async e=>{const i=[`file: ${e.file}:${e.line}`,`kind: ${e.kind}`,`pattern: ${e.pattern}`,`flags: ${e.flags}`,`evidence: ${e.evidence.join(" | ")}`,e.exploitInputPreview?`exploit: ${e.exploitInputPreview}`:""].filter(Boolean).join("\n"),[n,s,a]=await Promise.all([_(i,process.env.MESH_SAFETY_MODEL||L[0],t).catch(()=>{}),_(i,process.env.MESH_SAFETY_MODEL_SECONDARY||L[1],t).catch(()=>{}),I(i,process.env.MESH_PII_MODEL||T[0],t).catch(()=>{})]);e.aiSafety={guard:n,secondaryGuard:s,piiReview:a}}))}async scanFiles(s,a){const r=[];for(const c of s){const s=o(this.workspaceRoot,c),u=await g.readFile(s,"utf8").catch(()=>"");if(!u)continue;const l=n(u,c),d=[...t(u,c).map(e=>({...e,kind:"redos"})),...l.commandInjection.map(e=>({...e,kind:"command_injection"})),...i(u,c).map(e=>({...e,kind:"path_traversal"})),...l.sqli.map(e=>({...e,kind:"sqli"}))];for(const t of d){const i=await e(t,c,a);i&&r.push(i)}}return r.sort((e,t)=>t.score-e.score),r}async targetFiles(e,t){return"string"==typeof e.path&&e.path.trim()?[R(e.path.trim())]:await E(this.workspaceRoot,{maxFiles:t})}async status(){const e=await this.loadPolicy(),t=await M(w.join(this.workspaceRoot,".mesh","security","last-self-defense.json"),null);return{ok:!0,action:"status",policyPath:".mesh/security/policy.yaml",sensitivePath:".mesh/security/sensitive.yaml",logPath:".mesh/security/log.jsonl",companionStatePath:".mesh/security/companions.json",supportedProbeClasses:["redos","command_injection","path_traversal","sqli"],supportedAutoPatchClasses:["redos"],autoMergeDefault:e.autoMerge,last:t}}async notify(e){await j(w.join(this.workspaceRoot,".mesh","security","notifications.jsonl"),{at:(new Date).toISOString(),kind:"self_defense_notification",attempt:e})}async persist(e,t){await this.ensureDefaults(),await F(w.join(this.workspaceRoot,".mesh","security","last-self-defense.json"),t),await j(w.join(this.workspaceRoot,".mesh","security","log.jsonl"),{at:(new Date).toISOString(),kind:e,result:t})}async loadPolicy(){await this.ensureDefaults();const e=w.join(this.workspaceRoot,".mesh","security"),t=await g.readFile(w.join(e,"policy.yaml"),"utf8").catch(()=>""),i=await g.readFile(w.join(e,"sensitive.yaml"),"utf8").catch(()=>"");return{autoMerge:c(t,"autoMerge",!1),maxPatchLines:u(t,"maxPatchLines",20),requiredPrecision:u(t,"requiredPrecision",.95),probeBudgetPerRun:u(t,"probeBudgetPerRun",50),redosMaxInputLength:u(t,"redosMaxInputLength",2048),verificationCommand:l(t,"verificationCommand"),sensitivePaths:d(i,"paths")}}async ensureDefaults(){const e=w.join(this.workspaceRoot,".mesh","security");await g.mkdir(e,{recursive:!0});const t=w.join(e,"policy.yaml"),i=w.join(e,"sensitive.yaml");await h(t)||await g.writeFile(t,["autoMerge: false","maxPatchLines: 20","requiredPrecision: 0.95","probeBudgetPerRun: 50","redosMaxInputLength: 2048","# Optional. Example: npm test",'verificationCommand: ""',""].join("\n"),"utf8"),await h(i)||await g.writeFile(i,["# Paths here always require manual review.","paths:"," - src/auth"," - src/security"," - .env",""].join("\n"),"utf8")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from"node:crypto";import s from"node:fs/promises";import e from"node:os";import a from"node:path";const o=a.join(e.homedir(),".config","mesh","sessions");export class SessionCapsuleStore{workspaceRoot;statePath;constructor(s){this.workspaceRoot=s;const e=t.createHash("sha1").update(s).digest("hex");this.statePath=a.join(o,`${e}.json`)}async load(){try{const t=await s.readFile(this.statePath,"utf8"),e=JSON.parse(t),a=e?.capsule;if(!a)return null;return"string"==typeof a.summary&&a.summary.length>0&&"string"==typeof a.generatedAt&&"number"==typeof a.sourceMessages&&"number"==typeof a.retainedMessages&&!isNaN(a.sourceMessages)&&!isNaN(a.retainedMessages)?a:(console.warn(`[Mesh:DataQuality] Corrupt session state detected at ${this.statePath}. Discarding invalid capsule.`),null)}catch{return null}}async save(t){const e={workspaceRoot:this.workspaceRoot,updatedAt:(new Date).toISOString(),capsule:t};await s.mkdir(a.dirname(this.statePath),{recursive:!0}),await s.writeFile(this.statePath,JSON.stringify(e,null,2),"utf8")}async clear(){try{await s.unlink(this.statePath)}catch{}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as t}from"node:fs";import{statSync as s,readFileSync as e,unlinkSync as r}from"node:fs";import i from"node:path";export class DefaultSessionManager{workspaceRoot;sessionPath;turns=[];autoSaveTimer=null;stopped=!1;dirty=!1;flushInProgress=!1;constructor(t){this.workspaceRoot=t,this.sessionPath=i.join(t,".mesh/sessions","interrupted.jsonl")}start(){if(this.autoSaveTimer)return;const t=async()=>{await this.autoSave(),this.stopped||(this.autoSaveTimer=setTimeout(()=>{t()},3e4),this.autoSaveTimer.unref?.())};this.autoSaveTimer=setTimeout(()=>{t()},3e4),this.autoSaveTimer.unref?.()}async stop(){this.stopped||(this.stopped=!0,this.autoSaveTimer&&(clearTimeout(this.autoSaveTimer),this.autoSaveTimer=null),this.dirty&&await this.flush(),await this.clearInterruptedSession())}addMessage(t,s,e){this.stopped||(this.turns.push({role:t,content:s,toolCalls:e,timestamp:(new Date).toISOString()}),this.dirty=!0)}getTranscript(){return[...this.turns]}hasInterruptedSession(){try{return s(this.sessionPath).size>0}catch{return!1}}getInterruptedSession(){if(!this.hasInterruptedSession())return null;try{const t=e(this.sessionPath,"utf8").split("\n").filter(Boolean),s=[];for(const e of t)try{s.push(JSON.parse(e))}catch{}return s.length>0?s:null}catch{return null}}clearInterruptedSession(){try{r(this.sessionPath)}catch{}}async autoSave(){this.dirty&&!this.flushInProgress&&await this.flush()}async flush(){if(0!==this.turns.length){this.flushInProgress=!0;try{await t.mkdir(i.dirname(this.sessionPath),{recursive:!0});const s=this.turns.map(t=>JSON.stringify(t)).join("\n")+"\n";await t.writeFile(this.sessionPath,s,"utf8"),this.dirty=!1}catch(t){console.error("[SessionManager] Failed to persist session:",t)}finally{this.flushInProgress=!1}}}}export class NoopSessionManager{start(){}stop(){return Promise.resolve()}addMessage(){}getTranscript(){return[]}hasInterruptedSession(){return!1}getInterruptedSession(){return null}clearInterruptedSession(){}}export function buildSessionManager(t){return new DefaultSessionManager(t)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function o(t){const e={};for(const[r,s]of Object.entries(t))/token|secret|password|api[_-]?key|authorization/i.test(r)?e[r]="[redacted]":s&&"object"==typeof s&&!Array.isArray(s)?e[r]=o(s):e[r]=s;return e}import{promises as t}from"node:fs";import e from"node:os";import r from"node:path";export class StructuredLogger{workspaceRoot;logPath;constructor(o){this.workspaceRoot=o;const t=process.env.MESH_STATE_DIR||r.join(e.homedir(),".config","mesh"),s=(new Date).toISOString().slice(0,10);this.logPath=r.join(t,"logs",`${s}.jsonl`)}async write(e,s,i){const a={ts:(new Date).toISOString(),level:e,event:s,workspace:this.workspaceRoot,data:i?o(i):void 0};await t.mkdir(r.dirname(this.logPath),{recursive:!0}),await t.appendFile(this.logPath,JSON.stringify(a)+"\n","utf8")}}
|
package/dist/support.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile as t}from"node:child_process";import o from"node:os";import r from"node:path";import{promisify as n}from"node:util";const e=n(t);export async function collectSupportInfo(t,r=process.cwd()){const[n,a,i,c]=await Promise.all([e("npm",["--version"]).then(t=>t.stdout.trim()).catch(()=>{}),e("npm",["config","get","prefix"]).then(t=>t.stdout.trim()).catch(()=>{}),e("git",["branch","--show-current"],{cwd:r}).then(t=>t.stdout.trim()).catch(()=>{}),e("git",["status","--short"],{cwd:r}).then(t=>t.stdout.trim()).catch(()=>{})]);return{timestamp:(new Date).toISOString(),meshVersion:t,cwd:r,platform:`${o.type()} ${o.release()}`,arch:`${o.platform()}/${o.arch()}`,node:process.version,npm:n,npmPrefix:a,gitBranch:i,gitStatus:c}}export function formatSupportInfo(t){const o=["Mesh Support Info","",`timestamp: ${t.timestamp}`,`mesh: ${t.meshVersion}`,`node: ${t.node}`,`npm: ${t.npm??"unavailable"}`,`npm prefix: ${t.npmPrefix??"unavailable"}`,`platform: ${t.platform}`,`arch: ${t.arch}`,`cwd: ${t.cwd}`,"repo: "+(t.gitBranch?`branch ${t.gitBranch}`:"not a git worktree or branch unavailable"),`git status: ${t.gitStatus?t.gitStatus.replace(/\n/g,"\\n"):"clean or unavailable"}`,"","For bug reports, also include:"," mesh doctor full"," the exact command or prompt you ran"," the full error text"];return t.npmPrefix&&o.push("",`If global mesh is not found, verify PATH contains: ${r.join(t.npmPrefix,"bin")}`),`${o.join("\n")}\n`}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function e(){const e=await async function(){const e=[process.env.MESH_CHROME_PATH,"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",await t("google-chrome"),await t("google-chrome-stable"),await t("chromium"),await t("chromium-browser"),await t("microsoft-edge")].filter(e=>Boolean(e)).find(e=>a(e));if(!e)throw new Error("Chrome/Chromium not found. Set MESH_CHROME_PATH to a Chromium-compatible executable.");return e}(),r=await async function(){return new Promise((e,t)=>{const r=l.createServer();r.listen(0,"127.0.0.1",()=>{const o=r.address();r.close(()=>{o&&"object"==typeof o?e(o.port):t(new Error("Could not allocate a local CDP port."))})}),r.on("error",t)})}(),o=await s.mkdtemp(f.join(u.tmpdir(),"mesh-chrome-")),n=m(e,["--headless=new","--disable-gpu","--hide-scrollbars","--no-first-run","--no-default-browser-check","--disable-background-networking","--disable-dev-shm-usage",`--remote-debugging-port=${r}`,`--user-data-dir=${o}`,"about:blank"],{stdio:["ignore","pipe","pipe"]});return n.unref(),await async function(e,t){let r="";for(let o=0;o<60;o+=1){if(null!==t.exitCode)throw new Error(`Chrome exited before CDP became available. exitCode=${t.exitCode}`);try{const t=await fetch(`http://127.0.0.1:${e}/json/version`);if(t.ok)return;r=`${t.status} ${t.statusText}`}catch(e){r=e.message}await i(100)}throw new Error(`Timed out waiting for Chrome CDP on port ${e}: ${r}`)}(r,n),{child:n,port:r,userDataDir:o,executable:e}}async function t(e){try{const{stdout:t}=await w("which",[e]);return t.trim()||null}catch{return null}}function r(e,t){const r=Buffer.alloc(e.length);for(let o=0;o<e.length;o+=1)r[o]=e[o]^t[o%4];return r}function o(e,t,r,o){const n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,Math.round(n))):o}function n(e){return 0===p("which",[e],{stdio:"ignore"}).status}function i(e){return new Promise(t=>setTimeout(t,e))}import{promises as s}from"node:fs";import{existsSync as a,readFileSync as c}from"node:fs";import l from"node:net";import u from"node:os";import f from"node:path";import h from"node:crypto";import{execFile as d,spawn as m,spawnSync as p}from"node:child_process";import{promisify as g}from"node:util";const w=g(d);export async function captureFrontendPreview(t){const r=function(e){const t=e.trim();if(!t)throw new Error("frontend.preview requires url");return/^https?:\/\//i.test(t)?t:/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?/i.test(t)?`http://${t}`:t}(t.url),l=o(t.width,320,3840,1280),h=o(t.height,240,2400,800),d=o(t.waitMs,0,15e3,1200),m=t.outputPath||f.join(u.tmpdir(),`mesh-preview-${Date.now()}.png`),g=await e();let w=null;try{const e=await async function(e){const t=await fetch(`http://127.0.0.1:${e}/json/new?about:blank`,{method:"PUT"});if(t.ok){const e=await t.json();if(e.webSocketDebuggerUrl)return e}const r=await fetch(`http://127.0.0.1:${e}/json/list`),o=(await r.json()).find(e=>e.webSocketDebuggerUrl);if(!o)throw new Error("Chrome CDP did not expose a page target.");return o}(g.port);w=await b.connect(e.webSocketDebuggerUrl),await w.send("Page.enable"),await w.send("Runtime.enable"),await w.send("Emulation.setDeviceMetricsOverride",{width:l,height:h,deviceScaleFactor:1,mobile:!1}),await w.send("Page.navigate",{url:r}),await i(d);const o=await w.send("Page.captureScreenshot",{format:"png",fromSurface:!0,captureBeyondViewport:!1}),u=Buffer.from(String(o.data??""),"base64");await s.mkdir(f.dirname(m),{recursive:!0}),await s.writeFile(m,u);let y=pickTerminalImageProtocol(t.protocol??"auto"),k=!1;if(!1!==t.render){const e=function(e,t,r){if("kitty"===t){const t=a(e)?c(e).toString("base64"):"";if(!t)return{rendered:!1,protocol:"none"};const o=t.match(/.{1,4096}/g)??[];for(let e=0;e<o.length;e+=1){const t=e===o.length-1?0:1,n=0===e?`_Ga=T,f=100,m=${t};`:`_Gm=${t};`;r?.(`${n}${o[e]}\\`)}return r?.("\n"),{rendered:!0,protocol:"kitty"}}if("iterm2"===t){const t=a(e)?c(e).toString("base64"):"";return t?(r?.(`]1337;File=inline=1;preserveAspectRatio=1:${t}\n`),{rendered:!0,protocol:"iterm2"}):{rendered:!1,protocol:"none"}}if("sixel"===t){if(n("img2sixel")){const t=p("img2sixel",[e],{encoding:"utf8"});if(0===t.status&&t.stdout)return r?.(t.stdout+"\n"),{rendered:!0,protocol:"sixel"}}if(n("chafa")){const t=p("chafa",["-f","sixels",e],{encoding:"utf8"});if(0===t.status&&t.stdout)return r?.(t.stdout+"\n"),{rendered:!0,protocol:"sixel"}}}return{rendered:!1,protocol:"external"===t?"external":"none"}}(m,y,t.onProgress);k=e.rendered,y=e.protocol}return{ok:!0,url:r,screenshotPath:m,width:l,height:h,protocol:y,rendered:k,chromeExecutable:g.executable}}finally{w?.close(),await async function(e){if(null!==e.exitCode||e.killed)return;e.kill("SIGTERM"),await new Promise(t=>{const r=setTimeout(()=>t(!1),1500);e.once("close",()=>{clearTimeout(r),t(!0)})})||(e.kill("SIGKILL"),await new Promise(e=>setTimeout(e,100)))}(g.child),await s.rm(g.userDataDir,{recursive:!0,force:!0}).catch(()=>{})}}export function pickTerminalImageProtocol(e="auto"){return"auto"!==e?e:process.env.KITTY_WINDOW_ID||/kitty/i.test(process.env.TERM||"")?"kitty":/iTerm\.app/i.test(process.env.TERM_PROGRAM||"")||/WezTerm/i.test(process.env.TERM_PROGRAM||"")?"iterm2":n("img2sixel")||n("chafa")?"sixel":"none"}class b{socket;nextId=1;buffer=Buffer.alloc(0);textFragments="";pending=new Map;constructor(e){this.socket=e,this.socket.on("data",e=>this.onData(e)),this.socket.on("error",e=>this.rejectAll(e)),this.socket.on("close",()=>this.rejectAll(new Error("CDP socket closed")))}static async connect(e){const t=new URL(e),r=l.createConnection({host:t.hostname,port:Number(t.port)});await new Promise((e,t)=>{r.once("connect",e),r.once("error",t)});const o=h.randomBytes(16).toString("base64");r.write([`GET ${t.pathname}${t.search} HTTP/1.1`,`Host: ${t.host}`,"Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Key: ${o}`,"Sec-WebSocket-Version: 13","",""].join("\r\n"));let n=Buffer.alloc(0),i=Buffer.alloc(0);await new Promise((e,t)=>{const o=s=>{n=Buffer.concat([n,s]);const a=n.indexOf("\r\n\r\n");if(-1===a)return;r.off("data",o);const c=n.slice(0,a).toString("utf8");/^HTTP\/1\.1 101/i.test(c)?(i=n.slice(a+4),e()):t(new Error(`CDP websocket handshake failed: ${c.split("\r\n")[0]}`))};r.on("data",o),r.once("error",t)});const s=new b(r);return i.length>0&&s.onData(i),s}send(e,t={}){const r=this.nextId++,o=JSON.stringify({id:r,method:e,params:t});return this.socket.write(function(e){function t(e,t=o){const r=Buffer.alloc(e.length);for(let o=0;o<e.length;o+=1)r[o]=e[o]^t[o%4];return r}const r=Buffer.from(e,"utf8"),o=h.randomBytes(4),n=r.length<126?2:r.length<=65535?4:10,i=Buffer.alloc(n+4+r.length);return i[0]=129,r.length<126?(i[1]=128|r.length,o.copy(i,2),t(r).copy(i,6)):r.length<=65535?(i[1]=254,i.writeUInt16BE(r.length,2),o.copy(i,4),t(r,o).copy(i,8)):(i[1]=255,i.writeBigUInt64BE(BigInt(r.length),2),o.copy(i,10),t(r,o).copy(i,14)),i}(o)),new Promise((t,o)=>{const n=setTimeout(()=>{this.pending.delete(r)&&o(new Error(`CDP command timed out: ${e}`))},3e4);this.pending.set(r,{resolve:t,reject:o,timer:n})})}close(){try{this.socket.end(),this.socket.destroy()}catch{}}onData(e){for(this.buffer=Buffer.concat([this.buffer,e]);this.buffer.length>=2;){const e=this.buffer[0],t=this.buffer[1],o=Boolean(128&e),n=15&e;let i=2,s=127&t;if(126===s){if(this.buffer.length<i+2)return;s=this.buffer.readUInt16BE(i),i+=2}else if(127===s){if(this.buffer.length<i+8)return;const e=this.buffer.readBigUInt64BE(i);if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("CDP frame too large");s=Number(e),i+=8}let a=null;if(Boolean(128&t)){if(this.buffer.length<i+4)return;a=Buffer.from(this.buffer.subarray(i,i+4)),i+=4}if(this.buffer.length<i+s)return;let c=Buffer.from(this.buffer.subarray(i,i+s));if(this.buffer=this.buffer.slice(i+s),a&&(c=r(c,a)),8===n)return void this.close();if((1===n||0===n)&&(this.textFragments+=c.toString("utf8"),o)){const e=this.textFragments;this.textFragments="",this.handleMessage(e)}}}handleMessage(e){const t=JSON.parse(e);if(!t.id)return;const r=this.pending.get(t.id);r&&(this.pending.delete(t.id),clearTimeout(r.timer),t.error?r.reject(new Error(t.error.message||JSON.stringify(t.error))):r.resolve(t.result??{}))}rejectAll(e){for(const t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{exec as t}from"node:child_process";import{promisify as e}from"node:util";const i=e(t);export class SymptomBisectEngine{workspaceRoot;timelines;constructor(t,e){this.workspaceRoot=t,this.timelines=e}async run(t){const e=t.symptom.trim();if(!e)throw new Error("workspace.symptom_bisect requires symptom");const i=(t.verificationCommand||this.inferVerificationCommand(e)).trim(),o=Math.max(10,Math.min(t.searchDepth??50,200)),s=await this.readRecentCommits(o);if(s.length<3)return{ok:!1,symptom:e,message:"Not enough commits to bisect."};const r=s[0],n=s[s.length-1],m=await this.verifyCommit(r,i),a=await this.verifyCommit(n,i);if(m.ok===a.ok)return{ok:!1,symptom:e,verificationCommand:i,message:"Verification signal is not divergent across search window; refine symptom or command.",newest:r,oldest:n};const c=!1===m.ok;let p=0,d=s.length-1;const h=[];for(;d-p>1;){const t=Math.floor((p+d)/2),e=s[t],o=await this.verifyCommit(e,i);h.push({commit:e,ok:o.ok,exitCode:o.exitCode});(c?!o.ok:o.ok)?p=t:d=t}const u=s[p];return{ok:!0,symptom:e,verificationCommand:i,culpritCommit:u,authorHint:await this.readAuthorForCommit(u),probes:h,message:`Regression likely introduced in ${u}.`}}inferVerificationCommand(t){return/redirect|login|button|page|ui|click/i.test(t)?"npm test -- --grep redirect || npm test":/api|endpoint|request|response/i.test(t)?"npm test -- --grep api || npm test":"npm test"}async readRecentCommits(t){const{stdout:e}=await i(`git rev-list --max-count=${t} HEAD`,{cwd:this.workspaceRoot});return e.split(/\r?\n/g).map(t=>t.trim()).filter(Boolean)}async readAuthorForCommit(t){try{const{stdout:e}=await i(`git show -s --format='%an <%ae>' ${t}`,{cwd:this.workspaceRoot});return e.trim()}catch{return"unknown"}}async verifyCommit(t,e){const i=await this.timelines.create({name:`bisect-${t.slice(0,7)}`,baseRef:t}),o=await this.timelines.run({timelineId:i.timeline.id,command:e,timeoutMs:18e4});return{ok:o.ok,exitCode:o.exitCode}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t){return t.split(/\r?\n/g).map(t=>t.trim()).filter(Boolean).reduce((t,e)=>{const i=e.match(/^(\d+|-)\t(\d+|-)\t/);if(!i)return t;return t+("-"===i[1]?0:Number(i[1]))+("-"===i[2]?0:Number(i[2]))},0)}function e(t){const e=new Set;for(const i of t.split(/\r?\n/g)){const t=i.trim();t&&e.add(t)}return Array.from(e)}async function i(t,e,i,r){return new Promise(o=>{const a=m(t,e,{cwd:r});let n="",s="";a.stdout.on("data",t=>{n+=t.toString()}),a.stderr.on("data",t=>{s+=t.toString()}),a.on("error",t=>{o({ok:!1,stdout:n,stderr:`${s}\n${t.message}`})}),a.on("close",t=>{o({ok:0===t,stdout:n,stderr:s})}),a.stdin.write(i),a.stdin.end()})}async function r(t,e){try{const{stdout:i}=await w("git",t,{cwd:e,maxBuffer:5242880});return i}catch(t){return t.stdout||""}}function o(t,e=12e3){if(t.length<=e)return t;const i=t.slice(0,Math.floor(.35*e)),r=t.slice(-Math.floor(.55*e));return`${i}\n\n... [${t.length-i.length-r.length} bytes omitted] ...\n\n${r}`}import{promises as a}from"node:fs";import n from"node:path";import s from"node:os";import d from"node:crypto";import{execFile as c,spawn as m}from"node:child_process";import{promisify as l}from"node:util";import{StructuredLogger as u}from"./structured-logger.js";import{parseAllowedCommand as h}from"./command-safety.js";const w=l(c);export class TimelineManager{workspaceRoot;workspaceHash;basePath;runningChildren=new Set;logger;constructor(t){this.workspaceRoot=t,this.workspaceHash=d.createHash("sha256").update(n.resolve(t)).digest("hex").slice(0,24);const e=process.env.MESH_STATE_DIR||n.join(s.homedir(),".config","mesh"),i=function(t,e){const i=n.relative(n.resolve(t),n.resolve(e));return""===i||!i.startsWith("..")&&!n.isAbsolute(i)}(this.workspaceRoot,e)?n.join(s.tmpdir(),"mesh-state"):e;this.basePath=n.join(i,"timelines",this.workspaceHash),this.logger=new u(t)}async create(t={}){const e=`tl-${Date.now().toString(36)}-${d.randomBytes(3).toString("hex")}`,i=(t.name||e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"timeline";const r=n.join(this.basePath,e,"workspace"),o=t.baseRef?.trim()||"HEAD";await a.mkdir(n.dirname(r),{recursive:!0});let s="copy";try{await w("git",["rev-parse","--is-inside-work-tree"],{cwd:this.workspaceRoot}),await w("git",["worktree","add","--detach",r,o],{cwd:this.workspaceRoot,maxBuffer:1048576}),s="git-worktree"}catch{await async function(t,e){await a.mkdir(e,{recursive:!0}),await a.cp(t,e,{recursive:!0,filter:e=>{const i=n.relative(t,e).split(n.sep).join("/");return!i||!/(^|\/)(\.git|node_modules|dist|coverage|\.next|\.turbo|\.cache)(\/|$)/.test(i)}})}(this.workspaceRoot,r)}const c={id:e,name:i,kind:s,root:r,baseRef:o,status:"created",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString(),patches:[],commands:[],verdict:"unknown"};return await this.writeRecord(c),this.logger.write("info","timeline.create",{timelineId:e,kind:s,baseRef:o,root:r}).catch(()=>{}),{ok:!0,timeline:c}}async list(){await a.mkdir(this.basePath,{recursive:!0});const t=await a.readdir(this.basePath,{withFileTypes:!0}).catch(()=>[]),e=[];for(const i of t){if(!i.isDirectory())continue;const t=await this.readRecord(i.name).catch(()=>null);t&&e.push(t)}return e.sort((t,e)=>e.updatedAt.localeCompare(t.updatedAt)),{ok:!0,timelines:e}}async close(){for(const t of this.runningChildren)t.killed||t.kill("SIGTERM");this.runningChildren.clear(),this.logger.write("info","timeline.shutdown",{}).catch(()=>{})}async applyPatch(t){const e=await this.readRecord(t.timelineId),r=t.patch??"";if(!r.trim())throw new Error("workspace.timeline_apply_patch requires patch");const o=n.join(this.basePath,e.id,"patches",`${Date.now()}.patch`);await a.mkdir(n.dirname(o),{recursive:!0}),await a.writeFile(o,r,"utf8");const s=await i("git",["apply","--whitespace=nowarn","-"],r,e.root);return s.ok?(e.status="patched",e.updatedAt=(new Date).toISOString(),e.patches.push({path:o,appliedAt:e.updatedAt,bytes:Buffer.byteLength(r,"utf8")}),await this.writeRecord(e),{ok:!0,timelineId:e.id,message:"Patch applied in isolated timeline."}):{ok:!1,timelineId:e.id,message:"Patch rejected by git apply.",stderr:s.stderr}}async run(t){const e=await this.readRecord(t.timelineId),i=t.command?.trim();if(!i)throw new Error("workspace.timeline_run requires command");e.status="running",e.updatedAt=(new Date).toISOString(),await this.writeRecord(e);const r=n.join(this.basePath,e.id,"runs",Date.now().toString());await a.mkdir(r,{recursive:!0});const s=n.join(r,"stdout.log"),d=n.join(r,"stderr.log"),c=(new Date).toISOString(),l=await async function(t,e,i,r){return new Promise(o=>{let a;try{a=h(t)}catch(t){return void o({ok:!1,exitCode:126,stdout:"",stderr:t.message})}const n=m(a.command,a.args,{cwd:e});r.add(n);let s="",d="",c=!1;const l=setTimeout(()=>{c=!0,n.kill("SIGTERM")},i);n.stdout.on("data",t=>{s+=t.toString()}),n.stderr.on("data",t=>{d+=t.toString()}),n.on("error",t=>{r.delete(n),clearTimeout(l),o({ok:!1,exitCode:1,stdout:s,stderr:`${d}\n${t.message}`})}),n.on("close",t=>{r.delete(n),clearTimeout(l);const e=c?124:t??0;o({ok:0===e,exitCode:e,stdout:s,stderr:c?`[TIMEOUT after ${Math.round(i/1e3)}s]\n${d}`:d})})})}(i,e.root,t.timeoutMs??12e4,this.runningChildren),u=(new Date).toISOString();await a.writeFile(s,l.stdout,"utf8"),await a.writeFile(d,l.stderr,"utf8");const w={command:i,startedAt:c,finishedAt:u,durationMs:Math.max(0,Date.parse(u)-Date.parse(c)),exitCode:l.exitCode,ok:l.ok,stdoutPath:s,stderrPath:d};return e.commands.push(w),e.status=l.ok?"passed":"failed",e.verdict=l.ok?"pass":"fail",e.updatedAt=w.finishedAt,await this.writeRecord(e),this.logger.write("info","timeline.run.finish",{timelineId:e.id,command:i,ok:l.ok,exitCode:l.exitCode}).catch(()=>{}),{ok:l.ok,timelineId:e.id,exitCode:l.exitCode,stdout:o(l.stdout),stderr:o(l.stderr),commandRecord:w}}async compare(i){const a=Array.isArray(i.timelineIds)?i.timelineIds:[];if(0===a.length)throw new Error("workspace.timeline_compare requires timelineIds");const n=[];for(const i of a){const a=await this.readRecord(i),s=await r(["diff","--stat"],a.root),d=await r(["diff","--numstat"],a.root),c=await r(["diff","--name-only"],a.root),m=await r(["diff","--","."],a.root),l=a.commands.at(-1);n.push({id:a.id,name:a.name,kind:a.kind,status:a.status,verdict:a.verdict??"unknown",root:a.root,diffStat:s||"No tracked diff.",changedFiles:e(c),changedLineCount:t(d),diffPreview:o(m,8e3),lastCommand:l,commandDurationMs:l?.durationMs??null})}return{ok:!0,comparisons:n}}async promote(t){const e=await this.readRecord(t.timelineId);if("pass"!==e.verdict)return{ok:!1,timelineId:e.id,message:"Timeline has not passed verification. Run workspace.timeline_run first or review the failed verdict."};const o=await r(["diff","--binary"],e.root);if(!o.trim())return{ok:!0,timelineId:e.id,message:"No tracked diff to promote."};const a=await i("git",["apply","--whitespace=nowarn","-"],o,this.workspaceRoot);return a.ok?(e.status="promoted",e.promotedAt=(new Date).toISOString(),e.updatedAt=e.promotedAt,await this.writeRecord(e),{ok:!0,timelineId:e.id,message:"Timeline diff promoted to the main workspace."}):{ok:!1,timelineId:e.id,message:"Promotion failed while applying timeline diff to main workspace.",stderr:a.stderr}}async readRecord(t){const e=function(t){const e=t.replace(/[^a-zA-Z0-9._-]+/g,"");if(!e)throw new Error("Invalid timeline id");return e}(t),i=await a.readFile(n.join(this.basePath,e,"timeline.json"),"utf8");return JSON.parse(i)}async writeRecord(t){await a.mkdir(n.join(this.basePath,t.id),{recursive:!0}),await a.writeFile(n.join(this.basePath,t.id,"timeline.json"),JSON.stringify(t,null,2),"utf8")}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(t,n,o,s,u){if(void 0===t&&Object.prototype.hasOwnProperty.call(n,"default"))return function(e){return null==e?e:JSON.parse(JSON.stringify(e))}(n.default);if(void 0!==t){if(n.enum&&!n.enum.includes(t))return s.push(`${o} must be one of ${n.enum.map(e=>JSON.stringify(e)).join(", ")}`),t;switch(n.type){case"object":return function(t,n,o,s,u){if(!r(t))return s.push(`${o} must be an object`),t;const i=n.properties??{},a=new Set(n.required??[]),p={...t};for(const e of a)void 0===p[e]&&s.push(`${o}.${e} is required`);for(const[r,t]of Object.entries(i)){const n=e(p[r],t,`${o}.${r}`,s,u);(void 0!==n||Object.prototype.hasOwnProperty.call(t,"default"))&&(p[r]=n)}for(const e of Object.keys(p))Object.prototype.hasOwnProperty.call(i,e)||u.push(`${o}.${e} is not declared in inputSchema`);return p}(t,n,o,s,u);case"array":return function(r,t,n,o,s){if(!Array.isArray(r))return o.push(`${n} must be an array`),r;if(!t.items)return r;return r.map((r,u)=>e(r,t.items,`${n}[${u}]`,o,s))}(t,n,o,s,u);case"string":return"string"!=typeof t&&s.push(`${o} must be a string`),t;case"number":return"number"==typeof t&&Number.isFinite(t)||s.push(`${o} must be a finite number`),t;case"integer":return"number"==typeof t&&Number.isInteger(t)||s.push(`${o} must be an integer`),t;case"boolean":return"boolean"!=typeof t&&s.push(`${o} must be a boolean`),t;case void 0:return t;default:return u.push(`${o} uses unsupported schema type '${n.type}'`),t}}}function r(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))}export class ToolInputValidationError extends Error{toolName;issues;constructor(e,r){super(`Invalid input for ${e}: ${r.join("; ")}`),this.toolName=e,this.issues=r,this.name="ToolInputValidationError"}}export function validateToolInput(t,n,o){if(!function(e){return r(e)}(o))return{args:n??{},warnings:[]};const s=[],u=[],i=e(r(n)?n:{},o,t,s,u);if(s.length>0)throw new ToolInputValidationError(t,s);return{args:r(i)?i:{},warnings:u}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as e,execFileSync as t}from"node:child_process";import i from"node:fs";import n from"node:fs/promises";import o from"node:path";import r from"node:os";export class VoiceManager{config;isRecording=!1;constructor(e={}){this.config=e,this.config.voiceLanguage=e.voiceLanguage||"auto",this.config.voiceSpeed=e.voiceSpeed||260,this.config.voiceName=e.voiceName||"auto",this.config.voiceInput=e.voiceInput||"default"}updateConfig(e){this.config={...this.config,...e}}resolveBinary(e){if(o.isAbsolute(e)||e.includes(o.sep))return e;const n=[...(process.env.PATH||"").split(o.delimiter).filter(Boolean).map(t=>o.join(t,e)),o.join("/opt/homebrew/bin",e),o.join("/usr/local/bin",e),o.join("/usr/bin",e),o.join("/bin",e)];for(const e of n)if(i.existsSync(e))return e;try{return t("which",[e],{encoding:"utf8"}).trim()||e}catch{return e}}hasHomebrew(){return"brew"!==this.resolveBinary("brew")}hasGeminiStt(){return Boolean(this.config.googleApiKey||process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY)}listAudioInputDevices(){if("darwin"!==process.platform)return[];let e="";try{t("ffmpeg",["-hide_banner","-f","avfoundation","-list_devices","true","-i",""],{encoding:"utf8",stdio:["ignore","pipe","pipe"]})}catch(t){const i=t;e=`${i.stdout?.toString?.()??""}\n${i.stderr?.toString?.()??""}`}const i=new Map;let n=!1;for(const t of e.split(/\r?\n/)){if(t.includes("AVFoundation audio devices")){n=!0;continue}if(t.includes("AVFoundation video devices")){n=!1;continue}if(!n)continue;const e=t.match(/\[(\d+)\]\s+(.+)$/);if(!e)continue;const[,o,r]=e;i.has(o)||i.set(o,{id:o,name:r.trim()})}return Array.from(i.values())}async installCoreDependencies(t=["ffmpeg"],i={}){const n=this.resolveBinary("brew");if("brew"===n)throw new Error("Homebrew not found. Install Homebrew first from https://brew.sh");return new Promise((o,r)=>{const s=!1!==i.quiet;let a="";const c=e(n,["install",...t],{stdio:s?["ignore","pipe","pipe"]:"inherit",env:{...process.env,HOMEBREW_NO_ENV_HINTS:"1"}});if(s){const e=e=>{a+=e.toString(),a.length>24e3&&(a=a.slice(-24e3))};c.stdout?.on("data",e),c.stderr?.on("data",e)}c.on("error",e=>r(new Error(`brew spawn failed: ${e.message}`))),c.on("close",e=>{if(0===e)o();else{const t=a.trim().split(/\r?\n/).slice(-18).join("\n");r(new Error(`brew install failed with code ${e}${t?`\n${t}`:""}`))}})})}async checkDependencies(){const e=[],i=this.resolveBinary("ffmpeg");try{t(i,["-version"],{stdio:"ignore"}),e.push({name:"ffmpeg",ok:!0,required:!0})}catch{e.push({name:"ffmpeg",ok:!1,hint:"brew install ffmpeg",required:!0})}return this.hasGeminiStt()?e.push({name:"STT/TTS (Gemini)",ok:!0,hint:"via GOOGLE_API_KEY",required:!0}):e.push({name:"STT/TTS (Gemini)",ok:!1,hint:"Set GOOGLE_API_KEY — run /setup to configure",required:!0}),e}async record(t=30){const i=o.join(r.tmpdir(),`mesh_voice_${Date.now()}.wav`),n=this.resolveBinary("ffmpeg"),s=["-hide_banner","-loglevel","info","-f","avfoundation","-i",`:${this.resolveAudioInputId()}`,"-t",Math.max(3,Math.min(120,Number(t)||30)).toString(),"-ar","16000","-ac","1","-c:a","pcm_s16le","-af","volume=1.8,silencedetect=n=-35dB:d=1.5","-y",i];return new Promise((t,o)=>{const r=e(n,s);let a=!1,c=!1;const l=e=>{c||(c=!0,e())};r.on("error",e=>{l(()=>o(new Error(`ffmpeg spawn failed: ${e.message}`)))}),r.stderr.on("data",e=>{const t=e.toString();!a&&/silence_start:/i.test(t)&&(a=!0,r.kill("SIGINT"))}),r.on("close",e=>{l(()=>{0===e||a?t(i):o(new Error(`ffmpeg failed with code ${e}`))})})})}async transcribe(e){const t=this.resolveGoogleKey();return this.transcribeWithGemini(e,t)}async speak(e,t="en"){const i=this.prepareSpeechText(e);if(!i)return;const n=this.resolveGoogleKey();await this.speakWithGemini(i,t,n)}resolveGoogleKey(){const e=this.config.googleApiKey||process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;if(!e)throw new Error("GOOGLE_API_KEY is required for voice mode. Run /setup to configure.");return e}async transcribeWithGemini(e,t){const i=performance.now(),o=(await n.readFile(e)).toString("base64"),r=this.normalizeLanguage(this.config.voiceLanguage),s={model:"gemini-2.5-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:o,format:"wav"}},{type:"text",text:`Transcribe this audio exactly as spoken. Return only the transcribed text, nothing else.${"auto"!==r?` The audio is in language: ${r}.`:""}`}]}],max_tokens:512,temperature:0},a=await fetch("https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s),signal:AbortSignal.timeout(2e4)});if(!a.ok){const e=await a.text();throw new Error(`Gemini STT HTTP ${a.status}: ${e.slice(0,200)}`)}const c=await a.json(),l=c.choices?.[0]?.message?.content?.trim()??"";if(!l)throw new Error("Gemini STT returned empty transcription");const p=(performance.now()-i).toFixed(2);console.debug(`[Mesh:Voice] Gemini STT completed in ${p}ms`);return{text:l,language:"auto"!==r?r:this.detectLanguageHeuristic(l)}}detectLanguageHeuristic(e){return/\b(ich|du|er|sie|es|wir|ihr|nicht|ist|das|die|der|und|oder|mit|für|auf|ein|eine|einen)\b/i.test(e)?"de":"en"}prepareSpeechText(e){return e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/```[\s\S]*?```/g," Code ausgelassen. ").replace(/`([^`]+)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/\p{Extended_Pictographic}/gu,"").replace(/\s+/g," ").trim()}resolveGeminiVoice(e){const t=this.config.voiceName?.trim();if(t&&"auto"!==t)return t;return{de:"Kore",fr:"Aoede",es:"Charon",pt:"Aoede",ja:"Kore",zh:"Aoede"}[this.normalizeLanguage(e).split("-")[0]]??"Puck"}pcmToWav(e,t=24e3,i=1,n=16){const o=e.length,r=Buffer.alloc(44);return r.write("RIFF",0),r.writeUInt32LE(36+o,4),r.write("WAVE",8),r.write("fmt ",12),r.writeUInt32LE(16,16),r.writeUInt16LE(1,20),r.writeUInt16LE(i,22),r.writeUInt32LE(t,24),r.writeUInt32LE(t*i*(n/8),28),r.writeUInt16LE(i*(n/8),32),r.writeUInt16LE(n,34),r.write("data",36),r.writeUInt32LE(o,40),Buffer.concat([r,e])}async speakWithGemini(e,t,i){const s=performance.now(),a=this.resolveGeminiVoice(t),c=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{role:"user",parts:[{text:`Say this text aloud: ${e}`}]}],generationConfig:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:a}}}}}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text();throw new Error(`Gemini TTS HTTP ${c.status}: ${e.slice(0,200)}`)}const l=await c.json(),p=l.candidates?.[0]?.content?.parts?.[0]?.inlineData;if(!p?.data)throw new Error("Gemini TTS returned no audio data");const u=Buffer.from(p.data,"base64"),d=parseInt(p.mimeType?.match(/rate=(\d+)/)?.[1]??"24000",10),m=this.pcmToWav(u,d),g=o.join(r.tmpdir(),`mesh_tts_${Date.now()}.wav`);await n.writeFile(g,m),await this.playAudioFile(g),await n.unlink(g).catch(()=>{});const f=(performance.now()-s).toFixed(2);console.debug(`[Mesh:Voice] Gemini TTS completed in ${f}ms (voice: ${a})`)}async playAudioFile(t){let i,n;return"darwin"===process.platform?(i="afplay",n=[t]):"win32"===process.platform?(i="powershell",n=["-c",`(New-Object Media.SoundPlayer '${t}').PlaySync()`]):(i="aplay",n=[t]),new Promise((t,o)=>{const r=e(i,n);r.on("error",e=>o(new Error(`${i} failed: ${e.message}`))),r.on("close",()=>t())})}normalizeLanguage(e){return String(e||"en").trim().toLowerCase().replace(/_/g,"-")}resolveAudioInputId(){const e=String(this.config.voiceInput||"default").trim();return e&&"default"!==e?e:"0"}}
|