@tangle-network/sandbox-cli 0.23.17 → 0.23.19

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.
Files changed (31) hide show
  1. package/README.md +118 -0
  2. package/dist/{account-7XAhMt97.mjs → account-B0jBXI7i.mjs} +1 -1
  3. package/dist/{api-COxVvwlJ.mjs → api-BGYiAuZk.mjs} +1 -1
  4. package/dist/{clone-CWY8dI5d.mjs → clone-TrjN3dSh.mjs} +1 -1
  5. package/dist/{device-BEp1WVHD.mjs → device-D7ugbMa7.mjs} +1 -1
  6. package/dist/graph-3ml8wLV3.mjs +28 -0
  7. package/dist/graph-learning-Dlli1TSm.mjs +1 -0
  8. package/dist/graph-native-DqMbZ0no.mjs +1 -0
  9. package/dist/graph-native-producer-BnDMFjLO.mjs +1 -0
  10. package/dist/graph-operating-evidence-DQ3fJmWC.mjs +2 -0
  11. package/dist/graph-profile-learning-DO9BCDpy.mjs +1 -0
  12. package/dist/{graph-view-DOQKwuvP.mjs → graph-view-Cl3a9QXl.mjs} +1 -1
  13. package/dist/index.mjs +25 -52
  14. package/dist/rolldown-runtime-CgXYkLm_.mjs +1 -0
  15. package/dist/{run-B8ZGc03g.mjs → run-DoN6esPU.mjs} +1 -1
  16. package/dist/{solve-checker-gdxdE3g4.mjs → solve-checker-20YvRxEl.mjs} +1 -1
  17. package/dist/{solve-signer-CZZ0ccM_.mjs → solve-signer-BAxIt1Qi.mjs} +1 -1
  18. package/dist/{submit-B2ANeTIO.mjs → submit-D-p8N1-u.mjs} +1 -1
  19. package/dist/{transactions-C3dKwqB0.mjs → transactions-DFa7N-_-.mjs} +1 -1
  20. package/dist/{workspace-BOqrV945.mjs → workspace-BNZ3MDaM.mjs} +1 -1
  21. package/examples/graph-candidates.md +51 -0
  22. package/package.json +14 -14
  23. package/dist/graph-campaign-state-B51K1WNu.mjs +0 -1
  24. package/dist/graph-dataset-Bs03wlXZ.mjs +0 -1
  25. package/dist/graph-learning-Cjb4RyT2.mjs +0 -1
  26. package/dist/graph-native-B8Vtf07K.mjs +0 -1
  27. package/dist/graph-operating-evidence-DgfHPsFl.mjs +0 -2
  28. /package/dist/{credential-store-QcpDsEtL.mjs → credential-store-D4y6Kuec.mjs} +0 -0
  29. /package/dist/{deployment-t_Jhgj4Q.mjs → deployment-wpslctFo.mjs} +0 -0
  30. /package/dist/{dist-CzrZj_46.mjs → dist-B4pk_0j4.mjs} +0 -0
  31. /package/dist/{output-BqCeTtw4.mjs → output-OajdaYuM.mjs} +0 -0
@@ -0,0 +1 @@
1
+ import"node:module";var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
@@ -1 +1 @@
1
- import{a as e,f as t,o as n,r,u as i}from"./output-BqCeTtw4.mjs";import{y as a}from"./index.mjs";import{t as o}from"./solve-signer-CZZ0ccM_.mjs";import{c as s,f as c,n as l,o as u,s as d,t as f}from"./workspace-BOqrV945.mjs";import{n as p,t as m}from"./solve-checker-gdxdE3g4.mjs";import*as h from"node:path";import{randomBytes as g,randomUUID as _}from"node:crypto";import{toHex as v}from"viem";async function y(y,b){try{let{root:a,manifest:x}=await d(y,b.directory),S=await u(a),C=x.provenance?await s(a,x,S,{allowMissing:!0}):void 0,w=o(),T=i(`Running ${x.title} checker…`);b.json||T.start();let E;try{E=await m(a,x.checker)}finally{T.stop()}let D=l(E,C,x.provenance,void 0,{allowMissingSource:!0,requirePullRequest:!1}),O=v(g(32)),k=p(E.candidateRef,O),A={version:1,competition:x.slug,candidateRef:E.candidateRef,evidence:D.evidence,evidenceJson:E.evidenceJson,evidenceRefs:D.evidenceRefs,salt:O,candidateId:k,...C?{source:C}:{},deviceAddress:w.account.address,clientSubmissionId:_(),createdAt:new Date().toISOString()};await c(h.join(a,`.tangle-solve-run.json`),A),b.json?e({localRun:A}):(t(`Checker output recorded locally for operator evaluation`),n({Competition:x.slug,Candidate:E.candidateRef,"Device address":w.account.address,"Evidence refs":D.evidenceRefs.length}),r("Commit any changes, then run `tangle solve submit` from this directory."),x.provenance&&!C&&r(`Add your GitHub fork as 'origin' before submitting. The task repository is available as '${f}'.`))}catch(e){a(e)}}export{y as runCompetition};
1
+ import{a as e,f as t,o as n,r,u as i}from"./output-OajdaYuM.mjs";import{v as a}from"./index.mjs";import{t as o}from"./solve-signer-BAxIt1Qi.mjs";import{c as s,f as c,n as l,o as u,s as d,t as f}from"./workspace-BNZ3MDaM.mjs";import{n as p,t as m}from"./solve-checker-20YvRxEl.mjs";import*as h from"node:path";import{randomBytes as g,randomUUID as _}from"node:crypto";import{toHex as v}from"viem";async function y(y,b){try{let{root:a,manifest:x}=await d(y,b.directory),S=await u(a),C=x.provenance?await s(a,x,S,{allowMissing:!0}):void 0,w=o(),T=i(`Running ${x.title} checker…`);b.json||T.start();let E;try{E=await m(a,x.checker)}finally{T.stop()}let D=l(E,C,x.provenance,void 0,{allowMissingSource:!0,requirePullRequest:!1}),O=v(g(32)),k=p(E.candidateRef,O),A={version:1,competition:x.slug,candidateRef:E.candidateRef,evidence:D.evidence,evidenceJson:E.evidenceJson,evidenceRefs:D.evidenceRefs,salt:O,candidateId:k,...C?{source:C}:{},deviceAddress:w.account.address,clientSubmissionId:_(),createdAt:new Date().toISOString()};await c(h.join(a,`.tangle-solve-run.json`),A),b.json?e({localRun:A}):(t(`Checker output recorded locally for operator evaluation`),n({Competition:x.slug,Candidate:E.candidateRef,"Device address":w.account.address,"Evidence refs":D.evidenceRefs.length}),r("Commit any changes, then run `tangle solve submit` from this directory."),x.provenance&&!C&&r(`Add your GitHub fork as 'origin' before submitting. The task repository is available as '${f}'.`))}catch(e){a(e)}}export{y as runCompetition};
@@ -1 +1 @@
1
- import{n as e}from"./deployment-t_Jhgj4Q.mjs";import{_ as t,a as n,b as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./transactions-C3dKwqB0.mjs";import*as b from"node:path";import*as x from"node:os";import{execFile as S}from"node:child_process";import*as C from"node:fs/promises";import{promisify as w}from"node:util";import{encodeAbiParameters as T,keccak256 as E}from"viem";function D(e,t){return E(T(c,[e.trim(),t]))}function O(e){let t=/^submission=(\S+)/.exec(e);if(!t?.[1])throw Error(`COMMIT_CANDIDATE did not return a submission reference`);return t[1]}async function k(e,t,r,i,c){let l=c.resumeTransactions?.evaluation;if(l){let n=await e.publicClient.waitForTransactionReceipt({hash:l});if(a(n,l,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!u(n,t,e.account,i))throw Error(`Saved evaluation transaction did not emit EvaluationAccepted for this candidate`);return l}let d=Date.now();for(;!o(d,p);){if(await h(e,t,i)){let n=_(await e.publicClient.getLogs({address:t.managerAddress,event:s,args:{serviceId:t.serviceId,competitionId:t.competitionId,researcher:e.account.address},fromBlock:r.blockNumber,toBlock:`latest`}),i);if(n)return n;throw Error(`Candidate is already accepted, but its EvaluationAccepted transaction is unavailable`)}let[o,l,,d,f]=await e.publicClient.readContract({address:t.managerAddress,abi:v,functionName:`pendingResults`,args:[t.serviceId,r.callId]});if(d&&o!==4)throw Error(`Manager pending result ${r.callId} has unexpected job ${o}`);if(d&&f)throw Error(`Manager executed the report without EvaluationAccepted`);if(d&&!f){if(l.toLowerCase()!==E(r.output).toLowerCase())throw Error(`Manager pending report output does not match the aggregate`);let o=await n(e,{address:t.managerAddress,abi:v,functionName:`executePendingResult`,args:[t.serviceId,r.callId,r.output]});await c.onTransaction?.(`evaluation`,o);let s=await e.publicClient.waitForTransactionReceipt({hash:o});if(a(s,o,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!u(s,t,e.account,i))throw Error(`Evaluation transaction did not emit EvaluationAccepted for this candidate`);return o}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Manager did not emit EvaluationAccepted within 120 seconds`)}async function A(o,s,c,u={}){if(e(o),!/^0x[0-9a-f]{64}$/i.test(c.salt))throw Error(`Reveal salt must be bytes32`);if(!c.artifactRef.trim())throw Error(`Candidate reference is required`);if(!c.evidenceJson.trim()||c.evidenceRefs.length===0)throw Error(`Checker evidence is required`);let h=await f(o,s),_=await g(h,o,u.onTransaction,u.resumeTransactions?.authorization),b,x=await h.publicClient.readContract({address:o.managerAddress,abi:v,functionName:`stakes`,args:[o.serviceId,o.competitionId,h.account.address]});x<o.minStakeWei&&(b=await n(h,{address:o.managerAddress,abi:v,functionName:`postStake`,args:[o.serviceId,o.competitionId],value:o.minStakeWei-x}),await u.onTransaction?.(`stake`,b),a(await h.publicClient.waitForTransactionReceipt({hash:b}),b,`Stake`,{from:h.account.address,to:o.managerAddress}));let S=D(c.artifactRef,c.salt),C=T(t,[o.competitionId,o.minStakeWei]),w=T(d,[o.competitionId,S]),E=T(r,[o.competitionId,S,c.artifactRef.trim(),c.salt]),A=await m(h,o,1,C,`joined`,u.onTransaction,`join`,u.resumeTransactions),j=await m(h,o,2,w,`committed`,u.onTransaction,`commit`,u.resumeTransactions),M=O(j.acknowledgement.detail),N=await m(h,o,3,E,`revealed`,u.onTransaction,`reveal`,u.resumeTransactions),P=await l(h,o,4,T(y,[o.competitionId,S,M,c.evidenceJson,JSON.stringify(c.evidenceRefs)]),u.onTransaction,`report`,u.resumeTransactions),F=await i(h,o,P.callId,P.blockNumber,p),I=await k(h,o,{callId:P.callId,output:F,blockNumber:P.blockNumber},S,u);return{address:h.account.address,..._?{authorization:_}:{},...b?{stake:b}:{},join:A.hash,commit:j.hash,reveal:N.hash,report:P.hash,evaluation:I,candidateId:S,submissionRef:M}}const j=w(S),M=`/usr/bin/bwrap`,N=[`/usr`,`/bin`,`/sbin`,`/lib`,`/lib64`];function P(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function F(e,t){if(!e||e.length>2048||P(e))throw Error(`${t} contains invalid control characters or is too long`)}function I(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]??``);)n+=1;return n}function L(e,t){if(e[t]!==`"`)throw Error(`Checker output must be valid JSON`);let n=t+1;for(;n<e.length;){let t=e[n];if(t===`\\`){n+=2;continue}if(t===`"`)return n+1;if((t?.charCodeAt(0)??0)<32)throw Error(`Checker output must be valid JSON`);n+=1}throw Error(`Checker output must be valid JSON`)}function R(e,t,n){let r=new Set,i=I(e,t+1);if(e[i]===`}`)return i+1;for(;i<e.length;){let t=L(e,i),a=JSON.parse(e.slice(i,t));if(r.has(a))throw Error(`Checker output must not contain duplicate object keys`);if(r.add(a),i=I(e,t),e[i]!==`:`)throw Error(`Checker output must be valid JSON`);let o=I(e,i+1),s=B(e,o);if(n?.(a,o,s),i=I(e,s),e[i]===`}`)return i+1;if(e[i]!==`,`)throw Error(`Checker output must be valid JSON`);i=I(e,i+1)}throw Error(`Checker output must be valid JSON`)}function z(e,t){let n=I(e,t+1);if(e[n]===`]`)return n+1;for(;n<e.length;){if(n=I(e,B(e,n)),e[n]===`]`)return n+1;if(e[n]!==`,`)throw Error(`Checker output must be valid JSON`);n=I(e,n+1)}throw Error(`Checker output must be valid JSON`)}function B(e,t){if(e[t]===`"`)return L(e,t);if(e[t]===`{`)return R(e,t);if(e[t]===`[`)return z(e,t);let n=t;for(;n<e.length&&!/[\s,\]}]/.test(e[n]??``);)n+=1;return n}function V(e){let t=e.trim();if(I(t,B(t,0))!==t.length)throw Error(`Checker output must be valid JSON`)}function H(e,t){let n=e.trim();if(n[0]!==`{`)return;let r;return R(n,0,(e,i,a)=>{e===t&&(r=n.slice(i,a).trim())}),r}function U(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Checker output must be one JSON object`)}if(V(e),!t||typeof t!=`object`||Array.isArray(t))throw Error(`Checker output must be a JSON object`);let n=t,r=n.candidate_ref;if(typeof r!=`string`||!r.trim())throw Error(`Checker output must include candidate_ref`);let i=r.trim(),a=n.evidence_refs;if(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`||!e.trim()))throw Error(`Checker output must include a non-empty evidence_refs array`);F(i,`candidate_ref`);for(let e of a)F(e.trim(),`evidence_refs`);if(!n.evidence_json||typeof n.evidence_json!=`object`||Array.isArray(n.evidence_json))throw Error(`Checker output must include an evidence_json object`);let o={...n.evidence_json},s=H(e,`evidence_json`);if(!s)throw Error(`Checker evidence_json source text is missing`);if(o.candidate_ref!==i)throw Error(`Checker evidence_json candidate_ref must match candidate_ref`);return{candidateRef:i,evidenceRefs:a.map(e=>e.trim()),evidence:o,evidenceJson:s}}async function W(e,t,n){let r=n.trim();if(r.startsWith(`{`)&&r.endsWith(`}`)||!t.result_file)return r;let i=await X(e),a=b.resolve(i,t.result_file),o=b.relative(i,a);if(o.startsWith(`..`)||b.isAbsolute(o))throw Error(`Checker result_file must stay inside the competition repository`);let s;try{s=await C.lstat(a)}catch{throw Error(`Checker result_file must be an existing regular file inside the competition repository`)}if(s.isSymbolicLink())throw Error(`Checker result_file must not be a symbolic link`);if(!s.isFile())throw Error(`Checker result_file must be an existing regular file inside the competition repository`);let c;try{c=await C.realpath(a)}catch{throw Error(`Checker result_file must resolve to a regular file inside the competition repository`)}let l=b.relative(i,c);if(l.startsWith(`..`)||b.isAbsolute(l))throw Error(`Checker result_file must stay inside the competition repository`);return(await C.readFile(c,`utf8`)).trim()}function G(e,t){let n=b.relative(e,t);return n===``||!n.startsWith(`..`)&&!b.isAbsolute(n)}function K(e){return N.some(t=>G(t,e))}async function q(e,t,n){let r=e.includes(`/`)?[b.resolve(t,e)]:(process.env.PATH??``).split(b.delimiter).filter(Boolean).map(t=>b.join(t,e));for(let i of r){let r;try{r=await C.realpath(i),await C.access(r,C.constants.X_OK)}catch{continue}if(!G(t,r)&&!K(r)&&r!==n)throw Error(`Checker executable '${e}' must resolve inside the competition repository or a trusted runtime directory`);return r}throw Error(`Checker executable '${e}' was not found`)}async function J(e){let t=[];for(let n of e)try{(await C.stat(n)).isDirectory()&&t.push(n)}catch{}return t}async function Y(e){let t=await C.realpath(x.homedir());if(e===b.parse(e).root||e===t)throw Error(`Solve checker repository must be a dedicated directory, not the filesystem or home root`)}async function X(e){let t=await C.realpath(e);return await Y(t),t}async function Z(e){let t=b.join(e,`.git`),n;try{n=await C.lstat(t)}catch{return}if(n.isSymbolicLink())throw Error(`Solve checker repository .git must not be a symbolic link`);if(!n.isDirectory()&&!n.isFile())return;let r;try{let t={...process.env};for(let e of[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_CONFIG_COUNT`,`GIT_CONFIG_PARAMETERS`])delete t[e];let n=await j(`/usr/bin/git`,[`-C`,e,`rev-parse`,`--verify`,`HEAD^{commit}`],{encoding:`utf8`,maxBuffer:1e5,env:{...t,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_CONFIG_SYSTEM:`/dev/null`,GIT_CONFIG_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}),i=String(n.stdout).trim();/^[0-9a-f]{40}$/i.test(i)&&(r=i.toLowerCase())}catch{}return{kind:n.isDirectory()?`directory`:`file`,...r?{commit:r}:{}}}async function Q(e,t,n){let r=await X(e);if(process.platform!==`linux`)throw Error(`Solve checkers require the Linux sandbox runtime (bubblewrap) with network isolation`);try{await C.access(M,C.constants.X_OK)}catch{throw Error(`Solve checkers require /usr/bin/bwrap; install bubblewrap or run the checker in a Tangle sandbox`)}let i=await q(t,r,await C.realpath(process.execPath)),a=await Z(r),o=(await J(N)).flatMap(e=>[`--ro-bind`,e,e]),s=G(r,i)?`/work/${b.relative(r,i)}`:K(i)?i:`/checker/node`;!G(r,i)&&!K(i)&&o.push(`--ro-bind`,i,`/checker/node`);let c=a?.kind===`directory`?[`--tmpfs`,`/work/.git`]:a?.kind===`file`?[`--ro-bind`,`/dev/null`,`/work/.git`]:[];return{executable:M,args:[`--die-with-parent`,`--new-session`,`--unshare-all`,`--clearenv`,...o,`--proc`,`/proc`,`--dev`,`/dev`,`--tmpfs`,`/tmp`,`--dir`,`/tmp/home`,`--bind`,r,`/work`,...c,`--chdir`,`/work`,`--setenv`,`HOME`,`/tmp/home`,...a?.commit?[`--setenv`,`TANGLE_SOLVE_COMMIT`,a.commit]:[],`--setenv`,`TMPDIR`,`/tmp`,`--setenv`,`PATH`,`/checker:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,`--setenv`,`LANG`,`C.UTF-8`,`--setenv`,`PYTHONDONTWRITEBYTECODE`,`1`,`--setenv`,`XDG_CONFIG_HOME`,`/tmp/home/.config`,`--setenv`,`XDG_CACHE_HOME`,`/tmp/home/.cache`,`--setenv`,`XDG_DATA_HOME`,`/tmp/home/.local/share`,`--setenv`,`GIT_CONFIG_GLOBAL`,`/dev/null`,`--setenv`,`GIT_CONFIG_SYSTEM`,`/dev/null`,`--setenv`,`NPM_CONFIG_USERCONFIG`,`/dev/null`,s,...n]}}async function $(e,t){if(!t.command||t.command.includes(`/../`)||P(t.command))throw Error(`The competition checker command is invalid`);if(!Array.isArray(t.args))throw Error(`The competition checker arguments must be an array`);for(let e of t.args)F(e,`Checker argument`);let n=t.timeout_ms??15*6e4;if(!Number.isSafeInteger(n)||n<1e3||n>60*6e4)throw Error(`Checker timeout must be between one second and one hour`);let r=await X(e),i;try{let e=await Q(r,t.command,t.args);i=await j(e.executable,e.args,{cwd:r,timeout:n,maxBuffer:4194304,encoding:`utf8`})}catch(e){let t=e,n=t.stderr?.trim()||t.stdout?.trim()||t.message||`checker failed`;throw Error(`Pinned checker failed: ${n}`)}let a=String(i.stdout),o=String(i.stderr);return{...U(await W(r,t,a)),stdout:a,stderr:o}}export{D as n,A as r,$ as t};
1
+ import{n as e}from"./deployment-wpslctFo.mjs";import{_ as t,a as n,b as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./transactions-DFa7N-_-.mjs";import*as b from"node:path";import*as x from"node:os";import{execFile as S}from"node:child_process";import*as C from"node:fs/promises";import{promisify as w}from"node:util";import{encodeAbiParameters as T,keccak256 as E}from"viem";function D(e,t){return E(T(c,[e.trim(),t]))}function O(e){let t=/^submission=(\S+)/.exec(e);if(!t?.[1])throw Error(`COMMIT_CANDIDATE did not return a submission reference`);return t[1]}async function k(e,t,r,i,c){let l=c.resumeTransactions?.evaluation;if(l){let n=await e.publicClient.waitForTransactionReceipt({hash:l});if(a(n,l,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!u(n,t,e.account,i))throw Error(`Saved evaluation transaction did not emit EvaluationAccepted for this candidate`);return l}let d=Date.now();for(;!o(d,p);){if(await h(e,t,i)){let n=_(await e.publicClient.getLogs({address:t.managerAddress,event:s,args:{serviceId:t.serviceId,competitionId:t.competitionId,researcher:e.account.address},fromBlock:r.blockNumber,toBlock:`latest`}),i);if(n)return n;throw Error(`Candidate is already accepted, but its EvaluationAccepted transaction is unavailable`)}let[o,l,,d,f]=await e.publicClient.readContract({address:t.managerAddress,abi:v,functionName:`pendingResults`,args:[t.serviceId,r.callId]});if(d&&o!==4)throw Error(`Manager pending result ${r.callId} has unexpected job ${o}`);if(d&&f)throw Error(`Manager executed the report without EvaluationAccepted`);if(d&&!f){if(l.toLowerCase()!==E(r.output).toLowerCase())throw Error(`Manager pending report output does not match the aggregate`);let o=await n(e,{address:t.managerAddress,abi:v,functionName:`executePendingResult`,args:[t.serviceId,r.callId,r.output]});await c.onTransaction?.(`evaluation`,o);let s=await e.publicClient.waitForTransactionReceipt({hash:o});if(a(s,o,`Evaluation`,{from:e.account.address,to:t.managerAddress}),!u(s,t,e.account,i))throw Error(`Evaluation transaction did not emit EvaluationAccepted for this candidate`);return o}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Manager did not emit EvaluationAccepted within 120 seconds`)}async function A(o,s,c,u={}){if(e(o),!/^0x[0-9a-f]{64}$/i.test(c.salt))throw Error(`Reveal salt must be bytes32`);if(!c.artifactRef.trim())throw Error(`Candidate reference is required`);if(!c.evidenceJson.trim()||c.evidenceRefs.length===0)throw Error(`Checker evidence is required`);let h=await f(o,s),_=await g(h,o,u.onTransaction,u.resumeTransactions?.authorization),b,x=await h.publicClient.readContract({address:o.managerAddress,abi:v,functionName:`stakes`,args:[o.serviceId,o.competitionId,h.account.address]});x<o.minStakeWei&&(b=await n(h,{address:o.managerAddress,abi:v,functionName:`postStake`,args:[o.serviceId,o.competitionId],value:o.minStakeWei-x}),await u.onTransaction?.(`stake`,b),a(await h.publicClient.waitForTransactionReceipt({hash:b}),b,`Stake`,{from:h.account.address,to:o.managerAddress}));let S=D(c.artifactRef,c.salt),C=T(t,[o.competitionId,o.minStakeWei]),w=T(d,[o.competitionId,S]),E=T(r,[o.competitionId,S,c.artifactRef.trim(),c.salt]),A=await m(h,o,1,C,`joined`,u.onTransaction,`join`,u.resumeTransactions),j=await m(h,o,2,w,`committed`,u.onTransaction,`commit`,u.resumeTransactions),M=O(j.acknowledgement.detail),N=await m(h,o,3,E,`revealed`,u.onTransaction,`reveal`,u.resumeTransactions),P=await l(h,o,4,T(y,[o.competitionId,S,M,c.evidenceJson,JSON.stringify(c.evidenceRefs)]),u.onTransaction,`report`,u.resumeTransactions),F=await i(h,o,P.callId,P.blockNumber,p),I=await k(h,o,{callId:P.callId,output:F,blockNumber:P.blockNumber},S,u);return{address:h.account.address,..._?{authorization:_}:{},...b?{stake:b}:{},join:A.hash,commit:j.hash,reveal:N.hash,report:P.hash,evaluation:I,candidateId:S,submissionRef:M}}const j=w(S),M=`/usr/bin/bwrap`,N=[`/usr`,`/bin`,`/sbin`,`/lib`,`/lib64`];function P(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function F(e,t){if(!e||e.length>2048||P(e))throw Error(`${t} contains invalid control characters or is too long`)}function I(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]??``);)n+=1;return n}function L(e,t){if(e[t]!==`"`)throw Error(`Checker output must be valid JSON`);let n=t+1;for(;n<e.length;){let t=e[n];if(t===`\\`){n+=2;continue}if(t===`"`)return n+1;if((t?.charCodeAt(0)??0)<32)throw Error(`Checker output must be valid JSON`);n+=1}throw Error(`Checker output must be valid JSON`)}function R(e,t,n){let r=new Set,i=I(e,t+1);if(e[i]===`}`)return i+1;for(;i<e.length;){let t=L(e,i),a=JSON.parse(e.slice(i,t));if(r.has(a))throw Error(`Checker output must not contain duplicate object keys`);if(r.add(a),i=I(e,t),e[i]!==`:`)throw Error(`Checker output must be valid JSON`);let o=I(e,i+1),s=B(e,o);if(n?.(a,o,s),i=I(e,s),e[i]===`}`)return i+1;if(e[i]!==`,`)throw Error(`Checker output must be valid JSON`);i=I(e,i+1)}throw Error(`Checker output must be valid JSON`)}function z(e,t){let n=I(e,t+1);if(e[n]===`]`)return n+1;for(;n<e.length;){if(n=I(e,B(e,n)),e[n]===`]`)return n+1;if(e[n]!==`,`)throw Error(`Checker output must be valid JSON`);n=I(e,n+1)}throw Error(`Checker output must be valid JSON`)}function B(e,t){if(e[t]===`"`)return L(e,t);if(e[t]===`{`)return R(e,t);if(e[t]===`[`)return z(e,t);let n=t;for(;n<e.length&&!/[\s,\]}]/.test(e[n]??``);)n+=1;return n}function V(e){let t=e.trim();if(I(t,B(t,0))!==t.length)throw Error(`Checker output must be valid JSON`)}function H(e,t){let n=e.trim();if(n[0]!==`{`)return;let r;return R(n,0,(e,i,a)=>{e===t&&(r=n.slice(i,a).trim())}),r}function U(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Checker output must be one JSON object`)}if(V(e),!t||typeof t!=`object`||Array.isArray(t))throw Error(`Checker output must be a JSON object`);let n=t,r=n.candidate_ref;if(typeof r!=`string`||!r.trim())throw Error(`Checker output must include candidate_ref`);let i=r.trim(),a=n.evidence_refs;if(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`||!e.trim()))throw Error(`Checker output must include a non-empty evidence_refs array`);F(i,`candidate_ref`);for(let e of a)F(e.trim(),`evidence_refs`);if(!n.evidence_json||typeof n.evidence_json!=`object`||Array.isArray(n.evidence_json))throw Error(`Checker output must include an evidence_json object`);let o={...n.evidence_json},s=H(e,`evidence_json`);if(!s)throw Error(`Checker evidence_json source text is missing`);if(o.candidate_ref!==i)throw Error(`Checker evidence_json candidate_ref must match candidate_ref`);return{candidateRef:i,evidenceRefs:a.map(e=>e.trim()),evidence:o,evidenceJson:s}}async function W(e,t,n){let r=n.trim();if(r.startsWith(`{`)&&r.endsWith(`}`)||!t.result_file)return r;let i=await X(e),a=b.resolve(i,t.result_file),o=b.relative(i,a);if(o.startsWith(`..`)||b.isAbsolute(o))throw Error(`Checker result_file must stay inside the competition repository`);let s;try{s=await C.lstat(a)}catch{throw Error(`Checker result_file must be an existing regular file inside the competition repository`)}if(s.isSymbolicLink())throw Error(`Checker result_file must not be a symbolic link`);if(!s.isFile())throw Error(`Checker result_file must be an existing regular file inside the competition repository`);let c;try{c=await C.realpath(a)}catch{throw Error(`Checker result_file must resolve to a regular file inside the competition repository`)}let l=b.relative(i,c);if(l.startsWith(`..`)||b.isAbsolute(l))throw Error(`Checker result_file must stay inside the competition repository`);return(await C.readFile(c,`utf8`)).trim()}function G(e,t){let n=b.relative(e,t);return n===``||!n.startsWith(`..`)&&!b.isAbsolute(n)}function K(e){return N.some(t=>G(t,e))}async function q(e,t,n){let r=e.includes(`/`)?[b.resolve(t,e)]:(process.env.PATH??``).split(b.delimiter).filter(Boolean).map(t=>b.join(t,e));for(let i of r){let r;try{r=await C.realpath(i),await C.access(r,C.constants.X_OK)}catch{continue}if(!G(t,r)&&!K(r)&&r!==n)throw Error(`Checker executable '${e}' must resolve inside the competition repository or a trusted runtime directory`);return r}throw Error(`Checker executable '${e}' was not found`)}async function J(e){let t=[];for(let n of e)try{(await C.stat(n)).isDirectory()&&t.push(n)}catch{}return t}async function Y(e){let t=await C.realpath(x.homedir());if(e===b.parse(e).root||e===t)throw Error(`Solve checker repository must be a dedicated directory, not the filesystem or home root`)}async function X(e){let t=await C.realpath(e);return await Y(t),t}async function Z(e){let t=b.join(e,`.git`),n;try{n=await C.lstat(t)}catch{return}if(n.isSymbolicLink())throw Error(`Solve checker repository .git must not be a symbolic link`);if(!n.isDirectory()&&!n.isFile())return;let r;try{let t={...process.env};for(let e of[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_CONFIG_COUNT`,`GIT_CONFIG_PARAMETERS`])delete t[e];let n=await j(`/usr/bin/git`,[`-C`,e,`rev-parse`,`--verify`,`HEAD^{commit}`],{encoding:`utf8`,maxBuffer:1e5,env:{...t,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_CONFIG_SYSTEM:`/dev/null`,GIT_CONFIG_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}),i=String(n.stdout).trim();/^[0-9a-f]{40}$/i.test(i)&&(r=i.toLowerCase())}catch{}return{kind:n.isDirectory()?`directory`:`file`,...r?{commit:r}:{}}}async function Q(e,t,n){let r=await X(e);if(process.platform!==`linux`)throw Error(`Solve checkers require the Linux sandbox runtime (bubblewrap) with network isolation`);try{await C.access(M,C.constants.X_OK)}catch{throw Error(`Solve checkers require /usr/bin/bwrap; install bubblewrap or run the checker in a Tangle sandbox`)}let i=await q(t,r,await C.realpath(process.execPath)),a=await Z(r),o=(await J(N)).flatMap(e=>[`--ro-bind`,e,e]),s=G(r,i)?`/work/${b.relative(r,i)}`:K(i)?i:`/checker/node`;!G(r,i)&&!K(i)&&o.push(`--ro-bind`,i,`/checker/node`);let c=a?.kind===`directory`?[`--tmpfs`,`/work/.git`]:a?.kind===`file`?[`--ro-bind`,`/dev/null`,`/work/.git`]:[];return{executable:M,args:[`--die-with-parent`,`--new-session`,`--unshare-all`,`--clearenv`,...o,`--proc`,`/proc`,`--dev`,`/dev`,`--tmpfs`,`/tmp`,`--dir`,`/tmp/home`,`--bind`,r,`/work`,...c,`--chdir`,`/work`,`--setenv`,`HOME`,`/tmp/home`,...a?.commit?[`--setenv`,`TANGLE_SOLVE_COMMIT`,a.commit]:[],`--setenv`,`TMPDIR`,`/tmp`,`--setenv`,`PATH`,`/checker:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,`--setenv`,`LANG`,`C.UTF-8`,`--setenv`,`PYTHONDONTWRITEBYTECODE`,`1`,`--setenv`,`XDG_CONFIG_HOME`,`/tmp/home/.config`,`--setenv`,`XDG_CACHE_HOME`,`/tmp/home/.cache`,`--setenv`,`XDG_DATA_HOME`,`/tmp/home/.local/share`,`--setenv`,`GIT_CONFIG_GLOBAL`,`/dev/null`,`--setenv`,`GIT_CONFIG_SYSTEM`,`/dev/null`,`--setenv`,`NPM_CONFIG_USERCONFIG`,`/dev/null`,s,...n]}}async function $(e,t){if(!t.command||t.command.includes(`/../`)||P(t.command))throw Error(`The competition checker command is invalid`);if(!Array.isArray(t.args))throw Error(`The competition checker arguments must be an array`);for(let e of t.args)F(e,`Checker argument`);let n=t.timeout_ms??15*6e4;if(!Number.isSafeInteger(n)||n<1e3||n>60*6e4)throw Error(`Checker timeout must be between one second and one hour`);let r=await X(e),i;try{let e=await Q(r,t.command,t.args);i=await j(e.executable,e.args,{cwd:r,timeout:n,maxBuffer:4194304,encoding:`utf8`})}catch(e){let t=e,n=t.stderr?.trim()||t.stdout?.trim()||t.message||`checker failed`;throw Error(`Pinned checker failed: ${n}`)}let a=String(i.stdout),o=String(i.stderr);return{...U(await W(r,t,a)),stdout:a,stderr:o}}export{D as n,A as r,$ as t};
@@ -1 +1 @@
1
- import{i as e,n as t,r as n}from"./credential-store-QcpDsEtL.mjs";import{generatePrivateKey as r,privateKeyToAccount as i}from"viem/accounts";const a=`solve:device:secp256k1`,o=/^0x[0-9a-f]{64}$/i;function s(e){return e&&o.test(e)?e:void 0}function c(){let e=n(a),t=s(e.value);if(!(!t||e.source===`none`))return{account:i(t),source:e.source}}function l(){let t=c();if(t)return t;let n=r(),o=e(a,n);return{account:i(n),source:o}}function u(r){let o=s(n(a).value);if(!o||i(o).address!==r.account.address)throw Error(`The local Solve device key changed; it was not retired`);let c=`${a}:retired:${r.account.address.toLowerCase()}`;if(e(c,o),n(c).value!==o)throw Error(`The revoked device key could not be retired safely`);return t(a),c}export{c as n,u as r,l as t};
1
+ import{i as e,n as t,r as n}from"./credential-store-D4y6Kuec.mjs";import{generatePrivateKey as r,privateKeyToAccount as i}from"viem/accounts";const a=`solve:device:secp256k1`,o=/^0x[0-9a-f]{64}$/i;function s(e){return e&&o.test(e)?e:void 0}function c(){let e=n(a),t=s(e.value);if(!(!t||e.source===`none`))return{account:i(t),source:e.source}}function l(){let t=c();if(t)return t;let n=r(),o=e(a,n);return{account:i(n),source:o}}function u(r){let o=s(n(a).value);if(!o||i(o).address!==r.account.address)throw Error(`The local Solve device key changed; it was not retired`);let c=`${a}:retired:${r.account.address.toLowerCase()}`;if(e(c,o),n(c).value!==o)throw Error(`The revoked device key could not be retired safely`);return t(a),c}export{c as n,u as r,l as t};
@@ -1 +1 @@
1
- import{a as e,f as t,o as n,u as r}from"./output-BqCeTtw4.mjs";import{y as i}from"./index.mjs";import{n as a}from"./solve-signer-CZZ0ccM_.mjs";import{a as o,c as s,d as c,f as l,h as u,l as d,m as f,n as p,o as m,s as h,u as g}from"./workspace-BOqrV945.mjs";import{a as _,i as v,t as y}from"./api-COxVvwlJ.mjs";import{n as b,r as x,t as S}from"./solve-checker-gdxdE3g4.mjs";import*as C from"node:path";const w=/^0x[0-9a-f]{64}$/i;async function T(e){let t=await y({deviceAddress:e.deviceAddress,apiUrl:e.apiUrl,profile:e.profile}),n=await e.signer.signMessage({message:t.message});return{walletChallengeId:t.challengeId,walletSignature:n}}async function E(y,E){try{let{root:i,manifest:D}=await h(y,E.directory);v({profile:E.profile});let O=await m(i),k=await o(i);if(k.competition!==D.slug)throw Error(`.tangle-solve-run.json does not match this competition`);if(!w.test(k.salt)||!w.test(k.candidateId))throw Error("This run predates durable candidate identity. Run `tangle solve run` again");let A=D.provenance?await s(i,D,O):void 0;if(D.provenance&&k.source&&!d(k.source,A))throw Error("The saved run points to a different repository or revision. Keep your fork as 'origin' and run `tangle solve run` again before submitting");let j=a();if(!j)throw Error("No Solve device signer found. Run `tangle solve run` first");if(j.account.address.toLowerCase()!==k.deviceAddress.toLowerCase())throw Error("The local Solve device account changed after `tangle solve run`; run the checker again");let M=r(`Checking the committed candidate…`);E.json||M.start();let N;try{N=await S(i,D.checker)}finally{M.stop()}if(N.candidateRef!==k.candidateRef||N.evidenceJson!==k.evidenceJson)throw Error("The committed checker output changed after `tangle solve run`; run the checker again");if(b(N.candidateRef,k.salt).toLowerCase()!==k.candidateId.toLowerCase())throw Error(`The saved candidate identity does not match the checker output; run the checker again`);let P=u(E.prUrl);if(!D.provenance&&P)throw Error(`This competition does not accept GitHub pull request provenance`);if(P){if(!A)throw Error(`A provenance policy is required for a pull request`);await c({pullRequest:P,taskRepository:A.taskRepository,submissionRepository:A.submissionRepository,submissionRevision:O})}let F=p(N,A,D.provenance,P,{requirePullRequest:!0}),I={...k,...A?{source:A}:{},chainState:{status:`submitting`,transactions:{...k.chainState?.transactions??{}}}},L=C.join(i,`.tangle-solve-run.json`);await l(L,I);let R=r(`Submitting candidate to Tempo…`);E.json||R.start();let z;try{z=await x(f(D),j.account,{artifactRef:N.candidateRef,salt:k.salt,evidenceJson:N.evidenceJson,evidenceRefs:F.evidenceRefs},{resumeTransactions:I.chainState?.transactions,onTransaction:async(e,t)=>{I={...I,chainState:{status:`submitting`,transactions:{...I.chainState?.transactions??{},[e]:t}}},await l(L,I)}})}finally{R.stop()}I={...I,chainReceipt:z,chainState:{status:`accepted`,transactions:{...I.chainState?.transactions??{},...g(z)}}},await l(L,I);let B=await T({deviceAddress:z.address,signer:j.account,apiUrl:E.apiUrl,profile:E.profile}),V=await _({path:`/v1/submissions`,method:`POST`,apiUrl:E.apiUrl,profile:E.profile,body:{competition:D.slug,candidateRef:N.candidateRef,candidateId:z.candidateId,evidenceJson:N.evidenceJson,evidenceRefs:F.evidenceRefs,deviceAddress:z.address,reportTxHash:z.report,evaluationTxHash:z.evaluation,transactions:g(z),...D.provenance&&A?{source:{...A,...P?{pullRequest:P}:{}}}:{},clientSubmissionId:k.clientSubmissionId,...B,...E.model?{model:E.model}:{},...E.note?{note:E.note}:{}}});E.json?e({...V,transactions:g(z),candidateId:z.candidateId}):(t(`Submission accepted on Tempo`),n({Competition:D.slug,Candidate:z.candidateId,"Device address":z.address,"Report transaction":z.report,"Evaluation transaction":z.evaluation,"Submission ID":typeof V.id==`string`?V.id:V.submission?.id}))}catch(e){i(e)}}export{E as submitCompetition};
1
+ import{a as e,f as t,o as n,u as r}from"./output-OajdaYuM.mjs";import{v as i}from"./index.mjs";import{n as a}from"./solve-signer-BAxIt1Qi.mjs";import{a as o,c as s,d as c,f as l,h as u,l as d,m as f,n as p,o as m,s as h,u as g}from"./workspace-BNZ3MDaM.mjs";import{a as _,i as v,t as y}from"./api-BGYiAuZk.mjs";import{n as b,r as x,t as S}from"./solve-checker-20YvRxEl.mjs";import*as C from"node:path";const w=/^0x[0-9a-f]{64}$/i;async function T(e){let t=await y({deviceAddress:e.deviceAddress,apiUrl:e.apiUrl,profile:e.profile}),n=await e.signer.signMessage({message:t.message});return{walletChallengeId:t.challengeId,walletSignature:n}}async function E(y,E){try{let{root:i,manifest:D}=await h(y,E.directory);v({profile:E.profile});let O=await m(i),k=await o(i);if(k.competition!==D.slug)throw Error(`.tangle-solve-run.json does not match this competition`);if(!w.test(k.salt)||!w.test(k.candidateId))throw Error("This run predates durable candidate identity. Run `tangle solve run` again");let A=D.provenance?await s(i,D,O):void 0;if(D.provenance&&k.source&&!d(k.source,A))throw Error("The saved run points to a different repository or revision. Keep your fork as 'origin' and run `tangle solve run` again before submitting");let j=a();if(!j)throw Error("No Solve device signer found. Run `tangle solve run` first");if(j.account.address.toLowerCase()!==k.deviceAddress.toLowerCase())throw Error("The local Solve device account changed after `tangle solve run`; run the checker again");let M=r(`Checking the committed candidate…`);E.json||M.start();let N;try{N=await S(i,D.checker)}finally{M.stop()}if(N.candidateRef!==k.candidateRef||N.evidenceJson!==k.evidenceJson)throw Error("The committed checker output changed after `tangle solve run`; run the checker again");if(b(N.candidateRef,k.salt).toLowerCase()!==k.candidateId.toLowerCase())throw Error(`The saved candidate identity does not match the checker output; run the checker again`);let P=u(E.prUrl);if(!D.provenance&&P)throw Error(`This competition does not accept GitHub pull request provenance`);if(P){if(!A)throw Error(`A provenance policy is required for a pull request`);await c({pullRequest:P,taskRepository:A.taskRepository,submissionRepository:A.submissionRepository,submissionRevision:O})}let F=p(N,A,D.provenance,P,{requirePullRequest:!0}),I={...k,...A?{source:A}:{},chainState:{status:`submitting`,transactions:{...k.chainState?.transactions??{}}}},L=C.join(i,`.tangle-solve-run.json`);await l(L,I);let R=r(`Submitting candidate to Tempo…`);E.json||R.start();let z;try{z=await x(f(D),j.account,{artifactRef:N.candidateRef,salt:k.salt,evidenceJson:N.evidenceJson,evidenceRefs:F.evidenceRefs},{resumeTransactions:I.chainState?.transactions,onTransaction:async(e,t)=>{I={...I,chainState:{status:`submitting`,transactions:{...I.chainState?.transactions??{},[e]:t}}},await l(L,I)}})}finally{R.stop()}I={...I,chainReceipt:z,chainState:{status:`accepted`,transactions:{...I.chainState?.transactions??{},...g(z)}}},await l(L,I);let B=await T({deviceAddress:z.address,signer:j.account,apiUrl:E.apiUrl,profile:E.profile}),V=await _({path:`/v1/submissions`,method:`POST`,apiUrl:E.apiUrl,profile:E.profile,body:{competition:D.slug,candidateRef:N.candidateRef,candidateId:z.candidateId,evidenceJson:N.evidenceJson,evidenceRefs:F.evidenceRefs,deviceAddress:z.address,reportTxHash:z.report,evaluationTxHash:z.evaluation,transactions:g(z),...D.provenance&&A?{source:{...A,...P?{pullRequest:P}:{}}}:{},clientSubmissionId:k.clientSubmissionId,...B,...E.model?{model:E.model}:{},...E.note?{note:E.note}:{}}});E.json?e({...V,transactions:g(z),candidateId:z.candidateId}):(t(`Submission accepted on Tempo`),n({Competition:D.slug,Candidate:z.candidateId,"Device address":z.address,"Report transaction":z.report,"Evaluation transaction":z.evaluation,"Submission ID":typeof V.id==`string`?V.id:V.submission?.id}))}catch(e){i(e)}}export{E as submitCompetition};
@@ -1 +1 @@
1
- import{n as e}from"./deployment-t_Jhgj4Q.mjs";import{createPublicClient as t,createWalletClient as n,decodeAbiParameters as r,decodeEventLog as i,http as a,keccak256 as o,parseAbi as s,parseAbiItem as c,parseAbiParameters as l,stringToHex as u}from"viem";import{tempoModerato as d}from"viem/chains";import{Actions as f,withRelay as p}from"viem/tempo";const m=12e4,h=c(`event JobSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint8 jobIndex, address caller, bytes inputs)`),g=c(`event JobCompleted(uint64 indexed serviceId, uint64 indexed callId)`),_=c(`event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)`),v=c(`event AggregatedResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint256 signerBitmap, bytes output)`),y=c(`event EvaluationAccepted(uint64 indexed serviceId, uint64 indexed competitionId, address indexed researcher, bytes32 candidateId, bytes32 submissionRefHash, bytes32 evaluationDigest, bytes32 metricsHash, bytes32 evidenceRefsHash)`),b=[...s([`function submitJob(uint64 serviceId, uint8 jobIndex, bytes inputs) payable returns (uint64 callId)`,`function getJobEventRate(uint64 blueprintId, uint8 jobIndex) view returns (uint256 rate)`,`function getServicePaymentAsset(uint64 serviceId) view returns (address)`,`function isPermittedCaller(uint64 serviceId, address caller) view returns (bool)`]),h,g,_,v],x=s([`function authorizeSelf(uint64 serviceId)`,`function revokeSelf(uint64 serviceId)`,`function isDeviceRevoked(address device) view returns (bool)`,`function postStake(uint64 serviceId, uint64 competitionId) payable`,`function stakes(uint64 serviceId, uint64 competitionId, address researcher) view returns (uint256)`,`function pendingResults(uint64 serviceId, uint64 jobCallId) view returns (uint8 job, bytes32 outputHash, uint256 signerBitmap, bool exists, bool executed)`,`function executePendingResult(uint64 serviceId, uint64 jobCallId, bytes output)`,`function acceptedCandidates(uint64 serviceId, uint64 competitionId, address researcher, bytes32 candidateId) view returns (bool)`]),S=s([`function allowance(address owner, address spender) view returns (uint256)`,`function approve(address spender, uint256 amount) returns (bool)`]),C=l(`uint64 competitionId, uint256 stakeWei`),w=l(`uint64 competitionId, bytes32 commitment`),T=l(`uint64 competitionId, bytes32 commitment, string artifactRef, bytes32 salt`),E=l(`string artifactRef, bytes32 salt`),D=l(`uint64 competitionId, bytes32 candidateId, string submissionRef, string evidenceJson, string evidenceRefsJson`),O=l(`string status, string detail`),k=/^0x[0-9a-f]{64}$/i;function A(e,t){if(e!==t)throw Error(`Tempo RPC returned chain ${e}; expected ${t}`)}function j(e,t,n){return{...e,feePayer:!0,nonceKey:t,nonce:n}}function M(e,t){if(e!==`success`)throw Error(`${t} transaction reverted`)}function N(e,t,n,r){if(!k.test(t))throw Error(`${n} transaction hash is invalid`);if(typeof e.transactionHash!=`string`||e.transactionHash.toLowerCase()!==t.toLowerCase())throw Error(`${n} receipt hash does not match the saved transaction`);if(M(e.status??``,n),typeof e.from!=`string`||e.from.toLowerCase()!==r.from.toLowerCase())throw Error(`${n} receipt sender does not match the Solve device`);if(typeof e.to!=`string`||e.to.toLowerCase()!==r.to.toLowerCase())throw Error(`${n} receipt destination does not match the expected contract`)}function P(e,t){return e>=t?[]:e>0n?[0n,t]:[t]}function F(e,t,n=Date.now()){return n>=e+t}function I(e,t){return e.filter(e=>e.args?.candidateId?.toLowerCase()===t.toLowerCase()).at(-1)?.transactionHash}function L(e,t,n,r,a){for(let o of e.logs)if(o.address.toLowerCase()===t.tangleAddress.toLowerCase())try{let e=i({abi:[h],eventName:`JobSubmitted`,data:o.data,topics:o.topics});if(e.args.serviceId===t.serviceId&&e.args.jobIndex===n&&e.args.caller.toLowerCase()===r.toLowerCase()&&(!a||e.args.inputs.toLowerCase()===a.toLowerCase()))return e.args.callId}catch{}throw Error(`Tangle did not emit job ${n} for ${r}`)}function R(e,t,n,r){for(let a of e.logs)if(a.address.toLowerCase()===t.managerAddress.toLowerCase())try{let e=i({abi:[y],eventName:`EvaluationAccepted`,data:a.data,topics:a.topics}).args;if(e.serviceId===t.serviceId&&e.competitionId===t.competitionId&&e.researcher.toLowerCase()===n.address.toLowerCase()&&e.candidateId.toLowerCase()===r.toLowerCase())return!0}catch{}return!1}function z(e){if(e.chainId!==d.id)throw Error(`Solve submissions require Tempo Moderato (chain ${d.id}); received ${e.chainId}`);if(!e.sponsorUrl)throw Error(`Solve submissions require a Tempo sponsor relay URL; unsponsored writes are disabled`);return{...d,name:e.chainName,nativeCurrency:{name:e.nativeSymbol,symbol:e.nativeSymbol,decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}}async function B(r,i){e(r);let o=z(r),s=t({chain:o,transport:a(r.rpcUrl)});return A(await s.getChainId(),r.chainId),await V({publicClient:s},r),{publicClient:s,walletClient:n({account:i,chain:o,transport:p(a(r.rpcUrl),a(r.sponsorUrl))}),account:i}}async function V(e,t){let n=await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getServicePaymentAsset`,args:[t.serviceId]});if(n.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo service payment asset ${n} does not match the trusted Solve asset ${t.paymentAsset}`)}async function H(e,t,n){let[r,i]=await Promise.all([e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getJobEventRate`,args:[t.blueprintId,n]}),e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getServicePaymentAsset`,args:[t.serviceId]})]);if(i.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo job payment asset ${i} does not match the trusted Solve asset ${t.paymentAsset}`);return{asset:i,amount:r,value:i===`0x0000000000000000000000000000000000000000`?r:0n}}async function U(e,t,n){return await e.publicClient.readContract({address:t,abi:S,functionName:`allowance`,args:[e.account.address,n.tangleAddress]})}async function W(e,t,n,i,a,o){let s=Date.now();for(;!F(s,o);){if((await e.publicClient.getLogs({address:t.tangleAddress,event:g,args:{serviceId:t.serviceId,callId:n},fromBlock:i,toBlock:`latest`})).length>0){let o=(await e.publicClient.getLogs({address:t.tangleAddress,event:_,args:{serviceId:t.serviceId,callId:n},fromBlock:i,toBlock:`latest`}))[0]?.args.result;if(!o)throw Error(`Tangle job ${n} completed without a result`);let[s,c]=r(O,o);if(s!==a)throw Error(`Tangle job ${n} ${s}: ${c}`);return{status:s,detail:c}}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not complete within 120 seconds`)}async function G(e,t,n,r,i){let a=Date.now();for(;!F(a,i);){let i=(await e.publicClient.getLogs({address:t.tangleAddress,event:v,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.output;if(i)return i;await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not produce an aggregate within 120 seconds`)}async function K(e,t,n){return!!await e.publicClient.readContract({address:t.managerAddress,abi:x,functionName:`acceptedCandidates`,args:[t.serviceId,t.competitionId,e.account.address,n]})}const q=BigInt(o(u(`tangle.solve.v1`)));async function J(e,t){let n=await f.nonce.getNonce(e.publicClient,{account:e.account.address,nonceKey:q});if(n>BigInt(2**53-1))throw Error(`The Solve transaction nonce exceeds the safe range`);return e.walletClient.writeContract(j(t,q,Number(n)))}async function Y(e,t,n,r){if(!await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))try{let i=r??await J(e,{address:t.managerAddress,abi:x,functionName:`authorizeSelf`,args:[t.serviceId]});if(r||await n?.(`authorization`,i),N(await e.publicClient.waitForTransactionReceipt({hash:i}),i,`Authorization`,{from:e.account.address,to:t.managerAddress}),!await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))throw Error(`authorization transaction did not add the device`);return i}catch(e){let t=e instanceof Error?e.message:`unknown chain error`;throw Error(`The competition manager did not authorize this device. The deployed manager must expose authorizeSelf(uint64): ${t}`)}}async function X(e,t){let n=await J(e,{address:t.managerAddress,abi:x,functionName:`revokeSelf`,args:[t.serviceId]});return N(await e.publicClient.waitForTransactionReceipt({hash:n}),n,`Revocation`,{from:e.account.address,to:t.managerAddress}),n}async function Z(e,t,n,r,i=`allowance`,a={}){if(t.amount===0n||t.asset===`0x0000000000000000000000000000000000000000`)return;let o=await U(e,t.asset,n);for(let s of P(o,t.amount)){let o=s===0n?`${i}:reset`:`${i}:approval`,c=a[o];if(c){if(N(await e.publicClient.waitForTransactionReceipt({hash:c}),c,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset}),await U(e,t.asset,n)!==s)throw Error(`${s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`} did not set the expected allowance`);continue}let l=await J(e,{address:t.asset,abi:S,functionName:`approve`,args:[n.tangleAddress,s]});await r?.(o,l),N(await e.publicClient.waitForTransactionReceipt({hash:l}),l,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset})}}async function Q(e,t,n,r,i,a=`job:${n}`,o={}){let s=await H(e,t,n);await Z(e,s,t,i,`allowance:${a}`,o);let c=o[a],l=c??await J(e,{address:t.tangleAddress,abi:b,functionName:`submitJob`,args:[t.serviceId,n,r],value:s.value});c||await i?.(a,l);let u=await e.publicClient.waitForTransactionReceipt({hash:l});return N(u,l,`Job ${n}`,{from:e.account.address,to:t.tangleAddress}),{hash:l,callId:L(u,t,n,e.account.address,r),blockNumber:u.blockNumber}}async function $(e,t,n,r,i,a,o=`job:${n}`,s={}){let c=await Q(e,t,n,r,a,o,s),l=await W(e,t,c.callId,c.blockNumber,i,m);return{...c,acknowledgement:l}}export{C as _,J as a,T as b,G as c,N as d,F as f,y as g,E as h,Q as i,R as l,w as m,X as n,B as o,m as p,$ as r,K as s,Y as t,I as u,x as v,b as x,D as y};
1
+ import{n as e}from"./deployment-wpslctFo.mjs";import{createPublicClient as t,createWalletClient as n,decodeAbiParameters as r,decodeEventLog as i,http as a,keccak256 as o,parseAbi as s,parseAbiItem as c,parseAbiParameters as l,stringToHex as u}from"viem";import{tempoModerato as d}from"viem/chains";import{Actions as f,withRelay as p}from"viem/tempo";const m=12e4,h=c(`event JobSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint8 jobIndex, address caller, bytes inputs)`),g=c(`event JobCompleted(uint64 indexed serviceId, uint64 indexed callId)`),_=c(`event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)`),v=c(`event AggregatedResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, uint256 signerBitmap, bytes output)`),y=c(`event EvaluationAccepted(uint64 indexed serviceId, uint64 indexed competitionId, address indexed researcher, bytes32 candidateId, bytes32 submissionRefHash, bytes32 evaluationDigest, bytes32 metricsHash, bytes32 evidenceRefsHash)`),b=[...s([`function submitJob(uint64 serviceId, uint8 jobIndex, bytes inputs) payable returns (uint64 callId)`,`function getJobEventRate(uint64 blueprintId, uint8 jobIndex) view returns (uint256 rate)`,`function getServicePaymentAsset(uint64 serviceId) view returns (address)`,`function isPermittedCaller(uint64 serviceId, address caller) view returns (bool)`]),h,g,_,v],x=s([`function authorizeSelf(uint64 serviceId)`,`function revokeSelf(uint64 serviceId)`,`function isDeviceRevoked(address device) view returns (bool)`,`function postStake(uint64 serviceId, uint64 competitionId) payable`,`function stakes(uint64 serviceId, uint64 competitionId, address researcher) view returns (uint256)`,`function pendingResults(uint64 serviceId, uint64 jobCallId) view returns (uint8 job, bytes32 outputHash, uint256 signerBitmap, bool exists, bool executed)`,`function executePendingResult(uint64 serviceId, uint64 jobCallId, bytes output)`,`function acceptedCandidates(uint64 serviceId, uint64 competitionId, address researcher, bytes32 candidateId) view returns (bool)`]),S=s([`function allowance(address owner, address spender) view returns (uint256)`,`function approve(address spender, uint256 amount) returns (bool)`]),C=l(`uint64 competitionId, uint256 stakeWei`),w=l(`uint64 competitionId, bytes32 commitment`),T=l(`uint64 competitionId, bytes32 commitment, string artifactRef, bytes32 salt`),E=l(`string artifactRef, bytes32 salt`),D=l(`uint64 competitionId, bytes32 candidateId, string submissionRef, string evidenceJson, string evidenceRefsJson`),O=l(`string status, string detail`),k=/^0x[0-9a-f]{64}$/i;function A(e,t){if(e!==t)throw Error(`Tempo RPC returned chain ${e}; expected ${t}`)}function j(e,t,n){return{...e,feePayer:!0,nonceKey:t,nonce:n}}function M(e,t){if(e!==`success`)throw Error(`${t} transaction reverted`)}function N(e,t,n,r){if(!k.test(t))throw Error(`${n} transaction hash is invalid`);if(typeof e.transactionHash!=`string`||e.transactionHash.toLowerCase()!==t.toLowerCase())throw Error(`${n} receipt hash does not match the saved transaction`);if(M(e.status??``,n),typeof e.from!=`string`||e.from.toLowerCase()!==r.from.toLowerCase())throw Error(`${n} receipt sender does not match the Solve device`);if(typeof e.to!=`string`||e.to.toLowerCase()!==r.to.toLowerCase())throw Error(`${n} receipt destination does not match the expected contract`)}function P(e,t){return e>=t?[]:e>0n?[0n,t]:[t]}function F(e,t,n=Date.now()){return n>=e+t}function I(e,t){return e.filter(e=>e.args?.candidateId?.toLowerCase()===t.toLowerCase()).at(-1)?.transactionHash}function L(e,t,n,r,a){for(let o of e.logs)if(o.address.toLowerCase()===t.tangleAddress.toLowerCase())try{let e=i({abi:[h],eventName:`JobSubmitted`,data:o.data,topics:o.topics});if(e.args.serviceId===t.serviceId&&e.args.jobIndex===n&&e.args.caller.toLowerCase()===r.toLowerCase()&&(!a||e.args.inputs.toLowerCase()===a.toLowerCase()))return e.args.callId}catch{}throw Error(`Tangle did not emit job ${n} for ${r}`)}function R(e,t,n,r){for(let a of e.logs)if(a.address.toLowerCase()===t.managerAddress.toLowerCase())try{let e=i({abi:[y],eventName:`EvaluationAccepted`,data:a.data,topics:a.topics}).args;if(e.serviceId===t.serviceId&&e.competitionId===t.competitionId&&e.researcher.toLowerCase()===n.address.toLowerCase()&&e.candidateId.toLowerCase()===r.toLowerCase())return!0}catch{}return!1}function z(e){if(e.chainId!==d.id)throw Error(`Solve submissions require Tempo Moderato (chain ${d.id}); received ${e.chainId}`);if(!e.sponsorUrl)throw Error(`Solve submissions require a Tempo sponsor relay URL; unsponsored writes are disabled`);return{...d,name:e.chainName,nativeCurrency:{name:e.nativeSymbol,symbol:e.nativeSymbol,decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}}async function B(r,i){e(r);let o=z(r),s=t({chain:o,transport:a(r.rpcUrl)});return A(await s.getChainId(),r.chainId),await V({publicClient:s},r),{publicClient:s,walletClient:n({account:i,chain:o,transport:p(a(r.rpcUrl),a(r.sponsorUrl))}),account:i}}async function V(e,t){let n=await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getServicePaymentAsset`,args:[t.serviceId]});if(n.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo service payment asset ${n} does not match the trusted Solve asset ${t.paymentAsset}`)}async function H(e,t,n){let[r,i]=await Promise.all([e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getJobEventRate`,args:[t.blueprintId,n]}),e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`getServicePaymentAsset`,args:[t.serviceId]})]);if(i.toLowerCase()!==t.paymentAsset.toLowerCase())throw Error(`Tempo job payment asset ${i} does not match the trusted Solve asset ${t.paymentAsset}`);return{asset:i,amount:r,value:i===`0x0000000000000000000000000000000000000000`?r:0n}}async function U(e,t,n){return await e.publicClient.readContract({address:t,abi:S,functionName:`allowance`,args:[e.account.address,n.tangleAddress]})}async function W(e,t,n,i,a,o){let s=Date.now();for(;!F(s,o);){if((await e.publicClient.getLogs({address:t.tangleAddress,event:g,args:{serviceId:t.serviceId,callId:n},fromBlock:i,toBlock:`latest`})).length>0){let o=(await e.publicClient.getLogs({address:t.tangleAddress,event:_,args:{serviceId:t.serviceId,callId:n},fromBlock:i,toBlock:`latest`}))[0]?.args.result;if(!o)throw Error(`Tangle job ${n} completed without a result`);let[s,c]=r(O,o);if(s!==a)throw Error(`Tangle job ${n} ${s}: ${c}`);return{status:s,detail:c}}await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not complete within 120 seconds`)}async function G(e,t,n,r,i){let a=Date.now();for(;!F(a,i);){let i=(await e.publicClient.getLogs({address:t.tangleAddress,event:v,args:{serviceId:t.serviceId,callId:n},fromBlock:r,toBlock:`latest`}))[0]?.args.output;if(i)return i;await new Promise(e=>setTimeout(e,1e3))}throw Error(`Tangle job ${n} did not produce an aggregate within 120 seconds`)}async function K(e,t,n){return!!await e.publicClient.readContract({address:t.managerAddress,abi:x,functionName:`acceptedCandidates`,args:[t.serviceId,t.competitionId,e.account.address,n]})}const q=BigInt(o(u(`tangle.solve.v1`)));async function J(e,t){let n=await f.nonce.getNonce(e.publicClient,{account:e.account.address,nonceKey:q});if(n>BigInt(2**53-1))throw Error(`The Solve transaction nonce exceeds the safe range`);return e.walletClient.writeContract(j(t,q,Number(n)))}async function Y(e,t,n,r){if(!await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))try{let i=r??await J(e,{address:t.managerAddress,abi:x,functionName:`authorizeSelf`,args:[t.serviceId]});if(r||await n?.(`authorization`,i),N(await e.publicClient.waitForTransactionReceipt({hash:i}),i,`Authorization`,{from:e.account.address,to:t.managerAddress}),!await e.publicClient.readContract({address:t.tangleAddress,abi:b,functionName:`isPermittedCaller`,args:[t.serviceId,e.account.address]}))throw Error(`authorization transaction did not add the device`);return i}catch(e){let t=e instanceof Error?e.message:`unknown chain error`;throw Error(`The competition manager did not authorize this device. The deployed manager must expose authorizeSelf(uint64): ${t}`)}}async function X(e,t){let n=await J(e,{address:t.managerAddress,abi:x,functionName:`revokeSelf`,args:[t.serviceId]});return N(await e.publicClient.waitForTransactionReceipt({hash:n}),n,`Revocation`,{from:e.account.address,to:t.managerAddress}),n}async function Z(e,t,n,r,i=`allowance`,a={}){if(t.amount===0n||t.asset===`0x0000000000000000000000000000000000000000`)return;let o=await U(e,t.asset,n);for(let s of P(o,t.amount)){let o=s===0n?`${i}:reset`:`${i}:approval`,c=a[o];if(c){if(N(await e.publicClient.waitForTransactionReceipt({hash:c}),c,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset}),await U(e,t.asset,n)!==s)throw Error(`${s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`} did not set the expected allowance`);continue}let l=await J(e,{address:t.asset,abi:S,functionName:`approve`,args:[n.tangleAddress,s]});await r?.(o,l),N(await e.publicClient.waitForTransactionReceipt({hash:l}),l,s===0n?`ERC-20 allowance reset`:`ERC-20 allowance approval`,{from:e.account.address,to:t.asset})}}async function Q(e,t,n,r,i,a=`job:${n}`,o={}){let s=await H(e,t,n);await Z(e,s,t,i,`allowance:${a}`,o);let c=o[a],l=c??await J(e,{address:t.tangleAddress,abi:b,functionName:`submitJob`,args:[t.serviceId,n,r],value:s.value});c||await i?.(a,l);let u=await e.publicClient.waitForTransactionReceipt({hash:l});return N(u,l,`Job ${n}`,{from:e.account.address,to:t.tangleAddress}),{hash:l,callId:L(u,t,n,e.account.address,r),blockNumber:u.blockNumber}}async function $(e,t,n,r,i,a,o=`job:${n}`,s={}){let c=await Q(e,t,n,r,a,o,s),l=await W(e,t,c.callId,c.blockNumber,i,m);return{...c,acknowledgement:l}}export{C as _,J as a,T as b,G as c,N as d,F as f,y as g,E as h,Q as i,R as l,w as m,X as n,B as o,m as p,$ as r,K as s,Y as t,I as u,x as v,b as x,D as y};
@@ -1 +1 @@
1
- import{t as e}from"./deployment-t_Jhgj4Q.mjs";import*as t from"node:path";import{createHash as n}from"node:crypto";import{execFile as r}from"node:child_process";import*as i from"node:fs/promises";import{promisify as a}from"node:util";import{getAddress as o,isAddress as s}from"viem";const c=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;function l(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function u(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function d(e,t,n=2048){if(typeof e!=`string`||!e.trim()||e.length>n)throw Error(`${t} is missing or invalid`);if(l(e))throw Error(`${t} contains control characters`);return e.trim()}function f(e,t){let n=d(e,t,64).toLowerCase();if(!c.test(n))throw Error(`${t} must be a 40 or 64 character Git revision`);return n}function p(e,t,n=!1){let r=typeof e==`number`&&Number.isSafeInteger(e)?String(e):d(e,t,80);if(!/^\d+$/.test(r)||!n&&r===`0`)throw Error(`${t} must be an unsigned integer`);return BigInt(r).toString()}function m(e,t){let n=d(e,t,2048),r=new URL(n);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&(r.hostname===`localhost`||r.hostname===`127.0.0.1`)))throw Error(`${t} must use HTTPS outside local development`);return n.replace(/\/$/,``)}function h(e,t){let n=m(e,t).replace(/\.git$/,``),r=new URL(n),i=r.pathname.split(`/`).filter(Boolean);if(r.hostname!==`github.com`||r.username||r.password||r.search||r.hash||i.length!==2)throw Error(`${t} must be an HTTPS GitHub repository URL`);return`https://github.com/${i.join(`/`)}`}function g(e,t){let n=d(e,t,42);if(!s(n,{strict:!1}))throw Error(`${t} must be an EVM address`);return o(n)}function _(e,t){let n=p(e,t),r=Number(n);if(!Number.isSafeInteger(r)||r<=0)throw Error(`${t} is out of range`);return r}function v(...e){for(let t of e)if(typeof t==`string`&&t.trim())return t.trim()}function y(e){let t=e.trim().replace(/\.git$/,``);return t.startsWith(`git@github.com:`)?`https://github.com/${t.slice(15)}`:t.startsWith(`ssh://git@github.com/`)?`https://github.com/${t.slice(21)}`:t}function b(e){if(e===void 0)return;let t=d(e,`pull request URL`,2048);if(!/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:\/[^\s]*)?$/i.test(t))throw Error(`pull request URL must point to a GitHub pull request`);return t}function x(e,t){if(!/^https:\/\/[^\s]+$/i.test(e)&&!/^\/(?!\/).*$/.test(e)&&!/^[a-z][a-z0-9+.-]*:[^\s]+$/i.test(e))throw Error(`${t} must be an HTTPS URL or an absolute repository path`);if(e.split(/[?#]/,1)[0].split(`/`).includes(`..`))throw Error(`${t} cannot contain parent-directory segments`);return e}function S(e,t){let n=u(t.check??e.check,`competition.participation.check`),r=d(n.command,`competition.participation.check.command`,512);if(!Array.isArray(n.args)||n.args.some(e=>typeof e!=`string`))throw Error(`competition.participation.check.args must be an array of strings`);let i=n.args.map(e=>d(e,`competition checker argument`,2048)),a=v(n.result_file,n.resultFile),o=n.timeout_ms??n.timeoutMs,s=o===void 0?void 0:_(o,`competition checker timeout`);return{command:r,args:i,...a?{result_file:a}:{},...s?{timeout_ms:s}:{}}}function C(e){if(e.provenance===void 0)return;let t=u(e.provenance,`competition.participation.provenance`);if(t.mode!==`github_pull_request`)throw Error(`competition.participation.provenance.mode is unsupported`);if(t.required!==void 0&&typeof t.required!=`boolean`)throw Error(`competition.participation.provenance.required must be a boolean`);return{mode:`github_pull_request`,required:t.required===!0}}function w(t){let n=u(t.chain??t.network??{},`competition.chain`),r=t.rewards&&typeof t.rewards==`object`&&!Array.isArray(t.rewards)?u(t.rewards,`competition.rewards`):{},i=r.minStake&&typeof r.minStake==`object`&&!Array.isArray(r.minStake)?u(r.minStake,`competition.rewards.minStake`).raw:void 0,a=v(n.minStakeWei,n.min_stake_wei,t.minStakeWei,t.min_stake_wei,i),o=n.chainId??n.chain_id??t.chainId??t.chain_id,s=v(n.chainName,n.chain_name,t.chainName,t.chain_name)??`Tempo`,c=v(n.nativeSymbol,n.native_symbol,t.nativeSymbol,t.native_symbol)??`TNT`,l=v(n.rpcUrl,n.rpc_url,t.rpcUrl,t.rpc_url,process.env.TANGLE_SOLVE_RPC_URL),d=v(n.sponsorUrl,n.sponsor_url,t.sponsorUrl,t.sponsor_url,process.env.TANGLE_SOLVE_SPONSOR_URL),f=v(n.tangleAddress,n.tangle_address,n.coreAddress,n.core_address,t.tangleAddress,t.tangle_address,t.coreAddress,t.core_address),h=v(n.managerAddress,n.manager_address,t.managerAddress,t.manager_address),y=v(n.paymentAsset,n.payment_asset,n.servicePaymentAsset,n.service_payment_asset,t.paymentAsset,t.payment_asset,t.servicePaymentAsset,t.service_payment_asset),b=v(n.blueprintId,n.blueprint_id,t.blueprintId,t.blueprint_id),x=v(n.serviceId,n.service_id,t.serviceId,t.service_id),S=v(n.competitionId,n.competition_id,t.competitionId,t.competition_id,t.id);if(!l||!d||!f||!h||!b||!x||!S||!a||o===void 0)throw Error(`Solve competition metadata must include complete Tempo chain configuration`);return{chainId:_(o,`chain.chainId`),chainName:s,nativeSymbol:c,rpcUrl:m(l,`chain.rpcUrl`),sponsorUrl:m(d,`chain.sponsorUrl`),tangleAddress:g(f,`chain.tangleAddress`),managerAddress:g(h,`chain.managerAddress`),paymentAsset:g(y??e.paymentAsset,`chain.paymentAsset`),blueprintId:p(b,`chain.blueprintId`),serviceId:p(x,`chain.serviceId`),competitionId:p(S,`chain.competitionId`,!0),minStakeWei:p(a,`chain.minStakeWei`,!0)}}function T(e){let t=u(e,`competition`),n=u(t.participation??t.task,`competition.task`),r={...t,participation:{...n,...n.repositoryRevision===void 0&&n.revision!==void 0?{repositoryRevision:n.revision}:{}}},i=r.participation,a=h(v(r.repository,r.repo_url,i.repository)??``,`competition.repository`),o=f(v(r.repositoryRevision,r.repository_revision,i.revision,i.repositoryRevision,i.repository_revision),`competition.repositoryRevision`),s=d(r.slug??r.id,`competition.slug`,128),c=d(r.name??r.title??s,`competition.name`,256),l=S(r,i),p=C(i);return{version:1,slug:s,title:c,repository:a,taskRevision:o,checker:l,chain:w(r),...p?{provenance:p}:{}}}function E(e){return{chainId:e.chain.chainId,chainName:e.chain.chainName,nativeSymbol:e.chain.nativeSymbol,rpcUrl:e.chain.rpcUrl,sponsorUrl:e.chain.sponsorUrl,tangleAddress:e.chain.tangleAddress,managerAddress:e.chain.managerAddress,paymentAsset:e.chain.paymentAsset,blueprintId:BigInt(e.chain.blueprintId),serviceId:BigInt(e.chain.serviceId),competitionId:BigInt(e.chain.competitionId),minStakeWei:BigInt(e.chain.minStakeWei)}}async function D(e){let n=u(JSON.parse(await i.readFile(t.join(e,`.tangle-solve.json`),`utf8`)),`.tangle-solve.json`);if(n.version!==1)throw Error(`.tangle-solve.json has an unsupported version`);let r=u(n.checker,`.tangle-solve.json.checker`),a=u(n.chain,`.tangle-solve.json.chain`);return T({slug:n.slug,name:n.title,repository:n.repository,repositoryRevision:n.taskRevision,participation:{check:r,provenance:n.provenance},chain:a,competitionId:a.competitionId})}const O=a(r),k=`.tangle-solve-run.json`,A=`.tangle-solve.json`,j=`tangle.solve.manifestSha256`,M=new Set([A,k]),N=`upstream`;async function P(e,t){let n=await O(`git`,[`-C`,e,...t],{encoding:`utf8`,maxBuffer:1e6});return String(n.stdout).trim()}async function F(e,n){let r=t.resolve(n??process.cwd()),i=await D(r);if(e&&e!==i.slug&&e!==i.chain.competitionId)throw Error(`This directory contains '${i.slug}', not '${e}'`);return{root:r,manifest:i}}async function I(e){let r=t.join(e,A),a;try{a=await i.lstat(r)}catch{throw Error(`${A} is missing`)}if(a.isSymbolicLink()||!a.isFile())throw Error(`${A} must be a regular file`);return n(`sha256`).update(await i.readFile(r)).digest(`hex`)}async function L(e){let t=await I(e);return await P(e,[`config`,`--local`,`--replace-all`,j,t]),t}async function R(e){let t;try{t=await P(e,[`config`,`--local`,`--get`,j])}catch{throw Error(`The local Git metadata has no ${j} pin; run tangle solve clone again`)}if(!/^[0-9a-f]{64}$/i.test(t))throw Error(`The local ${j} pin is invalid`);if(await I(e)!==t.toLowerCase())throw Error(`${A} changed after clone; run tangle solve clone again`)}async function z(e,t){try{return await P(e,[`ls-files`,`--error-unmatch`,`--`,t]),!0}catch{return!1}}async function B(e){await R(e);for(let t of M)if(await z(e,t))throw Error(`${t} must remain untracked and local to this Solve workspace`);let t=await O(`git`,[`-C`,e,`status`,`--porcelain=v1`,`--untracked-files=all`,`--ignored=matching`],{encoding:`utf8`,maxBuffer:1e6});if(String(t.stdout).split(/\r?\n/).filter(Boolean).filter(e=>{let t=e.slice(0,2),n=e.slice(3);return!((t===`??`||t===`!!`)&&M.has(n))}).length>0)throw Error(`Commit the candidate before running Solve. Only the local manifest and run record may remain uncommitted.`);return f(await P(e,[`rev-parse`,`HEAD`]),`submission revision`)}async function V(e,t,n,r={}){let i=await H(e,t,r);if(i)return{taskRepository:t.repository,taskRevision:t.taskRevision,submissionRepository:i,submissionRevision:n}}async function H(e,t,n={}){let r;try{r=y(await P(e,[`config`,`--get`,`remote.origin.pushurl`]))}catch{try{r=y(await P(e,[`config`,`--get`,`remote.origin.url`]))}catch{if(n.allowMissing)return;throw Error(`Add your GitHub fork as the 'origin' remote before submitting. The task repository is available as '${N}'.`)}}let i=h(r,`git remote.origin.url`);if(i.toLowerCase()===t.repository.toLowerCase()){if(n.allowMissing)return;throw Error(`The 'origin' remote is the task repository. Add your GitHub fork as 'origin'; keep the task repository as '${N}' before submitting.`)}return i}function U(e,t){return!e||!t?!1:e.taskRepository.toLowerCase()===t.taskRepository.toLowerCase()&&e.taskRevision.toLowerCase()===t.taskRevision.toLowerCase()&&e.submissionRepository.toLowerCase()===t.submissionRepository.toLowerCase()&&e.submissionRevision.toLowerCase()===t.submissionRevision.toLowerCase()}function W(e,t){return`${e}/commit/${t}`}function G(e,t,n,r,i={}){let a=e.evidenceRefs.map(e=>x(e.trim(),`checker evidence reference`));if(n){if(!t){if(i.allowMissingSource)return{evidence:e.evidence,evidenceRefs:a};throw Error(`Provenance policy requires a submission source`)}let o=b(r);if(n.required&&(i.requirePullRequest??!0)&&!o)throw Error(`This competition requires a GitHub pull request`);a.push(W(t.taskRepository,t.taskRevision),W(t.submissionRepository,t.submissionRevision),...o?[o]:[])}return{evidence:e.evidence,evidenceRefs:[...new Set(a)]}}async function K(e,t){let n=`${e}.${process.pid}.tmp`;await i.writeFile(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await i.rename(n,e)}async function q(e){let n=JSON.parse(await i.readFile(t.join(e,k),`utf8`));if(n.version!==1||typeof n.competition!=`string`)throw Error(`${k} has an unsupported format`);return n}async function J(e){let t=b(e.pullRequest);if(!t)throw Error(`A pull request URL is required`);let n=new URL(t).pathname.split(`/`).filter(Boolean),r=await fetch(`https://api.github.com/repos/${n[0]}/${n[1]}/pulls/${n[3]}`,{headers:{Accept:`application/vnd.github+json`,"User-Agent":`tangle-solve-cli`},signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>null),a=e=>e.replace(/\/$/,``).toLowerCase();if(!r.ok||a(i?.base?.repo?.html_url??``)!==a(e.taskRepository)||i?.head?.sha?.toLowerCase()!==e.submissionRevision.toLowerCase()||a(i?.head?.repo?.html_url??``)!==a(e.submissionRepository))throw Error(`GitHub pull request must target the pinned task repository and contain the current committed submission`)}function Y(e){return{...e.authorization?{authorization:e.authorization}:{},...e.stake?{stake:e.stake}:{},join:e.join,commit:e.commit,reveal:e.reveal,report:e.report,evaluation:e.evaluation}}export{q as a,V as c,J as d,K as f,u as g,b as h,L as i,U as l,E as m,G as n,B as o,T as p,P as r,F as s,N as t,Y as u};
1
+ import{t as e}from"./deployment-wpslctFo.mjs";import*as t from"node:path";import{createHash as n}from"node:crypto";import{execFile as r}from"node:child_process";import*as i from"node:fs/promises";import{promisify as a}from"node:util";import{getAddress as o,isAddress as s}from"viem";const c=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;function l(e){return[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127})}function u(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function d(e,t,n=2048){if(typeof e!=`string`||!e.trim()||e.length>n)throw Error(`${t} is missing or invalid`);if(l(e))throw Error(`${t} contains control characters`);return e.trim()}function f(e,t){let n=d(e,t,64).toLowerCase();if(!c.test(n))throw Error(`${t} must be a 40 or 64 character Git revision`);return n}function p(e,t,n=!1){let r=typeof e==`number`&&Number.isSafeInteger(e)?String(e):d(e,t,80);if(!/^\d+$/.test(r)||!n&&r===`0`)throw Error(`${t} must be an unsigned integer`);return BigInt(r).toString()}function m(e,t){let n=d(e,t,2048),r=new URL(n);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&(r.hostname===`localhost`||r.hostname===`127.0.0.1`)))throw Error(`${t} must use HTTPS outside local development`);return n.replace(/\/$/,``)}function h(e,t){let n=m(e,t).replace(/\.git$/,``),r=new URL(n),i=r.pathname.split(`/`).filter(Boolean);if(r.hostname!==`github.com`||r.username||r.password||r.search||r.hash||i.length!==2)throw Error(`${t} must be an HTTPS GitHub repository URL`);return`https://github.com/${i.join(`/`)}`}function g(e,t){let n=d(e,t,42);if(!s(n,{strict:!1}))throw Error(`${t} must be an EVM address`);return o(n)}function _(e,t){let n=p(e,t),r=Number(n);if(!Number.isSafeInteger(r)||r<=0)throw Error(`${t} is out of range`);return r}function v(...e){for(let t of e)if(typeof t==`string`&&t.trim())return t.trim()}function y(e){let t=e.trim().replace(/\.git$/,``);return t.startsWith(`git@github.com:`)?`https://github.com/${t.slice(15)}`:t.startsWith(`ssh://git@github.com/`)?`https://github.com/${t.slice(21)}`:t}function b(e){if(e===void 0)return;let t=d(e,`pull request URL`,2048);if(!/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:\/[^\s]*)?$/i.test(t))throw Error(`pull request URL must point to a GitHub pull request`);return t}function x(e,t){if(!/^https:\/\/[^\s]+$/i.test(e)&&!/^\/(?!\/).*$/.test(e)&&!/^[a-z][a-z0-9+.-]*:[^\s]+$/i.test(e))throw Error(`${t} must be an HTTPS URL or an absolute repository path`);if(e.split(/[?#]/,1)[0].split(`/`).includes(`..`))throw Error(`${t} cannot contain parent-directory segments`);return e}function S(e,t){let n=u(t.check??e.check,`competition.participation.check`),r=d(n.command,`competition.participation.check.command`,512);if(!Array.isArray(n.args)||n.args.some(e=>typeof e!=`string`))throw Error(`competition.participation.check.args must be an array of strings`);let i=n.args.map(e=>d(e,`competition checker argument`,2048)),a=v(n.result_file,n.resultFile),o=n.timeout_ms??n.timeoutMs,s=o===void 0?void 0:_(o,`competition checker timeout`);return{command:r,args:i,...a?{result_file:a}:{},...s?{timeout_ms:s}:{}}}function C(e){if(e.provenance===void 0)return;let t=u(e.provenance,`competition.participation.provenance`);if(t.mode!==`github_pull_request`)throw Error(`competition.participation.provenance.mode is unsupported`);if(t.required!==void 0&&typeof t.required!=`boolean`)throw Error(`competition.participation.provenance.required must be a boolean`);return{mode:`github_pull_request`,required:t.required===!0}}function w(t){let n=u(t.chain??t.network??{},`competition.chain`),r=t.rewards&&typeof t.rewards==`object`&&!Array.isArray(t.rewards)?u(t.rewards,`competition.rewards`):{},i=r.minStake&&typeof r.minStake==`object`&&!Array.isArray(r.minStake)?u(r.minStake,`competition.rewards.minStake`).raw:void 0,a=v(n.minStakeWei,n.min_stake_wei,t.minStakeWei,t.min_stake_wei,i),o=n.chainId??n.chain_id??t.chainId??t.chain_id,s=v(n.chainName,n.chain_name,t.chainName,t.chain_name)??`Tempo`,c=v(n.nativeSymbol,n.native_symbol,t.nativeSymbol,t.native_symbol)??`TNT`,l=v(n.rpcUrl,n.rpc_url,t.rpcUrl,t.rpc_url,process.env.TANGLE_SOLVE_RPC_URL),d=v(n.sponsorUrl,n.sponsor_url,t.sponsorUrl,t.sponsor_url,process.env.TANGLE_SOLVE_SPONSOR_URL),f=v(n.tangleAddress,n.tangle_address,n.coreAddress,n.core_address,t.tangleAddress,t.tangle_address,t.coreAddress,t.core_address),h=v(n.managerAddress,n.manager_address,t.managerAddress,t.manager_address),y=v(n.paymentAsset,n.payment_asset,n.servicePaymentAsset,n.service_payment_asset,t.paymentAsset,t.payment_asset,t.servicePaymentAsset,t.service_payment_asset),b=v(n.blueprintId,n.blueprint_id,t.blueprintId,t.blueprint_id),x=v(n.serviceId,n.service_id,t.serviceId,t.service_id),S=v(n.competitionId,n.competition_id,t.competitionId,t.competition_id,t.id);if(!l||!d||!f||!h||!b||!x||!S||!a||o===void 0)throw Error(`Solve competition metadata must include complete Tempo chain configuration`);return{chainId:_(o,`chain.chainId`),chainName:s,nativeSymbol:c,rpcUrl:m(l,`chain.rpcUrl`),sponsorUrl:m(d,`chain.sponsorUrl`),tangleAddress:g(f,`chain.tangleAddress`),managerAddress:g(h,`chain.managerAddress`),paymentAsset:g(y??e.paymentAsset,`chain.paymentAsset`),blueprintId:p(b,`chain.blueprintId`),serviceId:p(x,`chain.serviceId`),competitionId:p(S,`chain.competitionId`,!0),minStakeWei:p(a,`chain.minStakeWei`,!0)}}function T(e){let t=u(e,`competition`),n=u(t.participation??t.task,`competition.task`),r={...t,participation:{...n,...n.repositoryRevision===void 0&&n.revision!==void 0?{repositoryRevision:n.revision}:{}}},i=r.participation,a=h(v(r.repository,r.repo_url,i.repository)??``,`competition.repository`),o=f(v(r.repositoryRevision,r.repository_revision,i.revision,i.repositoryRevision,i.repository_revision),`competition.repositoryRevision`),s=d(r.slug??r.id,`competition.slug`,128),c=d(r.name??r.title??s,`competition.name`,256),l=S(r,i),p=C(i);return{version:1,slug:s,title:c,repository:a,taskRevision:o,checker:l,chain:w(r),...p?{provenance:p}:{}}}function E(e){return{chainId:e.chain.chainId,chainName:e.chain.chainName,nativeSymbol:e.chain.nativeSymbol,rpcUrl:e.chain.rpcUrl,sponsorUrl:e.chain.sponsorUrl,tangleAddress:e.chain.tangleAddress,managerAddress:e.chain.managerAddress,paymentAsset:e.chain.paymentAsset,blueprintId:BigInt(e.chain.blueprintId),serviceId:BigInt(e.chain.serviceId),competitionId:BigInt(e.chain.competitionId),minStakeWei:BigInt(e.chain.minStakeWei)}}async function D(e){let n=u(JSON.parse(await i.readFile(t.join(e,`.tangle-solve.json`),`utf8`)),`.tangle-solve.json`);if(n.version!==1)throw Error(`.tangle-solve.json has an unsupported version`);let r=u(n.checker,`.tangle-solve.json.checker`),a=u(n.chain,`.tangle-solve.json.chain`);return T({slug:n.slug,name:n.title,repository:n.repository,repositoryRevision:n.taskRevision,participation:{check:r,provenance:n.provenance},chain:a,competitionId:a.competitionId})}const O=a(r),k=`.tangle-solve-run.json`,A=`.tangle-solve.json`,j=`tangle.solve.manifestSha256`,M=new Set([A,k]),N=`upstream`;async function P(e,t){let n=await O(`git`,[`-C`,e,...t],{encoding:`utf8`,maxBuffer:1e6});return String(n.stdout).trim()}async function F(e,n){let r=t.resolve(n??process.cwd()),i=await D(r);if(e&&e!==i.slug&&e!==i.chain.competitionId)throw Error(`This directory contains '${i.slug}', not '${e}'`);return{root:r,manifest:i}}async function I(e){let r=t.join(e,A),a;try{a=await i.lstat(r)}catch{throw Error(`${A} is missing`)}if(a.isSymbolicLink()||!a.isFile())throw Error(`${A} must be a regular file`);return n(`sha256`).update(await i.readFile(r)).digest(`hex`)}async function L(e){let t=await I(e);return await P(e,[`config`,`--local`,`--replace-all`,j,t]),t}async function R(e){let t;try{t=await P(e,[`config`,`--local`,`--get`,j])}catch{throw Error(`The local Git metadata has no ${j} pin; run tangle solve clone again`)}if(!/^[0-9a-f]{64}$/i.test(t))throw Error(`The local ${j} pin is invalid`);if(await I(e)!==t.toLowerCase())throw Error(`${A} changed after clone; run tangle solve clone again`)}async function z(e,t){try{return await P(e,[`ls-files`,`--error-unmatch`,`--`,t]),!0}catch{return!1}}async function B(e){await R(e);for(let t of M)if(await z(e,t))throw Error(`${t} must remain untracked and local to this Solve workspace`);let t=await O(`git`,[`-C`,e,`status`,`--porcelain=v1`,`--untracked-files=all`,`--ignored=matching`],{encoding:`utf8`,maxBuffer:1e6});if(String(t.stdout).split(/\r?\n/).filter(Boolean).filter(e=>{let t=e.slice(0,2),n=e.slice(3);return!((t===`??`||t===`!!`)&&M.has(n))}).length>0)throw Error(`Commit the candidate before running Solve. Only the local manifest and run record may remain uncommitted.`);return f(await P(e,[`rev-parse`,`HEAD`]),`submission revision`)}async function V(e,t,n,r={}){let i=await H(e,t,r);if(i)return{taskRepository:t.repository,taskRevision:t.taskRevision,submissionRepository:i,submissionRevision:n}}async function H(e,t,n={}){let r;try{r=y(await P(e,[`config`,`--get`,`remote.origin.pushurl`]))}catch{try{r=y(await P(e,[`config`,`--get`,`remote.origin.url`]))}catch{if(n.allowMissing)return;throw Error(`Add your GitHub fork as the 'origin' remote before submitting. The task repository is available as '${N}'.`)}}let i=h(r,`git remote.origin.url`);if(i.toLowerCase()===t.repository.toLowerCase()){if(n.allowMissing)return;throw Error(`The 'origin' remote is the task repository. Add your GitHub fork as 'origin'; keep the task repository as '${N}' before submitting.`)}return i}function U(e,t){return!e||!t?!1:e.taskRepository.toLowerCase()===t.taskRepository.toLowerCase()&&e.taskRevision.toLowerCase()===t.taskRevision.toLowerCase()&&e.submissionRepository.toLowerCase()===t.submissionRepository.toLowerCase()&&e.submissionRevision.toLowerCase()===t.submissionRevision.toLowerCase()}function W(e,t){return`${e}/commit/${t}`}function G(e,t,n,r,i={}){let a=e.evidenceRefs.map(e=>x(e.trim(),`checker evidence reference`));if(n){if(!t){if(i.allowMissingSource)return{evidence:e.evidence,evidenceRefs:a};throw Error(`Provenance policy requires a submission source`)}let o=b(r);if(n.required&&(i.requirePullRequest??!0)&&!o)throw Error(`This competition requires a GitHub pull request`);a.push(W(t.taskRepository,t.taskRevision),W(t.submissionRepository,t.submissionRevision),...o?[o]:[])}return{evidence:e.evidence,evidenceRefs:[...new Set(a)]}}async function K(e,t){let n=`${e}.${process.pid}.tmp`;await i.writeFile(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await i.rename(n,e)}async function q(e){let n=JSON.parse(await i.readFile(t.join(e,k),`utf8`));if(n.version!==1||typeof n.competition!=`string`)throw Error(`${k} has an unsupported format`);return n}async function J(e){let t=b(e.pullRequest);if(!t)throw Error(`A pull request URL is required`);let n=new URL(t).pathname.split(`/`).filter(Boolean),r=await fetch(`https://api.github.com/repos/${n[0]}/${n[1]}/pulls/${n[3]}`,{headers:{Accept:`application/vnd.github+json`,"User-Agent":`tangle-solve-cli`},signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>null),a=e=>e.replace(/\/$/,``).toLowerCase();if(!r.ok||a(i?.base?.repo?.html_url??``)!==a(e.taskRepository)||i?.head?.sha?.toLowerCase()!==e.submissionRevision.toLowerCase()||a(i?.head?.repo?.html_url??``)!==a(e.submissionRepository))throw Error(`GitHub pull request must target the pinned task repository and contain the current committed submission`)}function Y(e){return{...e.authorization?{authorization:e.authorization}:{},...e.stake?{stake:e.stake}:{},join:e.join,commit:e.commit,reveal:e.reveal,report:e.report,evaluation:e.evaluation}}export{q as a,V as c,J as d,K as f,u as g,b as h,L as i,U as l,E as m,G as n,B as o,T as p,P as r,F as s,N as t,Y as u};
@@ -0,0 +1,51 @@
1
+ # Code, topology and Knowledge candidates
2
+
3
+ Candidate generation, staging and promotion are different operations. These commands retain exact owner candidates and return held work. They do not publish a repository, change curated Knowledge or activate a workflow.
4
+
5
+ ```sh
6
+ tangle graph candidate generate graph.yaml cohort/ suite.json author.graph.yaml policy.json campaign/
7
+ tangle graph candidate code candidate-input.json policy.json
8
+ tangle graph candidate knowledge baseline-bundle.json ./knowledge-store measured-reference.json
9
+ tangle graph candidate knowledge-generate ./knowledge-store writer.graph.yaml suite.json campaign/
10
+ ```
11
+
12
+ `generate` uses Runtime's native code improvement method and its Git worktree driver. It does not use the profile optimizer selected for GEPA or another profile method. Only retained `train` cases reach this search. Its final holdout is explicitly deferred, so a training gain cannot authorize promotion.
13
+
14
+ The mutation repository must be committed. Native training currently supports one declared graph YAML or JSON file. The policy names that exact file in `allowedPaths` and `graph.path`. Runtime compiles each candidate with each case's retained parameters, trigger and task snapshot. Authored check definitions, their parameter declarations and incident check routes stay fixed. The calibrated domain evaluator remains outside candidate workspaces and its declared dependencies are checked before and after scoring.
15
+
16
+ The author is another native graph. It declares a string parameter named `instruction`, one agent and one command-verification node, and a deliverable requiring the verifier's `/pass` to equal `true`. Its budgets must fit the suite's proposal ceilings. The instruction may enter its task or one inline `prompt.systemPrompt` or `prompt.appendSystemPrompt` scalar. Other prompt fields, model settings, capabilities, checks, routes and budgets cannot change when proposal context is bound. The runner checks the exact context-compiled author profile before dispatch.
17
+
18
+ Native authoring and training execute explicitly selected, trusted local graphs. Local check commands and native shell are not protected candidate isolation. The command refuses declared external integration bindings and secret-bearing checks, but that refusal does not prove that arbitrary local commands have no external effects. Do not connect production replay to this mode automatically.
19
+
20
+ Author and training runs share the existing persisted Runtime budget pool. Runtime's native search account records their actual or unavailable billing receipts. Unavailable billing is not billed zero. Job summaries from older owners may lack token completeness; absence remains unavailable and is never filled with `true`. The retained Native run identifies each executed profile and attempt; an aggregate search receipt does not invent one provider model for a graph containing several models.
21
+
22
+ The result retains its `CodeSurface`, search ancestry, budget readout and evidence references. Author workspaces are captured through Runtime's bounded working-tree snapshot owner before the code driver cleans them up. A capture failure is recorded explicitly and stops the search. Each evaluated code tree is archived through Runtime and indexed by Eval's existing attempt artifact writer, including rejected cases. Toolchains and external services remain explicit reproduction gaps.
23
+
24
+ `code` accepts Runtime's `BuildAgentCandidateBundleInput` with a verified `code-surface` and an explicit path policy. It creates the unchanged baseline through Eval's Git worktree adapter and captures separate exact Git-tree snapshots for both arms. The supplied execution contract must name a real entrypoint in that repository. Sealing these bundles does not establish that this entrypoint passed an independent final experiment.
25
+
26
+ `knowledge` accepts an existing sealed base bundle and the Knowledge owner's measured candidate reference. Runtime reopens the persisted reference, evidence and isolated comparison, checks the current curated state, and captures both snapshots through the same implementation used by Knowledge improvement jobs. It does not rerun the single-use final evaluator. Exact file-backed Knowledge candidate operations use the platform supported by the Knowledge owner. Hub generation publication uses its separate source owner.
27
+
28
+ | Operation | Maintained owner |
29
+ | --- | --- |
30
+ | Generate, finalize and retain code candidates | Runtime `improve({ surface: 'code' })`, Eval Git worktree adapter |
31
+ | Capture executable code bytes | Runtime `captureAgentCodeCandidateWorkspace` and existing workspace archive |
32
+ | Generate and capture Knowledge candidates | Runtime `runKnowledgeImprovementJob`, `captureKnowledgeImprovementCandidatePair`; Knowledge isolated comparison |
33
+ | Seal the two Knowledge arms | Runtime `buildKnowledgeImprovementExperimentBundles` |
34
+ | Independently execute sealed candidates | Runtime `runAgentCandidateExperiment` and its canonical `placeCell` host port |
35
+ | Review and activate | Runtime proposal/review/activation contracts and the product's exact-state transaction |
36
+
37
+ Generic implementation execution and protected final comparison need that actual `placeCell` host. Missing placement means hold. The native profile proposal path has its own maintained Runtime executor contract; these commands do not replace it with guessed protected grants.
38
+
39
+ The candidate namespace requires the Runtime artifact exporting the capture functions above. CLI registration must follow normal owner publication and exact package adoption. Source fixtures cover the intended CLI paths, cohort boundaries, snapshots, stale references and denial cases; source changes alone do not qualify native model performance, hosted placement or production activation.
40
+
41
+ ## Generate a Knowledge candidate
42
+
43
+ `knowledge-generate` calls Runtime's maintained `runKnowledgeImprovementJob`. The owner creates an isolated candidate and supplies its exact workspace to the native execution callback. A single fixed writer graph runs there through the same retained execution and campaign budget used by code/profile learning. Bind the owner's task string through the writer's `instruction` parameter and entry task; its selected complete profile must stay unchanged when that task is bound. The writer must use `workspace: cwd`, one profile, one entry, no edges or integration bindings, and finite budgets within the suite's proposal bounds. This mode currently uses the maintained default Knowledge state scope.
44
+
45
+ After the actual Native settlement, the host runs the supplied Knowledge readiness deliverable before returning the exact result to the job. Readiness gates owner update admission. It is not the graph's terminal check or final quality. A false or unavailable readiness check refuses admission and retains the Native settlement, incurred budget and failure evidence. Runtime emits its job summary only when the callback returns; a refused job explicitly has no job measurement, while its attempted spend remains in authoritative Native settlements and the conserved pool.
46
+
47
+ The calibrated suite command separately receives `phase: development|final` and the owner's `knowledge` evaluation input, including the frozen candidate/baseline roots and indexes. Its declared executable, rubric and data files are checked around every score. It must return the actual `knowledgeMetric` validated by the existing Knowledge improvement metric schema, with explicit `passed` and true evaluator provenance. Its `score` must equal the outer `quality`; calibration checks this identity too. The CLI does not infer passing from a score or label an arbitrary command deterministic. Model/sample metrics require the owner's validated, corpus-bound run records. It must derive quality from independent evidence. The writer receives its task and findings, not final evaluator cases. The Knowledge owner enforces the single-use final boundary and freezes the measured pair. An optional `--bundle` attaches that exact pair to the unchanged sealed base bundle.
48
+
49
+ The command always reports hold. It neither promotes curated Knowledge nor supplies a protected final candidate host. The same local/native shell trust boundary and explicit tooling/service/accounting gaps above apply. A complete result can be reread without another Native update or final evaluation; stale curated state or changed evaluator/source/profile identity refuses reuse. Interrupted attempts and failures retain their original workspace and exact Native evidence.
50
+
51
+ This command additionally requires the Runtime artifact exposing the typed isolated execution context from Runtime PR #2584. Its real CLI/native-process fixture is authored, unexecuted source coverage until normal package and integration qualification succeeds.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sandbox-cli",
3
- "version": "0.23.17",
3
+ "version": "0.23.19",
4
4
  "description": "CLI for Tangle Sandbox operations",
5
5
  "type": "module",
6
6
  "engines": {
@@ -20,16 +20,16 @@
20
20
  ],
21
21
  "dependencies": {
22
22
  "@tangle-network/agent-core": "^1.0.3",
23
- "@tangle-network/agent-eval": "1.0.29",
24
- "@tangle-network/agent-interface": "^5.10.23",
25
- "@tangle-network/agent-provider-cli-bridge": "2.0.12",
26
- "@tangle-network/agent-runtime": "^9.0.12",
27
- "@tangle-network/harness-sessions": "^1.0.2",
28
- "@tangle-network/hub-sdk": "1.0.30",
29
- "@tangle-network/sandbox": "^1.0.428",
23
+ "@tangle-network/agent-eval": "1.0.38",
24
+ "@tangle-network/agent-interface": "^5.10.27",
25
+ "@tangle-network/agent-provider-cli-bridge": "2.0.16",
26
+ "@tangle-network/agent-runtime": "^10.0.6",
27
+ "@tangle-network/harness-sessions": "^1.0.13",
28
+ "@tangle-network/hub-sdk": "1.0.31",
29
+ "@tangle-network/sandbox": "^1.0.430",
30
30
  "@tangle-network/sdk-cli-runner": "^0.3.12",
31
31
  "chalk": "^5.6.2",
32
- "cli-bridge": "https://codeload.github.com/drewstone/cli-bridge/tar.gz/9c020ce3d94b3b0157c39f939c3c9b3738c1028a",
32
+ "cli-bridge": "https://codeload.github.com/drewstone/cli-bridge/tar.gz/b4a56761dcd4db0cf080792a3ddd967b797a4f90",
33
33
  "commander": "12.1.0",
34
34
  "ora": "^9.4.1",
35
35
  "proper-lockfile": "4.1.2",
@@ -37,7 +37,7 @@
37
37
  "ws": "^8.22.0",
38
38
  "yaml": "^2.9.1",
39
39
  "zod": "4.6.7",
40
- "@tangle-network/agent-knowledge": "23.0.3"
40
+ "@tangle-network/agent-knowledge": "23.0.5"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@drewstone/agent-record": "https://github.com/drewstone/agent-record/releases/download/v1.0.10/drewstone-agent-record-1.0.10.tgz",
@@ -60,9 +60,9 @@
60
60
  "typescript": "^6.0.3",
61
61
  "vitest": "^4.1.12",
62
62
  "@repo/shared": "0.0.0",
63
+ "@tangle-network/runtime-contracts": "0.20.0",
63
64
  "@tangle-network/sdk-session-persistence": "0.7.0",
64
- "@repo/knowledge-host": "0.0.0",
65
- "@tangle-network/runtime-contracts": "0.20.0"
65
+ "@repo/knowledge-host": "0.0.0"
66
66
  },
67
67
  "publishConfig": {
68
68
  "access": "public",
@@ -86,8 +86,8 @@
86
86
  "author": "Tangle Network",
87
87
  "license": "MIT",
88
88
  "tangleRelease": {
89
- "sourceSha": "5eba40d4387108715563fbcea3aa4337391131ab",
90
- "mergedAt": "2026-11-16T15:38:34-08:00"
89
+ "sourceSha": "70d515a4ce21b4181bca5c45673c1702996728d4",
90
+ "mergedAt": "2026-11-16T16:40:19-08:00"
91
91
  },
92
92
  "scripts": {
93
93
  "build": "tsdown",
@@ -1 +0,0 @@
1
- import{o as e}from"./index.mjs";import{dirname as t,join as n,resolve as r}from"node:path";import{randomBytes as i}from"node:crypto";import{canonicalCandidateDigest as a}from"@tangle-network/agent-interface";import{z as o}from"zod";import{homedir as s}from"node:os";import c,{readFile as l}from"node:fs/promises";import{SearchEnvironmentFault as u}from"@tangle-network/agent-runtime";import{readSettleRecord as d}from"@tangle-network/agent-runtime/durable";import{createBudgetPool as f}from"@tangle-network/agent-runtime/kernel";const p=e=>`${e}.tmp-${i(6).toString(`hex`)}`,m=new Map;function h(e){let t=r(e),n=m.get(t)??{};if(m.set(t,n),n.queued)return n.queued;let i=(n.running??Promise.resolve()).catch(()=>void 0).then(async()=>{n.running=i,n.queued=void 0;try{let e=await c.open(t,`r`);await e.sync().finally(()=>e.close())}finally{n.queued||m.delete(t)}});return n.queued=i,i}async function g(e,n,r={}){let{mode:i=384,owner:a,directory:o}=typeof r==`number`?{mode:r}:r;if(o&&!/^(?!\.\.?$)[^/]+$/.test(e))throw Error(`Not an entry name in the open directory: ${e}`);let s=o?`/proc/self/fd/${o.fd}/${e}`:e,l=p(s);try{let e=await c.open(l,`wx`,typeof r==`number`?i:384);try{await e.writeFile(n,`utf-8`),a&&await e.chown(a.uid,a.gid),typeof r!=`number`&&await e.chmod(i),await e.sync()}finally{await e.close()}await c.rename(l,s)}catch(e){throw await c.rm(l,{force:!0}).catch(()=>void 0),e}await(o?o.sync():h(t(s)))}const _=o.number().int().positive(),v=async e=>JSON.parse(await l(e,`utf8`)),y=(e,t)=>g(e,JSON.stringify(t));function b(e,t){let n=e.readout(),r=n.tokensKnown?n.deadlineMs>0&&Date.now()>=n.deadlineMs?`Campaign deadline exhausted`:t.maxTokens!==void 0&&n.tokensCapped&&t.maxTokens>n.tokensLeft?`Campaign token ceiling cannot fund the next graph`:t.maxIterations!==void 0&&n.iterationsCapped&&t.maxIterations>n.iterationsLeft?`Campaign iteration ceiling cannot fund the next graph`:void 0:`Campaign token accounting is incomplete`;if(r)throw Object.assign(new u(r),{code:`GRAPH_CAMPAIGN_BUDGET_EXHAUSTED`})}const x=o.strictObject({runId:o.uuid(),budget:o.object({maxTokens:_,maxIterations:_,deadlineMs:_}).passthrough(),sourceDigest:o.string(),graphDigest:o.string()});async function S(t,r,i,c){let l=n(t,`budget.json`),p;try{p=await v(l)}catch(e){if(e.code!==`ENOENT`)throw e;p={identity:i,startedAt:Date.now()}}if(p.identity!==i)throw Error(`Campaign configuration changed; use a new campaign directory`);let m=p.readout;if(m?.reservedTokens)throw Error(`Campaign backing has unresolved historical reservations`);let h=async t=>{let r=await d(n(s(),`.tangle`,`runs`,t.runId));if(!r)return;let i=await e(t.runId);if(r.tree.root!==t.runId||t.sourceDigest!==void 0&&i.sourceDigest!==t.sourceDigest||t.graphDigest!==void 0&&i.graphDigest!==t.graphDigest)throw Error(`Campaign settlement does not match its exact admitted graph`);return{settled:r,digest:a({runId:t.runId,sourceDigest:i.sourceDigest,graphDigest:i.graphDigest,spend:r.spentTotal})}},g=f(r,p.startedAt),_=o.record(o.uuid(),o.string()).parse(p.settlements??{});for(let[e,t]of Object.entries(_)){let n=await h({runId:e});if(!n||n.digest!==t)throw Error(`Historical campaign settlement is missing or changed; accounting cannot resume`);g.observe(n.settled.spentTotal,{alreadySpent:!0}),c?.(e,n.settled.spentTotal)}if(m&&a(m)!==a(JSON.parse(JSON.stringify(g.readout()))))throw Error(`Historical campaign backing cannot be reconstructed from its retained settlements`);let S=p.pending===void 0?void 0:x.parse(p.pending),C=m??g.readout(),w,T=()=>y(l,{identity:i,startedAt:p.startedAt,readout:S?C:g.readout(),settlements:_,...S?{pending:S}:{}}),E=(e,t=!1)=>{t||b(g,e.budget),C=g.readout();let n=g.reserve(e.budget,{assignment:e.runId,stage:`executing`});if(!n.ok)throw new u(`Campaign cannot reserve the next graph's complete ceiling`);w=n.ticket,S=e},D=async()=>{if(!S||!w)return;let e=await h(S);if(!e)return;let t=w,n;try{g.reconcile(t,e.settled.spentTotal)}catch(e){if(g.openReservations().some(({ticketId:e})=>e===t.id))throw await T(),e;n=e}let r=S.runId;if(_[r]=e.digest,S=void 0,w=void 0,await T(),c?.(r,e.settled.spentTotal),n)throw n};if(S){let e=S;S=void 0,E(e,!0),await D()}return await T(),{pool:g,checkpoint:async e=>{if(e){if(_[e.runId]){let t=await h(e);if(!t||t.digest!==_[e.runId])throw Error(`An accounted campaign settlement changed`);c?.(e.runId,t.settled.spentTotal);return}if(S&&a(S)!==a(e))throw new u(`Campaign must reconcile its exact pending run ${S.runId} before admitting another graph`);S||E(e)}else{if(await D(),S)throw new u(`Campaign run ${S.runId} has no retained settlement; its reservation remains pending`);g.assertNoOpenTickets()}await T()},startedAt:p.startedAt,pendingAttempt:()=>S&&structuredClone(S)}}export{S as openGraphCampaignBudget,v as readCampaignJson,h as t,y as writeCampaignJson};
@@ -1 +0,0 @@
1
- import{f as e,o as t,r as n,s as r,u as i}from"./index.mjs";import{join as a,resolve as o}from"node:path";import{randomUUID as s}from"node:crypto";import{canonicalCandidateDigest as c}from"@tangle-network/agent-interface";import{z as l}from"zod";import{homedir as u}from"node:os";import{mkdir as d,readFile as f,realpath as p,rename as m,writeFile as h}from"node:fs/promises";import{readSettleRecord as g,runEvidence as _}from"@tangle-network/agent-runtime/durable";import{acquireSingleRunLock as v}from"@tangle-network/agent-eval/campaign";import{runtimeRunRolloutLines as y}from"@tangle-network/agent-eval/supervisor-run";const b=l.strictObject({id:l.string(),kind:l.literal(`retained-graph`),domain:l.string().min(1),unit:l.string().min(1),split:l.enum([`train`,`dev`,`test`]),run:l.string().min(1),origin:l.string(),sourceDigest:l.string().nullable(),graphDigest:l.string().nullable(),params:l.record(l.string(),l.unknown()),trigger:l.record(l.string(),l.unknown()).nullable().optional(),mcpPolicy:e.optional(),taskWorkspace:i.optional(),outcome:l.string(),gaps:l.array(l.string()),evidence:l.string(),quality:l.null()}),x=async e=>JSON.parse(await f(e,`utf8`)),S=e=>e.code===`ENOENT`;function C(e,{name:t,provenance:n}){let r={train:0,dev:0,test:0,holdout:0};for(let t of e)r[t.split]++;return{name:t,provenance:n,contentHash:c(e.map(e=>({id:e.id,split:e.split,payload:e})).sort((e,t)=>e.id<t.id?-1:+(e.id>t.id))).slice(7),scenarioCount:e.length,splitCounts:r}}async function w(e,t){let n=c(t),r=a(e,`objects`,`${n.slice(7)}.json`);await d(a(e,`objects`),{recursive:!0,mode:448});let i=JSON.stringify(t);try{await h(r,i,{flag:`wx`,mode:384,flush:!0})}catch(e){if(e.code!==`EEXIST`)throw e;if(c(await x(r))!==n)throw Error(`Dataset evidence object changed`)}return n}async function T(e,t){if(!/^sha256:[a-f0-9]{64}$/.test(t))throw Error(`Invalid dataset object digest`);let n=await x(a(e,`objects`,`${t.slice(7)}.json`));if(c(n)!==t)throw Error(`Dataset evidence object changed`);return n}async function E(e,i){if(e.startsWith(`wfrun_`)){let t=await n(i),[r,a]=await Promise.all([t.workflows.getRun(e,{signal:i.signal}),t.workflows.getRunInput(e,{signal:i.signal})]),o=a.completeness===`complete`&&a.id===r.id&&a.workflowId===r.workflowId&&a.revUsed===r.revUsed&&c({definitionSnapshot:a.definitionSnapshot,execution:a.execution,triggerContext:a.triggerContext,revUsed:a.revUsed})===a.inputDigest?a:void 0,s=o?.execution,l=o?.triggerContext;return{origin:new URL(t.baseUrl).origin,sourceDigest:a.sourceSha,graphDigest:a.graphDigest,params:s?.params??{},...o?{trigger:l}:{},mcpPolicy:s?.deploy?.mcpPolicy,outcome:r.status,source:o?.definitionSnapshot??null,gaps:[`task-workspace-not-snapshotted`,`environment-and-toolchain-not-snapshotted`,...o?[]:[`retained-input-unavailable`,...a.gaps],...s?[]:[`graph-execution-missing`],...o?.definitionSnapshot?[]:[`source-snapshot-missing`],...r.runtime?[]:[`runtime-evidence-missing`],...r.runtime?.trace?.gaps.map(e=>e.reason)??[],...r.runtime?.blobs.filter(e=>!e.found).map(e=>`blob-missing:${e.ref}`)??[]],record:{run:r.id,workflowId:r.workflowId,revUsed:r.revUsed,execution:s??null,trigger:o?.triggerContext??null,retainedInput:{completeness:o?`complete`:a.completeness===`complete`?`invalid`:a.completeness,inputDigest:o?.inputDigest??null,gaps:o?[]:[...a.gaps,`retained-input-unavailable`]},...s?.deploy?.mcpPolicy&&{mcpPolicy:s.deploy?.mcpPolicy},status:r.status,error:r.error,graphResult:r.graphResult??null,runtime:r.runtime?{namespace:r.runtime.namespace??null,journal:r.runtime.journal,blobs:r.runtime.blobs,trace:r.runtime.trace??null}:null}}}if(!l.uuid().safeParse(e).success)throw Error(`Use a retained local UUID or cloud wfrun_ ID`);let o=a(u(),`.tangle`,`runs`,e),s=await t(e),[d,f,p,m]=await Promise.all([r(s),g(o),y(o,{capturedAt:s.startedAt,verdict:null}),_(o,{totalChars:48e3})]);return{origin:`local`,sourceDigest:s.sourceDigest,graphDigest:s.graphDigest,params:s.params,trigger:s.trigger??null,mcpPolicy:s.mcpPolicy,taskWorkspace:s.taskWorkspace,source:d,outcome:f?.kind??`interrupted`,gaps:[...s.taskWorkspace?.gaps??[`task-workspace-not-snapshotted`,`environment-and-toolchain-not-snapshotted`],...p.gaps.map(e=>e.code),...m.truncated?[`summary-truncated`]:[]],record:{run:e,sourceDigest:s.sourceDigest,graphDigest:s.graphDigest,params:s.params,trigger:s.trigger??null,...s.mcpPolicy&&{mcpPolicy:s.mcpPolicy},...s.taskWorkspace&&{taskWorkspace:s.taskWorkspace},settled:f??null,rollouts:p.lines,summary:m}}}async function D(e,t){let n=o(e),r=t??(await x(a(n,`latest.json`))).version;if(!/^[a-f0-9]{64}$/.test(r))throw Error(`Invalid graph dataset version`);let i=await x(a(n,`versions`,`${r}.json`)),s=l.array(b).parse(i.cases),u=C(s,i.manifest);if(u.contentHash!==r||c(u)!==c(i.manifest))throw Error(`Graph dataset manifest changed`);for(let e of s)if(s.some(t=>t.domain===e.domain&&t.unit===e.unit&&t.split!==e.split))throw Error(`An independent unit crosses dataset splits`);return{root:n,version:r,manifest:u,cases:s}}async function O(e,t,r){let i=r;if(t.some(e=>e.startsWith(`wfrun_`))){let e=await n(i);i={...i,baseUrl:e.baseUrl}}let l=o(e);await d(l,{recursive:!0,mode:448});let{release:u}=v({lockPath:`${await p(l)}.lock`});try{let e;try{e=await D(l)}catch(e){if(!S(e))throw e}let n=new Map((e?.cases??[]).map(e=>[e.id,e]));for(let e of t){i.signal?.throwIfAborted();let t;try{t=await E(e,i)}catch(n){i.signal?.throwIfAborted(),t={origin:e.startsWith(`wfrun_`)?new URL(i.baseUrl).origin:`local`,sourceDigest:null,graphDigest:null,params:{},source:null,outcome:`unavailable`,gaps:[`retained-attempt-unavailable`],record:{run:e,error:n.name}}}let r=c({origin:t.origin,run:e}),a=n.get(r);if(a&&[`domain`,`unit`,`split`].some(e=>a[e]!==i[e]))throw Error(`A retained attempt cannot change domain, unit or split; fork the dataset`);let o=await w(l,{...t.record,source:t.source});n.set(r,b.parse({id:r,kind:`retained-graph`,domain:i.domain,unit:i.unit,split:i.split,run:e,origin:t.origin,sourceDigest:t.sourceDigest,graphDigest:t.graphDigest,params:t.params,...t.trigger===void 0?{}:{trigger:t.trigger},...t.mcpPolicy===void 0?{}:{mcpPolicy:t.mcpPolicy},...`taskWorkspace`in t&&t.taskWorkspace?{taskWorkspace:t.taskWorkspace}:{},outcome:t.outcome,gaps:t.gaps,evidence:o,quality:null}))}let r=[...n.values()].sort((e,t)=>e.id.localeCompare(t.id));if(r.some(e=>r.some(t=>e.domain===t.domain&&e.unit===t.unit&&e.split!==t.split)))throw Error(`An independent unit crosses dataset splits`);let o=C(r,{name:e?.manifest.name??`graph-runs`,provenance:e?.manifest.provenance??{createdAt:new Date().toISOString(),version:`1`}});await d(a(l,`versions`),{recursive:!0});let u=a(l,`versions`,`${o.contentHash}.json`);try{await h(u,JSON.stringify({manifest:o,cases:r}),{flag:`wx`,mode:384,flush:!0})}catch(e){if(e.code!==`EEXIST`)throw e}let f=a(l,`latest-${s()}.json`);return await h(f,JSON.stringify({version:o.contentHash}),{mode:384,flush:!0}),await m(f,a(l,`latest.json`)),D(l)}finally{await u()}}export{b as graphCase,w as graphDatasetObject,O as ingestGraphDataset,D as readGraphDataset,T as readGraphDatasetObject};
@@ -1 +0,0 @@
1
- import{c as e,d as t,f as n,h as r,i,l as a,n as o,o as s,s as c,t as l}from"./index.mjs";import{openGraphCampaignBudget as u,readCampaignJson as d,writeCampaignJson as f}from"./graph-campaign-state-B51K1WNu.mjs";import{graphDatasetObject as p,readGraphDataset as m,readGraphDatasetObject as h}from"./graph-dataset-Bs03wlXZ.mjs";import{a as g,graphOperatingCell as _,graphOperatingDecision as v,i as y,n as b,r as x,t as S}from"./graph-operating-evidence-DgfHPsFl.mjs";import{findPackageJSON as C}from"node:module";import{join as w,resolve as T}from"node:path";import{randomUUID as E}from"node:crypto";import{canonicalCandidateDigest as D}from"@tangle-network/agent-interface";import{z as O}from"zod";import{homedir as k}from"node:os";import{mkdir as A,readFile as j,readdir as M,realpath as N,writeFile as P}from"node:fs/promises";import{SearchEnvironmentFault as F,improve as I,reflectiveProfileProposer as L,searchMethod as R,subscriptionLane as z}from"@tangle-network/agent-runtime";import{readSettleRecord as B,runEvidence as V}from"@tangle-network/agent-runtime/durable";import{readGraphStrings as H,setGraphStrings as U}from"@tangle-network/agent-runtime/kernel";import{acquireSingleRunLock as W,incumbent as G,uniform as K}from"@tangle-network/agent-eval/campaign";async function q(e,t,n,i,a,o={}){let s=a===void 0?r().seat??null:null,c=T(i);await A(c,{recursive:!0,mode:448});let{release:u}=W({lockPath:`${await N(c)}.lock`});try{let r=await ne(e,t,n,c,a,s,o),{suite:i,dataset:u,profile:m,sourceForProfile:y,assertUnchanged:b,baselineDigest:x,optimizedCoordinate:S,evaluatorIdentity:C,calibration:T,hostBindings:D}=r,O=g({profile:m,budget:{maxTokens:i.budget.proposalTokens,maxIterations:i.budget.proposalIterations,deadlineMs:i.budget.proposalDeadlineMs},run:async(e,t,n)=>{let r=await z(e,t,{},n),i=await B(w(k(),`.tangle`,`runs`,r.runId));if(!i)throw Error(`Reflection has no retained settlement`);return{...r,settlement:i}}}),A=await J(r,O);try{let e=await d(w(c,`result.json`)),t=await h(c,e.record);if(t.identity!==A)throw Error(`Completed campaign configuration changed; use a new directory`);if(l(await j(t.candidate))!==t.candidateDigest)throw Error(`Measured candidate bytes changed`);return{...t,record:e.record}}catch(e){if(e.code!==`ENOENT`)throw e}let I=await Y(r,A),L=new Map;for(let e of u.cases)L.set(e.id,await h(u.root,e.evidence));let R=E(),z=X(r,I,R),V=Z(r,L,R),H=await te(r,O,A,{...I,run:z,judge:V});if(!H.searchHistory?.complete)throw await H.dispose(),new F(`Optimizer did not retain complete verified search history`);let U=y(H.candidate.profile),W=l(U);await b();let G=await v(c,u.cases.filter(e=>e.split===`test`),i,W,x,H.searchHistory),K=w(c,`${W}.graph.yaml`);await P(K,U,{mode:384,flush:!0});let q=await Promise.all((await M(w(c,`judgments`)).catch(e=>{if(e.code!==`ENOENT`)throw e;return[]})).filter(e=>e.endsWith(`.json`)).map(async e=>{let t=_.parse(await d(w(c,`judgments`,e)));if(t.sourceDigest!==W)return null;let n=await h(c,t.evidence);if(n.artifact.sourceDigest!==W||typeof n.artifact.graphDigest!=`string`)throw Error(`Candidate judgment has no exact measured execution identity`);return{runId:n.artifact.runId,scenario:t.scenario,graphDigest:n.artifact.graphDigest}})),{dispose:ee,...re}=H,Q={version:1,identity:A,optimizedCoordinate:S,baselineDigest:x,candidateDigest:W,candidate:K,sourcePath:await N(e),dataset:{root:u.root,version:u.version},workspaceGaps:[...new Set(u.cases.flatMap(e=>e.taskWorkspace?.gaps??[`task-workspace-not-snapshotted`,`environment-and-toolchain-not-snapshotted`]))],suite:await N(n),evaluatorIdentity:C,calibration:T,executionIdentities:q.filter(e=>e!==null),mcpPolicy:D.mcpPolicy,decision:H.decision===`ship`&&G.admissible?`promote`:`hold`,operational:G,measurement:re,operatingCost:{known:!1,reason:`subscription and environment allocation are not metered as incremental provider charges`},campaignBudget:{limits:i.budget,readout:I.pool.readout()}};await b();let $=await p(c,Q);return await f(w(c,`result.json`),{record:$}),await H.dispose(),{...Q,record:$}}finally{await u()}}async function J(e,t){let{seat:n,defaultSeat:r,optimizedCoordinate:i,suite:a,baselineDigest:o,dataset:s,evaluatorIdentity:c,hostBindings:u,loaded:f}=e,p=C(import.meta.url);if(!p)throw Error(`Cannot identify the CLI dependency manifest`);return D({consumer:`graph-learning-v1`,optimizedCoordinate:i,optimizer:y.parse(a.optimizer),reflection:t.callRef,consumerBytes:l(await j(new URL(import.meta.url))),consumerManifest:l(await j(p)),environment:{node:process.version,platform:process.platform,architecture:process.arch,packages:await Promise.all([`@tangle-network/agent-runtime`,`@tangle-network/agent-eval`,`cli-bridge`].map(async e=>{let t=C(e,import.meta.url);if(!t)throw Error(`Cannot identify ${e} for reproducible learning`);return{name:e,version:(await d(t)).version,entryDigest:l(await j(new URL(import.meta.resolve(e))))}}))},baselineDigest:o,dataset:s.version,evaluatorIdentity:c,seat:n??null,defaultSeat:r,mcpPolicy:u.mcpPolicy,graph:f.graph,budget:a.budget,reps:a.reps})}async function Y(e,t){let{root:n,suite:r,defaultSeat:i,bindings:a}=e,l=new AbortController,{pool:d,checkpoint:f,startedAt:p,pendingAttempt:m}=await u(n,r.budget,t,(e,t)=>{if(t.usd-(t.usdEstimated??0)>0){let t=new F(`Native subscription run ${e} reported positive provider billing; no further campaign work is admitted`);throw l.abort(t),t}}),h=AbortSignal.any([AbortSignal.timeout(Math.max(1,p+r.budget.deadlineMs-Date.now())),l.signal]);h.throwIfAborted();let g=m();if(g){let e=await s(g.runId);if(e.sourceDigest!==g.sourceDigest||e.graphDigest!==g.graphDigest)throw Error(`Pending native input changed its admitted execution identity`);try{await o(e.file,{param:[],resume:e.runId,json:!0,mcpPolicy:e.mcpPolicy,mcpSecret:a.mcpSecret},{defaultSeat:i,cwd:e.cwd,source:await c(e),runId:e.runId,graphDigest:e.graphDigest,signal:h,...e.trigger&&{trigger:e.trigger}})}catch(e){if(e.code!==`GRAPH_RUN_FAILED`)throw e}finally{await f()}}return{pool:d,checkpoint:f,startedAt:p,signal:h}}function X(n,r,u){let{root:f,hostBindings:p,seat:m,defaultSeat:h}=n,{signal:g,checkpoint:_}=r;return async(n,r,v,y,b=null,x)=>{await A(w(f,`attempts`),{recursive:!0,mode:448});let S=w(f,`attempts`,`${l(r)}.json`),C=!1;try{await P(S,JSON.stringify({runId:E(),startedAt:Date.now()}),{flag:`wx`,mode:384,flush:!0}),C=!0}catch(e){if(e.code!==`EEXIST`)throw e}let{runId:T,startedAt:D}=O.strictObject({runId:O.uuid(),startedAt:O.number().int().nonnegative()}).parse(await d(S)),M=w(f,`executions`,T);await A(M,{recursive:!0,mode:448});let N=w(M,`graph.yaml`);try{await P(N,n,{flag:`wx`,mode:384,flush:!0})}catch(e){if(e.code!==`EEXIST`)throw e;if(l(await j(N))!==l(n))throw Error(`Attempt source identity changed`)}let I;try{await j(w(k(),`.tangle`,`runs`,T,`input.json`)),I=await s(T)}catch(e){if(e.code!==`ENOENT`)throw e}if(I&&l(await c(I))!==l(n))throw Error(`Attempt snapshot changed`);if(I&&(x?a(x):null)!==(I.taskWorkspace?a(I.taskWorkspace):null))throw Error(`Attempt task workspace identity changed`);let L=x?await e(x,{runId:T,resumeCwd:I?.cwd,signal:AbortSignal.any([g,y])}):void 0;try{let e=await o(N,{...p,param:i(v),dryRun:!0,...I&&{resume:T},...m&&{seat:m}},{defaultSeat:h,cwd:L?.cwd??M,signal:g,...b&&{trigger:b},...x&&{taskWorkspace:x}});if(!(`graph`in e))throw Error(`Attempt did not load locally`);if(!e.graph.budget?.maxTokens||!e.graph.budget.maxIterations||!e.graph.budget.deadlineMs)throw Error(`Every materialized case needs finite token, iteration and deadline budgets`);await _({runId:T,budget:e.graph.budget,sourceDigest:l(n),graphDigest:e.graph.digest});let r;try{await o(N,{...p,param:i(v),json:!0,...m&&{seat:m},...I&&{resume:T}},{defaultSeat:h,runId:T,cwd:L?.cwd??M,...x&&{taskWorkspace:x},graphDigest:e.graph.digest,signal:AbortSignal.any([g,y]),...b&&{trigger:b}})}catch(e){r=e}finally{await _()}let s=await B(w(k(),`.tangle`,`runs`,T));if(!s)throw new F(`Native graph attempt has no retained settlement`,{cause:r});return{...t(s),runId:T,sourceDigest:l(n),graphDigest:e.graph.digest,durationMs:Math.max(Date.now()-D,s.spentTotal.ms),latencyKnown:C,invocation:u,taskWorkspaceDigest:x?a(x):null}}finally{L?.release()}}}function Z(e,t,n){let{root:r,suite:i,evaluatorCwd:a,evaluatorIdentity:o,assertUnchanged:s}=e;return{name:`independent-domain-evaluator`,judgeVersion:o,dimensions:[{key:`quality`,description:i.objective}],score:async({artifact:e,scenario:c,signal:l})=>{let u=await S(i,a,{scenario:c,evidence:t.get(c.id),artifact:e},l,s),d=await p(r,{evaluatorIdentity:o,scenario:c.id,artifact:e,verdict:u});return await A(w(r,`judgments`),{recursive:!0,mode:448}),await f(w(r,`judgments`,`${e.runId}.json`),{evidence:d,sourceDigest:e.sourceDigest,scenario:c.id,unit:c.unit,split:c.split,quality:u.quality,tokens:e.tokenUsage.input===null||e.tokenUsage.output===null?null:e.tokenUsage.input+e.tokenUsage.output,durationMs:e.durationMs,latencyKnown:e.latencyKnown&&e.invocation===n,operatingCostUsd:null}),{dimensions:{quality:u.quality},composite:u.quality,notes:u.notes}}}}function ee(e,t){let{root:n,profile:r,suite:i,dataset:o}=e;return L({model:r.model?.default??`subscription-native`,pricing:{inputUsdPerMillion:0,outputUsdPerMillion:0},maxOutputTokens:i.budget.proposalTokens,frame:`Improve only the ${i.node} node's inline prompt. Domain: ${i.domain}. Objective: ${i.objective}. Preserve independent checks.`,evidence:async({trainCells:e})=>Promise.all(e.map(async e=>{let t=await d(w(n,`attempts`,`${l(`${e.cellId}:${e.attempt}`)}.json`)),r=await V(w(k(),`.tangle`,`runs`,t.runId),{totalChars:48e3});return JSON.stringify({cell:e,tasks:o.cases.filter(t=>t.split===`train`&&t.unit===e.unitId).map(e=>({id:e.id,params:e.params,trigger:e.trigger,taskWorkspace:e.taskWorkspace?a(e.taskWorkspace):null})),records:r})})),chat:async({messages:e,callId:n,signal:r})=>{let a=await t.call({callId:n,signal:r,request:{model:t.model,messages:e,maxTokens:i.budget.proposalTokens}});if(!a.succeeded)throw Error(a.error);return{content:a.response.content,usage:a.response.usage.captured===!1?null:{inputTokens:a.response.usage.promptTokens,outputTokens:a.response.usage.completionTokens}}}})}async function te(e,t,n,r){let{root:i,suite:a,dataset:o,profile:s,profileComponents:c,sourceForProfile:l}=e,{signal:u,startedAt:d,run:f,judge:p}=r,m=ee(e,t),h=x(a.optimizer,{subscriptionOnlyModel:t,runner:{},maxOutputTokens:a.budget.proposalTokens,timeoutMs:a.budget.proposalDeadlineMs,objective:a.objective,describeScenario:e=>({id:e.id,params:e.params,trigger:e.trigger}),describeArtifact:e=>({text:e.text,status:e.status})}),g={surface:`agent-profile`,profileComponents:c,executionRef:n,trainScenarios:o.cases.filter(e=>e.split===`train`),selectionScenarios:o.cases.filter(e=>e.split===`dev`),testScenarios:o.cases.filter(e=>e.split===`test`),judges:[p],costCeiling:0,runDir:w(i,`search`),signal:u,agent:async(e,t,n)=>{let r=l(e),i=await n.cost.runPaidCall({actor:`native-graph`,model:s.model?.default??`subscription-native`,maximumCharge:{externallyEnforcedMaximumUsd:0},signal:n.signal,execute:()=>f(r,`search`in n?n.search.runId:`${n.cellId}:${n.runAttemptId}`,t.params,n.signal,t.trigger??null,t.taskWorkspace),receipt:e=>({model:s.model?.default??`subscription-native`,...e.costUsd===null?{costUnknown:!0}:{actualCostUsd:e.costUsd},inputTokens:e.tokenUsage.input??0,outputTokens:e.tokenUsage.output??0,usageUnknown:e.tokenUsage.input===null||e.tokenUsage.output===null})});if(!i.succeeded)throw i.error;return i.value}};return h.kind===`official`?await I(s,{...g,method:h.method,minimumLift:a.minimumEffect,reps:a.reps,maxConcurrency:1,optimizationRunOptions:{reps:a.reps,maxConcurrency:1}}):await I(s,{...g,method:R({proposer:m,maxExpansions:a.budget.maxExpansions,policy:G(),allocation:K({reps:a.reps}),lanes:[z({seats:1,cellUsd:0})],deadline:new Date(d+a.budget.deadlineMs).toISOString(),maxAttempts:1}),claim:{use:`comparison`,population:{id:a.domain,description:a.objective},samplingFrame:`retained graph dataset ${o.version}`,independentUnit:`unit`,generalization:`new-units`,minimumEffect:a.minimumEffect},executionRunId:e=>e.runId})}async function ne(t,r,a,s,c,u,f){let{suite:p,cwd:h,identity:g,calibration:_,assertUnchanged:v}=await b(a),y=await j(t,`utf8`),x=H(y)[p.node];if(typeof x!=`string`)throw Error(`The selected node needs an unshared inline prompt`);let S=await m(r);if(S.cases.some(e=>e.domain!==p.domain))throw Error(`Dataset contains a different domain`);if(S.cases.some(e=>e.outcome===`unavailable`||!e.sourceDigest))throw Error(`Dataset retains unavailable attempts; reconcile them before freezing a learning cohort`);for(let e of[`train`,`dev`,`test`])if(!S.cases.some(t=>t.split===e))throw Error(`Dataset needs an independent ${e} partition`);if(S.cases.some(e=>e.trigger===void 0))throw Error(`Dataset lacks retained trigger context; reingest legacy runs before replay`);let C=[...new Set(S.cases.map(e=>JSON.stringify(n.parse(e.mcpPolicy??{}))))];if(!f.mcpPolicy&&C.length!==1)throw Error(`Retained MCP host policies differ; select an explicit --mcp-policy`);let T={...f,mcpPolicy:f.mcpPolicy??n.parse(JSON.parse(C[0]??`{}`))},D=S.cases.find(e=>e.split===`train`);if(!D)throw Error(`Dataset needs a train case`);let k=w(s,`baseline.graph.yaml`),A=l(y);try{await P(k,y,{flag:`wx`,mode:384,flush:!0})}catch(e){if(e.code!==`EEXIST`)throw e;if(l(await j(k))!==A)throw Error(`Frozen baseline changed`)}let M;if(D.taskWorkspace){let t=w(s,`task-workspace-admission.json`);try{await P(t,JSON.stringify({runId:E()}),{flag:`wx`,mode:384,flush:!0})}catch(e){if(e.code!==`EEXIST`)throw e}let n=O.strictObject({runId:O.uuid()}).parse(await d(t));M=await e(D.taskWorkspace,{...n,validationOnly:!0})}let N;try{N=await o(k,{...T,param:i(D.params),dryRun:!0,...c&&{seat:c}},{defaultSeat:u,...D.trigger&&{trigger:D.trigger},...M&&{cwd:M.cwd,taskWorkspace:D.taskWorkspace}})}finally{await M?.release()}if(!(`graph`in N))throw Error(`Baseline did not load locally`);if(!N.graph.budget?.maxTokens||!N.graph.budget.maxIterations||!N.graph.budget.deadlineMs)throw Error(`Graph needs finite token, iteration and deadline budgets for bounded improvement`);let F=N.graph.nodes.find(e=>e.id===p.node)?.profile;if(!F)throw Error(`Selected node was not materialized`);let I=typeof F.prompt?.systemPrompt==`string`?`systemPrompt`:`appendSystemPrompt`;if(typeof F.prompt?.[I]!=`string`)throw Error(`The selected source coordinate was not materialized`);let L=`prompt.${I}`,R={...F,prompt:{...F.prompt,[I]:x}},z=e=>{let t=e.prompt?.[I];if(typeof t!=`string`)throw Error(`Candidate lost its selected prompt coordinate`);return t},B={read:e=>({[L]:z(e)}),apply(e,t){if(Object.keys(t).length!==1||Object.keys(t)[0]!==L||typeof t[L]!=`string`)throw Error(`Candidate changed the selected prompt coordinate`);return{...e,prompt:{...e.prompt,[I]:t[L]}}}},V=e=>{let t=z(e);return t===x?y:U(y,{[p.node]:t})},W={node:p.node,profileField:L,binding:`authored-source-compiled-per-case`};return{root:s,seat:c,defaultSeat:u,bindings:f,suite:p,evaluatorCwd:h,evaluatorIdentity:g,calibration:_,assertUnchanged:v,baselineDigest:A,dataset:S,hostBindings:T,loaded:N,profile:R,profileComponents:B,sourceForProfile:V,optimizedCoordinate:W}}export{q as learnGraph};
@@ -1 +0,0 @@
1
- import{constants as e}from"node:fs";import{isAbsolute as t,join as n,relative as r}from"node:path";import{createHash as i}from"node:crypto";import{z as a}from"zod";import{open as o,opendir as s,realpath as c}from"node:fs/promises";import*as l from"@tangle-network/agent-runtime/kernel";import{CODEX_HOME_RULE as u,STORES as d,claudeCodeRefForFile as f,codexRefForFile as p,readSessionInput as m,storeGlob as h,withinPath as g}from"@tangle-network/harness-sessions";const _=a.object({harness:a.enum([`codex`,`claude-code`]),root:a.string().refine(t),basis:a.literal(`host-jail`),nativeSessionId:a.string().min(1),runId:a.string().min(1),requestDigest:a.string().regex(/^sha256:[a-f0-9]{64}$/)}),v=a.object({externalId:a.string(),internalId:a.string(),backend:a.enum([`codex`,`claude-code`]),cwd:a.string(),metadata:a.object({effective_native_store:_,agent_profile_binding:a.object({effectiveProfileDigest:a.string()})})});function y(){let e=new Map;return{observe(t){e.set(`${t.runId}:${t.requestDigest}`,t)},close(){e.clear()},redact(t,n){for(let n of t.runs){let r=e.get(`${n.runId}:${n.requestDigest}`);if(!r||r.sessionId!==t.sessionId||r.profileDigest!==t.profileDigest||r.cwd!==t.cwd)throw Error(`Exact native execution has no trusted redaction authority`)}if(!t.runs.length)throw Error(`Native redaction requires an exact execution binding`);let r=n;for(let n of e.values())n.sessionId===t.sessionId&&n.profileDigest===t.profileDigest&&n.cwd===t.cwd&&(r=n.redact(r));return r}}}function b(e,t){if(e===`codex`)return p(t);let n=t.split(`/`),r=n.indexOf(`subagents`,3);return f(t,r>0?n[r-1]??null:null)}async function x(e,t,i){let a=[],o=d[`claude-code.projects-jsonl`],f=n(t,...o.root.split(`/`).slice(1)),p=e===`codex`?u.sessionDirs.map(e=>n(t,e)):[f],m=e===`codex`?[h(u.rollout)]:o.files.map(e=>h(e)),_=0;for(;p.length;){i.throwIfAborted();let o=p.shift();if(o===void 0)break;let u;try{u=await c(o)}catch(e){if(e.code===`ENOENT`)continue;throw e}if(!g(u,t))throw Error(`Native inventory escaped its attested store`);let d=await s(u);for await(let o of d){if(i.throwIfAborted(),++_>l.HARNESS_TRANSCRIPT_READ_LIMITS.maxFiles)throw Error(`Native inventory exceeds the capture bound`);let s=n(d.path,o.name);o.isDirectory()?p.push(s):o.isFile()&&m.some(t=>t.test(e===`codex`?o.name:r(f,s)))&&a.push({path:r(t,s),nativeSessionId:b(e,r(t,s)).nativeSessionId})}}return a}function S(t){return async r=>{if(![`codex`,`claude-code`].includes(r.harness))return{status:`unavailable`,reason:`unknown-harness`,skipped:[{path:r.harness,reason:`Native transcript capture is not configured for this harness`}]};let s=await fetch(`${t.bridgeUrl}/v1/sessions?session_id=${encodeURIComponent(r.sessionId)}&backend=${r.harness}`,{headers:{authorization:`Bearer ${t.bridgeBearer}`},signal:r.signal});if(!s.ok)throw Error(`Bridge session lookup failed (HTTP ${s.status})`);let u=a.object({data:a.tuple([v])}).parse(await s.json()).data[0],d=u.metadata.effective_native_store,f=await c(d.root);if(u.backend!==r.harness||d.harness!==r.harness||u.externalId!==r.sessionId||u.internalId!==d.nativeSessionId||u.cwd!==t.cwd||r.cwd!==t.cwd||u.metadata.agent_profile_binding.effectiveProfileDigest!==r.profileDigest||f!==d.root||!g(f,n(t.cwd,`.agent-home`))||!r.runs.some(e=>e.runId===d.runId&&e.requestDigest===d.requestDigest))throw Error(`Bridge native binding does not match this execution`);let p=[],h=[...new Set(t.privateMcpSecrets?.()??[])].flatMap(e=>[e,JSON.stringify(e).slice(1,-1)]).filter(Boolean).sort((e,t)=>t.length-e.length),_=await l.captureBoundHarnessTranscript({harness:r.harness,binding:{kind:`bridge`,sessionId:r.sessionId,nativeSessionId:d.nativeSessionId,profileDigest:r.profileDigest,runs:r.runs,...r.node===void 0?{}:{node:r.node}},nativeSessionId:d.nativeSessionId,files:await x(r.harness,f,r.signal),signal:r.signal,parse:(e,t)=>m(r.harness,{text:e},{...b(r.harness,t.path),label:t.path},{corruption:`strict`}),read:async(a,s)=>{let u=await c(n(f,a.path));if(!g(u,f))throw Error(`Native session escaped its attested store`);let d=await o(u,e.O_RDONLY|e.O_NOFOLLOW);try{let e=await d.stat();if(!e.isFile()||e.size>l.HARNESS_TRANSCRIPT_READ_LIMITS.maxFileBytes)throw Error(`Native session is not a bounded regular file`);s?.throwIfAborted();let n=await d.readFile();if(s?.throwIfAborted(),!t.redact)throw Error(`The native host did not supply private redaction authority`);let o=t.redact(r,n),c=new TextDecoder(`utf-8`,{fatal:!0}).decode(o);for(let e of h)c=c.split(e).join(`[redacted:MCP]`);let u=Buffer.from(c,`utf8`);return u.equals(n)||p.push({path:a.path,reason:`Original bytes withheld for private MCP credential redaction; source sha256:${i(`sha256`).update(n).digest(`hex`)}; retained copy is redacted`}),u}finally{await d.close()}}});return _.status!==`captured`||!p.length?_:{..._,artifact:{..._.artifact,skipped:[..._.artifact.skipped,...p]},skippedCount:_.skippedCount+p.length,coverageComplete:!1,missing:[`private-mcp-secret-original-bytes`]}}}const C=async(e,t)=>{if(![`codex`,`claude-code`].includes(e.harness)||e.binding?.kind!==`bridge`)throw Error(`Native transcript reader is not configured for this capture`);return(await l.readBoundHarnessSessions({nativeSessionId:e.binding.nativeSessionId,files:e.files.map(t=>({path:t.path,nativeSessionId:b(e.harness,t.path).nativeSessionId,byteLength:t.bytes})),read:async t=>{let n=e.files.find(e=>e.path===t.path);if(!n)throw Error(`Retained native file is absent`);return Buffer.from(n.content,`utf8`)},parse:(t,n)=>m(e.harness,{text:t},{...b(e.harness,n.path),label:n.path},{corruption:`strict`}),signal:t})).sessions};export{S as graphNativeCapture,y as graphNativeRedaction,C as readGraphSessions};
@@ -1,2 +0,0 @@
1
- import{a as e,d as t,f as n,i as r,l as i,n as a,o,s,t as c}from"./index.mjs";import{readCampaignJson as l,t as u,writeCampaignJson as d}from"./graph-campaign-state-B51K1WNu.mjs";import{graphDatasetObject as f,readGraphDataset as p,readGraphDatasetObject as m}from"./graph-dataset-Bs03wlXZ.mjs";import{dirname as h,isAbsolute as g,join as _,resolve as v}from"node:path";import{createHash as y,randomUUID as b}from"node:crypto";import{canonicalCandidateDigest as x}from"@tangle-network/agent-interface";import{z as S}from"zod";import{execCli as C}from"@tangle-network/sdk-cli-runner";import{homedir as w}from"node:os";import{mkdir as T,readFile as E,readdir as D,realpath as O,rename as k,rm as A,writeFile as j}from"node:fs/promises";import{SearchEnvironmentFault as M,officialGepa as N}from"@tangle-network/agent-runtime";import{readSettleRecord as P}from"@tangle-network/agent-runtime/durable";import{acquireSingleRunLock as F,parseSearchLedgerLine as I,replaySearchLedgerText as L}from"@tangle-network/agent-eval/campaign";import{paretoFrontier as R}from"@tangle-network/agent-eval";const z=S.number().int().positive().max(2**53-1),B=S.strictObject({maxEvaluations:z,maxConcurrency:z.max(1,`Retained graph campaigns admit one pending graph`).default(1)}),V=S.discriminatedUnion(`kind`,[S.strictObject({kind:S.literal(`native`)}),S.strictObject({kind:S.literal(`gepa`),recipe:S.discriminatedUnion(`kind`,[S.strictObject({kind:S.literal(`engine`),run:B}),S.strictObject({kind:S.literal(`omni`),explore:S.array(B).min(1),continueWith:B,maxWorkers:z.max(1,`Retained graph campaigns admit one pending graph`).default(1)})]),maxModelRequests:z,maxRequestBytes:z,maxResponseBytes:z,maxCandidateChars:z,maxEvidenceChars:z,resume:S.enum([`never`,`if-compatible`,`required`]).default(`never`),trustLocalState:S.boolean().default(!1)})]);function H(e,t,n=`prompt`){if(n!==`prompt`)throw Error(`Graph learning currently materializes only the prompt surface`);let r=V.parse(e??{kind:`native`});if(r.kind===`native`)return{kind:`native`,identity:x(r)};if(!t)throw Error(`Official GEPA requires caller-owned subscription execution`);if(r.recipe.kind===`omni`&&r.resume!==`never`)throw Error(`Official Omni does not support resumable state; use resume=never`);if(r.resume!==`never`&&!r.trustLocalState)throw Error(`Resumable GEPA requires explicit trust in local pickle state`);z.parse(t.maxOutputTokens),S.number().int().positive().max(2147483647).parse(t.timeoutMs);let i=e=>({engine:`gepa`,...e,engineConfig:{engine:{capture_stdio:!1,max_workers:e.maxConcurrency,parallel:e.maxConcurrency>1,raise_on_exception:!0},reflection:{reflection_minibatch_size:1,skip_perfect_score:!1}}}),a=r.recipe.kind===`engine`?{kind:`engine`,run:i(r.recipe.run)}:{kind:`omni`,explore:r.recipe.explore.map(i),continueWith:i(r.recipe.continueWith),maxWorkers:r.recipe.maxWorkers},o=t.subscriptionOnlyModel,s={maxRequests:r.maxModelRequests,maxRequestBytes:r.maxRequestBytes,maxResponseBytes:r.maxResponseBytes,maxOutputTokensPerRequest:t.maxOutputTokens,requestTimeoutMs:t.timeoutMs,pricing:{inputUsdPerMillion:0,outputUsdPerMillion:0}};return{kind:`official`,identity:x({config:r,model:o.model,callRef:o.callRef,budget:s,objective:t.objective}),method:N({objective:t.objective,recipe:a,optimizer:{...o,budget:s,servedModelPolicy:`exact`},runner:t.runner,timeoutMs:t.timeoutMs,maxCandidateChars:r.maxCandidateChars,maxEvidenceChars:r.maxEvidenceChars,resume:r.resume,trustResumeState:r.trustLocalState,describeScenario:t.describeScenario,describeArtifact:t.describeArtifact})}}const U=`tangle-native-reflection-json-content-v1`,W=`You are a native-agent reflection adapter. The task contains the original ordered role/content messages as JSON. Follow those messages as the reflection request. Return exactly one JSON object {"content":string}; content is the complete text response to that request. Do not add usage, model, or other fields.`;function G(e){let{profile:t,budget:n}=structuredClone({profile:e.profile,budget:e.budget});for(let e of Object.values(n))z.parse(e);let r=t.model?.default;if(!r||!t.harness)throw Error(`Native reflection requires an exact admitted harness and model profile`);let i=`${U}:${x({profile:t,budget:n,reflectionInstruction:W,binding:`params.reflection:whole-json-value`})}`;return{model:r,call:async({request:a,callId:o,signal:s})=>{let c=S.strictObject({model:S.literal(r),messages:S.array(S.strictObject({role:S.enum([`system`,`user`,`assistant`]),content:S.union([S.string(),S.array(S.strictObject({type:S.literal(`text`),text:S.string()}))])})).min(1),maxTokens:S.literal(n.maxTokens).optional(),timeoutMs:z.max(n.deadlineMs).optional()}).parse(a),l=JSON.stringify({graph:U,workspace:`fresh`,params:{reflection:{type:`object`,default:{protocol:U,messages:c.messages}}},nodes:[{id:`proposal`,profile:{...t,connections:void 0,mcp:void 0,hooks:void 0,resources:void 0,subagents:void 0,tools:{websearch:!1,webfetch:!1},prompt:{systemPrompt:W}}}],entry:[{node:`proposal`,task:"${params.reflection}"}],edges:[],budget:{...n,...c.timeoutMs&&{deadlineMs:c.timeoutMs}},check:{node:`proposal`,pointer:`/content`,exists:!0}}),u=await e.run(l,o,s),d=u.settlement,f=d.spentTotal,p=u.sourceDigest===y(`sha256`).update(l).digest(`hex`)&&d.tree.root===u.runId,m=f.tokensKnown!==!1&&f.tokens.tokensKnown!==!1,h={model:r,inputTokens:f.tokens.input,outputTokens:f.tokens.output,usageUnknown:!p||!m,...!p||f.usdKnown===!1?{costUnknown:!0}:{actualCostUsd:f.usd}},g={kind:U,callRef:i,callId:o,runId:u.runId,sourceDigest:u.sourceDigest,graphDigest:u.graphDigest,providerModel:d.providerModel??null};if(!p)return{succeeded:!1,error:`Reflection source or settlement run identity mismatched`,receipt:h,execution:g};if(d.kind!==`winner`||d.providerModel?.status!==`known`||d.providerModel.models.length!==1||d.providerModel.models[0]!==r)return{succeeded:!1,error:`Reflection failed or served model identity is unavailable/mismatched`,receipt:h,execution:g};let _=d.out?.proposal,v=_&&typeof _==`object`&&`json`in _?_.json:_,b=S.strictObject({content:S.string()}).safeParse(v);return b.success?{succeeded:!0,receipt:h,execution:g,response:{content:b.data.content,model:r,servedModel:d.providerModel.models[0],usage:{promptTokens:f.tokens.input,completionTokens:f.tokens.output,totalTokens:f.tokens.input+f.tokens.output,captured:m},costUsd:f.usdKnown===!1?null:f.usd,durationMs:u.durationMs,raw:{runId:u.runId,sourceDigest:u.sourceDigest}}}:{succeeded:!1,error:`Reflection omitted its exact content envelope`,receipt:h,execution:g}},callRef:i}}const K=S.number().int().positive(),q=S.strictObject({quality:S.number().min(0).max(1),notes:S.string()}),J=S.strictObject({version:S.literal(1),optimizer:V.default({kind:`native`}),domain:S.string().min(1),node:S.string().min(1),objective:S.string().min(1),evaluator:S.strictObject({command:S.string().min(1).refine(g,`Use an absolute evaluator executable path`),args:S.array(S.string()),files:S.array(S.string().min(1)).min(1),timeoutMs:K}),calibration:S.array(S.strictObject({request:S.unknown(),quality:S.union([S.literal(0),S.literal(1)])})).min(2),budget:S.strictObject({maxTokens:K,maxIterations:K,deadlineMs:K,maxExpansions:K,proposalTokens:K,proposalIterations:K,proposalDeadlineMs:K}),minimumEffect:S.number().positive().max(1),reps:K,operatingConstraints:S.strictObject({maxMeanTokens:K,maxMeanDurationMs:K,requireKnownOperatingCost:S.boolean().default(!1)})});async function Y(e,t,n,r,i){await i?.();let a=await C({command:e.evaluator.command,args:e.evaluator.args,cwd:t,timeoutMs:e.evaluator.timeoutMs,signal:r,ownProcessGroup:!0},void 0,{stdin:`${JSON.stringify(n)}\n`,maxOutputBytes:1024*1024});if(await i?.(),!a.exit.success)throw new M(`Independent evaluator failed (exit ${a.exit.code??`unknown`})`);return q.parse(JSON.parse(a.stdout??``))}async function X(e,t){let n=await O(e),r=J.parse(await l(n)),i=async()=>x({suite:await l(n),files:await Promise.all([r.evaluator.command,...r.evaluator.files].map(async t=>{let n=await O(v(h(e),t));return{path:n,digest:c(await E(n))}}))}),a=await i(),o=async()=>{if(await i()!==a)throw Error(`Independent evaluator dependencies changed during use`)};if(!r.calibration.some(e=>e.quality===0)||!r.calibration.some(e=>e.quality===1))throw Error(`Evaluator calibration needs both accepted and rejected examples`);let s=[];for(let e of r.calibration){let i=await Y(r,h(n),e.request,t,o);if(i.quality!==e.quality)throw Error(`Independent evaluator failed its accepted/rejected calibration; no inference started`);s.push(i)}return{suite:r,cwd:h(n),identity:a,calibration:s,assertUnchanged:o}}const Z=S.strictObject({evidence:S.string(),sourceDigest:S.string(),scenario:S.string(),unit:S.string(),split:S.enum([`train`,`dev`,`test`]),quality:S.number().min(0).max(1),tokens:S.number().nonnegative().nullable(),durationMs:S.number().nonnegative(),latencyKnown:S.boolean().default(!1),operatingCostUsd:S.null()});async function Q(e,t,n,r,i,a){let o=await E(new URL(a.ledger.uri),`utf8`);if(`sha256:${c(o)}`!==a.ledger.sha256||Buffer.byteLength(o)!==a.ledger.byteLength)throw Error(`Closed search ledger bytes changed`);L(o,a.runId,a.ledger.uri);let s=new Map;for(let[t,n]of o.trim().split(`
2
- `).entries()){let{event:r}=I(n,a.runId,{path:a.ledger.uri,line:t+1});if(r.kind===`cell-settled`)try{let t=await l(_(e,`attempts`,`${c(r.runId)}.json`));s.set(t.runId,r.wallMs===null||r.queueMs===null?null:r.wallMs+r.queueMs)}catch(e){if(e.code!==`ENOENT`)throw e}}let u=_(e,`judgments`),d=await D(u).catch(e=>{if(e.code!==`ENOENT`)throw e;return[]}),f=await Promise.all(d.filter(e=>e.endsWith(`.json`)).map(async e=>({...Z.parse(await l(_(u,e))),durationMs:s.get(e.slice(0,-5))??null}))),p=e=>e.reduce((e,t)=>e+t,0)/e.length,m=[...new Set(f.map(e=>e.sourceDigest))].sort().map(e=>{let r=f.filter(t=>t.sourceDigest===e&&t.split===`test`),i=r.length===t.length*n.reps&&t.every(e=>r.filter(t=>t.scenario===e.id).length===n.reps),a=[...new Set(t.map(e=>e.unit))],o=e=>p(a.map(t=>p(r.filter(e=>e.unit===t).map(e))));return{sourceDigest:e,complete:i,observations:r.length,independentUnits:a.length,quality:i?o(e=>e.quality):null,meanTokens:i&&r.every(e=>e.tokens!==null)?o(e=>e.tokens):null,meanDurationMs:i&&r.every(e=>e.durationMs!==null&&e.latencyKnown)?o(e=>e.durationMs):null,operatingCostUsd:null}}),h=R(m,[{name:`independent quality`,direction:`maximize`,value:e=>e.quality??NaN},{name:`reported input plus output tokens`,direction:`minimize`,value:e=>e.meanTokens??NaN},{name:`end-to-end graph milliseconds`,direction:`minimize`,value:e=>e.meanDurationMs??NaN}]),g=m.find(e=>e.sourceDigest===r),v=m.find(e=>e.sourceDigest===i),y=[...!v?.complete||v.meanTokens===null||v.meanDurationMs===null?[`baseline operational evidence is incomplete`]:[],...g?.complete?[]:[`candidate final-test cohort is incomplete`],...g?.meanTokens==null?[`candidate token usage is unknown`]:g.meanTokens>n.operatingConstraints.maxMeanTokens?[`candidate exceeds mean token ceiling`]:[],...g?.meanDurationMs==null?[`candidate latency is unknown`]:g.meanDurationMs>n.operatingConstraints.maxMeanDurationMs?[`candidate exceeds mean latency ceiling`]:[],...h.frontier.some(e=>e.sourceDigest===r)?[]:[`candidate is absent from the matched quality/token/latency frontier`],...n.operatingConstraints.requireKnownOperatingCost?[`operating dollar cost is unknown`]:[]];return{admissible:y.length===0,reasons:y,constraints:n.operatingConstraints,reports:m,frontier:h.frontier.map(e=>e.sourceDigest),dollarFrontierEstablished:!1}}async function $(t,i){let s=v(t),{release:f}=F({lockPath:`${await O(s)}.lock`}),g,y;try{let{record:t}=await l(_(s,`result.json`)),f=await m(s,t);if(f.decision!==`promote`)throw Error(`The independent comparison held this candidate`);let v=await O(i);if(v!==f.sourcePath)throw Error(`Activation target differs from the measured source path`);g=F({lockPath:`${v}.lock`}).release;let C=await E(f.candidate,`utf8`);if(c(C)!==f.candidateDigest)throw Error(`Measured candidate bytes changed`);let w=c(await E(v));if(w!==f.baselineDigest&&w!==f.candidateDigest)throw Error(`Activation baseline changed; evaluate the new baseline`);let T=async()=>{if(c(await E(v))!==w)throw Error(`Activation target changed while evidence was checked; the edit was preserved`)},{identity:D,assertUnchanged:A}=await X(f.suite);if(await T(),D!==f.evaluatorIdentity)throw Error(`Independent evaluator changed since measurement`);if(!f.operational.admissible)throw Error(`Measured operational constraints held this candidate`);let M=S.array(S.strictObject({runId:S.uuid(),scenario:S.string(),graphDigest:S.string()})).min(1).parse(f.executionIdentities),N=await p(f.dataset.root,f.dataset.version),P=new Set;for(let t of M){let i=N.cases.find(e=>e.id===t.scenario);if(!i||i.trigger===void 0)throw Error(`Measured execution inputs are unavailable`);let s=await o(t.runId);if(s.sourceDigest!==f.candidateDigest||s.graphDigest!==t.graphDigest||x(n.parse(s.mcpPolicy??{}))!==x(n.parse(f.mcpPolicy??{})))throw Error(`Measured execution configuration changed`);P.add(await e(s));let c=await a(v,{param:r(i.params),dryRun:!0,mcpPolicy:n.parse(f.mcpPolicy??{})},{source:C,...i.trigger&&{trigger:i.trigger}});if(!(`graph`in c)||c.graph.digest!==t.graphDigest)throw Error(`Ordinary execution differs from the measured configuration; express its seat through the maintained graph contract and reevaluate under the intended host policy`)}await A(),await T();let I=await l(_(s,`activation.json`)).catch(e=>{if(e.code!==`ENOENT`)throw e}),L={record:t,baselineDigest:f.baselineDigest,candidateDigest:f.candidateDigest,executionConfigurations:[...P].sort(),target:v,activatedAt:I?.record===t&&w===f.candidateDigest?I.activatedAt:new Date().toISOString()};return await d(_(s,`activation.pending.json`),L),w!==f.candidateDigest&&(y=_(h(v),`.${b()}.graph.yaml`),await j(y,C,{mode:384,flush:!0}),await T(),await k(y,v),y=void 0,await u(h(v))),await d(_(s,`activation.json`),L),L}finally{y&&await A(y,{force:!0}),await g?.(),await f()}}async function ee(n,r,a){let u=v(n),{release:h}=F({lockPath:`${await O(u)}.lock`});try{let n=await l(_(u,`activation.json`)),h=await m(u,n.record),g=await o(r);if(c(await s(g))!==h.candidateDigest)throw Error(`Observation did not execute the activated candidate`);if(!S.array(S.string().regex(/^sha256:[a-f0-9]{64}$/)).min(1).parse(n.executionConfigurations).includes(await e(g)))throw Error(`Observation execution configuration differs from the activated measurement`);if(!a.trim())throw Error(`Observation needs an independent task unit`);if(Date.parse(g.startedAt)<=Date.parse(S.iso.datetime().parse(n.activatedAt)))throw Error(`Observation must have started after this candidate was activated`);let v=await p(h.dataset.root,h.dataset.version),y=x({params:g.params,trigger:g.trigger??null,taskWorkspace:g.taskWorkspace?i(g.taskWorkspace):null});if((await Promise.all((await D(_(u,`attempts`))).filter(e=>e.endsWith(`.json`)).map(e=>l(_(u,`attempts`,e))))).some(e=>e.runId===r)||v.cases.some(e=>e.run===r||e.unit===a||x({params:e.params,trigger:e.trigger??null,taskWorkspace:e.taskWorkspace?i(e.taskWorkspace):null})===y))throw Error(`A learning execution or task is not a subsequent independent production observation`);let b=_(u,`observations`);await T(b,{recursive:!0,mode:448});for(let e of(await D(b)).filter(e=>e.endsWith(`.json`))){let t=await l(_(b,e)),i=await m(u,t.record);if(i.runId===r){if(i.unit!==a||i.taskDigest!==y||i.activation.record!==n.record)throw Error(`The retained observation identity changed`);return{record:t.record,runId:r,verdict:i.verdict}}if(i.unit===a||i.taskDigest===y)throw Error(`An independent observation unit or task cannot be counted twice`)}let{suite:C,cwd:E,identity:O,assertUnchanged:k}=await X(h.suite);if(O!==h.evaluatorIdentity)throw Error(`Observation evaluator changed`);let A=await P(_(w(),`.tangle`,`runs`,r));if(!A)throw Error(`Observation has not settled`);if(A.tree.root!==r)throw Error(`Observation settlement names another native run`);let j={...t(A),runId:r,sourceDigest:g.sourceDigest,graphDigest:g.graphDigest},M=await Y(C,E,{scenario:{params:g.params,trigger:g.trigger??null,unit:a,taskDigest:y},artifact:j},void 0,k),N=await f(u,{activation:n,runId:r,unit:a,taskDigest:y,activatedAt:n.activatedAt,artifact:j,verdict:M});return await d(_(u,`observations`,`${r}.json`),{record:N}),{record:N,runId:r,verdict:M}}finally{h()}}export{G as a,$ as activateGraph,Z as graphOperatingCell,Q as graphOperatingDecision,V as i,X as n,ee as observeGraph,H as r,Y as t};
File without changes