@devflow-tools/cli 0.18.16 → 0.18.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/plugin-files/.claude-plugin/plugin.json +1 -1
- package/dist/plugin-files/dist/command-registry.json +6 -6
- package/dist/plugin-files/dist/hooks/hook-daemon.js +17 -17
- package/dist/plugin-files/dist/hooks/pre-tool-use.js +4 -4
- package/dist/plugin-files/dist/hooks/session-end.js +4 -4
- package/dist/plugin-files/dist/hooks/stop.js +2 -2
- package/dist/plugin-files/dist/skills/devflow:delivery/SKILL.md +16 -0
- package/dist/plugin-files/package.json +13 -13
- package/dist/plugin-files/skills/delivery/SKILL.md +16 -0
- package/package.json +28 -28
|
@@ -12,32 +12,32 @@ import {createServer,createConnection}from'net';import {createHash,randomUUID as
|
|
|
12
12
|
|
|
13
13
|
`)}}function Eo(t,e){let n=new Set,o=new Set(e.flatMap(c=>c.contract.requiredSections)),r=Ao(t.split(/\r?\n/)),i=To(r.headingLines);for(let c of o)i.found.has(c)||n.add(`missing_section:${c}`);if(e.every(c=>c.contract.runtimeProfilingOccurred))return [...n];let a=e.every(c=>c.contract.samplingEvidenceOccurred);for(let c=0;c<r.claimLines.length;c++){let d=r.claimLines[c].trim();if(!d||Ia(d))continue;let u=i.byLine.get(c);for(let l of Sa(d))ka(l,u,a,n);}return [...n]}function Ao(t){let e=false,n=[],o=[];for(let r of t){if(/^\s*```/.test(r)){e=!e,n.push(""),o.push(r.replace(/^\s*```+[^\s`]*/,"").replace(/```+\s*$/,"").trim());continue}n.push(e?"":r.replace(/`[^`]*`/g,"").trim()),o.push(r.replace(/`([^`]*)`/g,(i,s)=>_a(s)?"":s).trim());}return {headingLines:n,claimLines:o}}function _a(t){let e=t.trim().slice(0,256);return !e||/\s/.test(e)||t.trim().length>256?false:/^[A-Za-z_$][\w$.-]*$/.test(e)||/^(['"])[^'"`]*\1$/.test(e)}function Ia(t){if(t.length>2048)return false;let e=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").trim();return e?wa(e)||/^(?:\/\/|\/\*|\*\/|\*\s|#!)/.test(e)||/^(?:import|export|const|let|var|function|class|type|interface|enum|namespace|declare)\b/.test(e)||/^(?:async\s+)?(?:function\s+)?[A-Za-z_$][\w$]*\s*=\s*/.test(e)||/^[A-Za-z_$][\w$.[\]'"-]*\s*(?:=|\+=|-=|\*=|\/=|\?\?=|&&=|\|\|=)\s*/.test(e)||/^[A-Za-z_$'"-][\w$.'"-]*\s*:\s*[^:]+[,}]?$/.test(e)||/=>/.test(e)||/^(?:await\s+|return\s+|throw\s+|new\s+)?[A-Za-z_$][\w$.]*\s*\([^)]*\)\s*;?$/.test(e)||/^(['"])[\s\S]*\1[;,]?$/.test(e)?true:/[{}()[\]=<>]\s*;?$/.test(e)&&/(?:;|=>|\b(?:return|new|await)\b)/.test(e):false}function wa(t){if(t.length>1024)return false;let e="(?:--[A-Za-z0-9_-]+|(?:-webkit-|-moz-|-ms-)?(?:animation(?:-[a-z-]+)?|transition(?:-[a-z-]+)?|opacity|transform|will-change|contain|content-visibility|display|position|top|right|bottom|left|width|height|min-(?:width|height)|max-(?:width|height)|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|color|background(?:-[a-z-]+)?|border(?:-[a-z-]+)?|font(?:-[a-z-]+)?|line-height|z-index|overflow(?:-[xy])?))";return new RegExp(`^${e}\\s*:\\s*\\S[^;]{0,960};$`,"i").test(t)}function ka(t,e,n,o){let r=/\bP0\b/gi;for(let g of t.matchAll(r))Ro(t,g.index??0,g[0],"p0")||o.add("unsupported_p0_severity");let i=/(?:中高|高)(?:风险|优先级)|严重(?:问题|风险)|\bhigh[- ](?:risk|severity|priority)\b/gi;for(let g of t.matchAll(i))Ro(t,g.index??0,g[0],"high")||o.add("unsupported_high_severity");let s=/(?:性能)?瓶颈|卡顿|掉帧|CPU\s*(?:热点|尖峰)|\bbottleneck\b|\bjank\b|\bdropped frames?\b|\bCPU hotspot\b/gi;for(let g of t.matchAll(s))Ra(t,g.index??0,g[0])||(/(?:瓶颈|bottleneck)/i.test(g[0])?o.add("unsupported_confirmed_bottleneck"):o.add("unsupported_runtime_effect"));let a=/\b\d{1,3}(?:\.\d+)?\s*%/.test(t),c=/(?:预计|预期|估计|提升|降低|减少|节省|改善|收益|加速|improve|reduce|faster|gain|benefit|speedup|expected|estimated)/i.test(t),d=/\b\d+(?:\.\d+)?\s*[x×]\b/i.test(t);(a||d)&&c&&o.add(a?"unsupported_benefit_percentage":"unsupported_performance_number");let u=/\b\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:ms|fps|hz)\b/i.test(t)||/\d+(?:\.\d+)?(?:\s*[-–~]\s*\d+(?:\.\d+)?)?\s*(?:毫秒|次\s*\/\s*秒|帧)/.test(t),l=e==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&/(?:采集|记录|测量|收集|collect|measure|record)/i.test(t)&&!/(?:预计|预期|估计|约|大约|通常|平均|每(?:隔)?|达到|提升|降低|减少|节省|改善|improve|reduce|faster|expected|estimated|average|typically|every)/i.test(t);a&&!c&&!l&&o.add("unsupported_benefit_percentage"),u&&!l&&o.add("unsupported_performance_number");let m=/(?:requestAnimationFrame|\bRAF\b)/i.test(t),f=/(?:建议|应该|应当|使用|添加|采用|切换|包裹|优化|节流|\buse\b|\badopt\b|\brecommend\b|\bswitch\b|\bwrap\b|\bthrottl(?:e|ing)\b)/i.test(t),p=/(?:不要|不得|不能|不应|避免|不建议|不推荐).{0,16}(?:使用|采用|添加|切换|包裹|节流)?.{0,8}(?:requestAnimationFrame|\bRAF\b)|\b(?:do\s+not|don't|never|avoid)\s+(?:use|adopt|recommend|switch|wrap|throttle)?.{0,8}(?:requestAnimationFrame|RAF)\b/i.test(t);m&&f&&!p&&!n&&o.add("raf_without_sampling_evidence");}function Ro(t,e,n,o){let r=t.slice(Math.max(0,e-64),e),i=t.slice(e+n.length,e+n.length+28),s=ba(r),a=/^(?:\s+)?(?:未发现|不存在|并不存在|未被发现)/.test(i)||/^(?:\s+)?(?:was\s+|is\s+)?not found\b/i.test(i);return s||a?true:o==="high"?/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?)\s*(?:任何|明确的)?\s*P0\s*(?:或|和|及|、)\s*$/i.test(r)||/\b(?:no evidence (?:of|for)|no)\s+P0\s+(?:or|and)\s+$/i.test(r):false}function ba(t){if(/(?:未发现|没有发现|不存在|无证据(?:表明|证明)?|不是|并非|未被)\s*(?:任何|明确的)?\s*(?:(?:问题|发现|证据|项|内容)\s*)?(?:(?:属于|(?:被)?(?:评|判定|认定|标记|列|视|定|归(?:类)?)为)\s*)?$/i.test(t)||/\b(?:no evidence (?:of|for)|no|not|isn't|is\s+not)\s+(?:an?\s+)?(?:(?:issues?|findings?|evidence|items?)\s+)?(?:(?:classified|rated|marked|labelled|labeled)(?:\s+as)?\s+)?$/i.test(t))return true;let n=/(?:不得|不能|不应|不宜|不要)\s*(?:被\s*)?(?:(?:直接|轻易|简单|明确|正式|合理|据此|当前|目前)\s*){0,2}(?:(?:评|判定|认定|标记|列|视|定|归(?:类)?)为|属于)\s*$/i,o=/\b(?:cannot|can't|must not|should not|shouldn't|do not|don't)\s+(?:(?:reasonably|directly|formally|currently)\s+){0,2}(?:be\s+)?(?:classified|labeled|labelled|rated|marked)(?:\s+as)?\s+$/i;return n.test(t)||o.test(t)}function Ra(t,e,n){let o=t.slice(Math.max(0,e-40),e),r=t.slice(e+n.length,e+n.length+32),i=/(?:是否|待验证|候选|可能|潜在|未观察到|没有观察到|未发现|不存在|无证据(?:表明)?|不能(?:据此)?确认|尚未(?:确认|证明)|验证(?:是否)?|测量(?:是否)?|采集|记录|收集).{0,16}$/i.test(o)||/\b(?:whether|measure|validate|candidate|potential|possible|may|might|no|no evidence(?: of| for)?|not observed|unobserved|collect|record).{0,18}$/i.test(o),s=/^(?:是否|有待验证|待验证|候选|可能|潜在|指标|需要(?:验证|测量)|需(?:验证|测量))/.test(r)||/^(?:\s+)?(?:candidate|potential|possible|metric|metrics|to (?:measure|validate)|needs? (?:measurement|validation)|is (?:a )?(?:candidate|potential))/i.test(r);return i||s}function Sa(t){return t.split(/(?:[。!?;;,,]|\b(?:but|however|yet|nevertheless|nonetheless)\b|但是|但|然而|却|不过|可是)/i).map(e=>e.trim()).filter(Boolean)}function fe(t,e,n){if(e>pa||t===null||t===void 0)return null;if(typeof t=="string"){if(Buffer.byteLength(t,"utf8")>da)return null;try{return fe(JSON.parse(t),e+1,n)}catch{return null}}if(typeof t!="object"||n.has(t))return null;if(n.add(t),Array.isArray(t)){for(let r of t.slice(0,16)){let i=fe(r,e+1,n);if(i)return i}return null}let o=t;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let r of ["structuredContent","data","result"])if(r in o){let i=fe(o[r],e+1,n);if(i)return i}if(Array.isArray(o.content))for(let r of o.content.slice(0,16)){let i=r&&typeof r=="object"&&"text"in r?r.text:r,s=fe(i,e+1,n);if(s)return s}return null}function xa(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t;if(n.version!=="1.0"||typeof n.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(n.id)||typeof n.runtimeProfilingOccurred!="boolean"||typeof n.samplingEvidenceOccurred!="boolean"||!Array.isArray(n.requiredSections)||n.requiredSections.length!==pe.length)return null;let o=n.requiredSections.filter(c=>typeof c=="string");if(o.length!==pe.length||pe.some((c,d)=>o[d]!==c)||!Array.isArray(n.prohibitedClaims)||n.prohibitedClaims.length>16)return null;let r=n.prohibitedClaims.filter(c=>typeof c=="string"&&c.length<=128);if(r.length!==n.prohibitedClaims.length)return null;let i=n.correctionPolicy;if(!i||typeof i!="object"||Array.isArray(i))return null;let s=i;if(s.maxAttempts!==1||s.repeatedViolation!=="fail_open")return null;let a=typeof n.canonicalReport=="string"?n.canonicalReport:e;return typeof a!="string"||Buffer.byteLength(a,"utf8")>la||pe.some(c=>!a.includes(c))?null:{version:"1.0",id:n.id,runtimeProfilingOccurred:n.runtimeProfilingOccurred,samplingEvidenceOccurred:n.samplingEvidenceOccurred,requiredSections:o,prohibitedClaims:r,correctionPolicy:{maxAttempts:1,repeatedViolation:"fail_open"},canonicalReport:a}}function xt(t,e){if(!t||t.length>4096)return {degradationReason:"transcript_path_missing"};let n;try{let o=lstatSync$1(t);if(!o.isFile()||o.isSymbolicLink())return {degradationReason:"transcript_path_unsafe"};n=openSync$1(t,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let r=fstatSync$1(n);if(!r.isFile()||r.dev!==o.dev||r.ino!==o.ino)return {degradationReason:"transcript_path_changed"};let i=Math.min(r.size,ua),s=Buffer.alloc(i),a=0;for(;a<i;){let p=readSync(n,s,a,i-a,r.size-i+a);if(p===0)break;a+=p;}let c=s.subarray(0,a).toString("utf8");r.size>i&&(c=c.slice(Math.max(0,c.indexOf(`
|
|
14
14
|
`)+1)));let d=c.split(/\r?\n/).slice(-ma),u=e.length>0?Math.min(...e.map(p=>p.promptedAt)):0,l=Aa(d,u),f=[...l].reverse().find(p=>Ea(p.text,e))??l.at(-1);return f?.text?{answer:f.text,fingerprint:f.fingerprint}:{degradationReason:"transcript_answer_unavailable"}}catch{return {degradationReason:"transcript_unreadable"}}finally{n!==void 0&&closeSync$1(n);}}function Ea(t,e){let n=new Set(e.flatMap(r=>r.contract.requiredSections)),o=To(Ao(t.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function We(t){return xt(t,[]).answer}function Aa(t,e){let n=[];for(let o=0;o<t.length;o++){let r=t[o];if(r.trim())try{let i=JSON.parse(r),s=i.message;if(!s||typeof s!="object"||s.role!=="assistant")continue;let a=s,c=Ta(i.timestamp);if(c>0&&c+5e3<e)continue;let d=s.content,u=typeof d=="string"?d:Array.isArray(d)?d.filter(l=>l&&typeof l=="object"&&l.type==="text").map(l=>l.text).filter(l=>typeof l=="string").join(`
|
|
15
|
-
`):"";if(u.trim()){let l=u.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${o}:${createHash("sha256").update(r).digest("hex")}`,f=createHash("sha256").update(l).digest("hex"),p=createHash("sha256").update(`${m}\0${f}`).digest("hex");n.push({text:l,timestamp:c,fingerprint:p});}}catch{continue}}return n}function Ta(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?e:0}function To(t){let e=new Set,n=new Map,o;for(let r=0;r<t.length;r++){let i=t[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=pe.find(a=>i===a);s&&(o=s,e.add(s)),n.set(r,o);}return {found:e,byLine:n}}function Mo(t){let e;try{if($a(t.toolResponse))return null;e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=e.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!n)return null;let o=Ma(t.toolInput);if(o.length===0)return null;let r=t.toolName==="Read"?Oa(t.toolInput):void 0,i=r?n.selectedFiles?.find(u=>Pa(t.projectRoot,u,r)):void 0,s=ja(t.toolName),a=i?"code":n.canonicalNextAction===s?"action":null,c=i&&o.includes(i)?i:a==="action"&&o.includes(s)?s:void 0;if(a&&c){let u=[n.contextHash,n.requestId??"",a,c,t.toolUseId??`${t.sessionId}:${t.executionId??n.executionId}`].join("\0");e.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:t.toolName,toolUseId:t.toolUseId,selectedAt:Date.now()});}let d=e.listRetrievalLedgerEvents({projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)e.appendRetrievalLedgerEvent({...u,id:retrievalLedgerTransitionId(u.id,"consumed",t.toolUseId??t.toolName),stage:"consumed",toolEvidence:[t.toolUseId??t.toolName],evidenceIds:o,actor:t.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:t.toolName},createdAt:Date.now()});return d.length>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:t.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){throw ge({event:"hook.runtime.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:t.toolName,reason:n instanceof Error?n.message:String(n)}}),n}finally{try{e?.close();}catch{}}}function Oo(t){let e=openGlobalDevFlowDatabase();try{let n=e.listRetrievalLedgerEvents(t),o=new Map(n.filter(l=>l.stage==="selected").map(l=>[Do(l),l])),r=new Map(n.filter(l=>l.stage==="consumed").map(l=>[Do(l),l])),i=0,s=0,a=0;for(let[l,m]of o){let f=r.get(l);f&&t.verificationReceipt&&e.appendRetrievalLedgerEvent({...f,id:retrievalLedgerTransitionId(f.id,"verified",t.verificationReceipt),stage:"verified",verificationReceipt:t.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:t.finishedAt??Date.now()});let p=f&&t.verificationReceipt&&t.outcome!=="unknown"?t.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";e.appendRetrievalLedgerEvent({...m,id:retrievalLedgerTransitionId(m.id,g,t.verificationReceipt??t.sessionId),stage:g,reason:f?t.outcomeReason:"selected_not_consumed",toolEvidence:f?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:t.verificationReceipt,payload:{...m.payload,consumed:!!f},createdAt:t.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c=t.requiredChannels.map(l=>{let m=[...o.values()].filter(p=>p.sourceType===l).length,f=[...r.values()].filter(p=>p.sourceType===l).length;return {channel:l,selected:m,consumed:f,verified:t.verificationReceipt?f:0}}),d={status:c.length>0&&c.every(l=>l.selected>0&&l.consumed===l.selected&&l.verified===l.selected)?"complete":"unavailable",channels:c},u={consumed:r.size,positive:i,negative:s,unknown:a,consumedSources:[...r.values()].map(l=>({sourceType:l.sourceType,sourceId:l.sourceId})),proof:d};return t.verificationReceipt&&r.size>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"info",timestamp:t.finishedAt??Date.now(),data:{stage:"verified",verifiedCount:r.size}}),ge({event:"task.proof.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:d.status==="complete"?"info":"warn",timestamp:t.finishedAt??Date.now(),data:d}),ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:a>0?"warn":"info",timestamp:t.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:t.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),u}finally{e.close();}}function Ma(...t){let e=new Set,n=(o,r=0)=>{if(!(r>6||o==null)){if(typeof o=="string"){try{n(JSON.parse(o),r+1);}catch{}return}if(Array.isArray(o)){for(let i of o)n(i,r+1);return}if(typeof o=="object")for(let[i,s]of Object.entries(o))if((i==="evidenceRefs"||i==="_devflow_evidence_refs")&&Array.isArray(s))for(let a of s)typeof a=="string"&&a.trim()&&e.add(a.trim());else n(s,r+1);}};for(let o of t)n(o);return [...e]}function Oa(t){for(let e of ["file_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}}function Pa(t,e,n){let o=resolve(t,e),r=isAbsolute(n)?resolve(n):resolve(t,n);return o===r}function ja(t){return t.startsWith("mcp__")?t.split("__").at(-1)??t:t}function $a(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error||["failed","rejected","unavailable"].includes(String(e.status??""))}function Do(t){return [t.requestId,t.contextReceipt,t.sourceType,t.sourceId].join("\0")}function ge(t){try{h(t);}catch{}}var za=8*1024*1024;function $o(t){if(!t.transcriptPath||!existsSync(t.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=e.getLatestTranscriptCheckpoint({projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath}),o=statSync(t.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(za,o-r);if(i<=0)return {status:"completed",eventsRead:0,failuresFound:0,failuresRecorded:0,checkpointId:n?.id};let s=Buffer.alloc(i),a=openSync$1(t.transcriptPath,"r");try{readSync(a,s,0,i,r);}finally{closeSync$1(a);}let c=s.toString("utf8").split(/\r?\n/u).filter(Boolean),d=e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId),u=new Map,l=new Set,m=0,f=0;for(let S of c){let b;try{b=JSON.parse(S);}catch{continue}for(let k of Tt(b,u)){let w=claudeCodeRuntimeAdapter.normalizeToolResult(k,{projectRoot:t.projectRoot});if(w.success||!w.error)continue;let T=w.toolUseId??w.sourceHash;if(l.has(T))continue;l.add(T),m++;let x=w.toolUseId?e.getToolCallEventByToolUseId(t.sessionId,w.toolUseId):null,O=jo(x?.input,"_devflow_turn_id"),N=jo(x?.input,"_devflow_request_id"),R=O?d.find(A=>A.turnId===O):[...d].reverse().find(A=>(!x?.executionId||A.executionId===x.executionId)&&A.createdAt<=(x?.timestamp??w.timestamp))??d.at(-1),D=`host-failure:${w.sourceHash}`;e.insertEvent({kind:"host_transcript_tool_failure",timestamp:w.timestamp,success:!1,toolName:w.canonicalName??w.requestedName,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:O??R?.turnId,requestId:N??R?.requestId,sourceId:D,toolUseId:w.toolUseId,correlatedEventId:x?.eventId,requestedName:w.requestedName,canonicalName:w.canonicalName,failureCategory:w.failureCategory,error:w.error.slice(0,1e3)}}),h({event:"host.tool.result.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:O??R?.turnId,requestId:N??R?.requestId,executionId:x?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:w.toolUseId,toolName:w.canonicalName??w.requestedName,failureCategory:w.failureCategory,correlation:x?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}\0${t.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return e.appendTranscriptCheckpoint({id:g,projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),h({event:"session.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:m>0?"warn":"info",timestamp:Date.now(),data:{stage:"transcript",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}),{status:"completed",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}catch(n){return {status:"degraded",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:n instanceof Error?n.message:String(n)}}finally{e.close();}}function jo(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function Tt(t,e,n=0){if(n>7||t===null||t===void 0)return [];if(Array.isArray(t))return t.flatMap(s=>Tt(s,e,n+1));if(typeof t!="object")return [];let o=t,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&e.set(o.id,o.name);let i=[];if(r==="tool_result"){let s=typeof o.tool_use_id=="string"?o.tool_use_id:void 0;i.push({tool_name:s?e.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:Dt(o.content)||"host tool result failed"}:{},timestamp:o.timestamp});}else (o.tool_name||o.toolName)&&(o.tool_response!==void 0||o.output!==void 0||o.error!==void 0)&&i.push(o);for(let[s,a]of Object.entries(o))s==="content"&&r==="tool_result"||i.push(...Tt(a,e,n+1));return i}function Dt(t){if(typeof t=="string")return t.slice(0,4e3);if(Array.isArray(t))return t.map(Dt).filter(Boolean).join(`
|
|
15
|
+
`):"";if(u.trim()){let l=u.trim(),m=typeof a.id=="string"&&a.id?`message:${a.id}`:typeof i.uuid=="string"&&i.uuid?`uuid:${i.uuid}`:`record:${String(i.timestamp??"")}:${o}:${createHash("sha256").update(r).digest("hex")}`,f=createHash("sha256").update(l).digest("hex"),p=createHash("sha256").update(`${m}\0${f}`).digest("hex");n.push({text:l,timestamp:c,fingerprint:p});}}catch{continue}}return n}function Ta(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?e:0}function To(t){let e=new Set,n=new Map,o;for(let r=0;r<t.length;r++){let i=t[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=pe.find(a=>i===a);s&&(o=s,e.add(s)),n.set(r,o);}return {found:e,byLine:n}}function Mo(t){let e;try{if($a(t.toolResponse))return null;e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=e.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!n)return null;let o=Ma(t.toolInput);if(o.length===0)return null;let r=t.toolName==="Read"?Oa(t.toolInput):void 0,i=r?n.selectedFiles?.find(u=>Pa(t.projectRoot,u,r)):void 0,s=ja(t.toolName),a=i?"code":n.canonicalNextAction===s?"action":null,c=i&&o.includes(i)?i:a==="action"&&o.includes(s)?s:void 0;if(a&&c){let u=[n.contextHash,n.requestId??"",a,c,t.toolUseId??`${t.sessionId}:${t.executionId??n.executionId}`].join("\0");e.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:t.toolName,toolUseId:t.toolUseId,selectedAt:Date.now()});}let d=e.listRetrievalLedgerEvents({projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)e.appendRetrievalLedgerEvent({...u,id:retrievalLedgerTransitionId(u.id,"consumed",t.toolUseId??t.toolName),stage:"consumed",toolEvidence:[t.toolUseId??t.toolName],evidenceIds:o,actor:t.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:t.toolName},createdAt:Date.now()});return d.length>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:t.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){throw ge({event:"hook.runtime.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:t.toolName,reason:n instanceof Error?n.message:String(n)}}),n}finally{try{e?.close();}catch{}}}function Oo(t){let e=openGlobalDevFlowDatabase();try{let n=e.listRetrievalLedgerEvents(t),o=new Map(n.filter(l=>l.stage==="selected").map(l=>[Do(l),l])),r=new Map(n.filter(l=>l.stage==="consumed").map(l=>[Do(l),l])),i=0,s=0,a=0;for(let[l,m]of o){let f=r.get(l);f&&t.verificationReceipt&&e.appendRetrievalLedgerEvent({...f,id:retrievalLedgerTransitionId(f.id,"verified",t.verificationReceipt),stage:"verified",verificationReceipt:t.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:t.finishedAt??Date.now()});let p=f&&t.verificationReceipt&&t.outcome!=="unknown"?t.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";e.appendRetrievalLedgerEvent({...m,id:retrievalLedgerTransitionId(m.id,g,t.verificationReceipt??t.sessionId),stage:g,reason:f?t.outcomeReason:"selected_not_consumed",toolEvidence:f?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:t.verificationReceipt,payload:{...m.payload,consumed:!!f},createdAt:t.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c=t.requiredChannels.map(l=>{let m=[...o.values()].filter(p=>p.sourceType===l).length,f=[...r.values()].filter(p=>p.sourceType===l).length;return {channel:l,selected:m,consumed:f,verified:t.verificationReceipt?f:0}}),d={status:c.length>0&&c.every(l=>l.selected>0&&l.consumed===l.selected&&l.verified===l.selected)?"complete":"unavailable",channels:c},u={consumed:r.size,positive:i,negative:s,unknown:a,consumedSources:[...r.values()].map(l=>({sourceType:l.sourceType,sourceId:l.sourceId})),proof:d};return t.verificationReceipt&&r.size>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:"info",timestamp:t.finishedAt??Date.now(),data:{stage:"verified",verifiedCount:r.size}}),ge({event:"task.proof.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:d.status==="complete"?"info":"warn",timestamp:t.finishedAt??Date.now(),data:d}),ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,requestId:t.requestId},level:a>0?"warn":"info",timestamp:t.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:t.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),u}finally{e.close();}}function Ma(...t){let e=new Set,n=(o,r=0)=>{if(!(r>6||o==null)){if(typeof o=="string"){try{n(JSON.parse(o),r+1);}catch{}return}if(Array.isArray(o)){for(let i of o)n(i,r+1);return}if(typeof o=="object")for(let[i,s]of Object.entries(o))if((i==="evidenceRefs"||i==="_devflow_evidence_refs")&&Array.isArray(s))for(let a of s)typeof a=="string"&&a.trim()&&e.add(a.trim());else n(s,r+1);}};for(let o of t)n(o);return [...e]}function Oa(t){for(let e of ["file_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}}function Pa(t,e,n){let o=resolve(t,e),r=isAbsolute(n)?resolve(n):resolve(t,n);return o===r}function ja(t){return t.startsWith("mcp__")?t.split("__").at(-1)??t:t}function $a(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error||["failed","rejected","unavailable"].includes(String(e.status??""))}function Do(t){return [t.requestId,t.contextReceipt,t.sourceType,t.sourceId].join("\0")}function ge(t){try{h(t);}catch{}}var za=8*1024*1024;function $o(t){if(!t.transcriptPath||!existsSync(t.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=e.getLatestTranscriptCheckpoint({projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath}),o=statSync(t.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(za,o-r);if(i<=0)return {status:"completed",eventsRead:0,failuresFound:0,failuresRecorded:0,checkpointId:n?.id};let s=Buffer.alloc(i),a=openSync$1(t.transcriptPath,"r");try{readSync(a,s,0,i,r);}finally{closeSync$1(a);}let c=s.toString("utf8").split(/\r?\n/u).filter(Boolean),d=e.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId),u=new Map,l=new Set,m=0,f=0;for(let R of c){let k;try{k=JSON.parse(R);}catch{continue}for(let b of Tt(k,u)){let w=claudeCodeRuntimeAdapter.normalizeToolResult(b,{projectRoot:t.projectRoot});if(w.success||!w.error)continue;let T=w.toolUseId??w.sourceHash;if(l.has(T))continue;l.add(T),m++;let x=w.toolUseId?e.getToolCallEventByToolUseId(t.sessionId,w.toolUseId):null,O=jo(x?.input,"_devflow_turn_id"),N=jo(x?.input,"_devflow_request_id"),S=O?d.find(A=>A.turnId===O):[...d].reverse().find(A=>(!x?.executionId||A.executionId===x.executionId)&&A.createdAt<=(x?.timestamp??w.timestamp))??d.at(-1),D=`host-failure:${w.sourceHash}`;e.insertEvent({kind:"host_transcript_tool_failure",timestamp:w.timestamp,success:!1,toolName:w.canonicalName??w.requestedName,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:O??S?.turnId,requestId:N??S?.requestId,sourceId:D,toolUseId:w.toolUseId,correlatedEventId:x?.eventId,requestedName:w.requestedName,canonicalName:w.canonicalName,failureCategory:w.failureCategory,error:w.error.slice(0,1e3)}}),h({event:"host.tool.result.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:O??S?.turnId,requestId:N??S?.requestId,executionId:x?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:w.toolUseId,toolName:w.canonicalName??w.requestedName,failureCategory:w.failureCategory,correlation:x?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${t.projectRoot}\0${t.sessionId}\0${t.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return e.appendTranscriptCheckpoint({id:g,projectRoot:t.projectRoot,hostId:"claude-code",sessionId:t.sessionId,sourcePath:t.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),h({event:"session.reconciled",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId},level:m>0?"warn":"info",timestamp:Date.now(),data:{stage:"transcript",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}),{status:"completed",eventsRead:c.length,failuresFound:m,failuresRecorded:f,checkpointId:g}}catch(n){return {status:"degraded",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:n instanceof Error?n.message:String(n)}}finally{e.close();}}function jo(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function Tt(t,e,n=0){if(n>7||t===null||t===void 0)return [];if(Array.isArray(t))return t.flatMap(s=>Tt(s,e,n+1));if(typeof t!="object")return [];let o=t,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&e.set(o.id,o.name);let i=[];if(r==="tool_result"){let s=typeof o.tool_use_id=="string"?o.tool_use_id:void 0;i.push({tool_name:s?e.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:Dt(o.content)||"host tool result failed"}:{},timestamp:o.timestamp});}else (o.tool_name||o.toolName)&&(o.tool_response!==void 0||o.output!==void 0||o.error!==void 0)&&i.push(o);for(let[s,a]of Object.entries(o))s==="content"&&r==="tool_result"||i.push(...Tt(a,e,n+1));return i}function Dt(t){if(typeof t=="string")return t.slice(0,4e3);if(Array.isArray(t))return t.map(Dt).filter(Boolean).join(`
|
|
16
16
|
`).slice(0,4e3);if(!t||typeof t!="object")return "";let e=t;return [e.text,e.content,e.message].map(Dt).filter(Boolean).join(`
|
|
17
|
-
`).slice(0,4e3)}var Ja={open:["intent_bound"],intent_bound:["context_ready","context_degraded"],context_ready:["action_required","action_not_required"],context_degraded:["action_required","action_not_required"],action_required:["action_satisfied","action_degraded","action_failed"],action_not_required:["memory_decided","memory_quarantined"],action_satisfied:["memory_decided","memory_quarantined"],action_degraded:["memory_decided","memory_quarantined"],action_failed:["action_satisfied","action_degraded"],memory_decided:["closed","closed_with_degradation","closed_with_retry_work"],memory_quarantined:["closed_with_degradation","closed_with_retry_work"],closed:[],closed_with_degradation:[],closed_with_retry_work:[]};function Fo(t){return Ka(t)}function Ka(t){let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Qa(e,t.artifact);if(Za(n.toState))return n;let o=e.getContextReceiptForRequest(t.artifact.projectRoot,t.artifact.sessionId,t.artifact.requestId),r=e.getMemoryTurn(t.artifact.turnId),i=t.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Ga(t.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=$(e,n,t,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Ya(t.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=$(e,n,t,"action_not_required","task_action_not_required"):n=$(e,n,t,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return $(e,n,t,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=$(e,n,t,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=$(e,n,t,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=$(e,n,t,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=$(e,n,t,"action_degraded","canonical_action_retry_degraded");else return n;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=$(e,n,t,t.memoryStatus==="pending"?"memory_quarantined":"memory_decided",t.memoryStatus==="pending"?t.reason:`canonical_memory_${t.memoryStatus}`)),n.toState==="memory_decided"?$(e,n,t,c?"closed_with_degradation":"closed",t.reason):n.toState==="memory_quarantined"?$(e,n,t,t.retryOwned?"closed_with_retry_work":"closed_with_degradation",t.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{e.close();}}function Ga(t,e){return t.intent==="memory"||t.intent==="knowledge"||(e.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ya(t,e){let n=e.canonicalAction,r=(n?(e.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return e.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":e.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||Xa(t)?"action_required":"action_not_required"}function Xa(t){return ["create","modify","debug","test","format"].includes(t.action)||["feature","refactor","performance"].includes(t.intent)}function Qa(t,e){let n=t.getLatestTerminalTransition(e.projectRoot,e.sessionId,e.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${e.turnId}`);return n}function $(t,e,n,o,r){if(!Ja[e.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${e.toState}->${o}`);let i=e.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=t.appendTerminalTransition({projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,executionId:n.artifact.executionId,sequence:i,fromState:e.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??e.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return h({event:"terminal.state.transitioned",identity:{projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,...n.artifact.executionId?{executionId:n.artifact.executionId}:{}},level:o==="closed"?"info":o.includes("degradation")||o.includes("retry")||o==="action_failed"?"warn":"info",timestamp:Date.now(),data:{fromState:e.toState,nextState:o,receiptId:s,reason:r}}),a}function Za(t){return t==="closed"||t==="closed_with_degradation"||t==="closed_with_retry_work"}var ec=new Set(["delivered","cancelled","rejected"]),tc=new Set(["Write","Edit","NotebookEdit","Bash"]);function qo(t,e){let n=join(t,".devflow","delivery-line","state.db");if(!existsSync(n)||!e.trim())return 0;let o;try{o=new DatabaseSync(n,{timeout:250});let r=o.prepare("SELECT id, payload FROM delivery_cases WHERE id = ? OR json_extract(payload, '$.sessionId') = ?").all(e,e),i=0,s=!!o.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'delivery_events'").get();for(let a of r){let c="incomplete";try{let d=JSON.parse(a.payload);c=d.evidence?.some(u=>u.metadata?.trust==="external-untrusted")?"untrusted":d.stage==="delivered"?"clean":"incomplete";}catch{}if(i+=Number(o.prepare("UPDATE delivery_tasks SET lease_owner = NULL, lease_expires_at = NULL WHERE case_id = ? AND lease_owner IS NOT NULL").run(a.id).changes),s){let d=`session.closed:${a.id}:${e}`;o.prepare("INSERT OR IGNORE INTO delivery_events (id,case_id,idempotency_key,actor,type,payload,created_at,processed_at) VALUES (?,?,?,?,?,?,?,NULL)").run(d,a.id,d,JSON.stringify({id:"devflow:session-end",kind:"system"}),"session.closed",JSON.stringify({sessionId:e,releasedLeases:i,outcome:c}),Date.now());}}return i}catch{return 0}finally{o?.close();}}function Wo(t,e,n,o){if(!tc.has(n)||!e.trim())return null;let r=join(t,".devflow","delivery-line","state.db");if(!existsSync(r))return null;let i;try{i=new DatabaseSync(r,{readOnly:!0,timeout:250});let s=i.prepare("SELECT id, payload FROM delivery_cases").all();for(let a of s){let c=JSON.parse(a.payload),d=typeof c.stage=="string"?c.stage:"unknown";if(!ec.has(d)){if(o&&d==="executing"){let u=i.prepare("SELECT id, lease_owner, fencing_token FROM delivery_tasks WHERE case_id = ? AND lease_expires_at > ? AND lease_owner IS NOT NULL AND fencing_token > 0 LIMIT 1").get(a.id,Date.now()),l=typeof c.sessionId=="string"?c.sessionId:void 0,m=typeof c.executionId=="string"?c.executionId:void 0,f=o===u?.id||o===u?.lease_owner||o===m,p=e===a.id||e===l;if(u?.id&&f&&p)return null}if(c.sessionId===e||e===a.id)return {code:"DELIVERY_AUTHORITY_REQUIRED",caseId:a.id,stage:d,message:`Delivery case ${a.id} is ${d}; use the Delivery task lease before modifying files.`}}}return null}catch{return {code:"DELIVERY_AUTHORITY_UNAVAILABLE",caseId:"unknown",stage:"unknown",message:"Delivery state cannot be read; file writes are blocked until runtime health is restored."}}finally{i?.close();}}function Ct(t){let e={committed:0,skipped:0,pending:0},n=[];for(let o of t)e[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function F(t){return (t instanceof Error?t.message:String(t)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(e,n){super(`session_finalize_${e}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${e}`;}};function ye(t){let e;try{e=openGlobalDevFlowDatabase();let n=(t.executionId?e.getSkillExecution(t.executionId):null)??e.getLatestSkillExecutionForSession(t.sessionId),o={stage:t.stage,reason:t.reason,degradedAt:Date.now()};n&&e.mergeSkillExecutionMetadata(n.executionId,{...t.metadata,sessionFinalizationDegradations:[o]}),e.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId,...o}}),h({event:"hook.session_end.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:t.stage,reason:t.reason}});}catch{}finally{e?.close();}}function Ue(t,e=Te(),n=true,o,r=true){let i;try{i=JSON.parse(t);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:t,sessionId:s,cleanupSharedState:n,executionId:o};try{qo(e,s);}catch{}let d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),l=d.getWorkByIdempotencyKey(a),m={status:u.state==="closed"||u.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:l?.state??"pending",closureState:u.state,pendingWorkCount:u.pendingWorkCount,...l?.id?{workItemId:l.id}:{}};return h({event:"hook.session_end.completed",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:m.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...m}}),m}catch(u){if(!r)throw u;return ho(e,{receiptId:a,...c}),h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:F(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function zo(t,e=Te(),n=true,o){let r;try{r=JSON.parse(t);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new H(e),a=s.get(i),c=$o({projectRoot:e,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(p=>p.contractId)??[],transcriptReconciliation:c},u=o?.telemetry??new Z,l=!o?.telemetry,m=false,f;try{try{await u.flushAndAggregate();}catch{}let p=Date.now(),g=o?.executionId??a?.executionId,S;try{let _=openGlobalDevFlowDatabase();try{S=_.listSessionMemoryTurnsForReconciliation(e,i);for(let y of S){let I=`memory:${y.turnId}`,v=_.getSessionObligation(e,i,I);v?v.state==="open"&&y.status!=="pending"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:I,state:"satisfied",receiptId:y.receiptId,reason:y.reason,resolvedAt:y.decidedAt}):_.upsertSessionObligation({obligationId:I,projectRoot:e,sessionId:i,turnId:y.turnId,kind:"memory_decision",state:y.status==="pending"?"open":"satisfied",payload:{eventId:y.eventId,promptHash:y.promptHash},receiptId:y.receiptId,reason:y.reason,createdAt:y.createdAt,updatedAt:y.decidedAt??y.createdAt,resolvedAt:y.decidedAt});}}finally{_.close();}}catch(_){let y=F(_),I={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"turn_load",reason:y,metadata:I}),new K("turn_load",y)}let b=Ct(S),k=o?.memory??(f=new MemoryGate(e)),w={status:"completed"};try{w=typeof k.reconcileTurnObservationLineage=="function"?{status:"completed",...await k.reconcileTurnObservationLineage(S)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let y=F(_);throw w={status:"degraded",reason:y},ye({projectRoot:e,sessionId:i,executionId:g,stage:"memory_lineage",reason:y,metadata:{...b,...d,memoryLineageReconciliation:w}}),new K("memory_lineage",y)}let T={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=We(r.transcript_path),y=openGlobalDevFlowDatabase(),I="unknown",v="no_terminal_host_action_evidence",de,L,q,Y=[],at=[];try{let z=y.listHostActionsForSession(e,i,g),kn=z.filter(M=>M.state==="verified"),ct=z.filter(M=>["failed","cancelled","degraded"].includes(M.state));ct.length>0?(I="negative",v=`terminal_host_action_${ct[0].state}`):kn.length>0&&(I="positive",v="host_action_verified");let xe=ct[0]??kn.at(-1);if(de=xe?.runId,L=xe?.contextReceipt,q=xe?.evidenceHash,at=z.flatMap(M=>{let X=M.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!xe&&g){let M=y.getSkillExecution(g),X=M?.metadata&&typeof M.metadata=="object"&&Array.isArray(M.metadata.policyVerificationOutcomes)?M.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),dt=X.filter(B=>B.status==="passed");le?(I="negative",v="policy_verification_failed",q=typeof le.receiptId=="string"?le.receiptId:void 0):dt.length>0&&(I="positive",v="policy_verification_passed",q=typeof dt.at(-1)?.receiptId=="string"?String(dt.at(-1).receiptId):void 0),L=y.getActiveContextReceipt(e,i,g)?.contextHash,at=X.map(B=>B.command).filter(B=>typeof B=="string");}L&&(Y=y.getSemanticExecutionContextByHash(L)?.dispositions.filter(M=>M.requirement==="required").map(M=>M.channel)??[]);}finally{y.close();}let wn=Oo({projectRoot:e,sessionId:i,executionId:g,outcome:I,outcomeReason:v,verificationReceipt:q,requiredChannels:Y,finishedAt:p}),gi=await k.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:I,outcomeReason:v,workflowRunId:de,contextReceipt:L,toolEvidence:at,verificationReceipt:q,consumedSourceIds:wn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});T={status:_?"evaluated":"unknown",...gi,retrievalLedger:wn};}catch(_){T={...T,status:"degraded",reason:F(_)};}let x;try{x=await k.reconcileDecidedTurnEventWindows(i,S,p);}catch(_){let y=F(_),I={...b,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"event_reconciliation",reason:y,metadata:I}),new K("event_reconciliation",y)}let O;try{O=await me({projectRoot:e,sessionId:i,trigger:"session_end",memory:k,details:{eventReconciliation:x},strictPersistence:!0});}catch(_){let y=F(_),I={...b,...d,memoryEventReconciliation:{status:"completed",...x,checkpointPending:null},memoryCheckpointDegradation:y};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"checkpoint",reason:y,metadata:I}),new K("checkpoint",y)}let N={memoryLineageReconciliation:w,memoryBenefitAttribution:T,memoryEventReconciliation:{status:"completed",...x,checkpointPending:O.pendingEvents},memoryDistillCheckpoint:O};try{let _=openGlobalDevFlowDatabase();try{let y=`session-finalize:${i}:events`,I=Math.max(Number(O.pendingEvents??0),Number(x.remainingUndecided??0)),v=_.getSessionObligation(e,i,y);I>0?_.upsertSessionObligation({obligationId:y,projectRoot:e,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:I,reconciliation:x,checkpointId:O.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:y,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:F(_)}});}try{await k.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let y=F(_),I={...b,...d,...N,memorySessionCloseDegradation:y};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"memory_close",reason:y,metadata:I}),new K("memory_close",y)}let R={...b,...d,...N},D=[];try{let _=openGlobalDevFlowDatabase();try{let y=new Map(_.listLatestTaskIntentArtifacts(e,i).map(I=>[I.turnId,I]));for(let I of S){let v=y.get(I.turnId);if(!v)continue;let L=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${I.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${I.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),q=Fo({artifact:v,memoryStatus:I.status,memoryReceiptId:I.receiptId,retryOwned:L,reason:I.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});D.push({turnId:I.turnId,state:q.toState,receiptId:q.receiptId});}}finally{_.close();}}catch(_){D.push({state:"terminal_integrity_failure",reason:F(_)});}R.terminalOutcomes=D,m=!0;let A;try{A=openGlobalDevFlowDatabase();let _=g;if(_)try{A.reconcileSkillExecution(_,"completed",p,R);let v=A.getSkillExecution(_);await V("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:p,status:"completed",summary:{totalToolCalls:v?.totalToolCalls??0,mcpToolCalls:v?.mcpToolCalls??0,directToolCalls:v?.directToolCalls??0,subagentCount:v?.subagentCount??0,totalDuration:v?.totalDuration??0,mcpComplianceRate:v?.mcpComplianceRate??0,missedTools:v?.missedMcpTools??[],actualFailureCount:v?.failedToolCalls??0,fallbackCount:v?.fallbackCount??0,fallbackReasons:v?.fallbackReasons??[]},metadata:R},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let y=A.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...R});for(let v of y)await V("/api/telemetry/skill-execution/complete",{executionId:v.executionId,finishedAt:v.finishedAt,status:v.status,summary:{totalToolCalls:v.totalToolCalls??0,mcpToolCalls:v.mcpToolCalls??0,directToolCalls:v.directToolCalls??0,subagentCount:v.subagentCount??0,totalDuration:v.totalDuration??0,mcpComplianceRate:v.mcpComplianceRate??0,missedTools:v.missedMcpTools??[],actualFailureCount:v.failedToolCalls??0,fallbackCount:v.fallbackCount??0,fallbackReasons:v.fallbackReasons??[]},metadata:R},{fallbackReason:"skill_execution_already_reconciled_locally"});let I=A.getLatestSkillExecutionForSession(i);if(I&&!y.some(v=>v.executionId===I.executionId)&&A.mergeSkillExecutionMetadata(I.executionId,R),n){A.deleteHookReceipt(e);let v=j(e),de=createHash("sha256").update(e).digest("hex").slice(0,12);for(let L of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,L),{force:!0});}A.deleteContextReceipt(e,i);}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:F(_),fallback:"fail_open"}});}finally{A?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:F(_),fallback:"local_state_authoritative"}});}}finally{if(f)try{f.close();}catch{}l&&u.close(),m&&s.removeSession(i),h({event:m?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:o?.executionId??a?.executionId},level:m?"info":"warn",timestamp:Date.now(),data:{stage:"finalize",criticalStagesCompleted:m,transcriptStatus:c.status}});}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let t=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n;}),process.stdin.on("end",async()=>{let n=Ue(e.trim()||process.argv[2]||"");n&&t(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var lc=/^\/(?:devflow:)?[\w-]+\b\s*/iu,uc=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu,mc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,pc=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function he(t){let e=t.trim().replace(lc,"").trim();return !e||uc.test(e)?null:(pc.exec(e)??mc.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function fc(t){return join(getProjectStateDir(t),"memory-intents.jsonl")}function gc(t){try{return readFileSync$1(t,"utf8").split(`
|
|
18
|
-
`).filter(Boolean).flatMap(e=>{try{let n=JSON.parse(e);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function Go(t){let e=
|
|
17
|
+
`).slice(0,4e3)}var Ja={open:["intent_bound"],intent_bound:["context_ready","context_degraded"],context_ready:["action_required","action_not_required"],context_degraded:["action_required","action_not_required"],action_required:["action_satisfied","action_degraded","action_failed"],action_not_required:["memory_decided","memory_quarantined"],action_satisfied:["memory_decided","memory_quarantined"],action_degraded:["memory_decided","memory_quarantined"],action_failed:["action_satisfied","action_degraded"],memory_decided:["closed","closed_with_degradation","closed_with_retry_work"],memory_quarantined:["closed_with_degradation","closed_with_retry_work"],closed:[],closed_with_degradation:[],closed_with_retry_work:[]};function Fo(t){return Ka(t)}function Ka(t){let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Qa(e,t.artifact);if(Za(n.toState))return n;let o=e.getContextReceiptForRequest(t.artifact.projectRoot,t.artifact.sessionId,t.artifact.requestId),r=e.getMemoryTurn(t.artifact.turnId),i=t.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Ga(t.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=$(e,n,t,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Ya(t.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=$(e,n,t,"action_not_required","task_action_not_required"):n=$(e,n,t,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return $(e,n,t,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=$(e,n,t,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=$(e,n,t,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=$(e,n,t,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=$(e,n,t,"action_degraded","canonical_action_retry_degraded");else return n;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(n.toState)&&(n=$(e,n,t,t.memoryStatus==="pending"?"memory_quarantined":"memory_decided",t.memoryStatus==="pending"?t.reason:`canonical_memory_${t.memoryStatus}`)),n.toState==="memory_decided"?$(e,n,t,c?"closed_with_degradation":"closed",t.reason):n.toState==="memory_quarantined"?$(e,n,t,t.retryOwned?"closed_with_retry_work":"closed_with_degradation",t.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{e.close();}}function Ga(t,e){return t.intent==="memory"||t.intent==="knowledge"||(e.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ya(t,e){let n=e.canonicalAction,r=(n?(e.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return e.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":e.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||Xa(t)?"action_required":"action_not_required"}function Xa(t){return ["create","modify","debug","test","format"].includes(t.action)||["feature","refactor","performance"].includes(t.intent)}function Qa(t,e){let n=t.getLatestTerminalTransition(e.projectRoot,e.sessionId,e.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${e.turnId}`);return n}function $(t,e,n,o,r){if(!Ja[e.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${e.toState}->${o}`);let i=e.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=t.appendTerminalTransition({projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,executionId:n.artifact.executionId,sequence:i,fromState:e.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??e.receiptId,reason:r,payload:{memoryStatus:n.memoryStatus,retryOwned:n.retryOwned??false,sourceIntentHash:n.artifact.artifactHash},createdAt:Date.now()});return h({event:"terminal.state.transitioned",identity:{projectRoot:n.artifact.projectRoot,projectId:n.artifact.projectId,hostId:n.artifact.hostId,sessionId:n.artifact.sessionId,turnId:n.artifact.turnId,requestId:n.artifact.requestId,...n.artifact.executionId?{executionId:n.artifact.executionId}:{}},level:o==="closed"?"info":o.includes("degradation")||o.includes("retry")||o==="action_failed"?"warn":"info",timestamp:Date.now(),data:{fromState:e.toState,nextState:o,receiptId:s,reason:r}}),a}function Za(t){return t==="closed"||t==="closed_with_degradation"||t==="closed_with_retry_work"}var ec=new Set(["delivered","cancelled","rejected"]),tc=new Set(["cancelled","rejected"]),nc=new Set(["Write","Edit","NotebookEdit","Bash"]);function qo(t,e){let n=join(t,".devflow","delivery-line","state.db");if(!existsSync(n)||!e.trim())return 0;let o;try{o=new DatabaseSync(n,{timeout:250});let r=o.prepare("SELECT id, payload FROM delivery_cases WHERE id = ? OR json_extract(payload, '$.sessionId') = ?").all(e,e),i=0,s=!!o.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'delivery_events'").get();for(let a of r){let c="incomplete";try{let d=JSON.parse(a.payload);c=d.evidence?.some(u=>u.metadata?.trust==="external-untrusted")?"untrusted":d.stage==="delivered"?"clean":"incomplete";}catch{}if(i+=Number(o.prepare("UPDATE delivery_tasks SET lease_owner = NULL, lease_expires_at = NULL WHERE case_id = ? AND lease_owner IS NOT NULL").run(a.id).changes),s){let d=`session.closed:${a.id}:${e}`;o.prepare("INSERT OR IGNORE INTO delivery_events (id,case_id,idempotency_key,actor,type,payload,created_at,processed_at) VALUES (?,?,?,?,?,?,?,NULL)").run(d,a.id,d,JSON.stringify({id:"devflow:session-end",kind:"system"}),"session.closed",JSON.stringify({sessionId:e,releasedLeases:i,outcome:c}),Date.now());}}return i}catch{return 0}finally{o?.close();}}function Wo(t,e,n,o){if(!nc.has(n)||!e.trim())return null;let r=join(t,".devflow","delivery-line","state.db");if(!existsSync(r))return null;let i;try{i=new DatabaseSync(r,{readOnly:!0,timeout:250});let s=i.prepare("SELECT id, payload, updated_at FROM delivery_cases").all(),a=[];for(let u of s){let l=JSON.parse(u.payload);(l.sessionId===e||e===u.id)&&a.push({id:u.id,payload:l,updatedAt:typeof u.updated_at=="number"?u.updated_at:typeof l.updatedAt=="number"?l.updatedAt:0});let m=typeof l.stage=="string"?l.stage:"unknown";if(!ec.has(m)){if(o&&m==="executing"){let f=i.prepare("SELECT id, lease_owner, fencing_token FROM delivery_tasks WHERE case_id = ? AND lease_expires_at > ? AND lease_owner IS NOT NULL AND fencing_token > 0 LIMIT 1").get(u.id,Date.now()),p=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.executionId=="string"?l.executionId:void 0,R=o===f?.id||o===f?.lease_owner||o===g,k=e===u.id||e===p;if(f?.id&&R&&k)return null}if(l.sessionId===e||e===u.id)return {code:"DELIVERY_AUTHORITY_REQUIRED",caseId:u.id,stage:m,message:`Delivery case ${u.id} is ${m}; use the Delivery task lease before modifying files.`}}}let c=a.sort((u,l)=>l.updatedAt-u.updatedAt)[0],d=typeof c?.payload.stage=="string"?c.payload.stage:void 0;return c&&d&&tc.has(d)?{code:"DELIVERY_AUTHORITY_REQUIRED",caseId:c.id,stage:d,message:`Delivery case ${c.id} is ${d}; start a new Delivery case or session before modifying files.`}:null}catch{return {code:"DELIVERY_AUTHORITY_UNAVAILABLE",caseId:"unknown",stage:"unknown",message:"Delivery state cannot be read; file writes are blocked until runtime health is restored."}}finally{i?.close();}}function Ct(t){let e={committed:0,skipped:0,pending:0},n=[];for(let o of t)e[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:e.pending,memoryTurnOutcomes:e}}function F(t){return (t instanceof Error?t.message:String(t)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(e,n){super(`session_finalize_${e}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${e}`;}};function ye(t){let e;try{e=openGlobalDevFlowDatabase();let n=(t.executionId?e.getSkillExecution(t.executionId):null)??e.getLatestSkillExecutionForSession(t.sessionId),o={stage:t.stage,reason:t.reason,degradedAt:Date.now()};n&&e.mergeSkillExecutionMetadata(n.executionId,{...t.metadata,sessionFinalizationDegradations:[o]}),e.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId,...o}}),h({event:"hook.session_end.degraded",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:t.stage,reason:t.reason}});}catch{}finally{e?.close();}}function Ue(t,e=Te(),n=true,o,r=true){let i;try{i=JSON.parse(t);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${e}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:t,sessionId:s,cleanupSharedState:n,executionId:o};try{qo(e,s);}catch{}let d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:e,sessionId:s,payload:c}),l=d.getWorkByIdempotencyKey(a),m={status:u.state==="closed"||u.state==="closed_with_pending_work"?"completed":"accepted",receiptId:a,workState:l?.state??"pending",closureState:u.state,pendingWorkCount:u.pendingWorkCount,...l?.id?{workItemId:l.id}:{}};return h({event:"hook.session_end.completed",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:m.status==="completed"?"info":"debug",timestamp:Date.now(),data:{stage:"enqueue",...m}}),m}catch(u){if(!r)throw u;return ho(e,{receiptId:a,...c}),h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:F(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function zo(t,e=Te(),n=true,o){let r;try{r=JSON.parse(t);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new H(e),a=s.get(i),c=$o({projectRoot:e,sessionId:i,transcriptPath:r.transcript_path}),d={evidenceDegradations:a?.evidenceDegradations??[],evidenceContractOutcomes:a?.evidenceOutcomes??[],pendingEvidenceContractIds:a?.evidenceObligations.map(p=>p.contractId)??[],transcriptReconciliation:c},u=o?.telemetry??new Z,l=!o?.telemetry,m=false,f;try{try{await u.flushAndAggregate();}catch{}let p=Date.now(),g=o?.executionId??a?.executionId,R;try{let _=openGlobalDevFlowDatabase();try{R=_.listSessionMemoryTurnsForReconciliation(e,i);for(let y of R){let I=`memory:${y.turnId}`,v=_.getSessionObligation(e,i,I);v?v.state==="open"&&y.status!=="pending"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:I,state:"satisfied",receiptId:y.receiptId,reason:y.reason,resolvedAt:y.decidedAt}):_.upsertSessionObligation({obligationId:I,projectRoot:e,sessionId:i,turnId:y.turnId,kind:"memory_decision",state:y.status==="pending"?"open":"satisfied",payload:{eventId:y.eventId,promptHash:y.promptHash},receiptId:y.receiptId,reason:y.reason,createdAt:y.createdAt,updatedAt:y.decidedAt??y.createdAt,resolvedAt:y.decidedAt});}}finally{_.close();}}catch(_){let y=F(_),I={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"turn_load",reason:y,metadata:I}),new K("turn_load",y)}let k=Ct(R),b=o?.memory??(f=new MemoryGate(e)),w={status:"completed"};try{w=typeof b.reconcileTurnObservationLineage=="function"?{status:"completed",...await b.reconcileTurnObservationLineage(R)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let y=F(_);throw w={status:"degraded",reason:y},ye({projectRoot:e,sessionId:i,executionId:g,stage:"memory_lineage",reason:y,metadata:{...k,...d,memoryLineageReconciliation:w}}),new K("memory_lineage",y)}let T={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=We(r.transcript_path),y=openGlobalDevFlowDatabase(),I="unknown",v="no_terminal_host_action_evidence",de,L,q,Y=[],at=[];try{let z=y.listHostActionsForSession(e,i,g),kn=z.filter(M=>M.state==="verified"),ct=z.filter(M=>["failed","cancelled","degraded"].includes(M.state));ct.length>0?(I="negative",v=`terminal_host_action_${ct[0].state}`):kn.length>0&&(I="positive",v="host_action_verified");let xe=ct[0]??kn.at(-1);if(de=xe?.runId,L=xe?.contextReceipt,q=xe?.evidenceHash,at=z.flatMap(M=>{let X=M.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!xe&&g){let M=y.getSkillExecution(g),X=M?.metadata&&typeof M.metadata=="object"&&Array.isArray(M.metadata.policyVerificationOutcomes)?M.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),dt=X.filter(B=>B.status==="passed");le?(I="negative",v="policy_verification_failed",q=typeof le.receiptId=="string"?le.receiptId:void 0):dt.length>0&&(I="positive",v="policy_verification_passed",q=typeof dt.at(-1)?.receiptId=="string"?String(dt.at(-1).receiptId):void 0),L=y.getActiveContextReceipt(e,i,g)?.contextHash,at=X.map(B=>B.command).filter(B=>typeof B=="string");}L&&(Y=y.getSemanticExecutionContextByHash(L)?.dispositions.filter(M=>M.requirement==="required").map(M=>M.channel)??[]);}finally{y.close();}let wn=Oo({projectRoot:e,sessionId:i,executionId:g,outcome:I,outcomeReason:v,verificationReceipt:q,requiredChannels:Y,finishedAt:p}),gi=await b.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:I,outcomeReason:v,workflowRunId:de,contextReceipt:L,toolEvidence:at,verificationReceipt:q,consumedSourceIds:wn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});T={status:_?"evaluated":"unknown",...gi,retrievalLedger:wn};}catch(_){T={...T,status:"degraded",reason:F(_)};}let x;try{x=await b.reconcileDecidedTurnEventWindows(i,R,p);}catch(_){let y=F(_),I={...k,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"event_reconciliation",reason:y,metadata:I}),new K("event_reconciliation",y)}let O;try{O=await me({projectRoot:e,sessionId:i,trigger:"session_end",memory:b,details:{eventReconciliation:x},strictPersistence:!0});}catch(_){let y=F(_),I={...k,...d,memoryEventReconciliation:{status:"completed",...x,checkpointPending:null},memoryCheckpointDegradation:y};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"checkpoint",reason:y,metadata:I}),new K("checkpoint",y)}let N={memoryLineageReconciliation:w,memoryBenefitAttribution:T,memoryEventReconciliation:{status:"completed",...x,checkpointPending:O.pendingEvents},memoryDistillCheckpoint:O};try{let _=openGlobalDevFlowDatabase();try{let y=`session-finalize:${i}:events`,I=Math.max(Number(O.pendingEvents??0),Number(x.remainingUndecided??0)),v=_.getSessionObligation(e,i,y);I>0?_.upsertSessionObligation({obligationId:y,projectRoot:e,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:I,reconciliation:x,checkpointId:O.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:e,sessionId:i,obligationId:y,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:F(_)}});}try{await b.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let y=F(_),I={...k,...d,...N,memorySessionCloseDegradation:y};throw ye({projectRoot:e,sessionId:i,executionId:g,stage:"memory_close",reason:y,metadata:I}),new K("memory_close",y)}let S={...k,...d,...N},D=[];try{let _=openGlobalDevFlowDatabase();try{let y=new Map(_.listLatestTaskIntentArtifacts(e,i).map(I=>[I.turnId,I]));for(let I of R){let v=y.get(I.turnId);if(!v)continue;let L=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${I.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${I.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),q=Fo({artifact:v,memoryStatus:I.status,memoryReceiptId:I.receiptId,retryOwned:L,reason:I.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});D.push({turnId:I.turnId,state:q.toState,receiptId:q.receiptId});}}finally{_.close();}}catch(_){D.push({state:"terminal_integrity_failure",reason:F(_)});}S.terminalOutcomes=D,m=!0;let A;try{A=openGlobalDevFlowDatabase();let _=g;if(_)try{A.reconcileSkillExecution(_,"completed",p,S);let v=A.getSkillExecution(_);await V("/api/telemetry/skill-execution/complete",{executionId:_,finishedAt:p,status:"completed",summary:{totalToolCalls:v?.totalToolCalls??0,mcpToolCalls:v?.mcpToolCalls??0,directToolCalls:v?.directToolCalls??0,subagentCount:v?.subagentCount??0,totalDuration:v?.totalDuration??0,mcpComplianceRate:v?.mcpComplianceRate??0,missedTools:v?.missedMcpTools??[],actualFailureCount:v?.failedToolCalls??0,fallbackCount:v?.fallbackCount??0,fallbackReasons:v?.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});}catch{}let y=A.reconcileRunningSkillExecutionsForSession(i,p,{closureReason:"session_finalize",...S});for(let v of y)await V("/api/telemetry/skill-execution/complete",{executionId:v.executionId,finishedAt:v.finishedAt,status:v.status,summary:{totalToolCalls:v.totalToolCalls??0,mcpToolCalls:v.mcpToolCalls??0,directToolCalls:v.directToolCalls??0,subagentCount:v.subagentCount??0,totalDuration:v.totalDuration??0,mcpComplianceRate:v.mcpComplianceRate??0,missedTools:v.missedMcpTools??[],actualFailureCount:v.failedToolCalls??0,fallbackCount:v.fallbackCount??0,fallbackReasons:v.fallbackReasons??[]},metadata:S},{fallbackReason:"skill_execution_already_reconciled_locally"});let I=A.getLatestSkillExecutionForSession(i);if(I&&!y.some(v=>v.executionId===I.executionId)&&A.mergeSkillExecutionMetadata(I.executionId,S),n){A.deleteHookReceipt(e);let v=j(e),de=createHash("sha256").update(e).digest("hex").slice(0,12);for(let L of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,L),{force:!0});}A.deleteContextReceipt(e,i);}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:F(_),fallback:"fail_open"}});}finally{A?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:F(_),fallback:"local_state_authoritative"}});}}finally{if(f)try{f.close();}catch{}l&&u.close(),m&&s.removeSession(i),h({event:m?"hook.session_end.completed":"hook.session_end.degraded",identity:{projectRoot:e,sessionId:i,executionId:o?.executionId??a?.executionId},level:m?"info":"warn",timestamp:Date.now(),data:{stage:"finalize",criticalStagesCompleted:m,transcriptStatus:c.status}});}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let t=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n;}),process.stdin.on("end",async()=>{let n=Ue(e.trim()||process.argv[2]||"");n&&t(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var uc=/^\/(?:devflow:)?[\w-]+\b\s*/iu,mc=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu,pc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,fc=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function he(t){let e=t.trim().replace(uc,"").trim();return !e||mc.test(e)?null:(fc.exec(e)??pc.exec(e))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function gc(t){return join(getProjectStateDir(t),"memory-intents.jsonl")}function yc(t){try{return readFileSync$1(t,"utf8").split(`
|
|
18
|
+
`).filter(Boolean).flatMap(e=>{try{let n=JSON.parse(e);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function Go(t){let e=gc(t),n=`${e}.claim-`,o=`${basename(e)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(e)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(e),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(e,i);}catch{return null}let s=yc(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Mt(t){if(t.intents.shift(),t.intents.length===0){try{unlinkSync$1(t.path);}catch{}return}let e=`${t.path}.tmp-${process.pid}`;writeFileSync$1(e,t.intents.map(n=>JSON.stringify(n)).join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`,{mode:384}),renameSync(e,t.path);}function ze(t){let e=t.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let n=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Yo(t){let e=t.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let n=ze(e[1]);return n?{rawName:e[1],skillName:n}:null}function ve(t,e){return e?`evt_tool_${createHash$1("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var Ie=1,Lt="memory-snapshot-v1.json",cr=512*1024,dr=256*1024,lr=2e3,
|
|
20
|
+
`,{mode:384}),renameSync(e,t.path);}function ze(t){let e=t.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let n=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Yo(t){let e=t.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let n=ze(e[1]);return n?{rawName:e[1],skillName:n}:null}function ve(t,e){return e?`evt_tool_${createHash$1("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var Ie=1,Lt="memory-snapshot-v1.json",cr=512*1024,dr=256*1024,lr=2e3,Rc=500,Sc=10,xc=240,Ec=300*1e3,Ac=720*60*60*1e3,ur=2147483647,Tc=100,er=250,Dc=3e4,Cc=10,Be=new Map;function mr(t){return t.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:t.ownerUid===t.currentUid,modeSafe:(t.mode&18)===0}}function G(t){return resolve(t)}function re(t){return createHash("sha256").update(G(t)).digest("hex").slice(0,16)}function Nt(t,e={}){let n=re(t),o=e.stateRoot?join(e.stateRoot,n):getProjectStateDir(G(t));return join(o,Lt)}function Je(t,e){let o=(t instanceof Error?t.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${e}:${o}`:e}function qt(t,e){return Array.isArray(t)&&t.length<=e&&t.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function Mc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.id=="string"&&e.id.length>0&&e.id.length<=512&&typeof e.kind=="string"&&e.kind.length>0&&e.kind.length<=128&&(e.family===void 0||typeof e.family=="string"&&e.family.length>0&&e.family.length<=256)&&(e.entity===void 0||typeof e.entity=="string"&&e.entity.length>0&&e.entity.length<=256)&&qt(e.memoryIds,100)&&(e.status==="withheld"||e.status==="resolved")&&(e.summary===void 0||typeof e.summary=="string"&&e.summary.length<=2e3)}function Oc(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.reason=="string"&&e.reason.length>0&&e.reason.length<=512&&(e.stale===void 0||typeof e.stale=="boolean")}function Wt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return null;let o=t,r=G(e),i=re(r),s=o.generation===void 0?0:o.generation;return o.version!==Ie||o.projectRoot!==r||o.projectHash!==i||typeof o.markdown!="string"||Buffer.byteLength(o.markdown,"utf8")>dr||!qt(o.memoryIds,lr)||!Array.isArray(o.conflicts)||o.conflicts.length>Rc||!o.conflicts.every(Mc)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+Ec||!Number.isInteger(s)||s<0||s>ur||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!Oc(o.degradation)?null:{...o,generation:s}}function Ut(t,e,n,o,r=0){let i=G(t);return {version:Ie,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:e,degradation:{reason:n}}}function ne(t,e={}){let n=e.now??Date.now(),o=Nt(t,e),r;try{r=openSync$1(o,constants.O_RDONLY|constants.O_NOFOLLOW);let i=fstatSync$1(r);if(!i.isFile()||i.size<=0||i.size>cr)throw new Error("cache_size_invalid");let s=mr({...typeof process.getuid=="function"?{currentUid:process.getuid()}:{},ownerUid:i.uid,mode:i.mode});if(!s.ownerSafe)throw new Error("cache_owner_invalid");if(!s.modeSafe)throw new Error("cache_permissions_unsafe");let a=JSON.parse(readFileSync$1(r,"utf8")),c=Wt(a,t,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>Ac?{snapshot:{...c,status:"degraded",degradation:{reason:"cache_stale",stale:!0}},source:"cache",valid:!0,stale:!0}:{snapshot:c,source:"cache",valid:!0,stale:!1}}catch(i){let a=i.code==="ENOENT";return {snapshot:Ut(t,a?"pending":"degraded",a?"cache_missing":Je(i,"cache_invalid"),n),source:"none",valid:false,stale:false}}finally{if(r!==void 0)try{closeSync$1(r);}catch{}}}function tr(t){if(!Number.isInteger(t)||t<0||t>=ur)throw new Error("memory_snapshot_generation_exhausted");return t+1}function Pc(t){let e=dirname$1(t);mkdirSync$1(e,{recursive:true,mode:448}),chmodSync(e,448);}function jc(t){Pc(t);let e=`${t}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(e,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:e,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(e);}catch{}}if(i.code==="EEXIST")return null;throw i}}function $c(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return Number.isInteger(e.pid)&&Number(e.pid)>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function Fc(t){try{return process.kill(t,0),!1}catch(e){return e.code==="ESRCH"}}function Hc(t){return !t.canonicalCachePath||!t.directoryIsSafe||!t.lockIsRegularFile||!t.metadataValid||!t.contentsUnchanged||!t.ownerDead&&!t.stale?false:t.currentUid!==void 0?t.directoryUid===t.currentUid&&t.lockUid===t.currentUid:true}function Lc(t){return isAbsolute(t)&&resolve(t)===t&&basename(t)===Lt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(t)))}function Nc(t,e){let n=`${t}.lock`;try{let o=lstatSync$1(dirname$1(t)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let f=JSON.parse(i);$c(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>e,d=s?Fc(s.pid):!1,u=readFileSync$1(n,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=mr({...l!==void 0?{currentUid:l}:{},ownerUid:o.uid,mode:o.mode});return Hc({canonicalCachePath:Lc(t),directoryIsSafe:o.isDirectory()&&!o.isSymbolicLink()&&m.modeSafe,lockIsRegularFile:r.isFile()&&!r.isSymbolicLink(),metadataValid:s!==null,ownerDead:d,stale:c,contentsUnchanged:u,...l!==void 0?{currentUid:l}:{},directoryUid:o.uid,lockUid:r.uid})?(unlinkSync$1(n),!0):!1}catch{return false}}function qc(t){try{closeSync$1(t.fd);}catch{}try{readFileSync$1(t.path,"utf8")===t.contents&&unlinkSync$1(t.path);}catch{}}function Wc(t){return new Promise(e=>setTimeout(e,t))}function Ot(t,e,n,o){let r=Number.isFinite(t)?Math.floor(t):e;return Math.min(o,Math.max(n,r))}async function Uc(t,e){let n=Ot(e.lockTimeoutMs,Tc,0,er),o=Ot(e.lockRetryMs,Cc,1,er),r=Ot(e.lockStaleMs,Dc,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=jc(t);if(s)return s;if(Nc(t,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await Wc(Math.min(o,a));}}async function nr(t,e,n){let o=await Uc(t,e);try{return await n()}finally{qc(o);}}function or(t,e,n,o){let r=o.now??Date.now(),i=G(t),s={version:Ie,projectRoot:i,projectHash:re(i),markdown:e.markdown,memoryIds:e.memoryIds??[],conflicts:e.conflicts??[],generatedAt:r,generation:n,status:e.status??"ready",...e.degradation?{degradation:e.degradation}:{}};if(!Wt(s,t,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>cr)throw new Error("memory_snapshot_cache_too_large");let c=Nt(t,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${Lt}.${process.pid}.${randomUUID$1()}.tmp`),l;try{l=openSync$1(u,"wx",384),writeFileSync$1(l,a),fsyncSync(l),closeSync$1(l),l=void 0,chmodSync(u,384),renameSync(u,c),chmodSync(c,384);let m;try{m=openSync$1(d,"r");try{fsyncSync(m);}catch{}}finally{m!==void 0&&closeSync$1(m);}return s}finally{if(l!==void 0)try{closeSync$1(l);}catch{}rmSync$1(u,{force:true});}}function zc(t,e){let o=(Be.get(t)??Promise.resolve()).catch(()=>{}).then(e),r=o.then(()=>{},()=>{});return Be.set(t,r),o.finally(()=>{Be.get(t)===r&&Be.delete(t);})}function Pt(t,e,n,o,r){return t.valid?t.snapshot.generation>r?{...t,persisted:false}:{...t,snapshot:{...t.snapshot,status:"degraded",degradation:{reason:n,stale:t.stale||void 0}},persisted:false}:{snapshot:Ut(e,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function zt(t){let e=Nt(t.projectRoot,t.cacheOptions);return zc(e,async()=>{let n=ne(t.projectRoot,t.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await t.load();}catch(i){let s=Je(i,`refresh_failed:${t.reason}`);try{return await nr(e,t.cacheOptions??{},()=>{let a=ne(t.projectRoot,t.cacheOptions);if(a.valid)return Pt(a,t.projectRoot,s,t.cacheOptions?.now??Date.now(),o);let c=tr(o),d=Ut(t.projectRoot,"degraded",s,t.cacheOptions?.now??Date.now(),c);return {snapshot:or(t.projectRoot,d,c,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=ne(t.projectRoot,t.cacheOptions);return Pt(c,t.projectRoot,Je(a,s),t.cacheOptions?.now??Date.now(),o)}}try{return await nr(e,t.cacheOptions??{},()=>{let i=ne(t.projectRoot,t.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=tr(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:or(t.projectRoot,r,s,t.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=ne(t.projectRoot,t.cacheOptions);return Pt(s,t.projectRoot,Je(i,`refresh_commit_failed:${t.reason}`),t.cacheOptions?.now??Date.now(),o)}})}async function Ye(t){return zt({projectRoot:t.projectRoot,reason:t.reason,cacheOptions:t.cacheOptions,load:async()=>{if(t.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let e=typeof t.injectConfig=="object"?t.injectConfig:{},n=Number.isFinite(e.topN)?Math.max(0,Math.floor(e.topN)):4,o=Number.isFinite(e.budgetTokens)?Math.max(1,Math.floor(e.budgetTokens)):400,r=await t.memory.getAll({purpose:"session_bootstrap",budgetTokens:o,limit:n}),s=Number.isInteger(r.truncatedCount)&&r.truncatedCount>=0?r.truncatedCount:null,a=r.memories.length===0&&s!==0,c=s!==null&&s>0?"snapshot_results_truncated":"snapshot_truncation_unknown",d=(r.conflicts??[]).map(l=>({id:l.id,kind:l.kind,family:l.family,entity:l.entity,memoryIds:l.memoryIds,status:l.status,...l.summary?{summary:l.summary}:{}})),u=a?`## Project memory
|
|
21
21
|
DevFlow memory snapshot=degraded; reason=${c}. Memory result completeness is not authoritative; do not conclude that the project has no memories.`:r.memories.length===0&&d.length>0?`## Project memory
|
|
22
22
|
${d.length} explicit preference conflict(s) are withheld from automatic guidance; an explicit choice is required.`:r.memories.length===0?`## Project memory
|
|
23
23
|
\u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`:`## Project memory (auto-injected, ${r.memories.length} items, ${r.tokenCount} tokens)
|
|
24
24
|
${r.memories.map(l=>`- **${l.title||l.type}**: ${l.content} (confidence ${l.confidence.toFixed(2)}, ${l.source})`).join(`
|
|
25
|
-
`)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:r.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function
|
|
25
|
+
`)}`;return {status:a?"degraded":"ready",markdown:u,memoryIds:r.memories.map(l=>l.id),conflicts:d,...a?{degradation:{reason:c}}:{}}}})}function Bc(t){if(!t)return true;try{return JSON.parse(readFileSync$1(t,"utf8")).sessionStart?.injectMemories??!0}catch{return true}}function Vc(t,e,n){if(!e.trim())return null;try{let o=JSON.parse(e);if(o.status!=="ok"&&o.status!=="degraded")return null;if(o.enabled===!1){let i=G(t);return {version:Ie,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"disabled"}}let r=Wt(o.snapshot,t,n);if(r)return r;if(o.status==="ok"&&typeof o.markdown=="string"&&o.markdown.length>0&&Buffer.byteLength(o.markdown,"utf8")<=dr){let i=G(t);return {version:Ie,projectRoot:i,projectHash:re(i),markdown:o.markdown,memoryIds:qt(o.memoryIds,lr)?o.memoryIds:[],conflicts:[],generatedAt:n,generation:0,status:"ready"}}}catch{}return null}function jt(t,e){return [...(t??e).replace(/[\r\n\t|]+/gu," ").trim()||e].slice(0,xc).join("")}function Jc(t){if(t.length===0)return "";let e=t.slice(0,Sc),n=e.map(o=>{let r=jt(o.family,"unknown"),i=jt(o.entity,"unknown"),s=jt(o.summary,"Explicit choice required.");return `- family=${r}; entity=${i}; status=${o.status}; summary=${s}`});return t.length>e.length&&n.push(`- ${t.length-e.length} additional conflict(s) omitted from SessionStart output.`),`## Withheld preference conflicts (${t.length})
|
|
26
26
|
${n.join(`
|
|
27
|
-
`)}`}function
|
|
28
|
-
DevFlow memory snapshot=pending; source=${o.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(r.generatedAt).toISOString(),s=r.degradation?.reason?`; reason=${r.degradation.reason}`:"",a=`DevFlow memory snapshot=${r.status}; source=${o.source}; generatedAt=${i}${s}.`,c=
|
|
27
|
+
`)}`}function Kc(t){let e=t.now??Date.now();if(Bc(t.configPath)===false)return "";let n=Vc(t.projectRoot,t.daemonResponse??"",e),o=n?{snapshot:n,source:"daemon"}:ne(t.projectRoot,{...t.cacheOptions,now:e}),{snapshot:r}=o;if(r.status==="disabled")return `## Project memory
|
|
28
|
+
DevFlow memory snapshot=pending; source=${o.source}; reason=previous_snapshot_disabled. Memory availability is not yet known; do not conclude that the project has no memories.`;let i=new Date(r.generatedAt).toISOString(),s=r.degradation?.reason?`; reason=${r.degradation.reason}`:"",a=`DevFlow memory snapshot=${r.status}; source=${o.source}; generatedAt=${i}${s}.`,c=Jc(r.conflicts);return r.markdown?[r.markdown,c,a].filter(Boolean).join(`
|
|
29
29
|
`):["## Project memory",c,`${a} Memory availability is not yet known; do not conclude that the project has no memories.`].filter(Boolean).join(`
|
|
30
|
-
`)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,t,e,n]=process.argv;t!=="session-start"||!e?process.exitCode=2:process.stdout.write(Jc({projectRoot:e,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Gc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,Yc=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Xc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu,Qc=/(?:召回|查询|检索|查找|定位|询问|什么|如何|是否|哪里|哪个)|\b(?:recall|query|search|find|locate|ask|what|how|whether|where|which)\b/iu;function Zc(t){let e=t.trim();return e.length>0&&!Gc.test(e)}function ed(t){let e=t.normalize("NFKC").trim(),n=Qc.test(e);return e.length>=4&&(Xc.test(e)||n)&&(!Yc.test(e)||n)&&he(e)===null}function td(t,e,n=Date.now()){let o=createHash("sha256").update(e.trim()).digest("hex"),r=createHash("sha256").update(`${t}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function be(t,e,n=[]){return `memory-receipt:${createHash("sha256").update(`${t}\0${e}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Xe(t){return `DevFlow memory decision required for ${t.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. For candidates, copy exact evidenceSpans from this user prompt, preserve package names, flags, versions, paths, and identifiers, and provide subject, predicate, value, polarity, and entities when known. To replace or retire an existing fact, provide operation=supersede or operation=retire plus referencedFactIds from the canonical memory receipt; aliases and entity names are not fact identity. Do not save assistant echoes, task narration, retries, or unverified guesses. Express a change from an old choice as the new durable value. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function we(t){let e=t.memoryIds.length>0?t.memoryIds.join(","):"none",n=t.status==="committed"?"accepted":t.status,o=t.status==="committed"?"; indexStatus=pending":"",r=t.memoryIds.some(a=>a.startsWith("raw-memory:")),i=t.status==="committed"&&t.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":t.status==="committed"&&t.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=t.status==="committed"&&t.source==="explicit_intent"?` The deterministic explicit-memory save is complete and remains authoritative if refinement fails. Before the final response, call mcp__devflow__memory_commit_turn once with turnId=${t.turnId} and semantic candidates. Split every distinct reusable fact into a durable_memory candidate, classify instructions that apply only to this turn as turn_constraint, and include evidenceSpans copied verbatim from the user prompt for every candidate. Preserve exact flags, package names, versions, paths, and identifiers. Keep narrative and value in the user prompt language; do not translate evidence into a different surface form. The tool refines the existing receipt idempotently; it must not create native Claude memory. If refinement is unavailable, return the existing canonical receipt without claiming refinement.`:"";return `DevFlow canonical memory receipt: status=${n}; receiptId=${t.receiptId??"missing"}; turnId=${t.turnId}; memoryIds=${e}; source=${t.source??"unknown"}${o}${i}.`+s}function Bt(t){if(!Zc(t.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=t.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=e.listMemoryTurns(t.projectRoot,t.sessionId,5).find(l=>l.promptHash===o&&Date.now()-l.createdAt<1e4),i=r?{turnId:r.turnId,eventId:r.eventId,promptHash:r.promptHash,createdAt:r.createdAt}:t.identity??td(t.sessionId,n),s=r??e.beginMemoryTurn({...i,projectRoot:t.projectRoot,sessionId:t.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:we(s),skipSkillRouting:s.source==="explicit_intent"};let c=(t.activation?.semantic??"degraded_structural")==="degraded_structural"?he(n)??void 0:void 0;if(!c&&ed(n)){let l=be(s.turnId,"skipped"),m=e.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),h({event:"memory.semantic.decided",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId},level:"info",timestamp:Date.now(),data:{status:"semantic_empty",operation:"none",reason:"high_confidence_transient_task"}}),{turn:m,additionalContext:we(m),skipSkillRouting:!1}}let d=c?"commit_explicit":"capture_prompt",u=e.enqueueWork({idempotencyKey:`memory-turn:${d}:${s.turnId}`,kind:c?"memory.explicit_commit":"memory.turn_capture",projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,payload:{operation:d,turnId:s.turnId,eventId:s.eventId,sessionId:t.sessionId,prompt:n,explicitContent:c,createdAt:s.createdAt}});if(c){let l=`raw-memory:${createHash("sha256").update(`${t.projectRoot}\0${i.turnId}\0${c}`).digest("hex").slice(0,24)}`,m=be(s.turnId,"committed",[l]),f=e.commitMemoryTurn({turnId:s.turnId,receiptId:m,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:m,reasonCode:"explicit_raw_queued"},dedupeKey:m,producer:"devflow-memory-turn"}),h({event:"memory.write.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,actionReceipt:m},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:l,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:f,explicitContent:c,additionalContext:we(f),skipSkillRouting:!0}}return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),{turn:s,explicitContent:c,additionalContext:Xe(s),skipSkillRouting:!1}}finally{e.close();}}async function Vt(t){let{payload:e,memory:n,projectRoot:o}=t,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);let s=e.operation==="commit_explicit"&&i.status==="committed"&&i.source==="explicit_intent"&&i.memoryIds.some(l=>l.startsWith("raw-memory:"));if(i.status!=="pending"&&!s){if(i.receiptId&&typeof n.reconcileTurnObservationLineage=="function")try{await n.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:we(i),skipSkillRouting:i.source==="explicit_intent"}}if(await n.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await n.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Xe(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(e.explicitContent,{actorId:"actor:claude-code",sessionId:e.sessionId},e.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];h({event:"memory.semantic.decided",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId},level:a.semanticDecision?.status==="semantic_ready"?"info":"warn",timestamp:Date.now(),data:{status:a.semanticDecision?.status??"semantic_unavailable",operations:a.semanticDecision?.operations??["add"],memoryIds:c,rejectedCount:a.semanticDecision?.rejectedCount??0,durable:a.durable,lexicallyReady:a.lexicallyReady,policyReady:a.policyReady,vectorStatus:a.vectorStatus}});let d=i.receiptId??be(i.turnId,"committed",c),u=s?r.updateCommittedMemoryTurnProjection({turnId:i.turnId,memoryIds:c,reason:"explicit_async_ready"}):r.commitMemoryTurn({turnId:i.turnId,receiptId:d,memoryIds:c,source:"explicit_intent",reason:"explicit_user_request"});C({projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,kind:"memory.committed",payload:{receiptId:d,reasonCode:"explicit_async_ready"},dedupeKey:`${d}:async_ready`,producer:"devflow-memory-worker"}),h({event:"memory.write.completed",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,actionReceipt:d},level:"info",timestamp:Date.now(),data:{stage:"explicit_async_ready",durable:!0,memoryIds:c,receiptLatencyMs:Math.max(0,(i.decidedAt??Date.now())-i.createdAt),asyncReadinessMs:Math.max(0,Date.now()-i.createdAt),vectorStatus:a.vectorStatus}});try{typeof n.finalizeTurnDecision=="function"&&await n.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:d,status:"committed",memoryIds:c,reason:"explicit_user_request"});}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"lineage_finalize",reason:l.message,fallback:"session_end_reconciliation"}});}try{await n.enrichExplicitMemoryObservation(a.id);}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"explicit_enrichment",memoryId:a.id,reason:l.message,fallback:"durable_work_queue"}}),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${a.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});try{await Ye({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:l.message,fallback:"durable_memory_authoritative"}});}return {turn:u,explicitContent:e.explicitContent,additionalContext:we(u),skipSkillRouting:!0}}finally{r.close();}}var rd=new Set(["Write","Edit","NotebookEdit"]),fr="Claude native memory writes are disabled for this project. Use DevFlow explicit memory or mcp__devflow__memory_commit_turn so a canonical receipt is created.";function _r(t){if(!rd.has(t.toolName))return null;let e=id(t.toolInput);if(!e)return null;let n=sd(e,t.projectRoot),o=resolve(t.projectRoot,".claude");if(gr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return fr;let r=resolve(t.home??homedir(),".claude","projects");return gr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?fr:null}function id(t){for(let e of ["file_path","notebook_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}return null}function sd(t,e){return resolve(isAbsolute(t)?t:resolve(e,t))}function gr(t,e){let n=relative(e,t);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var md=1024*1024;function kr(t){let e=join(getProjectStateDir(t),"session-start-pending");mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=readFileSync$1(i,"utf8");if(Buffer.byteLength(s,"utf8")>md)throw unlinkSync$1(i),new Error("session_start_spool_input_too_large");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),input:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function br(t){unlinkSync$1(t.path);}function Rr(t){let e=t.path.replace(/\.claim-\d+$/u,"");try{renameSync(t.path,e);}catch{}}function xr(t,e){let n=Dr(t);mkdirSync$1(n,{recursive:true,mode:448});let o=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID$1()}`,r=join(n,`${o}.json`),i=`${r}.tmp`;return writeFileSync$1(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function Er(t){let e=Dr(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.sessionId!="string"||typeof s.prompt!="string"||typeof s.createdAt!="number")throw unlinkSync$1(i),new Error("memory_turn_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Ar(t){unlinkSync$1(t.path);}function Tr(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function Dr(t){return join(j(t),"memory-turn-pending")}var E=class extends Error{constructor(e,n){super(n),this.name="PermanentWorkError",this.category=e;}},Id=1e3,wd=3e4,kd=1,bd=5*6e4,Ze=class{constructor(e){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=e.projectRoot,this.handlers=e.handlers,this.pollIntervalMs=Xt(e.pollIntervalMs,Id),this.leaseMs=Xt(e.leaseMs,wd),this.batchSize=Xt(e.batchSize,kd),this.owner=e.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=e.now??Date.now,this.random=e.random??Math.random,this.openDatabase=e.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=e.afterComplete;}start(){this.stopped&&(this.stopped=false,this.schedule(0));}stop(){this.stopped=true,this.timer&&clearTimeout(this.timer),this.timer=null;}drainOnce(){return this.draining?this.draining:(this.draining=this.performDrain().finally(()=>{this.draining=null;}),this.draining)}async drainWorkItemOnce(e){return e.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([e])).finally(()=>{this.draining=null;}),this.draining):0}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.drainOnce().catch(n=>this.logDegradation("drain",n)).finally(()=>this.schedule(this.pollIntervalMs));},e),this.timer.unref());}async performDrain(e,n){let o=Object.keys(this.handlers).filter(i=>!e||e.has(i));if(o.length===0)return 0;let r=this.openDatabase();try{let i=this.now();r.recoverExpiredWork(this.projectRoot,i);let s=r.leaseWork({projectRoot:this.projectRoot,owner:this.owner,kinds:o,workItemIds:n?[...n]:void 0,limit:this.batchSize,leaseMs:this.leaseMs,now:i});for(let a of s)await this.processItem(r,a);return s.length}finally{r.close();}}async processItem(e,n){let o=this.handlers[n.kind];if(!o){e.deadLetterWork(n.id,this.owner,{category:"unsupported_work_kind",message:`No work handler is registered for ${n.kind}`}),this.logWorkTransition("dead_letter",n,{errorCategory:"unsupported_work_kind"},"error");return}let r=setInterval(()=>{e.heartbeatWork(n.id,this.owner,this.leaseMs,this.now())||this.logDegradation("lease_heartbeat",new Error("work_lease_heartbeat_rejected"),n);},Math.max(1e3,Math.floor(this.leaseMs/3)));r.unref();try{if(await o({item:n}),!e.completeWork(n.id,this.owner,this.now()))throw new Error(`Work lease was lost before completion: ${n.id}`);this.logWorkTransition("completed",n,{attempt:n.attempts});try{await this.afterComplete?.({item:n,database:e});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=Rd(i);if(i instanceof E||s.permanent){e.deadLetterWork(n.id,this.owner,s),this.logWorkTransition("dead_letter",n,{attempt:n.attempts,errorCategory:s.category},"error");return}let a=this.now()+Math.max(Sd(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){e.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}e.retryWork(n.id,this.owner,s,a),this.logWorkTransition("retry_wait",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");}finally{clearInterval(r);}}logDegradation(e,n,o){h({event:"hook.runtime.degraded",identity:{projectRoot:this.projectRoot,sessionId:o?.sessionId,turnId:o?.turnId,executionId:o?.executionId},level:"warn",timestamp:this.now(),data:{stage:`work_${e}`,workId:o?.id,workKind:o?.kind,reason:Cr(n)}});}logWorkTransition(e,n,o,r="info"){try{h({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:e,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Xt(t,e){return Number.isSafeInteger(t)&&t>0?t:e}function Rd(t){if(t instanceof E)return {category:t.category,message:t.message};let e=t&&typeof t=="object"?t:null,n=typeof e?.category=="string"?e.category:"runtime_error";return {category:n,message:Cr(t),retryAfterMs:typeof e?.retryAfterMs=="number"&&Number.isFinite(e.retryAfterMs)?Math.max(0,e.retryAfterMs):void 0,retryWithoutAttempt:e?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function Sd(t,e){let n=Math.min(bd,500*2**Math.max(0,t-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,e)));return n+o}function Cr(t){return t instanceof Error?t.message:String(t)}var Dd=250;function Pr(t,e=process.env){let n=Or(join(getDevFlowStateRoot({env:e}),"config.json")),o=Or(join(t,".devflow","config.json")),r=Qt(e.DEVFLOW_HOOK_PROFILE)??Qt(o.profile)??Qt(n.profile)??"standard",i=Number(e.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):Dd,a=new Set([...Zt(n.disabledHandlers),...Zt(o.disabledHandlers),...Zt(e.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(Pd).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function jr(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{h({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:t,budgetMs:e,fallback:"timeout_result"}}),a(o());},e),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function $r(t,e=process.env){let n=e.DEVFLOW_HOST_ADAPTER??(e.CLAUDE_PROJECT_DIR||e.CLAUDE_PLUGIN_ROOT||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:t,env:e,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:t,env:e,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function en(t,e,n){let o=Od(t,e.profile);if(!n.profiles.has(e.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${e.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(e.disabledHandlers.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(e.profile==="minimal"&&!Cd.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=Md[t];if(!r)return {enabled:true,policy:o};let i=n.capabilities.get(r);return !i||i.status!=="supported"?{enabled:false,policy:"fail_open",reason:i?.reason??`${r}_unsupported_by_${n.hostId}`,fallback:i?.fallback??"host_event_continues_without_native_hook_processing"}:{enabled:true,policy:o}}var Cd=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),Md={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Od(t,e){return t==="user-prompt-submit"||t==="stop"||t==="session-end"?"enqueue_and_open":t==="pre-tool-use"&&e==="strict"?"fail_closed":"fail_open"}function Or(t){if(!existsSync(t))return {};try{let n=JSON.parse(readFileSync$1(t,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Qt(t){return t==="minimal"||t==="standard"||t==="strict"?t:void 0}function Zt(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Pd(t){let e=t.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase();return ({sessionstart:"session-start",userpromptsubmit:"user-prompt-submit",pretooluse:"pre-tool-use",posttooluse:"post-tool-use",posttoolusefailure:"post-tool-use-failure",sessionend:"session-end",precompact:"pre-compact",memorysnapshot:"memory-snapshot"}[e.replace(/-/g,"")]??e)||void 0}var et=class{decode(e){let n;try{let d=JSON.parse(e.rawInput);if(!d||typeof d!="object"||Array.isArray(d))return null;n=d;}catch{return null}let o=$d[e.requestType];if(typeof n.hook_event_name=="string"&&n.hook_event_name!==o)return null;let r=resolve(nn(n.cwd)??e.projectRoot??process.cwd()),i=nn(n.session_id),s=nn(n.tool_use_id),a=e.receivedAt??Date.now(),c={requestType:e.requestType,projectRoot:r,sessionId:i??"",toolUseId:s??"",payloadHash:stableRuntimeHash(n)};return {schemaVersion:"normalized-hook-event.v1",eventId:`hook-event:${stableRuntimeHash(c).slice(0,32)}`,requestType:e.requestType,eventName:o,projectRoot:r,...i?{sessionId:i}:{},...s?{toolUseId:s}:{},retryKey:`${e.requestType}:${stableRuntimeHash(c).slice(0,24)}`,receivedAt:a,rawInput:e.rawInput,payload:n}}},$d={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"};function nn(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Fr(t){let e=Object.keys(t.handlers).map(n=>{let o=Hd[n];return [n,{requestType:n,eventName:o,capability:Ld[n],failurePolicy:t.failurePolicy(n),acknowledgeWithinBudget:Fd.has(n),handler:t.handlers[n],timeoutResult:()=>Nd(n)}]});return new Map(e)}async function Hr(t){let e=t.registry.get(t.requestType);if(!e)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=new et().decode({requestType:t.requestType,rawInput:t.rawInput,projectRoot:t.projectRoot}),o=()=>Promise.resolve(e.handler(n?.rawInput??t.rawInput));return e.acknowledgeWithinBudget?jr(e.eventName,t.acknowledgementBudgetMs,o,e.timeoutResult,t.projectRoot):o()}var Fd=new Set(["stop","session-end","user-prompt-submit"]),Hd={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"},Ld={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Nd(t){return t==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:"DevFlow background processing exceeded its acknowledgement budget; continue in degraded mode and do not claim unreceipted work completed."}}:{status:"degraded",reason:"hook_budget_exceeded",fallback:t==="session-end"?"durable_session_recovery":"background_processing"}}var nt=class{constructor(e){this.records=new Map;this.path=join(j(e),"hook-handler-health.json"),this.load();}recordSuccess(e,n,o=Date.now()){let r={handler:e,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(tt(e,n),r),this.persist(),r}recordFailure(e,n,o,r,i=Date.now()){let s=this.records.get(tt(e,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:e,host:n,status:"degraded",consecutiveFailures:a,lastFailureCategory:o,lastFailureReason:r.slice(0,500),retryAt:i+c,lastSuccessAt:s?.lastSuccessAt,updatedAt:i};return this.records.set(tt(e,n),d),this.persist(),d}list(){return [...this.records.values()].sort((e,n)=>e.handler.localeCompare(n.handler))}load(){try{let e=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of e)n?.handler&&n?.host&&this.records.set(tt(n.handler,n.host),n);}catch{}}persist(){try{mkdirSync$1(dirname$1(this.path),{recursive:!0,mode:448});let e=`${this.path}.${process.pid}.tmp`;writeFileSync$1(e,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(e,this.path);}catch{}}};function tt(t,e){return `${e}\0${t}`}function Lr(t,e){return e||(t==="post-tool-use"||t==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function Nr(t){let e=t instanceof Error?t.message:String(t??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(e)?"timeout":/sqlite|database|locked|busy/iu.test(e)?"storage":/socket|connect|unreachable/iu.test(e)?"transport":/json|parse|schema|invalid/iu.test(e)?"protocol":"handler",reason:e}}function qr(t){let e=xo({projectRoot:t.projectRoot,sessionId:t.sessionId,transcriptPath:t.transcriptPath,runtimeStore:t.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Xd(t.runtimeStore,t.sessionId,n);let o=n.getPendingMemoryTurn(t.projectRoot,t.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];e&&i.push(e.reason),o&&r&&i.push(Xe(o)),o&&!r&&Gd(n,o.turnId)&&Yd(We(t.transcriptPath))&&i.push(`DevFlow explicit memory ${o.turnId} still has no canonical receipt. Remove the memory-success claim and tell the user that the memory was not saved, or complete the pending turn.`);let a=n.listSessionObligations(t.projectRoot,t.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?c.payload.subtype==="policy_verification"?`Complete the required project verification: ${String(c.payload.command??c.payload.verificationKind??"unknown command")}.`:"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
|
|
30
|
+
`)}if(process.env.DEVFLOW_MEMORY_SNAPSHOT_CLI==="1"){let[,,t,e,n]=process.argv;t!=="session-start"||!e?process.exitCode=2:process.stdout.write(Kc({projectRoot:e,configPath:n,daemonResponse:process.env.DEVFLOW_MEMORY_RESPONSE}));}var Yc=/^(?:ok(?:ay)?|yes|no|thanks?|thank you|continue|好的?|可以|行|是|否|谢谢|继续|收到|明白了?)[.!。!\s]*$/iu,Xc=/(?:记住|记下|保存|持久化|跨会话|以后|始终|永远|统一使用|项目约定|团队约定|偏好|决定采用|保留可复用|提炼结论|沉淀|记录(?:下来|为|成)?(?:架构|规则|约定|知识|结论))|\b(?:remember|memorize|persist|across sessions|from now on|always|project convention|team convention|preference|we use|adopt|retain reusable|distill)\b/iu,Qc=/(?:分析|审查|检查|评估|性能|生成|创建|新建|添加|编写|实现|开发|设计|撰写|总结|修改|重构|修复|调试|解释|查看)|\b(?:analy[sz]e|review|inspect|audit|performance|generate|create|add|build|implement|develop|design|write|summarize|modify|refactor|fix|debug|explain)\b/iu,Zc=/(?:召回|查询|检索|查找|定位|询问|什么|如何|是否|哪里|哪个)|\b(?:recall|query|search|find|locate|ask|what|how|whether|where|which)\b/iu;function ed(t){let e=t.trim();return e.length>0&&!Yc.test(e)}function td(t){let e=t.normalize("NFKC").trim(),n=Zc.test(e);return e.length>=4&&(Qc.test(e)||n)&&(!Xc.test(e)||n)&&he(e)===null}function nd(t,e,n=Date.now()){let o=createHash("sha256").update(e.trim()).digest("hex"),r=createHash("sha256").update(`${t}\0${n}\0${o}`).digest("hex").slice(0,24);return {turnId:`turn:${r}`,eventId:`memory-turn:${r}`,promptHash:o,createdAt:n}}function be(t,e,n=[]){return `memory-receipt:${createHash("sha256").update(`${t}\0${e}\0${[...n].sort().join("\0")}`).digest("hex").slice(0,24)}`}function Xe(t){return `DevFlow memory decision required for ${t.turnId}. Before the final response, semantically decide whether this turn contains durable project knowledge. Call mcp__devflow__memory_commit_turn with evidence-bound candidates, or mcp__devflow__memory_skip_turn with a concrete reason. Do not claim memory success without a canonical receipt. For candidates, copy exact evidenceSpans from this user prompt, preserve package names, flags, versions, paths, and identifiers, and provide subject, predicate, value, polarity, and entities when known. To replace or retire an existing fact, provide operation=supersede or operation=retire plus referencedFactIds from the canonical memory receipt; aliases and entity names are not fact identity. Do not save assistant echoes, task narration, retries, or unverified guesses. Express a change from an old choice as the new durable value. If the decision tool remains unavailable, explicitly state that the memory was not saved.`}function we(t){let e=t.memoryIds.length>0?t.memoryIds.join(","):"none",n=t.status==="committed"?"accepted":t.status,o=t.status==="committed"?"; indexStatus=pending":"",r=t.memoryIds.some(a=>a.startsWith("raw-memory:")),i=t.status==="committed"&&t.source==="explicit_intent"&&!r?"; memoryOnlyCompleted=true; skipProjectContext=true; hostRefinementRequired=true":t.status==="committed"&&t.source==="explicit_intent"?"; asyncReadiness=queued; hostRefinementRequired=true":"",s=t.status==="committed"&&t.source==="explicit_intent"?` The deterministic explicit-memory save is complete and remains authoritative if refinement fails. Before the final response, call mcp__devflow__memory_commit_turn once with turnId=${t.turnId} and semantic candidates. Split every distinct reusable fact into a durable_memory candidate, classify instructions that apply only to this turn as turn_constraint, and include evidenceSpans copied verbatim from the user prompt for every candidate. Preserve exact flags, package names, versions, paths, and identifiers. Keep narrative and value in the user prompt language; do not translate evidence into a different surface form. The tool refines the existing receipt idempotently; it must not create native Claude memory. If refinement is unavailable, return the existing canonical receipt without claiming refinement.`:"";return `DevFlow canonical memory receipt: status=${n}; receiptId=${t.receiptId??"missing"}; turnId=${t.turnId}; memoryIds=${e}; source=${t.source??"unknown"}${o}${i}.`+s}function Bt(t){if(!ed(t.prompt))return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let n=t.prompt.trim().slice(0,4e3),o=createHash("sha256").update(n).digest("hex"),r=e.listMemoryTurns(t.projectRoot,t.sessionId,5).find(l=>l.promptHash===o&&Date.now()-l.createdAt<1e4),i=r?{turnId:r.turnId,eventId:r.eventId,promptHash:r.promptHash,createdAt:r.createdAt}:t.identity??nd(t.sessionId,n),s=r??e.beginMemoryTurn({...i,projectRoot:t.projectRoot,sessionId:t.sessionId});if(s.status!=="pending")return {turn:s,additionalContext:we(s),skipSkillRouting:s.source==="explicit_intent"};let c=(t.activation?.semantic??"degraded_structural")==="degraded_structural"?he(n)??void 0:void 0;if(!c&&td(n)){let l=be(s.turnId,"skipped"),m=e.skipMemoryTurn({turnId:s.turnId,receiptId:l,source:"automatic_transient_skip",reason:"high_confidence_transient_task"});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.skipped",payload:{receiptId:l,reasonCode:"high_confidence_transient_task"},dedupeKey:l,producer:"devflow-memory-turn"}),h({event:"memory.semantic.decided",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId},level:"info",timestamp:Date.now(),data:{status:"semantic_empty",operation:"none",reason:"high_confidence_transient_task"}}),{turn:m,additionalContext:we(m),skipSkillRouting:!1}}let d=c?"commit_explicit":"capture_prompt",u=e.enqueueWork({idempotencyKey:`memory-turn:${d}:${s.turnId}`,kind:c?"memory.explicit_commit":"memory.turn_capture",projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,payload:{operation:d,turnId:s.turnId,eventId:s.eventId,sessionId:t.sessionId,prompt:n,explicitContent:c,createdAt:s.createdAt}});if(c){let l=`raw-memory:${createHash("sha256").update(`${t.projectRoot}\0${i.turnId}\0${c}`).digest("hex").slice(0,24)}`,m=be(s.turnId,"committed",[l]),f=e.commitMemoryTurn({turnId:s.turnId,receiptId:m,memoryIds:[l],source:"explicit_intent",reason:"explicit_raw_queued",decidedAt:Date.now()});return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.committed",payload:{receiptId:m,reasonCode:"explicit_raw_queued"},dedupeKey:m,producer:"devflow-memory-turn"}),h({event:"memory.write.completed",identity:{projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,actionReceipt:m},level:"info",timestamp:Date.now(),data:{stage:"explicit_fast_ack",durable:!0,rawMemoryId:l,receiptLatencyMs:Date.now()-i.createdAt,asyncReadiness:"queued"}}),{turn:f,explicitContent:c,additionalContext:we(f),skipSkillRouting:!0}}return C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"memory.pending",payload:{reasonCode:"semantic_decision_queued"},dedupeKey:`${s.turnId}:pending`,producer:"devflow-memory-turn"}),C({projectRoot:t.projectRoot,sessionId:t.sessionId,turnId:s.turnId,kind:"durable_work.owned",payload:{workId:u.id,obligation:"memory"},dedupeKey:`${u.id}:owned`,producer:"devflow-memory-turn"}),{turn:s,explicitContent:c,additionalContext:Xe(s),skipSkillRouting:!1}}finally{e.close();}}async function Vt(t){let{payload:e,memory:n,projectRoot:o}=t,r=openGlobalDevFlowDatabase();try{let i=r.getMemoryTurn(e.turnId);if(!i)throw new Error(`Memory turn ${e.turnId} does not exist`);let s=e.operation==="commit_explicit"&&i.status==="committed"&&i.source==="explicit_intent"&&i.memoryIds.some(l=>l.startsWith("raw-memory:"));if(i.status!=="pending"&&!s){if(i.receiptId&&typeof n.reconcileTurnObservationLineage=="function")try{await n.reconcileTurnObservationLineage([i]);}catch{}return {turn:i,additionalContext:we(i),skipSkillRouting:i.source==="explicit_intent"}}if(await n.recordUserMessage(e.prompt,e.sessionId,e.prompt.slice(0,200)),await n.recordEvent({id:e.eventId,sessionId:e.sessionId,tool:"UserPromptSubmit",kind:"user_message",payload:{prompt:e.prompt,turnId:e.turnId},createdAt:e.createdAt}),e.operation==="capture_prompt"||!e.explicitContent)return {turn:i,additionalContext:Xe(i),skipSkillRouting:!1};let a=await n.saveExplicitMemoryIntent(e.explicitContent,{actorId:"actor:claude-code",sessionId:e.sessionId},e.eventId),c=[...new Set([a.id,...a.relatedMemoryIds??[]])];h({event:"memory.semantic.decided",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId},level:a.semanticDecision?.status==="semantic_ready"?"info":"warn",timestamp:Date.now(),data:{status:a.semanticDecision?.status??"semantic_unavailable",operations:a.semanticDecision?.operations??["add"],memoryIds:c,rejectedCount:a.semanticDecision?.rejectedCount??0,durable:a.durable,lexicallyReady:a.lexicallyReady,policyReady:a.policyReady,vectorStatus:a.vectorStatus}});let d=i.receiptId??be(i.turnId,"committed",c),u=s?r.updateCommittedMemoryTurnProjection({turnId:i.turnId,memoryIds:c,reason:"explicit_async_ready"}):r.commitMemoryTurn({turnId:i.turnId,receiptId:d,memoryIds:c,source:"explicit_intent",reason:"explicit_user_request"});C({projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,kind:"memory.committed",payload:{receiptId:d,reasonCode:"explicit_async_ready"},dedupeKey:`${d}:async_ready`,producer:"devflow-memory-worker"}),h({event:"memory.write.completed",identity:{projectRoot:o,sessionId:i.sessionId,turnId:i.turnId,actionReceipt:d},level:"info",timestamp:Date.now(),data:{stage:"explicit_async_ready",durable:!0,memoryIds:c,receiptLatencyMs:Math.max(0,(i.decidedAt??Date.now())-i.createdAt),asyncReadinessMs:Math.max(0,Date.now()-i.createdAt),vectorStatus:a.vectorStatus}});try{typeof n.finalizeTurnDecision=="function"&&await n.finalizeTurnDecision({turnEventId:i.eventId,sessionId:i.sessionId,turnId:i.turnId,receiptId:d,status:"committed",memoryIds:c,reason:"explicit_user_request"});}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"lineage_finalize",reason:l.message,fallback:"session_end_reconciliation"}});}try{await n.enrichExplicitMemoryObservation(a.id);}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"explicit_enrichment",memoryId:a.id,reason:l.message,fallback:"durable_work_queue"}}),r.enqueueWork({idempotencyKey:`explicit-enrichment:${o}:${a.id}`,kind:"memory.explicit_enrichment",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});}r.enqueueWork({idempotencyKey:`vector:${o}:${a.id}`,kind:"memory.vector_backfill",projectRoot:o,sessionId:e.sessionId,turnId:u.turnId,payload:{observationId:a.id},maxAttempts:20});try{await Ye({projectRoot:o,memory:n,injectConfig:loadConfig(o).sessionStart?.injectMemories,reason:"explicit_memory_commit"});}catch(l){h({event:"memory.write.degraded",identity:{projectRoot:o,sessionId:e.sessionId,turnId:i.turnId},level:"warn",timestamp:Date.now(),data:{stage:"snapshot_refresh",reason:l.message,fallback:"durable_memory_authoritative"}});}return {turn:u,explicitContent:e.explicitContent,additionalContext:we(u),skipSkillRouting:!0}}finally{r.close();}}var id=new Set(["Write","Edit","NotebookEdit"]),fr="Claude native memory writes are disabled for this project. Use DevFlow explicit memory or mcp__devflow__memory_commit_turn so a canonical receipt is created.";function _r(t){if(!id.has(t.toolName))return null;let e=sd(t.toolInput);if(!e)return null;let n=ad(e,t.projectRoot),o=resolve(t.projectRoot,".claude");if(gr(n,o)&&basename(n).toLocaleUpperCase("en-US")==="MEMORY.MD")return fr;let r=resolve(t.home??homedir(),".claude","projects");return gr(n,r)&&relative(r,n).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?fr:null}function sd(t){for(let e of ["file_path","notebook_path","path"]){let n=t[e];if(typeof n=="string"&&n.trim())return n.trim()}return null}function ad(t,e){return resolve(isAbsolute(t)?t:resolve(e,t))}function gr(t,e){let n=relative(e,t);return n===""||!n.startsWith(`..${sep}`)&&n!==".."&&!isAbsolute(n)}var pd=1024*1024;function kr(t){let e=join(getProjectStateDir(t),"session-start-pending");mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=readFileSync$1(i,"utf8");if(Buffer.byteLength(s,"utf8")>pd)throw unlinkSync$1(i),new Error("session_start_spool_input_too_large");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),input:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function br(t){unlinkSync$1(t.path);}function Rr(t){let e=t.path.replace(/\.claim-\d+$/u,"");try{renameSync(t.path,e);}catch{}}function xr(t,e){let n=Dr(t);mkdirSync$1(n,{recursive:true,mode:448});let o=`memory-turn-spool-${Date.now()}-${process.pid}-${randomUUID$1()}`,r=join(n,`${o}.json`),i=`${r}.tmp`;return writeFileSync$1(i,JSON.stringify({...e,prompt:e.prompt.trim().slice(0,4e3)}),{mode:384}),renameSync(i,r),o}function Er(t){let e=Dr(t);mkdirSync$1(e,{recursive:true,mode:448});let n=readdirSync$1(e).filter(s=>s.endsWith(".json")||/\.json\.claim-\d+$/u.test(s)).sort()[0];if(!n)return null;let o=join(e,n),r=/\.json\.claim-\d+$/u.test(n),i=r?o:`${o}.claim-${process.pid}`;if(!r)try{renameSync(o,i);}catch{return null}try{let s=JSON.parse(readFileSync$1(i,"utf8"));if(typeof s.sessionId!="string"||typeof s.prompt!="string"||typeof s.createdAt!="number")throw unlinkSync$1(i),new Error("memory_turn_spool_payload_invalid");return {receiptId:basename(n).replace(/\.json(?:\.claim-\d+)?$/u,""),payload:s,path:i}}catch(s){try{unlinkSync$1(i);}catch{}throw s}}function Ar(t){unlinkSync$1(t.path);}function Tr(t){try{renameSync(t.path,t.path.replace(/\.claim-\d+$/u,""));}catch{}}function Dr(t){return join(j(t),"memory-turn-pending")}var E=class extends Error{constructor(e,n){super(n),this.name="PermanentWorkError",this.category=e;}},wd=1e3,kd=3e4,bd=1,Rd=5*6e4,Ze=class{constructor(e){this.timer=null;this.draining=null;this.stopped=true;this.projectRoot=e.projectRoot,this.handlers=e.handlers,this.pollIntervalMs=Xt(e.pollIntervalMs,wd),this.leaseMs=Xt(e.leaseMs,kd),this.batchSize=Xt(e.batchSize,bd),this.owner=e.owner??`hook-daemon:${process.pid}:${randomUUID$1()}`,this.now=e.now??Date.now,this.random=e.random??Math.random,this.openDatabase=e.openDatabase??(()=>openGlobalDevFlowDatabase()),this.afterComplete=e.afterComplete;}start(){this.stopped&&(this.stopped=false,this.schedule(0));}stop(){this.stopped=true,this.timer&&clearTimeout(this.timer),this.timer=null;}drainOnce(){return this.draining?this.draining:(this.draining=this.performDrain().finally(()=>{this.draining=null;}),this.draining)}async drainWorkItemOnce(e){return e.trim()?(this.draining&&await this.draining,this.draining=this.performDrain(void 0,new Set([e])).finally(()=>{this.draining=null;}),this.draining):0}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.drainOnce().catch(n=>this.logDegradation("drain",n)).finally(()=>this.schedule(this.pollIntervalMs));},e),this.timer.unref());}async performDrain(e,n){let o=Object.keys(this.handlers).filter(i=>!e||e.has(i));if(o.length===0)return 0;let r=this.openDatabase();try{let i=this.now();r.recoverExpiredWork(this.projectRoot,i);let s=r.leaseWork({projectRoot:this.projectRoot,owner:this.owner,kinds:o,workItemIds:n?[...n]:void 0,limit:this.batchSize,leaseMs:this.leaseMs,now:i});for(let a of s)await this.processItem(r,a);return s.length}finally{r.close();}}async processItem(e,n){let o=this.handlers[n.kind];if(!o){e.deadLetterWork(n.id,this.owner,{category:"unsupported_work_kind",message:`No work handler is registered for ${n.kind}`}),this.logWorkTransition("dead_letter",n,{errorCategory:"unsupported_work_kind"},"error");return}let r=setInterval(()=>{e.heartbeatWork(n.id,this.owner,this.leaseMs,this.now())||this.logDegradation("lease_heartbeat",new Error("work_lease_heartbeat_rejected"),n);},Math.max(1e3,Math.floor(this.leaseMs/3)));r.unref();try{if(await o({item:n}),!e.completeWork(n.id,this.owner,this.now()))throw new Error(`Work lease was lost before completion: ${n.id}`);this.logWorkTransition("completed",n,{attempt:n.attempts});try{await this.afterComplete?.({item:n,database:e});}catch(i){this.logDegradation("completion_follow_up",i,n);}}catch(i){let s=Sd(i);if(i instanceof E||s.permanent){e.deadLetterWork(n.id,this.owner,s),this.logWorkTransition("dead_letter",n,{attempt:n.attempts,errorCategory:s.category},"error");return}let a=this.now()+Math.max(xd(n.attempts,this.random()),s.retryAfterMs??0);if(s.retryWithoutAttempt){e.deferWork(n.id,this.owner,s,a),this.logWorkTransition("deferred",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");return}e.retryWork(n.id,this.owner,s,a),this.logWorkTransition("retry_wait",n,{attempt:n.attempts,nextAttemptAt:a,errorCategory:s.category},"warn");}finally{clearInterval(r);}}logDegradation(e,n,o){h({event:"hook.runtime.degraded",identity:{projectRoot:this.projectRoot,sessionId:o?.sessionId,turnId:o?.turnId,executionId:o?.executionId},level:"warn",timestamp:this.now(),data:{stage:`work_${e}`,workId:o?.id,workKind:o?.kind,reason:Cr(n)}});}logWorkTransition(e,n,o,r="info"){try{h({event:"durable.work.transitioned",identity:{projectRoot:this.projectRoot,sessionId:n.sessionId,turnId:n.turnId,executionId:n.executionId},level:r,timestamp:this.now(),data:{stage:e,workId:n.id,workKind:n.kind,...o}});}catch{}}};function Xt(t,e){return Number.isSafeInteger(t)&&t>0?t:e}function Sd(t){if(t instanceof E)return {category:t.category,message:t.message};let e=t&&typeof t=="object"?t:null,n=typeof e?.category=="string"?e.category:"runtime_error";return {category:n,message:Cr(t),retryAfterMs:typeof e?.retryAfterMs=="number"&&Number.isFinite(e.retryAfterMs)?Math.max(0,e.retryAfterMs):void 0,retryWithoutAttempt:e?.retryWithoutAttempt===true,permanent:n==="policy_verification_failed"||n==="invalid_payload"}}function xd(t,e){let n=Math.min(Rd,500*2**Math.max(0,t-1)),o=Math.floor(n*.2*Math.max(0,Math.min(1,e)));return n+o}function Cr(t){return t instanceof Error?t.message:String(t)}var Cd=250;function Pr(t,e=process.env){let n=Or(join(getDevFlowStateRoot({env:e}),"config.json")),o=Or(join(t,".devflow","config.json")),r=Qt(e.DEVFLOW_HOOK_PROFILE)??Qt(o.profile)??Qt(n.profile)??"standard",i=Number(e.DEVFLOW_HOOK_ACK_BUDGET_MS??o.acknowledgementBudgetMs??n.acknowledgementBudgetMs),s=Number.isSafeInteger(i)&&i>0?Math.min(i,5e3):Cd,a=new Set([...Zt(n.disabledHandlers),...Zt(o.disabledHandlers),...Zt(e.DEVFLOW_DISABLED_HOOK_HANDLERS?.split(","))].map(jd).filter(c=>!!c));return {profile:r,acknowledgementBudgetMs:s,disabledHandlers:a}}async function jr(t,e,n,o,r=process.env.CLAUDE_PROJECT_DIR||process.cwd()){let i,s=new Promise(a=>{i=setTimeout(()=>{h({event:"hook.runtime.degraded",identity:{projectRoot:r},level:"warn",timestamp:Date.now(),data:{stage:"acknowledgement_budget",eventName:t,budgetMs:e,fallback:"timeout_result"}}),a(o());},e),i.unref();});try{return await Promise.race([Promise.resolve().then(n),s])}finally{i&&clearTimeout(i);}}async function $r(t,e=process.env){let n=e.DEVFLOW_HOST_ADAPTER??(e.CLAUDE_PROJECT_DIR||e.CLAUDE_PLUGIN_ROOT||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":void 0),o=await selectHostAdapter({projectRoot:t,env:e,explicitHost:n});if(o.status==="failed")throw new Error(`host_adapter_selection_failed:${o.code}:${o.reason}`);let r=await o.adapter.capabilities({projectRoot:t,env:e,explicitHost:n});return {hostId:o.adapter.id,capabilities:new Map(r.map(i=>[i.capability,i])),profiles:new Set(o.adapter.hooks?.profileSupport??[])}}function en(t,e,n){let o=Pd(t,e.profile);if(!n.profiles.has(e.profile))return {enabled:false,policy:"fail_open",reason:`hook_profile_${e.profile}_unsupported_by_${n.hostId}`,fallback:"host_event_continues_without_devflow_handler"};if(e.disabledHandlers.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_disabled",fallback:"host_event_continues_without_devflow_handler"};if(e.profile==="minimal"&&!Md.has(t))return {enabled:false,policy:"fail_open",reason:"hook_handler_not_in_minimal_profile",fallback:"critical_receipts_only"};let r=Od[t];if(!r)return {enabled:true,policy:o};let i=n.capabilities.get(r);return !i||i.status!=="supported"?{enabled:false,policy:"fail_open",reason:i?.reason??`${r}_unsupported_by_${n.hostId}`,fallback:i?.fallback??"host_event_continues_without_native_hook_processing"}:{enabled:true,policy:o}}var Md=new Set(["session-start","user-prompt-submit","stop","session-end","memory-snapshot"]),Od={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function Pd(t,e){return t==="user-prompt-submit"||t==="stop"||t==="session-end"?"enqueue_and_open":t==="pre-tool-use"&&e==="strict"?"fail_closed":"fail_open"}function Or(t){if(!existsSync(t))return {};try{let n=JSON.parse(readFileSync$1(t,"utf8")).hooks;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return {}}}function Qt(t){return t==="minimal"||t==="standard"||t==="strict"?t:void 0}function Zt(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function jd(t){let e=t.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase();return ({sessionstart:"session-start",userpromptsubmit:"user-prompt-submit",pretooluse:"pre-tool-use",posttooluse:"post-tool-use",posttoolusefailure:"post-tool-use-failure",sessionend:"session-end",precompact:"pre-compact",memorysnapshot:"memory-snapshot"}[e.replace(/-/g,"")]??e)||void 0}var et=class{decode(e){let n;try{let d=JSON.parse(e.rawInput);if(!d||typeof d!="object"||Array.isArray(d))return null;n=d;}catch{return null}let o=Fd[e.requestType];if(typeof n.hook_event_name=="string"&&n.hook_event_name!==o)return null;let r=resolve(nn(n.cwd)??e.projectRoot??process.cwd()),i=nn(n.session_id),s=nn(n.tool_use_id),a=e.receivedAt??Date.now(),c={requestType:e.requestType,projectRoot:r,sessionId:i??"",toolUseId:s??"",payloadHash:stableRuntimeHash(n)};return {schemaVersion:"normalized-hook-event.v1",eventId:`hook-event:${stableRuntimeHash(c).slice(0,32)}`,requestType:e.requestType,eventName:o,projectRoot:r,...i?{sessionId:i}:{},...s?{toolUseId:s}:{},retryKey:`${e.requestType}:${stableRuntimeHash(c).slice(0,24)}`,receivedAt:a,rawInput:e.rawInput,payload:n}}},Fd={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"};function nn(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Fr(t){let e=Object.keys(t.handlers).map(n=>{let o=Ld[n];return [n,{requestType:n,eventName:o,capability:Nd[n],failurePolicy:t.failurePolicy(n),acknowledgeWithinBudget:Hd.has(n),handler:t.handlers[n],timeoutResult:()=>qd(n)}]});return new Map(e)}async function Hr(t){let e=t.registry.get(t.requestType);if(!e)return {status:"degraded",reason:"unknown_hook_handler",fallback:"host_event_continues"};let n=new et().decode({requestType:t.requestType,rawInput:t.rawInput,projectRoot:t.projectRoot}),o=()=>Promise.resolve(e.handler(n?.rawInput??t.rawInput));return e.acknowledgeWithinBudget?jr(e.eventName,t.acknowledgementBudgetMs,o,e.timeoutResult,t.projectRoot):o()}var Hd=new Set(["stop","session-end","user-prompt-submit"]),Ld={"session-start":"SessionStart","user-prompt-submit":"UserPromptSubmit","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","post-tool-use-failure":"PostToolUseFailure",stop:"Stop","session-end":"SessionEnd","pre-compact":"PreCompact","memory-snapshot":"MemorySnapshot"},Nd={"session-start":"hooks.session_start","user-prompt-submit":"hooks.prompt_submit","pre-tool-use":"hooks.pre_tool_use","post-tool-use":"hooks.post_tool_use","post-tool-use-failure":"hooks.post_tool_use",stop:"hooks.stop","session-end":"hooks.session_end"};function qd(t){return t==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:"DevFlow background processing exceeded its acknowledgement budget; continue in degraded mode and do not claim unreceipted work completed."}}:{status:"degraded",reason:"hook_budget_exceeded",fallback:t==="session-end"?"durable_session_recovery":"background_processing"}}var nt=class{constructor(e){this.records=new Map;this.path=join(j(e),"hook-handler-health.json"),this.load();}recordSuccess(e,n,o=Date.now()){let r={handler:e,host:n,status:"healthy",consecutiveFailures:0,lastSuccessAt:o,updatedAt:o};return this.records.set(tt(e,n),r),this.persist(),r}recordFailure(e,n,o,r,i=Date.now()){let s=this.records.get(tt(e,n)),a=(s?.consecutiveFailures??0)+1,c=Math.min(5*6e4,1e3*2**Math.min(8,a-1)),d={handler:e,host:n,status:"degraded",consecutiveFailures:a,lastFailureCategory:o,lastFailureReason:r.slice(0,500),retryAt:i+c,lastSuccessAt:s?.lastSuccessAt,updatedAt:i};return this.records.set(tt(e,n),d),this.persist(),d}list(){return [...this.records.values()].sort((e,n)=>e.handler.localeCompare(n.handler))}load(){try{let e=JSON.parse(readFileSync$1(this.path,"utf8"));for(let n of e)n?.handler&&n?.host&&this.records.set(tt(n.handler,n.host),n);}catch{}}persist(){try{mkdirSync$1(dirname$1(this.path),{recursive:!0,mode:448});let e=`${this.path}.${process.pid}.tmp`;writeFileSync$1(e,JSON.stringify(this.list(),null,2),{mode:384}),renameSync(e,this.path);}catch{}}};function tt(t,e){return `${e}\0${t}`}function Lr(t,e){return e||(t==="post-tool-use"||t==="post-tool-use-failure"?{status:"ok"}:{status:"ok"})}function Nr(t){let e=t instanceof Error?t.message:String(t??"hook_handler_failed");return {category:/timeout|budget|deadline/iu.test(e)?"timeout":/sqlite|database|locked|busy/iu.test(e)?"storage":/socket|connect|unreachable/iu.test(e)?"transport":/json|parse|schema|invalid/iu.test(e)?"protocol":"handler",reason:e}}function qr(t){let e=xo({projectRoot:t.projectRoot,sessionId:t.sessionId,transcriptPath:t.transcriptPath,runtimeStore:t.runtimeStore}),n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{Qd(t.runtimeStore,t.sessionId,n);let o=n.getPendingMemoryTurn(t.projectRoot,t.sessionId),r=o?n.markMemoryTurnStopPrompted(o.turnId):!1,i=[];e&&i.push(e.reason),o&&r&&i.push(Xe(o)),o&&!r&&Yd(n,o.turnId)&&Xd(We(t.transcriptPath))&&i.push(`DevFlow explicit memory ${o.turnId} still has no canonical receipt. Remove the memory-success claim and tell the user that the memory was not saved, or complete the pending turn.`);let a=n.listSessionObligations(t.projectRoot,t.sessionId,["open"]).map(c=>({obligationId:c.obligationId,kind:c.kind,action:c.kind==="memory_decision"?"Call mcp__devflow__memory_decide_turn using the canonical turn ID.":c.kind==="evidence_contract"?c.payload.subtype==="policy_verification"?`Complete the required project verification: ${String(c.payload.command??c.payload.verificationKind??"unknown command")}.`:"Return a final answer that satisfies the canonical evidence contract.":"Allow SessionEnd durable finalization to complete.",canonicalInput:c.kind==="memory_decision"&&c.turnId?{turnId:c.turnId}:void 0}));return i.length>0?{decision:"block_once",unresolved:a,additionalContext:["DevFlow has unresolved terminal obligations. Complete all actions below before stopping.",...i].join(`
|
|
31
31
|
|
|
32
|
-
`)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{n.close();}}function
|
|
33
|
-
${JSON.stringify(t.trigger)}`,n=[];Qd.some(r=>r.test(e))&&n.push("high_risk_operation"),Zd.some(r=>r.test(e))&&n.push("broad_or_migrating_change"),t.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||t.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var el=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function sn(t){let e=t.payload.executionId?t.database.getSkillExecution(t.payload.executionId):t.database.getLatestSkillExecutionForSession(t.payload.sessionId),n=t.database.listHostActionsForSession(t.payload.projectRoot,t.payload.sessionId,t.payload.executionId),o=n.find(u=>u.state==="verified"),r=n.find(u=>["failed","cancelled","degraded"].includes(u.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,d=0;for(let u of t.evidence){if(!tl(u)){d+=1;continue}let l=Br(u),m=nl(u,e?.skillName),f=Vr(u),p=il(t.payload.projectRoot,l,u.facetKey??u.semanticKey??u.id,m),g=t.database.getLearningCandidate(p),S=on({scope:"project",kind:l,instruction:f,trigger:m});t.database.upsertLearningCandidate({id:p,projectRoot:t.payload.projectRoot,scope:"project",kind:l,trigger:m,instruction:f,confidence:ol(u),manualOnly:S.manualOnly,risk:S.risk});g&&g.instruction!==f&&t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"contradicting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Ur(p,t.payload,u,"contradicting"),receipt:t.payload.closureReceipt,payload:{previousInstruction:g.instruction,replacementInstruction:f,projectRevision:t.payload.projectRevision},createdAt:u.createdAt});let k=t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"supporting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,outcomeId:o?.id??r?.id,sourceType:rl(u),polarity:"supporting",outcome:i,evidenceHash:Ur(p,t.payload,u,"supporting"),receipt:t.payload.closureReceipt,payload:{semanticKey:u.semanticKey,facetKey:u.facetKey,evidenceStatus:u.evidenceStatus,source:u.source,projectRevision:t.payload.projectRevision,executionStatus:e?.status,policyReasons:S.reasons},createdAt:u.createdAt});c+=1,s.add(p),t.rolloutMode!=="off"&&k.state==="candidate"&&k.supportingSessions>=3&&k.successfulOutcomes>=2&&t.database.transitionLearningCandidate(p,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(p);}return {considered:t.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function tl(t){return !(!el.has(t.type)||t.source!=="explicit_intent"&&t.source!=="manual"&&t.evidenceStatus!=="verified"||!t.narrative.trim()&&!t.title.trim())}function Br(t){return t.type==="decision_made"?"workflow":t.type==="user_preference"&&(t.semanticValue.startsWith("--")||t.tools.length>0)?"tool_preference":"convention"}function nl(t,e){return {...e?{skills:[e]}:{},...t.entities.length>0?{entities:[...new Set(t.entities)].slice(0,8)}:{},...t.files.length>0?{files:[...new Set(t.files)].slice(0,8)}:{},...t.tools.length>0?{commands:[...new Set(t.tools)].slice(0,8)}:{},semantic:{subject:t.semanticSubject,predicate:t.semanticPredicate,value:t.semanticValue,polarity:t.semanticPolarity}}}function Vr(t){return (t.narrative.trim()||t.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function ol(t){let e=t.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,t.confidence+e))}function rl(t){return t.semanticPolarity==="negative"?"correction":Br(t)==="tool_preference"?"tool_preference":t.source==="explicit_intent"?"memory":"convention"}function il(t,e,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${t}\0project\0${e}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function Wr(t,e,n,o){return `learning-evidence:${createHash("sha256").update(`${t}\0${e}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Ur(t,e,n,o){return createHash("sha256").update(stableLearningJson({candidateId:t,sessionId:e.sessionId,executionId:e.executionId,closureReceipt:e.closureReceipt,projectRevision:e.projectRevision,observationId:n.id,instruction:Vr(n),polarity:o})).digest("hex")}var ie=3e4,dn=1e3,wl=new Set(["git","npm","pnpm","yarn"]);function Jr(t){return {"workflow.worker_start":async({item:e})=>kl(t,e),"workflow.worker_monitor":async({item:e})=>bl(t,e),"workflow.worker_verify":async({item:e})=>Rl(t,e),"workflow.worker_merge":async({item:e})=>Sl(t,e),"workflow.worker_cleanup":async({item:e})=>xl(t,e)}}async function kl(t,e){await Se(t,e,async(n,o)=>{if(o.state==="running"||o.state==="starting"){an(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(t,o.workerId,r,ie);let i=await createManagedWorktree({projectRoot:t,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Yr(o.workerId),a=El(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!d)throw new E("unsupported_worker_host",`Unsupported worker host ${o.host}`);let u=se(o.handoff.actionId,"actionId"),l=n.getHostAction(t,u);if(!l)throw new E("worker_host_action_missing",`Host action ${u} was not found`);l.state==="waiting"&&n.startHostAction({actionId:u,projectRoot:t});let m=launchWorker(d,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,host:o.host==="codex"?"codex":"claude-code",worktreePath:o.worktreePath,taskFile:s.taskFile,handoffFile:s.handoffFile,statusFile:s.statusFile,sessionId:o.sessionId??"worker",executionId:o.executionId??o.workerId,contextReceipt:o.contextReceipt,timeoutMs:30*6e4},s,{onHeartbeat:()=>{let f=openGlobalDevFlowDatabase();try{f.heartbeatWorkflowWorker(t,o.workerId,r,ie);}catch{}finally{f.close();}}});Al(s,{state:"running",pid:m.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+ie}),an(n,o),m.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{an(f,o,Date.now());}finally{f.close();}});});}async function bl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Yr(o.workerId);if(existsSync(r.handoffFile)){let c=readWorkerHandoff(r.handoffFile,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,contextReceipt:o.contextReceipt,worktreePath:o.worktreePath}),d=se(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:t,report:{workerId:o.workerId,handoff:c},evidenceHash:Qr(c)}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"reported",leaseOwner:o.leaseOwner,finalRevision:c.finalRevision,handoff:{...o.handoff,terminalHandoff:c}}),n.enqueueWork({idempotencyKey:`workflow-worker-verify:${o.workerId}:${c.finalRevision}`,kind:"workflow.worker_verify",projectRoot:t,payload:{workerId:o.workerId}});return}let i=Tl(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&Cl(s)){let c=typeof i?.startedAt=="number"?i.startedAt:o.updatedAt;if(Date.now()-c>30*6e4){try{process.kill(s,"SIGTERM");}catch{}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let u=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:u,projectRoot:t,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(t,o.workerId,d,ie),Xr("worker_running",dn)):new E("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:t,report:{reason:"worker_exited_without_handoff"}});});}async function Rl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new E("worker_handoff_missing","Persisted worker handoff is missing");let i=se(o.handoff.actionId,"actionId"),s=n.getHostAction(t,i);if(!s)throw new E("worker_host_action_missing",`Host action ${i} was not found`);let a=Gr(o),c=new GraderRegistry,d=await Kr(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:t,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await Dl(t),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async u=>{let l=await c.run({taskId:o.stepId,taskKind:u.taskKind,projectRoot:u.projectRoot,acceptanceCriteria:[],evidence:u.evidence});return {...l,unavailableBlocking:l.unavailableRequired}}}}));if(!d.passed){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:t,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merge_ready",leaseOwner:o.leaseOwner,finalRevision:d.finalRevision,handoff:{...o.handoff,terminalHandoff:r,verification:d}}),n.enqueueWork({idempotencyKey:`workflow-worker-merge:${o.workerId}:${d.finalRevision}`,kind:"workflow.worker_merge",projectRoot:t,payload:{workerId:o.workerId}});});}async function Sl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new E("worker_verification_missing","Verified merge evidence is missing");let i=se(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(t,i);n.verifyHostAction({actionId:i,projectRoot:t,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Qr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:t,payload:{workerId:o.workerId}});}}),a=await Kr(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:t,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function xl(t,e){await Se(t,e,async(n,o)=>{let r=e.payload,i=await cleanupManagedWorktree({repositoryRoot:t,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Xr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Kr(t,e,n){let o=e.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{t.heartbeatWorkflowWorker(e.projectRoot,e.workerId,o,ie);}catch{}},Math.floor(ie/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Se(t,e,n){let o=Ml(e.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(t,o);if(!i)throw new E("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function El(t){let e=t.handoff.task;if(!e||typeof e!="object"||Array.isArray(e))throw new E("worker_task_missing","Worker task envelope is missing");let n=Gr(t);return {workerId:t.workerId,runId:t.runId,stepId:t.stepId,projectRoot:t.projectRoot,worktreePath:t.worktreePath,baseRevision:t.baseRevision,contextReceipt:t.contextReceipt,retrievalSessionId:t.retrievalSessionId,allowedFiles:t.allowedFiles,requiredTools:[],task:e,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function Gr(t){let e=t.handoff.verificationCommands;if(!Array.isArray(e)||e.length===0)throw new E("verification_contract_missing","Worker verification commands are missing");return e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new E("verification_contract_invalid","Worker verification command is malformed");let o=n;if(typeof o.command!="string"||!wl.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new E("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function Yr(t){let e=workerCoordinationRoot(t,homedir());return {root:e,taskFile:join(e,"task.json"),handoffFile:join(e,"handoff.json"),statusFile:join(e,"status.json"),stdoutFile:join(e,"stdout.log"),stderrFile:join(e,"stderr.log")}}function Al(t,e){writeJsonAtomic(t.statusFile,e);}function Tl(t){try{return JSON.parse(readFileSync$1(t.statusFile,"utf8"))}catch{return null}}function an(t,e,n=Date.now()+dn){t.enqueueWork({idempotencyKey:`workflow-worker-monitor:${e.workerId}:${Math.floor(n/dn)}`,kind:"workflow.worker_monitor",projectRoot:e.projectRoot,payload:{workerId:e.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function Dl(t){let{gitRevision:e}=await import('@devflow-tools/workflow-engine');return e(t,"HEAD")}function Cl(t){try{return process.kill(t,0),!0}catch{return false}}function Xr(t,e){return Object.assign(new Error(t),{category:t,retryAfterMs:e,retryWithoutAttempt:true})}function Ml(t){if(!t||typeof t!="object"||typeof t.workerId!="string")throw new E("invalid_worker_payload","Worker work item requires workerId");return t.workerId}function se(t,e){if(typeof t!="string"||!t.trim())throw new E("worker_identity_missing",`Worker ${e} is missing`);return t}function Qr(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}var jl=new Set(["Write","Edit","NotebookEdit"]);function ni(t){if(!jl.has(t.toolName)||Nl(t.toolResponse))return null;let e=Ll(t.projectRoot,t.toolInput);if(!e)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=$l({projectRoot:t.projectRoot,targetFile:e,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),u=`${o.contextHash}\0${t.toolUseId??e}\0${c.kind}\0${e}`,l=`policy-verification:${createHash("sha256").update(u).digest("hex")}`,m=Date.now();if(!d){let g=`verification_unavailable:${c.kind}`;n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:e,contextReceipt:o.contextHash},reason:g,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind),c.required===!0&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"verification.failed",payload:{receiptId:l,reasonCode:g},dedupeKey:`${l}:unavailable`,producer:"devflow-verification-scheduler"});continue}let f={...d,obligationId:l,sessionId:t.sessionId,executionId:t.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:e,contextReceipt:o.contextHash,required:c.required===!0},createdAt:m,updatedAt:m});let p=n.enqueueWork({idempotencyKey:l,kind:"verification.policy",projectRoot:t.projectRoot,sessionId:t.sessionId,payload:f,maxAttempts:2,nextAttemptAt:m});C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"durable_work.owned",payload:{workId:p.id,obligation:"verification"},dedupeKey:`${p.id}:owned`,producer:"devflow-verification-scheduler"}),i.push(d.display);}return [i.length>0?`DevFlow scheduled policy verification: ${i.join(" && ")}`:"",s.length>0?`Verification unavailable and recorded as unknown: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
34
|
-
`)||null}finally{n.close();}}async function oi(t,e){let n=
|
|
35
|
-
${u.message}`.slice(-32768)});}),o.on("close",u=>{clearTimeout(d),s({exitCode:u,timedOut:c,spawnError:false,output:r});});})}function Ll(t,e){let n=e.file_path??e.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(t,n);return ri(t,o)?relative(t,o).split(sep).join("/"):null}function ri(t,e){let n=isAbsolute(e)?resolve(e):resolve(t,e),o=relative(resolve(t),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function Nl(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error}function ql(t){try{return JSON.parse(readFileSync$1(join(t,"package.json"),"utf8"))}catch{return null}}function Wl(t){return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"bun.lockb"))||existsSync(join(t,"bun.lock"))?"bun":"npm"}function Ul(t){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(e=>existsSync(join(t,e)))}function mn(t,e){return e.find(n=>typeof t[n]=="string"&&t[n].trim())??null}function zl(t,e){let n=e.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${n}${s}`;if(existsSync(join(t,a)))return a}let r=join(t,e.split("/").slice(0,-1).join("/")),i=e.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!i||!existsSync(r))return null;try{return readdirSync$1(r).filter(s=>s.startsWith(`${i}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(t,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function Bl(t,e,n){let o=e.split(sep).join("/"),r=resolve(n,e).split(sep).join("/"),i=t.split(/\r?\n/u).map(s=>s.trim().split(sep).join("/")).filter(s=>s.includes(o)||s.includes(r)).map(s=>s.replace(/:\d+:\d+/gu,":#:#").replace(/\(\d+,\d+\)/gu,"(#,#)")).filter(s=>/\berror\s+TS\d+\b/iu.test(s));return [...new Set(i.map(s=>createHash("sha256").update(s).digest("hex")))]}function Vl(t,e,n){if(!e.executionId)return;let o=t.getSkillExecution(e.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];t.updateSkillExecution(e.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function Jl(t){try{let e=readFileSync$1(join(t,".git","HEAD"),"utf8").trim();return e.startsWith("ref:")?readFileSync$1(join(t,".git",e.slice(5).trim()),"utf8").trim():e}catch{return}}function ei(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Kl(t){return /^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)}async function ci(t){let e=Date.now(),n=au(t.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(t.hostEvent??{session_id:t.sessionId,prompt:t.prompt},{projectRoot:n}),r=semanticTextHash(ai(o.rawPrompt)),i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:t.sessionId,sourceHash:r});if(s){let S=ii(s).identity,b=i.getRuntimeActivation(S.projectRoot,S.sessionId,S.turnId,s.version);if(!b)throw new Error(`RUNTIME_ACTIVATION_MISSING:${s.artifactHash}`);return {artifact:ii(s),memoryIdentity:si(s),activation:b,reused:!0}}let a=`turn:${it(`${t.sessionId}\0${r}`)}`,c=`request:${it(`${n}\0${t.sessionId}\0${a}`)}`,d={projectRoot:n,projectId:`project:${stableRuntimeHash(n).slice(0,20)}`,hostId:o.hostId,sessionId:t.sessionId,executionId:t.sessionId,turnId:a,requestId:c},u=1,l=resolveRuntimeActivationSnapshot({projectRoot:n,createdAt:o.timestamp}),m=iu(o.rawPrompt),f={identity:d,version:u,rawPrompt:o.rawPrompt,normalizedPrompt:ai(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:"unknown",action:"unknown",entities:[],targetAnchors:m,policyConstraints:[],classificationEvidence:[],sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},p={...f,artifactHash:cu(f)};i.appendTaskIntentArtifact(ou(p)),i.bindRuntimeActivation({identity:d,revision:u,snapshot:l});let g=nu(i,p);return h({event:"host.prompt.normalized",identity:d,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:p.command,activeSkill:p.activeSkill,rawPromptBytes:Buffer.byteLength(p.rawPrompt)}}),h({event:"intent.artifact.created",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,targetCount:m.length}}),h({event:"intent.artifact.persisted",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,version:p.version,sourceHash:p.sourceHash,authority:"immutable-intent",captureLatencyMs:Date.now()-e}}),h({event:"terminal.transition.persisted",identity:d,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:g,sourceIntentHash:p.artifactHash}}),{artifact:p,memoryIdentity:si(p),activation:l,reused:!1}}finally{i.close();}}function nu(t,e){let n=t.getLatestTerminalTransition(e.identity.projectRoot,e.identity.sessionId,e.identity.turnId);if(n)return n.receiptId;let o=`terminal:${it(`${e.artifactHash}\0open`)}`;return t.appendTerminalTransition({...e.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:e.sourceHash},createdAt:e.createdAt}),t.appendTerminalTransition({...e.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${it(`${e.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:e.artifactHash},createdAt:Math.max(e.createdAt,Date.now())}).receiptId}function ou(t){return {...t.identity,version:t.version,supersedesHash:t.supersedesHash,rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,command:t.command,slashArgs:t.slashArgs,activeSkill:t.activeSkill,intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence.map(e=>({...e})),sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function ii(t){return {identity:ru(t),version:t.version,...t.supersedesHash?{supersedesHash:t.supersedesHash}:{},rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,...t.command?{command:t.command}:{},slashArgs:t.slashArgs,...t.activeSkill?{activeSkill:t.activeSkill}:{},intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence,sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function ru(t){return {projectRoot:t.projectRoot,projectId:t.projectId,hostId:t.hostId,sessionId:t.sessionId,turnId:t.turnId,requestId:t.requestId,...t.executionId?{executionId:t.executionId}:{}}}function si(t){let e=t.rawPrompt.trim().slice(0,4e3),n="identity"in t?t.identity.turnId:t.turnId;return {turnId:n,eventId:`memory-turn:${n.replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(e).digest("hex"),createdAt:t.createdAt}}function iu(t){let e=t.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return su(e.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function ai(t){return t.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function su(t){return [...new Set(t.filter(Boolean))]}function au(t){let e=resolve(t);try{return realpathSync(e)}catch{return e}}function cu(t){return createHash("sha256").update(yn(t)).digest("hex")}function it(t){return createHash("sha256").update(t).digest("hex").slice(0,24)}function yn(t){if(t===null||typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number")return Number.isFinite(t)?JSON.stringify(t):"null";if(Array.isArray(t))return `[${t.map(yn).join(",")}]`;if(!t||typeof t!="object")return JSON.stringify(String(t));let e=t;return `{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yn(e[n])}`).join(",")}}`}var bu=600*1e3,Ru=2e3,Su=250,xu=2e3,Eu=1e3,mi=1024*1024,Au=2*1024*1024,Tu=6e4,Du=100,Cu={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Mu(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.status=="string"?e.status:void 0;if(!(e.ok===false||e.success===false||e.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!e.error))return;let r=e.error;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return n?`Tool response status: ${n}`:"Tool response reported failure"}function pi(t){return /timeout|timed out|deadline|warming/i.test(t)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(t)?"unavailable":"failed"}function fi(t,e,n,o,r){let i=t.recordDomainActionOutcome;typeof i=="function"&&i.call(t,e,n,o,r);}function Ou(t){switch(t){case "Read":case "Glob":return "file_read";case "Write":case "Edit":case "NotebookEdit":return "file_write";case "Bash":return "bash_command";case "Agent":return "subagent";case "Skill":return "skill_invoke";default:return "tool_use"}}function _n(t){return typeof t=="string"&&t.trim().length>0}function Pu(t,e,n=process.env,o){if(!t.startsWith("mcp__devflow__"))return e;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(_n(r.projectRoot))return r;let i=_n(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return _n(i)&&(r.projectRoot=i),r}var In=class{constructor(e,n){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.hostRuntime=null;this.memoryTurnSpoolTimer=null;this.sessionFinalizeSpoolTimer=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new Z,this.runtimeStore=new H(this.projectRoot),this.serverManager=new Oe(e),this.hookRuntime=Pr(e),this.hookHealth=new nt(e),this.hookHandlers=Fr({handlers:{"pre-tool-use":o=>this.handlePreToolUse(o),"post-tool-use":o=>this.handlePostToolUse(o),"post-tool-use-failure":o=>this.handlePostToolUseFailure(o),stop:o=>this.handleStop(o),"memory-snapshot":()=>this.handleMemorySnapshot(),"session-start":o=>this.handleSessionStart(o),"session-end":o=>this.handleSessionEnd(o),"user-prompt-submit":o=>this.handleUserPromptSubmit(o),"pre-compact":o=>this.handlePreCompact(o)},failurePolicy:o=>en(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new Ze({projectRoot:e,handlers:{...Jr(e),"memory.explicit_commit":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.turn_capture":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.explicit_enrichment":async({item:o})=>{let r=o.payload;if(typeof r?.observationId!="string"||!r.observationId)throw new E("invalid_payload","Explicit enrichment requires observationId");await(await this.getMemoryGate()).enrichExplicitMemoryObservation(r.observationId);},"session.bootstrap":async({item:o})=>{await this.bootstrapSessionWork(o.payload);},"memory.vector_backfill":async()=>{await(await this.getMemoryGate()).backfillObservationVectors({batchSize:32});},"memory.turn_distill":async({item:o})=>{await me({projectRoot:this.projectRoot,sessionId:o.sessionId,trigger:"session_end",memory:await this.getMemoryGate()}),await this.refreshMemorySnapshot("memory_turn_distill");},"context.prefetch":async({item:o})=>{let r=o.payload;if(typeof r.prompt!="string"||typeof r.sessionId!="string"||typeof r.executionId!="string"||typeof r.profileFingerprint!="string"||typeof r.rolloutMode!="string")throw new E("invalid_payload","Context prefetch identity is incomplete");let[{createEngines:i},{projectDiagnosticCodeResult:s},{writeContextPrefetchCache:a}]=await Promise.all([import('@devflow-tools/mcp-server/composition'),import('@devflow-tools/mcp-server/retrieval'),import('@devflow-tools/context-engine')]),c=await i(this.projectRoot);try{let d=await c.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName}),u=s(d,0,{projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,requestId:`prefetch:${r.sessionId}:${r.executionId}`,turnId:`prefetch:${r.sessionId}:${r.executionId}`,host:"claude-code"});if(!a({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},u))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let d of Object.values(c))try{d.close?.();}catch{}}},"verification.policy":async({item:o})=>{await oi(this.projectRoot,o);},"learning.analyze_session":async({item:o})=>{let r=o.payload;if(typeof r.projectRoot!="string"||typeof r.sessionId!="string"||typeof r.closureReceipt!="string"||typeof r.projectRevision!="string"||typeof r.createdAt!="number")throw new E("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=sn({payload:r,evidence:s,database:i,rolloutMode:resolveCapabilityRollout(this.projectRoot).config.learningOverlays});i.insertEvent({kind:"learning_analysis",timestamp:Date.now(),success:!0,metadata:{...r,...a}});}finally{i.close();}},"session.finalize":async({item:o})=>{await this.finalizeSessionWork(o.payload,o.id);},"telemetry.reconcile":async()=>{await this.flushTelemetry();}},afterComplete:({item:o,database:r})=>{let i=o.kind==="memory.explicit_commit"||o.kind==="memory.turn_capture"?"memory":o.kind==="verification.policy"?"verification":null;i&&o.sessionId&&o.turnId&&C({projectRoot:this.projectRoot,sessionId:o.sessionId,turnId:o.turnId,kind:"durable_work.completed",payload:{workId:o.id,obligation:i},dedupeKey:`${o.id}:completed`,producer:"devflow-work-runtime"}),o.sessionId&&this.enqueueLearningAnalysisIfReady(r,o.sessionId);}});}logRuntime(e,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;h({event:e==="warn"||e==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:e,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await $r(this.projectRoot),po(this.projectRoot,process.pid),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),mkdirSync(dirname(this.pidPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),co(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}if(this.server.on("error",e=>{this.logRuntime("error","server_error",{reason:e.message});}),this.logRuntime("info","server_listening",{socketHash:createHash("sha256").update(this.socketPath).digest("hex").slice(0,16)}),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},Tu),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(e=>{this.logRuntime("info","embedding_ready",{source:e.source,cacheRootHash:createHash("sha256").update(e.cacheRoot).digest("hex").slice(0,16)});}).catch(e=>{this.logRuntime("warn","embedding_unavailable",{reason:e.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let e=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:e});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(e){let n="",o=false,r=false,i=0,s=Promise.resolve();e.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},Ru).unref(),d=async u=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(e,u);}catch{}finally{e.destroy();}}};e.on("data",u=>{if(r)return;n+=u;let l=n.split(`
|
|
36
|
-
`);if(n=l.pop()??"",Buffer.byteLength(n,"utf8")>mi){a();return}if(l.length===0)return;let m=0;for(let f of l){let p=Buffer.byteLength(f,"utf8");if(p>mi){a();return}m+=p+1;}if(i+m>
|
|
32
|
+
`)}:a.length>0?{decision:"degrade",unresolved:a,additionalContext:"DevFlow terminal obligations remain unresolved after their one-shot correction budget."}:{decision:"allow",unresolved:[]}}finally{n.close();}}function Yd(t,e){return !!t.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${e}`)}function Xd(t){if(!t)return false;let e=t.normalize("NFKC").replace(/\s+/gu," ");return /(?:未|没有|无法|失败|暂未|尚未).{0,24}(?:记住|记下|记录|保存|持久化|回执)|(?:memory|receipt).{0,24}(?:failed|missing|pending|degraded|not saved)|status=(?:pending|degraded|rejected|failed)/iu.test(e)?false:/(?:已|已经|成功).{0,20}(?:记住|记下|记录|保存|持久化)|跨会话生效|(?:memory|preference).{0,20}(?:saved|remembered|persisted)|status=(?:accepted|committed)/iu.test(e)}function Qd(t,e,n){let o=t.get(e);if(o){for(let r of o.evidenceObligations)n.upsertSessionObligation({obligationId:`evidence:${r.obligationId}`,projectRoot:o.projectRoot,sessionId:e,executionId:o.executionId,kind:"evidence_contract",state:"open",payload:{contract:r.contract,runtimeObligationId:r.obligationId},createdAt:r.promptedAt,updatedAt:o.lastActivityAt});for(let r of o.evidenceOutcomes){let i=`evidence:${r.obligationId}`,s=n.getSessionObligation(o.projectRoot,e,i);if(!s||s.state!=="open"&&!(s.state==="degraded"&&r.status==="resolved"))continue;let a=r.status==="resolved"?`evidence-receipt:${createHash("sha256").update(`${r.obligationId}\0${r.completedAt}\0${r.attempt}`).digest("hex").slice(0,24)}`:void 0;n.resolveSessionObligation({projectRoot:o.projectRoot,sessionId:e,obligationId:i,state:r.status==="resolved"?"satisfied":"degraded",receiptId:a,reason:r.reason,resolvedAt:r.completedAt});}}}var Zd=[/\b(?:rm\s+-rf|sudo|chmod|chown|force\s+push|reset\s+--hard|publish|release|deploy)\b/iu,/\b(?:secret|credential|token|password|security|authentication|authorization)\b/iu,/(?:删除|强制推送|发布|部署|凭据|密钥|安全|权限)/u],el=[/\b(?:migration|upgrade|dependency|dependencies|generated files?|write all|rewrite)\b/iu,/(?:迁移|升级|依赖|生成文件|批量写入)/u];function on(t){let e=`${t.instruction}
|
|
33
|
+
${JSON.stringify(t.trigger)}`,n=[];Zd.some(r=>r.test(e))&&n.push("high_risk_operation"),el.some(r=>r.test(e))&&n.push("broad_or_migrating_change"),t.kind==="correction"&&n.push("user_correction_requires_observation");let o=n.includes("high_risk_operation")?"high":n.includes("broad_or_migrating_change")||t.scope==="global"?"medium":"low";return {risk:o,manualOnly:o==="high"||n.includes("broad_or_migrating_change"),reasons:n}}var tl=new Set(["project_convention","user_preference","decision_made","config_discovery"]);function sn(t){let e=t.payload.executionId?t.database.getSkillExecution(t.payload.executionId):t.database.getLatestSkillExecutionForSession(t.payload.sessionId),n=t.database.listHostActionsForSession(t.payload.projectRoot,t.payload.sessionId,t.payload.executionId),o=n.find(u=>u.state==="verified"),r=n.find(u=>["failed","cancelled","degraded"].includes(u.state)),i=r?"negative":o?"positive":"unknown",s=new Set,a=[],c=0,d=0;for(let u of t.evidence){if(!nl(u)){d+=1;continue}let l=Br(u),m=ol(u,e?.skillName),f=Vr(u),p=sl(t.payload.projectRoot,l,u.facetKey??u.semanticKey??u.id,m),g=t.database.getLearningCandidate(p),R=on({scope:"project",kind:l,instruction:f,trigger:m});t.database.upsertLearningCandidate({id:p,projectRoot:t.payload.projectRoot,scope:"project",kind:l,trigger:m,instruction:f,confidence:rl(u),manualOnly:R.manualOnly,risk:R.risk});g&&g.instruction!==f&&t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"contradicting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,sourceType:"correction",polarity:"contradicting",outcome:i,evidenceHash:Ur(p,t.payload,u,"contradicting"),receipt:t.payload.closureReceipt,payload:{previousInstruction:g.instruction,replacementInstruction:f,projectRevision:t.payload.projectRevision},createdAt:u.createdAt});let b=t.database.addLearningCandidateEvidence({id:Wr(p,t.payload.sessionId,u.id,"supporting"),candidateId:p,projectRoot:t.payload.projectRoot,sessionId:t.payload.sessionId,executionId:t.payload.executionId,memoryObservationId:u.id,outcomeId:o?.id??r?.id,sourceType:il(u),polarity:"supporting",outcome:i,evidenceHash:Ur(p,t.payload,u,"supporting"),receipt:t.payload.closureReceipt,payload:{semanticKey:u.semanticKey,facetKey:u.facetKey,evidenceStatus:u.evidenceStatus,source:u.source,projectRevision:t.payload.projectRevision,executionStatus:e?.status,policyReasons:R.reasons},createdAt:u.createdAt});c+=1,s.add(p),t.rolloutMode!=="off"&&b.state==="candidate"&&b.supportingSessions>=3&&b.successfulOutcomes>=2&&t.database.transitionLearningCandidate(p,{target:"shadow",reason:"evidence_threshold_satisfied"}).state==="shadow"&&a.push(p);}return {considered:t.evidence.length,accepted:c,excluded:d,candidateIds:[...s],promotedToShadow:a}}function nl(t){return !(!tl.has(t.type)||t.source!=="explicit_intent"&&t.source!=="manual"&&t.evidenceStatus!=="verified"||!t.narrative.trim()&&!t.title.trim())}function Br(t){return t.type==="decision_made"?"workflow":t.type==="user_preference"&&(t.semanticValue.startsWith("--")||t.tools.length>0)?"tool_preference":"convention"}function ol(t,e){return {...e?{skills:[e]}:{},...t.entities.length>0?{entities:[...new Set(t.entities)].slice(0,8)}:{},...t.files.length>0?{files:[...new Set(t.files)].slice(0,8)}:{},...t.tools.length>0?{commands:[...new Set(t.tools)].slice(0,8)}:{},semantic:{subject:t.semanticSubject,predicate:t.semanticPredicate,value:t.semanticValue,polarity:t.semanticPolarity}}}function Vr(t){return (t.narrative.trim()||t.title.trim()).replace(/\s+/gu," ").slice(0,1200)}function rl(t){let e=t.source==="explicit_intent"?.08:0;return Math.max(0,Math.min(1,t.confidence+e))}function il(t){return t.semanticPolarity==="negative"?"correction":Br(t)==="tool_preference"?"tool_preference":t.source==="explicit_intent"?"memory":"convention"}function sl(t,e,n,o){let r={...o,semantic:void 0};return `learning:${createHash("sha256").update(`${t}\0project\0${e}\0${n}\0${stableLearningJson(r)}`).digest("hex").slice(0,24)}`}function Wr(t,e,n,o){return `learning-evidence:${createHash("sha256").update(`${t}\0${e}\0${n}\0${o}`).digest("hex").slice(0,24)}`}function Ur(t,e,n,o){return createHash("sha256").update(stableLearningJson({candidateId:t,sessionId:e.sessionId,executionId:e.executionId,closureReceipt:e.closureReceipt,projectRevision:e.projectRevision,observationId:n.id,instruction:Vr(n),polarity:o})).digest("hex")}var ie=3e4,dn=1e3,kl=new Set(["git","npm","pnpm","yarn"]);function Jr(t){return {"workflow.worker_start":async({item:e})=>bl(t,e),"workflow.worker_monitor":async({item:e})=>Rl(t,e),"workflow.worker_verify":async({item:e})=>Sl(t,e),"workflow.worker_merge":async({item:e})=>xl(t,e),"workflow.worker_cleanup":async({item:e})=>El(t,e)}}async function bl(t,e){await Se(t,e,async(n,o)=>{if(o.state==="running"||o.state==="starting"){an(n,o);return}if(o.state!=="planned")return;let r=`worker-plane:${process.pid}`;n.leaseWorkflowWorker(t,o.workerId,r,ie);let i=await createManagedWorktree({projectRoot:t,runId:o.runId,stepId:o.stepId,baseRevision:o.baseRevision,registered:!0});if(i.worktreePath!==o.worktreePath||i.branch!==o.branch){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:r,reason:"managed_worktree_identity_mismatch"});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"starting",leaseOwner:r});let s=Yr(o.workerId),a=Al(o);createWorkerArtifacts(s,a);let d=createDefaultHostAdapterRegistry().list().find(f=>f.id===o.host);if(!d)throw new E("unsupported_worker_host",`Unsupported worker host ${o.host}`);let u=se(o.handoff.actionId,"actionId"),l=n.getHostAction(t,u);if(!l)throw new E("worker_host_action_missing",`Host action ${u} was not found`);l.state==="waiting"&&n.startHostAction({actionId:u,projectRoot:t});let m=launchWorker(d,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,host:o.host==="codex"?"codex":"claude-code",worktreePath:o.worktreePath,taskFile:s.taskFile,handoffFile:s.handoffFile,statusFile:s.statusFile,sessionId:o.sessionId??"worker",executionId:o.executionId??o.workerId,contextReceipt:o.contextReceipt,timeoutMs:30*6e4},s,{onHeartbeat:()=>{let f=openGlobalDevFlowDatabase();try{f.heartbeatWorkflowWorker(t,o.workerId,r,ie);}catch{}finally{f.close();}}});Tl(s,{state:"running",pid:m.child.pid,owner:r,startedAt:Date.now()}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"running",leaseOwner:r,heartbeatAt:Date.now(),leaseExpiresAt:Date.now()+ie}),an(n,o),m.completion.finally(()=>{let f=openGlobalDevFlowDatabase();try{an(f,o,Date.now());}finally{f.close();}});});}async function Rl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="running"&&o.state!=="starting")return;let r=Yr(o.workerId);if(existsSync(r.handoffFile)){let c=readWorkerHandoff(r.handoffFile,{workerId:o.workerId,runId:o.runId,stepId:o.stepId,contextReceipt:o.contextReceipt,worktreePath:o.worktreePath}),d=se(o.handoff.actionId,"actionId");n.reportHostAction({actionId:d,projectRoot:t,report:{workerId:o.workerId,handoff:c},evidenceHash:Qr(c)}),n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"reported",leaseOwner:o.leaseOwner,finalRevision:c.finalRevision,handoff:{...o.handoff,terminalHandoff:c}}),n.enqueueWork({idempotencyKey:`workflow-worker-verify:${o.workerId}:${c.finalRevision}`,kind:"workflow.worker_verify",projectRoot:t,payload:{workerId:o.workerId}});return}let i=Dl(r),s=typeof i?.pid=="number"?i.pid:void 0;if(s&&Ml(s)){let c=typeof i?.startedAt=="number"?i.startedAt:o.updatedAt;if(Date.now()-c>30*6e4){try{process.kill(s,"SIGTERM");}catch{}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_process_timeout"});let u=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:u,projectRoot:t,report:{reason:"worker_process_timeout"}});return}let d=o.leaseOwner??(typeof i?.owner=="string"?i.owner:void 0);throw d?(n.heartbeatWorkflowWorker(t,o.workerId,d,ie),Xr("worker_running",dn)):new E("worker_lease_owner_missing","Worker lease owner is missing")}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"failed",leaseOwner:o.leaseOwner,reason:"worker_exited_without_handoff"});let a=se(o.handoff.actionId,"actionId");n.failHostAction({actionId:a,projectRoot:t,report:{reason:"worker_exited_without_handoff"}});});}async function Sl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="reported")return;n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"verifying",leaseOwner:o.leaseOwner});let r=o.handoff.terminalHandoff;if(!r)throw new E("worker_handoff_missing","Persisted worker handoff is missing");let i=se(o.handoff.actionId,"actionId"),s=n.getHostAction(t,i);if(!s)throw new E("worker_host_action_missing",`Host action ${i} was not found`);let a=Gr(o),c=new GraderRegistry,d=await Kr(n,o,async()=>verifyWorkerOutput({workerId:o.workerId,projectRoot:t,worktreePath:o.worktreePath,baseRevision:o.baseRevision,parentRevision:await Cl(t),contextReceipt:o.contextReceipt,allowedFiles:o.allowedFiles,handoff:r,hostAction:s,verificationCommands:a,graderIds:["receipt_validity","lifecycle_terminal_state","workflow_evidence"],graderRunner:{run:async u=>{let l=await c.run({taskId:o.stepId,taskKind:u.taskKind,projectRoot:u.projectRoot,acceptanceCriteria:[],evidence:u.evidence});return {...l,unavailableBlocking:l.unavailableRequired}}}}));if(!d.passed){n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:d.state,leaseOwner:o.leaseOwner,reason:d.reason}),d.state==="failed"&&n.failHostAction({actionId:i,projectRoot:t,outcome:"failed",report:{...s.report,verification:d},evidenceHash:d.simulationHash});return}n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merge_ready",leaseOwner:o.leaseOwner,finalRevision:d.finalRevision,handoff:{...o.handoff,terminalHandoff:r,verification:d}}),n.enqueueWork({idempotencyKey:`workflow-worker-merge:${o.workerId}:${d.finalRevision}`,kind:"workflow.worker_merge",projectRoot:t,payload:{workerId:o.workerId}});});}async function xl(t,e){await Se(t,e,async(n,o)=>{if(o.state!=="merge_ready")return;let r=o.handoff.verification;if(!r?.passed)throw new E("worker_verification_missing","Verified merge evidence is missing");let i=se(o.handoff.actionId,"actionId"),s=new SerializedWorkerMergeQueue(n,{onMerged:async({mergeCommit:c})=>{n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"merged",leaseOwner:o.leaseOwner,finalRevision:o.finalRevision,reason:`merged:${c}`});let d=n.getHostAction(t,i);n.verifyHostAction({actionId:i,projectRoot:t,report:{...d?.report??{},mergeCommit:c,verification:r},evidenceHash:Qr({mergeCommit:c,verification:r})});},scheduleCleanup:()=>{n.enqueueWork({idempotencyKey:`workflow-worker-cleanup:${o.workerId}:merged`,kind:"workflow.worker_cleanup",projectRoot:t,payload:{workerId:o.workerId}});}}),a=await Kr(n,o,()=>s.enqueueAndMerge({workerId:o.workerId,projectRoot:t,baseRevision:o.baseRevision,verification:r,message:`merge(devflow-worker): ${o.runId}/${o.stepId}`}));a.state==="conflict"&&n.transitionWorkflowWorker({projectRoot:t,workerId:o.workerId,target:"hold",leaseOwner:o.leaseOwner,reason:a.reason??"merge_conflict"});});}async function El(t,e){await Se(t,e,async(n,o)=>{let r=e.payload,i=await cleanupManagedWorktree({repositoryRoot:t,worktreePath:o.worktreePath,branch:o.branch,registered:!0,handoffDurable:!!o.handoff.terminalHandoff||r.operatorApproved===!0});if(!i.cleaned)throw Xr(`cleanup_${i.reason??"refused"}`,3e4)});}async function Kr(t,e,n){let o=e.leaseOwner;if(!o)return n();let r=setInterval(()=>{try{t.heartbeatWorkflowWorker(e.projectRoot,e.workerId,o,ie);}catch{}},Math.floor(ie/3));r.unref();try{return await n()}finally{clearInterval(r);}}async function Se(t,e,n){let o=Ol(e.payload),r=openGlobalDevFlowDatabase();try{let i=r.getWorkflowWorker(t,o);if(!i)throw new E("worker_not_found",`Worker ${o} was not found`);await n(r,i);}finally{r.close();}}function Al(t){let e=t.handoff.task;if(!e||typeof e!="object"||Array.isArray(e))throw new E("worker_task_missing","Worker task envelope is missing");let n=Gr(t);return {workerId:t.workerId,runId:t.runId,stepId:t.stepId,projectRoot:t.projectRoot,worktreePath:t.worktreePath,baseRevision:t.baseRevision,contextReceipt:t.contextReceipt,retrievalSessionId:t.retrievalSessionId,allowedFiles:t.allowedFiles,requiredTools:[],task:e,verification:{commands:n,graders:["receipt_validity","lifecycle_terminal_state","workflow_evidence"]},constraints:{recursiveWorkers:false,maxContextCycles:3}}}function Gr(t){let e=t.handoff.verificationCommands;if(!Array.isArray(e)||e.length===0)throw new E("verification_contract_missing","Worker verification commands are missing");return e.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new E("verification_contract_invalid","Worker verification command is malformed");let o=n;if(typeof o.command!="string"||!kl.has(o.command)||!Array.isArray(o.args)||o.args.some(r=>typeof r!="string"))throw new E("verification_contract_invalid","Worker verification command is not allowlisted");return {command:o.command,args:o.args}})}function Yr(t){let e=workerCoordinationRoot(t,homedir());return {root:e,taskFile:join(e,"task.json"),handoffFile:join(e,"handoff.json"),statusFile:join(e,"status.json"),stdoutFile:join(e,"stdout.log"),stderrFile:join(e,"stderr.log")}}function Tl(t,e){writeJsonAtomic(t.statusFile,e);}function Dl(t){try{return JSON.parse(readFileSync$1(t.statusFile,"utf8"))}catch{return null}}function an(t,e,n=Date.now()+dn){t.enqueueWork({idempotencyKey:`workflow-worker-monitor:${e.workerId}:${Math.floor(n/dn)}`,kind:"workflow.worker_monitor",projectRoot:e.projectRoot,payload:{workerId:e.workerId},nextAttemptAt:n,maxAttempts:1e3});}async function Cl(t){let{gitRevision:e}=await import('@devflow-tools/workflow-engine');return e(t,"HEAD")}function Ml(t){try{return process.kill(t,0),!0}catch{return false}}function Xr(t,e){return Object.assign(new Error(t),{category:t,retryAfterMs:e,retryWithoutAttempt:true})}function Ol(t){if(!t||typeof t!="object"||typeof t.workerId!="string")throw new E("invalid_worker_payload","Worker work item requires workerId");return t.workerId}function se(t,e){if(typeof t!="string"||!t.trim())throw new E("worker_identity_missing",`Worker ${e} is missing`);return t}function Qr(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}var $l=new Set(["Write","Edit","NotebookEdit"]);function ni(t){if(!$l.has(t.toolName)||ql(t.toolResponse))return null;let e=Nl(t.projectRoot,t.toolInput);if(!e)return null;let n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId),r=o?.canonicalAction?.verificationPlan??[];if(!o||r.length===0)return null;let i=[],s=[];for(let c of r){let d=Fl({projectRoot:t.projectRoot,targetFile:e,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),u=`${o.contextHash}\0${t.toolUseId??e}\0${c.kind}\0${e}`,l=`policy-verification:${createHash("sha256").update(u).digest("hex")}`,m=Date.now();if(!d){let g=`verification_unavailable:${c.kind}`;n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:e,contextReceipt:o.contextHash},reason:g,createdAt:m,updatedAt:m,resolvedAt:m}),s.push(c.kind),c.required===!0&&C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"verification.failed",payload:{receiptId:l,reasonCode:g},dedupeKey:`${l}:unavailable`,producer:"devflow-verification-scheduler"});continue}let f={...d,obligationId:l,sessionId:t.sessionId,executionId:t.executionId,requestId:o.requestId};n.upsertSessionObligation({obligationId:l,projectRoot:t.projectRoot,sessionId:t.sessionId,executionId:t.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:d.display,targetFile:e,contextReceipt:o.contextHash,required:c.required===!0},createdAt:m,updatedAt:m});let p=n.enqueueWork({idempotencyKey:l,kind:"verification.policy",projectRoot:t.projectRoot,sessionId:t.sessionId,payload:f,maxAttempts:2,nextAttemptAt:m});C({projectRoot:t.projectRoot,sessionId:t.sessionId,requestId:o.requestId,executionId:t.executionId,kind:"durable_work.owned",payload:{workId:p.id,obligation:"verification"},dedupeKey:`${p.id}:owned`,producer:"devflow-verification-scheduler"}),i.push(d.display);}return [i.length>0?`DevFlow scheduled policy verification: ${i.join(" && ")}`:"",s.length>0?`Verification unavailable and recorded as unknown: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
34
|
+
`)||null}finally{n.close();}}async function oi(t,e){let n=Hl(t,e.payload),o=await Ll(n,t),r=n.kind==="typecheck"?Vl(o.output,n.targetFile,t):[],i=ei({command:n.command,args:n.args}),s=openGlobalDevFlowDatabase();try{let a=Kl(t),c=n.kind==="typecheck"?s.getPolicyVerificationBaseline(t,n.kind,i):null,d=c&&c.sourceRevision===a?c:null,u=d?r.filter(k=>!d.diagnosticHashes.includes(k)):[],l;o.spawnError||/could not determine executable|command not found|not recognized as an internal|ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL/iu.test(o.output)?l="unavailable":o.timedOut?l="unknown":o.exitCode===0?l="passed":n.kind==="typecheck"&&!d?l="unknown":n.kind==="typecheck"&&u.length===0?l="passed":l="failed";let m=createHash("sha256").update(o.output).digest("hex"),f=`verification-receipt:${ei({obligationId:n.obligationId,commandHash:i,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introduced:u,status:l})}`,p={status:l,kind:n.kind,command:n.display,exitCode:o.exitCode,timedOut:o.timedOut,outputHash:m,diagnosticHashes:r,introducedDiagnosticHashes:u,baselineAvailable:d!==null,receiptId:f},g=s.getWorkByIdempotencyKey(n.obligationId)?.id,R=s.getSessionObligation(t,n.sessionId,n.obligationId);if(R?.state==="open"&&(s.upsertSessionObligation({...R,payload:{...R.payload,status:l,outcome:p},updatedAt:Date.now()}),l!=="failed"&&s.resolveSessionObligation({projectRoot:t,sessionId:n.sessionId,obligationId:n.obligationId,state:l==="passed"?"satisfied":"degraded",receiptId:f,reason:l==="unknown"?"verification_result_unknown":l==="unavailable"?"verification_command_unavailable":void 0})),n.kind==="typecheck"&&o.exitCode===0&&s.upsertPolicyVerificationBaseline({projectRoot:t,kind:n.kind,commandHash:i,diagnosticHashes:[],sourceRevision:a,updatedAt:Date.now()}),Jl(s,n,p),C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:l==="passed"?"verification.succeeded":"verification.failed",payload:{receiptId:f,reasonCode:`verification_${l}`,verificationKind:n.kind},dedupeKey:f,producer:"devflow-verification-worker"}),g&&l!=="failed"&&C({projectRoot:t,sessionId:n.sessionId,requestId:n.requestId,executionId:n.executionId,kind:"durable_work.completed",payload:{workId:g,obligation:"verification"},dedupeKey:`${g}:completed`,producer:"devflow-verification-worker"}),l==="failed"){let k=new Error(`Policy verification failed: ${n.display}`);throw k.category="policy_verification_failed",k}return p}finally{s.close();}}function Fl(t){let e=Wl(t.projectRoot),n=Ul(t.projectRoot),o=e?.scripts??{},r={...e?.dependencies,...e?.devDependencies},i=null;if(t.kind==="formatter"&&(r.prettier||zl(t.projectRoot)))i=ot(n,"prettier",[t.mode==="write"?"--write":"--check",t.targetFile],6e4);else if(t.kind==="typecheck"){let s=mn(o,["typecheck","type-check","check:types"]);s?i=ln(n,s,12e4):r.typescript&&existsSync(join(t.projectRoot,"tsconfig.json"))&&(i=ot(n,"tsc",["--noEmit","--pretty","false"],12e4));}else if(t.kind==="lint"){let s=mn(o,["lint"]);s&&(i=ln(n,s,12e4));}else if(t.kind==="test"){let s=Bl(t.projectRoot,t.targetFile);s&&r.vitest?i=ot(n,"vitest",["run",s],12e4):s&&(r.jest||r["@jest/core"])&&(i=ot(n,"jest",["--runTestsByPath",s],12e4));}else if(t.kind==="build"){let s=mn(o,["build"]);s&&(i=ln(n,s,18e4));}else t.kind==="generated_files"&&(i={command:"git",args:["diff","--check","--",t.targetFile],timeoutMs:3e4});return i?{kind:t.kind,...i,display:[i.command,...i.args].map(Gl).join(" "),required:t.required,targetFile:t.targetFile,contextReceipt:t.contextReceipt}:null}function ln(t,e,n){return t==="yarn"?{command:"yarn",args:["run",e],timeoutMs:n}:t==="pnpm"?{command:"pnpm",args:["run",e],timeoutMs:n}:t==="bun"?{command:"bun",args:["run",e],timeoutMs:n}:{command:"npm",args:["run",e],timeoutMs:n}}function ot(t,e,n,o){return t==="pnpm"?{command:"pnpm",args:["exec",e,...n],timeoutMs:o}:t==="yarn"?{command:"yarn",args:[e,...n],timeoutMs:o}:t==="bun"?{command:"bunx",args:[e,...n],timeoutMs:o}:{command:"npx",args:["--no-install",e,...n],timeoutMs:o}}function Hl(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw un();let n=e,o=new Set(["npm","npx","pnpm","yarn","bun","bunx","git"]);if(!n.command||!o.has(n.command)||!Array.isArray(n.args)||!n.args.every(r=>typeof r=="string")||!n.obligationId||!n.sessionId||!n.kind||!n.targetFile||!n.contextReceipt||!n.display||!Number.isFinite(n.timeoutMs)||!ri(t,n.targetFile))throw un();return n}function un(){let t=new Error("Policy verification work payload is invalid");return t.category="invalid_payload",t}function Ll(t,e){return new Promise(n=>{let o=spawn(t.command,t.args,{cwd:e,shell:false,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),r="",i=false,s=u=>{i||(i=true,n(u));},a=u=>{r=(r+String(u)).slice(-32768);};o.stdout.on("data",a),o.stderr.on("data",a);let c=false,d=setTimeout(()=>{c=true,o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),1e3).unref();},t.timeoutMs);o.on("error",u=>{clearTimeout(d),s({exitCode:null,timedOut:false,spawnError:true,output:`${r}
|
|
35
|
+
${u.message}`.slice(-32768)});}),o.on("close",u=>{clearTimeout(d),s({exitCode:u,timedOut:c,spawnError:false,output:r});});})}function Nl(t,e){let n=e.file_path??e.notebook_path;if(typeof n!="string"||!n.trim())return null;let o=isAbsolute(n)?resolve(n):resolve(t,n);return ri(t,o)?relative(t,o).split(sep).join("/"):null}function ri(t,e){let n=isAbsolute(e)?resolve(e):resolve(t,e),o=relative(resolve(t),n);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function ql(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.ok===false||e.success===false||e.isError===true||!!e.error}function Wl(t){try{return JSON.parse(readFileSync$1(join(t,"package.json"),"utf8"))}catch{return null}}function Ul(t){return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"bun.lockb"))||existsSync(join(t,"bun.lock"))?"bun":"npm"}function zl(t){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(e=>existsSync(join(t,e)))}function mn(t,e){return e.find(n=>typeof t[n]=="string"&&t[n].trim())??null}function Bl(t,e){let n=e.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${n}${s}`;if(existsSync(join(t,a)))return a}let r=join(t,e.split("/").slice(0,-1).join("/")),i=e.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!i||!existsSync(r))return null;try{return readdirSync$1(r).filter(s=>s.startsWith(`${i}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(t,join(r,s)).split(sep).join("/"))[0]??null}catch{return null}}function Vl(t,e,n){let o=e.split(sep).join("/"),r=resolve(n,e).split(sep).join("/"),i=t.split(/\r?\n/u).map(s=>s.trim().split(sep).join("/")).filter(s=>s.includes(o)||s.includes(r)).map(s=>s.replace(/:\d+:\d+/gu,":#:#").replace(/\(\d+,\d+\)/gu,"(#,#)")).filter(s=>/\berror\s+TS\d+\b/iu.test(s));return [...new Set(i.map(s=>createHash("sha256").update(s).digest("hex")))]}function Jl(t,e,n){if(!e.executionId)return;let o=t.getSkillExecution(e.executionId);if(!o)return;let r=o.metadata&&typeof o.metadata=="object"?o.metadata:{},i=Array.isArray(r.policyVerificationOutcomes)?r.policyVerificationOutcomes:[];t.updateSkillExecution(e.executionId,{metadata:{...r,policyVerificationOutcomes:[...i,n]}});}function Kl(t){try{let e=readFileSync$1(join(t,".git","HEAD"),"utf8").trim();return e.startsWith("ref:")?readFileSync$1(join(t,".git",e.slice(5).trim()),"utf8").trim():e}catch{return}}function ei(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Gl(t){return /^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)}async function ci(t){let e=Date.now(),n=cu(t.projectRoot),o=claudeCodeRuntimeAdapter.normalizePrompt(t.hostEvent??{session_id:t.sessionId,prompt:t.prompt},{projectRoot:n}),r=semanticTextHash(ai(o.rawPrompt)),i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100});try{let s=i.getTaskIntentArtifactBySource({projectRoot:n,sessionId:t.sessionId,sourceHash:r});if(s){let R=ii(s).identity,k=i.getRuntimeActivation(R.projectRoot,R.sessionId,R.turnId,s.version);if(!k)throw new Error(`RUNTIME_ACTIVATION_MISSING:${s.artifactHash}`);return {artifact:ii(s),memoryIdentity:si(s),activation:k,reused:!0}}let a=`turn:${it(`${t.sessionId}\0${r}`)}`,c=`request:${it(`${n}\0${t.sessionId}\0${a}`)}`,d={projectRoot:n,projectId:`project:${stableRuntimeHash(n).slice(0,20)}`,hostId:o.hostId,sessionId:t.sessionId,executionId:t.sessionId,turnId:a,requestId:c},u=1,l=resolveRuntimeActivationSnapshot({projectRoot:n,createdAt:o.timestamp}),m=su(o.rawPrompt),f={identity:d,version:u,rawPrompt:o.rawPrompt,normalizedPrompt:ai(o.rawPrompt),...o.command?{command:o.command}:{},slashArgs:o.slashArgs,...o.activeSkill?{activeSkill:o.activeSkill}:{},intent:"unknown",action:"unknown",entities:[],targetAnchors:m,policyConstraints:[],classificationEvidence:[],sourceEventIds:[o.sourceEventId??`host-event:${r.slice(0,24)}`],sourceHash:r,createdAt:o.timestamp},p={...f,artifactHash:du(f)};i.appendTaskIntentArtifact(ru(p)),i.bindRuntimeActivation({identity:d,revision:u,snapshot:l});let g=ou(i,p);return h({event:"host.prompt.normalized",identity:d,level:"info",timestamp:Date.now(),data:{sourceHash:r,command:p.command,activeSkill:p.activeSkill,rawPromptBytes:Buffer.byteLength(p.rawPrompt)}}),h({event:"intent.artifact.created",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,targetCount:m.length}}),h({event:"intent.artifact.persisted",identity:d,level:"info",timestamp:Date.now(),data:{artifactHash:p.artifactHash,version:p.version,sourceHash:p.sourceHash,authority:"immutable-intent",captureLatencyMs:Date.now()-e}}),h({event:"terminal.transition.persisted",identity:d,level:"info",timestamp:Date.now(),data:{state:"intent_bound",receiptId:g,sourceIntentHash:p.artifactHash}}),{artifact:p,memoryIdentity:si(p),activation:l,reused:!1}}finally{i.close();}}function ou(t,e){let n=t.getLatestTerminalTransition(e.identity.projectRoot,e.identity.sessionId,e.identity.turnId);if(n)return n.receiptId;let o=`terminal:${it(`${e.artifactHash}\0open`)}`;return t.appendTerminalTransition({...e.identity,sequence:1,toState:"open",receiptId:o,reason:"host_prompt_accepted",payload:{sourceHash:e.sourceHash},createdAt:e.createdAt}),t.appendTerminalTransition({...e.identity,sequence:2,fromState:"open",toState:"intent_bound",receiptId:`terminal:${it(`${e.artifactHash}\0intent_bound`)}`,sourceReceiptId:o,reason:"immutable_intent_persisted",payload:{intentArtifactHash:e.artifactHash},createdAt:Math.max(e.createdAt,Date.now())}).receiptId}function ru(t){return {...t.identity,version:t.version,supersedesHash:t.supersedesHash,rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,command:t.command,slashArgs:t.slashArgs,activeSkill:t.activeSkill,intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence.map(e=>({...e})),sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function ii(t){return {identity:iu(t),version:t.version,...t.supersedesHash?{supersedesHash:t.supersedesHash}:{},rawPrompt:t.rawPrompt,normalizedPrompt:t.normalizedPrompt,...t.command?{command:t.command}:{},slashArgs:t.slashArgs,...t.activeSkill?{activeSkill:t.activeSkill}:{},intent:t.intent,action:t.action,entities:t.entities,targetAnchors:t.targetAnchors,policyConstraints:t.policyConstraints,classificationEvidence:t.classificationEvidence,sourceEventIds:t.sourceEventIds,sourceHash:t.sourceHash,artifactHash:t.artifactHash,createdAt:t.createdAt}}function iu(t){return {projectRoot:t.projectRoot,projectId:t.projectId,hostId:t.hostId,sessionId:t.sessionId,turnId:t.turnId,requestId:t.requestId,...t.executionId?{executionId:t.executionId}:{}}}function si(t){let e=t.rawPrompt.trim().slice(0,4e3),n="identity"in t?t.identity.turnId:t.turnId;return {turnId:n,eventId:`memory-turn:${n.replace(/^turn:/u,"")}`,promptHash:createHash("sha256").update(e).digest("hex"),createdAt:t.createdAt}}function su(t){let e=t.match(/(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_@.-]+\/)+[A-Za-z0-9_@.-]+(?:\.[A-Za-z0-9]+)?)/gu)??[];return au(e.map(n=>n.trim().replace(/^[`'"(]+|[`'"),.;:,。;:]+$/gu,"")).filter(n=>!n.startsWith("/")||/\.[A-Za-z0-9]+$/u.test(n))).slice(0,16)}function ai(t){return t.normalize("NFKC").replace(/\s+/gu," ").trim().slice(0,4e3)}function au(t){return [...new Set(t.filter(Boolean))]}function cu(t){let e=resolve(t);try{return realpathSync(e)}catch{return e}}function du(t){return createHash("sha256").update(yn(t)).digest("hex")}function it(t){return createHash("sha256").update(t).digest("hex").slice(0,24)}function yn(t){if(t===null||typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number")return Number.isFinite(t)?JSON.stringify(t):"null";if(Array.isArray(t))return `[${t.map(yn).join(",")}]`;if(!t||typeof t!="object")return JSON.stringify(String(t));let e=t;return `{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yn(e[n])}`).join(",")}}`}var Ru=600*1e3,Su=2e3,xu=250,Eu=2e3,Au=1e3,mi=1024*1024,Tu=2*1024*1024,Du=6e4,Cu=100,Mu={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Ou(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.status=="string"?e.status:void 0;if(!(e.ok===false||e.success===false||e.isError===true||n==="failed"||n==="rejected"||n==="unavailable"||n==="warming"||!!e.error))return;let r=e.error;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return n?`Tool response status: ${n}`:"Tool response reported failure"}function pi(t){return /timeout|timed out|deadline|warming/i.test(t)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(t)?"unavailable":"failed"}function fi(t,e,n,o,r){let i=t.recordDomainActionOutcome;typeof i=="function"&&i.call(t,e,n,o,r);}function Pu(t){switch(t){case "Read":case "Glob":return "file_read";case "Write":case "Edit":case "NotebookEdit":return "file_write";case "Bash":return "bash_command";case "Agent":return "subagent";case "Skill":return "skill_invoke";default:return "tool_use"}}function _n(t){return typeof t=="string"&&t.trim().length>0}function ju(t,e,n=process.env,o){if(!t.startsWith("mcp__devflow__"))return e;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(_n(r.projectRoot))return r;let i=_n(n.CLAUDE_PROJECT_DIR)?n.CLAUDE_PROJECT_DIR:o;return _n(i)&&(r.projectRoot=i),r}var In=class{constructor(e,n){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.hostRuntime=null;this.memoryTurnSpoolTimer=null;this.sessionFinalizeSpoolTimer=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new Z,this.runtimeStore=new H(this.projectRoot),this.serverManager=new Oe(e),this.hookRuntime=Pr(e),this.hookHealth=new nt(e),this.hookHandlers=Fr({handlers:{"pre-tool-use":o=>this.handlePreToolUse(o),"post-tool-use":o=>this.handlePostToolUse(o),"post-tool-use-failure":o=>this.handlePostToolUseFailure(o),stop:o=>this.handleStop(o),"memory-snapshot":()=>this.handleMemorySnapshot(),"session-start":o=>this.handleSessionStart(o),"session-end":o=>this.handleSessionEnd(o),"user-prompt-submit":o=>this.handleUserPromptSubmit(o),"pre-compact":o=>this.handlePreCompact(o)},failurePolicy:o=>en(o,this.hookRuntime,this.hostRuntime??{hostId:"unresolved",capabilities:new Map,profiles:new Set(["minimal","standard","strict"])}).policy}),this.initialSessionInput=n,this.workRuntime=new Ze({projectRoot:e,handlers:{...Jr(e),"memory.explicit_commit":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.turn_capture":async({item:o})=>{await this.persistMemoryTurnItem(o.payload);},"memory.explicit_enrichment":async({item:o})=>{let r=o.payload;if(typeof r?.observationId!="string"||!r.observationId)throw new E("invalid_payload","Explicit enrichment requires observationId");await(await this.getMemoryGate()).enrichExplicitMemoryObservation(r.observationId);},"session.bootstrap":async({item:o})=>{await this.bootstrapSessionWork(o.payload);},"memory.vector_backfill":async()=>{await(await this.getMemoryGate()).backfillObservationVectors({batchSize:32});},"memory.turn_distill":async({item:o})=>{await me({projectRoot:this.projectRoot,sessionId:o.sessionId,trigger:"session_end",memory:await this.getMemoryGate()}),await this.refreshMemorySnapshot("memory_turn_distill");},"context.prefetch":async({item:o})=>{let r=o.payload;if(typeof r.prompt!="string"||typeof r.sessionId!="string"||typeof r.executionId!="string"||typeof r.profileFingerprint!="string"||typeof r.rolloutMode!="string")throw new E("invalid_payload","Context prefetch identity is incomplete");let[{createEngines:i},{projectDiagnosticCodeResult:s},{writeContextPrefetchCache:a}]=await Promise.all([import('@devflow-tools/mcp-server/composition'),import('@devflow-tools/mcp-server/retrieval'),import('@devflow-tools/context-engine')]),c=await i(this.projectRoot);try{let d=await c.context.buildTaskContext(r.prompt,{mode:"fast",sessionId:r.sessionId,executionId:r.executionId,activeSkill:r.skillName}),u=s(d,0,{projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,requestId:`prefetch:${r.sessionId}:${r.executionId}`,turnId:`prefetch:${r.sessionId}:${r.executionId}`,host:"claude-code"});if(!a({projectRoot:this.projectRoot,query:r.prompt,sessionId:r.sessionId,executionId:r.executionId,profileFingerprint:r.profileFingerprint,rolloutMode:r.rolloutMode,retrievalVersion:r.retrievalVersion},u))throw new Error("Context prefetch envelope was not receipt-valid")}finally{for(let d of Object.values(c))try{d.close?.();}catch{}}},"verification.policy":async({item:o})=>{await oi(this.projectRoot,o);},"learning.analyze_session":async({item:o})=>{let r=o.payload;if(typeof r.projectRoot!="string"||typeof r.sessionId!="string"||typeof r.closureReceipt!="string"||typeof r.projectRevision!="string"||typeof r.createdAt!="number")throw new E("invalid_payload","Learning analysis identity is incomplete");let i=openGlobalDevFlowDatabase();try{let s=await(await this.getMemoryGate()).listLearningEvidence(r.sessionId),a=sn({payload:r,evidence:s,database:i,rolloutMode:resolveCapabilityRollout(this.projectRoot).config.learningOverlays});i.insertEvent({kind:"learning_analysis",timestamp:Date.now(),success:!0,metadata:{...r,...a}});}finally{i.close();}},"session.finalize":async({item:o})=>{await this.finalizeSessionWork(o.payload,o.id);},"telemetry.reconcile":async()=>{await this.flushTelemetry();}},afterComplete:({item:o,database:r})=>{let i=o.kind==="memory.explicit_commit"||o.kind==="memory.turn_capture"?"memory":o.kind==="verification.policy"?"verification":null;i&&o.sessionId&&o.turnId&&C({projectRoot:this.projectRoot,sessionId:o.sessionId,turnId:o.turnId,kind:"durable_work.completed",payload:{workId:o.id,obligation:i},dedupeKey:`${o.id}:completed`,producer:"devflow-work-runtime"}),o.sessionId&&this.enqueueLearningAnalysisIfReady(r,o.sessionId);}});}logRuntime(e,n,o={},r){let i=r?this.runtimeStore.get(r):void 0;h({event:e==="warn"||e==="error"?"hook.runtime.degraded":"hook.runtime.completed",identity:{projectRoot:this.projectRoot,sessionId:r,executionId:i?.executionId},level:e,timestamp:Date.now(),data:{stage:n,...o}});}async start(){this.hostRuntime=await $r(this.projectRoot),po(this.projectRoot,process.pid),mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),mkdirSync(dirname(this.pidPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),co(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}if(this.server.on("error",e=>{this.logRuntime("error","server_error",{reason:e.message});}),this.logRuntime("info","server_listening",{socketHash:createHash("sha256").update(this.socketPath).digest("hex").slice(0,16)}),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},Du),this.telemetryFlushTimer.unref(),prepareEmbeddingModel().then(e=>{this.logRuntime("info","embedding_ready",{source:e.source,cacheRootHash:createHash("sha256").update(e.cacheRoot).digest("hex").slice(0,16)});}).catch(e=>{this.logRuntime("warn","embedding_unavailable",{reason:e.message,fallback:"lexical_retrieval"});}),this.workRuntime.start(),this.initialSessionInput){let e=this.initialSessionInput;this.initialSessionInput=void 0,this.handleRequest({type:"session-start",input:e});}this.drainSessionStartSpool(),this.scheduleMemoryTurnSpoolDrain(0),this.scheduleSessionFinalizeSpoolDrain(0),this.resetIdleTimer();}handleConnection(e){let n="",o=false,r=false,i=0,s=Promise.resolve();e.setEncoding("utf8");let a=()=>{r||(r=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},Su).unref(),d=async u=>{if(!r){r=true,clearTimeout(c);try{await this.writeFrame(e,u);}catch{}finally{e.destroy();}}};e.on("data",u=>{if(r)return;n+=u;let l=n.split(`
|
|
36
|
+
`);if(n=l.pop()??"",Buffer.byteLength(n,"utf8")>mi){a();return}if(l.length===0)return;let m=0;for(let f of l){let p=Buffer.byteLength(f,"utf8");if(p>mi){a();return}m+=p+1;}if(i+m>Tu){a();return}i+=m,s=s.then(async()=>{for(let f of l){if(r)return;if(!o){let p;try{p=JSON.parse(f);}catch{await d({error:"handshake_invalid"});return}if(p?.type!=="hello"||typeof p.rootPath!="string"){await d({error:"handshake_invalid"});return}if(p.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}o=true,clearTimeout(c),this.resetIdleTimer();continue}if(f.trim())try{let p=JSON.parse(f),g=await this.handleRequest(p);g!==null&&!r&&await this.writeFrame(e,g);}catch(p){r||await this.writeFrame(e,{error:p.message});}}}).catch(()=>{a();}).finally(()=>{i-=m;});}),e.on("close",()=>clearTimeout(c)),e.on("error",()=>{});}writeFrame(e,n){return new Promise((o,r)=>{if(e.destroyed||!e.writable){r(new Error("Socket is not writable"));return}let i=false,s=true,a=false,c=setTimeout(()=>{e.destroy(),u(new Error("Timed out writing daemon response"));},Au),d=()=>{clearTimeout(c),e.off("close",l),e.off("error",m),e.off("drain",f);},u=g=>{a||!g&&(!i||!s)||(a=true,d(),g?r(g):o());},l=()=>u(new Error("Socket closed during write")),m=g=>u(g),f=()=>{s=true,u();};e.once("close",l),e.once("error",m),e.write(`${JSON.stringify(n)}
|
|
37
37
|
`,g=>{if(g){u(g);return}i=true,u();})||(s=false,e.once("drain",f));})}async cleanStaleStartupResources(){let e=this.getPathIdentity(this.socketPath);if(e){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,e,"stale socket");}let n=this.getPathIdentity(this.pidPath);n&&this.removePathIfOwned(this.pidPath,n,"stale PID file");}getPathIdentity(e){try{let n=lstatSync(e);return {dev:n.dev,ino:n.ino}}catch(n){if(n.code==="ENOENT")return null;throw n}}pathMatchesIdentity(e,n){if(!n)return false;try{let o=this.getPathIdentity(e);return o?.dev===n.dev&&o.ino===n.ino}catch(o){return this.logRuntime("warn","path_ownership_check",{reason:o.message}),false}}writePidFile(){let e=openSync(this.pidPath,"wx",384);try{writeFileSync(e,`${process.pid}
|
|
38
|
-
`);let n=fstatSync(e);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(e);}}removePathIfOwned(e,n,o,r){try{return !this.pathMatchesIdentity(e,n)||r!==void 0&&readFileSync(e,"utf8")!==r||!this.pathMatchesIdentity(e,n)?!1:(unlinkSync(e),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((e,n)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),n(new Error(`Timed out probing daemon socket ${this.socketPath}`));},
|
|
39
|
-
${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(p.hookSpecificOutput.updatedInput=n.tool_input);let g={...n.tool_input};delete g._devflow_session_id,delete g._devflow_execution_id,delete g._devflow_tool_use_id;let
|
|
38
|
+
`);let n=fstatSync(e);this.pidIdentity={dev:n.dev,ino:n.ino};}finally{closeSync(e);}}removePathIfOwned(e,n,o,r){try{return !this.pathMatchesIdentity(e,n)||r!==void 0&&readFileSync(e,"utf8")!==r||!this.pathMatchesIdentity(e,n)?!1:(unlinkSync(e),!0)}catch(i){return i.code!=="ENOENT"&&this.logRuntime("warn","owned_path_cleanup",{label:o,reason:i.message}),false}}isSocketAcceptingConnections(){return new Promise((e,n)=>{let o=createConnection(this.socketPath),r=setTimeout(()=>{o.destroy(),n(new Error(`Timed out probing daemon socket ${this.socketPath}`));},xu),i=s=>{clearTimeout(r),o.destroy(),e(s);};o.once("connect",()=>i(true)),o.once("error",s=>{let a=s.code;a==="ENOENT"||a==="ECONNREFUSED"?i(false):(clearTimeout(r),n(s));});})}listen(){return new Promise((e,n)=>{let o=this.server;if(!o){n(new Error("Daemon server is not initialized"));return}let r=s=>{o.off("listening",i),n(s);},i=()=>{o.off("error",r);try{let s=this.getPathIdentity(this.socketPath);if(!s)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=s,e();}catch(s){n(s);}};o.once("error",r),o.once("listening",i),o.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!(this.activeSessionIds.size>0)&&(this.idleTimer=setTimeout(()=>{let e=openGlobalDevFlowDatabase();try{if(e.listWorkflowWorkers(this.projectRoot,{states:["leased","starting","running","reported","verifying","merge_ready"],limit:1}).length>0){this.logRuntime("debug","idle_timeout_deferred",{reason:"active_workflow_worker"}),this.resetIdleTimer();return}}finally{e.close();}this.logRuntime("info","idle_timeout_exit"),this.shutdown();},Ru).unref());}async handleRequest(e){let n=this.hostRuntime,o=$u(e.input);if(!n)return this.hookFailureResponse(e.type,{enabled:false,policy:"fail_open",reason:"host_adapter_not_ready",fallback:"host_event_continues_without_devflow_handler"});let r=en(e.type,this.hookRuntime,n);if(!r.enabled)return this.hookFailureResponse(e.type,r);let i=Date.now();try{let s=Lr(e.type,await Hr({registry:this.hookHandlers,requestType:e.type,rawInput:e.input??"",acknowledgementBudgetMs:this.hookRuntime.acknowledgementBudgetMs,projectRoot:this.projectRoot})),a="status"in s&&s.status==="degraded";if(a){let c="reason"in s?String(s.reason):"handler_degraded";this.hookHealth.recordFailure(e.type,n.hostId,"degraded",c);}else this.hookHealth.recordSuccess(e.type,n.hostId);return Q("hook_handler_outcome",{success:!a,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,degraded:a},Date.now()-i),this.logRuntime(a?"warn":"info","handler_outcome",{handler:e.type,host:n.hostId,degraded:a,durationMs:Date.now()-i,..."reason"in s&&s.reason?{reason:String(s.reason)}:{}},o),s}catch(s){let a=Nr(s);return this.hookHealth.recordFailure(e.type,n.hostId,a.category,a.reason),Q("hook_handler_outcome",{success:false,projectRoot:this.projectRoot,host:n.hostId,handler:e.type,category:a.category,reason:a.reason},Date.now()-i),this.logRuntime("error","handler_outcome",{handler:e.type,host:n.hostId,category:a.category,reason:a.reason,durationMs:Date.now()-i},o),this.hookFailureResponse(e.type,r,s)}}async drainSessionStartSpool(){for(;;){let e=kr(this.projectRoot);if(!e)return;try{let n=await this.handleRequest({type:"session-start",input:e.input});if(n&&"status"in n&&n.status==="degraded")throw new Error(`session_start_degraded:${String(n.reason??"unknown")}`);br(e),this.logRuntime("info","session_start_spool_accepted",{receiptId:e.receiptId});}catch(n){Rr(e),this.logRuntime("warn","session_start_spool_deferred",{reason:n.message,fallback:"durable_spool"});return}}}hookFailureResponse(e,n,o){let r=o instanceof Error?o.message:n.reason??"hook_handler_unavailable",i=n.fallback??(n.policy==="enqueue_and_open"?"durable_background_processing":"host_event_continues");return e==="pre-tool-use"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:n.policy==="fail_closed"?"deny":"allow",permissionDecisionReason:r,additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}.`}}:e==="user-prompt-submit"?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",additionalContext:`DevFlow hook degraded: ${r}; fallback=${i}. Do not claim unreceipted work completed.`}}:{status:"degraded",reason:r,fallback:i}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let n=JSON.parse(e);n.tool_input=ju(n.tool_name,n.tool_input,process.env,this.projectRoot);let o=this.trackSession(n.session_id),r="";if(n.tool_name==="Skill"){let T=n.tool_input?.skill,x=T?ze(T):null;x&&(r=this.startSkillExecution(o,x));}let i=this.runtimeStore.get(o);n.tool_name==="mcp__devflow__get_project_context"&&this.runtimeStore.beginContextInitialization(o,n.tool_use_id),n.tool_name.startsWith("mcp__devflow__")&&(n.tool_input._devflow_session_id=o,n.tool_input._devflow_execution_id=i?.executionId??o,i?.activeTurnId&&(n.tool_input._devflow_turn_id=i.activeTurnId),i?.activeRequestId&&(n.tool_input._devflow_request_id=i.activeRequestId),i?.intentArtifactHash&&(n.tool_input._devflow_intent_artifact_hash=i.intentArtifactHash),i?.skillName&&(n.tool_input._devflow_active_skill=i.skillName),n.tool_use_id&&(n.tool_input._devflow_tool_use_id=n.tool_use_id));let s=n.tool_name.startsWith("mcp__"),a=s?n.tool_name.replace(/^mcp__[^_]+__/,""):void 0,c=this.runtimeStore.get(o),d=new te(this.projectRoot,o,c?.executionId),u=d.getPhase(),l=Wo(this.projectRoot,o,n.tool_name,c?.executionId),m=_r({toolName:n.tool_name,toolInput:n.tool_input,projectRoot:this.projectRoot}),f=m?{permissionDecision:"deny",reason:m}:d.evaluate(n.tool_name,s),p;if(l?p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${l.message} Resolve the case blocker or obtain an authorized task lease before retrying.`}}:f.permissionDecision==="deny"?p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:f.reason??"MCP context required"}}:f.additionalContext?p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:f.additionalContext}}:p={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},r){let T=p.hookSpecificOutput,x=typeof T.additionalContext=="string"?T.additionalContext:"";T.additionalContext=x?`${x}
|
|
39
|
+
${r}`:r;}n.tool_name.startsWith("mcp__devflow__")&&(p.hookSpecificOutput.updatedInput=n.tool_input);let g={...n.tool_input};delete g._devflow_session_id,delete g._devflow_execution_id,delete g._devflow_tool_use_id;let R=c?.executionId??o,b={eventId:ve(o,n.tool_use_id),executionId:R,sessionId:o,projectRoot:this.projectRoot,toolUseId:n.tool_use_id,timestamp:Date.now(),toolName:n.tool_name,toolType:s?"mcp":n.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:a,mcpEnforced:s&&(u==="context_gathering"||u==="context_initializing"),mcpFallback:!s&&(u==="context_gathering"||u==="context_initializing"),kind:Pu(n.tool_name),input:g,duration:0,blocked:p&&p.hookSpecificOutput?.permissionDecision==="deny"},w=await this.telemetry.sendEvent({...b,blockReason:b.blocked?l?.code??(m?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED"):void 0,error:b.blocked?l?.code??(m?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED"):void 0});return w&&!b.blocked&&(this.eventMap.push({toolName:n.tool_name,toolUseId:n.tool_use_id,eventId:w,sessionId:o,timestamp:b.timestamp}),this.noteTelemetryOperation()),w&&b.blocked&&await this.telemetry.completeEvent({eventId:w,sessionId:o,error:l?.code??(m?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":"DEVFLOW_CONTEXT_REQUIRED"),duration:Date.now()-b.timestamp,completedAt:Date.now()}),p}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let n=e?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!n)throw new Error("session_id_required");return this.registerSession(n),n}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&je(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(e);}startSkillExecution(e,n,o){let r=this.runtimeStore.get(e)?.executionId,i=this.runtimeStore.startExecution(e,n,Hn(n));return i.executionId&&i.executionId!==r&&this.telemetry.sendExecutionStart(i.executionId,e,n,i.lastActivityAt,this.projectRoot,i.requiredMcpTools).catch(()=>{}),Ln(n,this.projectRoot,o)}async handleSessionStart(e){try{let n=JSON.parse(e);if(typeof n.session_id!="string"||!n.session_id.trim())return {error:"session_id_required"};let o=n.session_id.trim();this.registerSession(o);let r=`session-start:${createHash("sha256").update(`${this.projectRoot}\0${o}`).digest("hex").slice(0,24)}`,i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),s="pending";try{s=i.enqueueWork({idempotencyKey:r,kind:"session.bootstrap",projectRoot:this.projectRoot,sessionId:o,payload:{sessionId:o}}).state;}finally{i.close();}return {status:s==="completed"?"completed":"accepted",receiptId:r,workState:s}}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,n,o){let r=this.eventMap.filter(s=>s.toolName===e&&s.sessionId===n);if(r.length===0)return null;let i=o?r.find(s=>s.toolUseId===o):r.sort((s,a)=>s.timestamp-a.timestamp)[0];return i?(this.eventMap=this.eventMap.filter(s=>s.eventId!==i.eventId),i):null}enforcePostToolUse(e){if(!Mu[e])return null;let n=Math.floor(Date.now()/1e3),o=ht(this.projectRoot,s=>n-(s.lastMcpCall??0)<30?s:{...s,bypassCount:(s.bypassCount??0)+1});if(!o.applied||!o.changed)return null;let r=o.receipt.bypassCount??0;if(r===1)return null;let i;switch(e){case "Agent":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:i=`\u7B2C ${r} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return r>=3?i=`${i} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:r>=2?i=`${i} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:i=`${i} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,i}async handlePostToolUse(e){if(!e)return null;let n;try{n=JSON.parse(e);}catch{return null}let o=n.tool_name||"",r=n.tool_input||{},i=n.tool_response,s=this.trackSession(n.session_id);o==="mcp__devflow__get_project_context"&&this.runtimeStore.completeContextInitialization(s,n.tool_use_id);let a=this.enforcePostToolUse(o);if(a&&this.logRuntime("warn","post_tool_enforcement",{tool:o,reason:a},s),Mo({projectRoot:this.projectRoot,sessionId:s,executionId:this.runtimeStore.get(s)?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),o==="Skill"){let S=r?.skill,D=S?ze(S):null;D&&(this.startSkillExecution(s,D),je(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}if(o.startsWith("mcp__")){let S=this.runtimeStore.get(s),D=new te(this.projectRoot,s,S?.executionId??s);D.recordMcpCall();let A=Ou(i);fi(D,o.replace(/^mcp__[^_]+__/,""),A?pi(A):"succeeded",A,n.tool_use_id);}let c=this.popEventFromMap(o,s,n.tool_use_id);if(c){let S=typeof i=="string"?i:JSON.stringify(i),D=S.length>5e3?{_truncated:true,_originalSize:S.length,text:S.slice(0,5e3)}:i,A=Date.now()-c.timestamp;await this.telemetry.completeEvent({eventId:c.eventId,sessionId:s,output:D,duration:A,completedAt:Date.now()})&&this.noteTelemetryOperation();}let d=typeof i=="object"&&i!==null?i:null,u=d?.exitCode,l=d?.stderr,m=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,f=r.command||"",p=JSON.stringify(i),g=Buffer.byteLength(p,"utf8"),R=this.countResults(i),k,b,w=true;if(o.startsWith("mcp__"))k="mcp_call",b={mcpTool:o.replace(/^mcp__[^_]+__/,""),query:r.query??null,resultCount:R,resultSizeBytes:g};else if(o==="Read"||o==="Write"||o==="Edit")k=o==="Read"?"file_read":"file_write",b={filePath:r.file_path??null,fileContentSize:g};else if(o==="Bash"){let S=m.test(f),D=u!==void 0&&u!==0;w=!S||D,k=D?"bash_error":"bash_command",b={command:f||o,exitCode:u??null,stderr:l??null};}else o==="Agent"?(k="subagent",b={subagentType:r.subagent_type??null,description:typeof r.description=="string"?r.description.slice(0,200):null}):o==="WebSearch"||o==="WebFetch"?(k=o==="WebSearch"?"web_search":"web_fetch",b={query:typeof r.query=="string"?r.query.slice(0,200):null}):(w=false,k="tool_use",b={});if(w){let S={id:n.tool_use_id?`memory:${ve(s,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s,tool:o,kind:k,payload:{...b,durationMs:0},createdAt:Date.now()};this.postMemoryEvent(S);}let T=So({toolName:o,toolResponse:i,sessionId:s,toolUseId:n.tool_use_id,runtimeStore:this.runtimeStore}),x=this.runtimeStore.get(s),O=ni({projectRoot:this.projectRoot,sessionId:s,executionId:x?.executionId,toolName:o,toolInput:r,toolResponse:i,toolUseId:n.tool_use_id}),N=[T,O,a].filter(S=>!!S).join(`
|
|
40
40
|
|
|
41
41
|
`);return N?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:N}}:null}async handlePostToolUseFailure(e){let n;try{n=JSON.parse(e);}catch{return null}let o=this.trackSession(n.session_id),r=n.tool_name??"unknown",i=n.error??`${r} failed`;if(r==="mcp__devflow__get_project_context"&&this.runtimeStore.completeContextInitialization(o,n.tool_use_id),r.startsWith("mcp__devflow__")){let a=this.runtimeStore.get(o),c=new te(this.projectRoot,o,a?.executionId??o);fi(c,r.replace(/^mcp__[^_]+__/,""),pi(i),i,n.tool_use_id);}let s=this.popEventFromMap(r,o,n.tool_use_id);if(s)await this.telemetry.completeEvent({eventId:s.eventId,sessionId:o,error:i,duration:Date.now()-s.timestamp,completedAt:Date.now()})&&this.noteTelemetryOperation();else {let a=ve(o,n.tool_use_id);await this.telemetry.sendEvent({eventId:a,executionId:this.runtimeStore.get(o)?.executionId??o,sessionId:o,projectRoot:this.projectRoot,toolUseId:n.tool_use_id,timestamp:Date.now(),toolName:r,toolType:r.startsWith("mcp__")?"mcp":"direct",isMcpTool:r.startsWith("mcp__"),mcpToolName:r.startsWith("mcp__")?r.replace(/^mcp__[^_]+__/,""):void 0,mcpEnforced:false,mcpFallback:false,kind:"error",input:n.tool_input??{},duration:0,error:i,blocked:false});}return this.postMemoryEvent({id:n.tool_use_id?`memory:${ve(o,n.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:o,tool:r,command:typeof n.tool_input?.command=="string"?n.tool_input.command:r,exitCode:-1,stderr:i,durationMs:s?Date.now()-s.timestamp:0,createdAt:Date.now(),kind:r==="Bash"?"bash_error":"tool_use",payload:{command:n.tool_input?.command??r,exitCode:-1,stderr:i}}),null}countResults(e){if(!e)return 0;let n=e;if(typeof e=="string")try{n=JSON.parse(e);}catch{return 1}let o=n,r=["files","results","data","result","memories","nodes","chunks","findings","symbols"],i=Array.isArray(o.data)?o.data:o.structuredContent??o;if(Array.isArray(i))return i.length;if(typeof i=="object"&&i!==null){let s=i,a=0,c=false;for(let d of r)Array.isArray(s[d])&&(c=true,a+=s[d].length);for(let[,d]of Object.entries(s))d&&typeof d=="object"&&!Array.isArray(d)&&(a+=this.countResults(d));return a>0?a:c?0:Object.keys(s).length>0?1:0}return 0}async postMemoryEvent(e){await new Promise(n=>setImmediate(n)),V(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,e);try{await(await this.getMemoryGate()).recordEvent(e);}catch(n){this.logRuntime("warn","memory_event_write",{reason:n.message,fallback:"http_mirror"},e.sessionId);}}async getMemoryGate(){let e=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=e.forceWarmUp().catch(n=>{throw this.memoryWarmup=null,n}),await this.memoryWarmup,e}async handleUserPromptSubmit(e){let n=[];try{let o=JSON.parse(e),r=typeof o.prompt=="string"?o.prompt:"",i=typeof o.session_id=="string"&&o.session_id.trim()?this.trackSession(o.session_id):null,s=Yo(r),a=!1,c;if(r.trim()&&i){try{c=await ci({projectRoot:this.projectRoot,sessionId:i,prompt:r,hostEvent:o}),this.runtimeStore.bindTaskIdentity(i,{turnId:c.artifact.identity.turnId,requestId:c.artifact.identity.requestId,intentArtifactHash:c.artifact.artifactHash}),n.push(`DevFlow immutable task identity: turnId=${c.artifact.identity.turnId}; requestId=${c.artifact.identity.requestId}; intentArtifactHash=${c.artifact.artifactHash}. Retrieval query expansion must not replace this original intent.`);}catch(d){n.push("DevFlow task intent persistence degraded; preserve the original user command and do not claim canonical context binding."),h({event:"intent.artifact.failed",identity:{projectRoot:this.projectRoot,sessionId:i},level:"error",timestamp:Date.now(),data:{stage:"daemon_user_prompt_submit",category:"intent_persistence_unavailable",error:d instanceof Error?d.message:String(d)}});}try{let d=Bt({projectRoot:this.projectRoot,sessionId:i,prompt:r,...c?{identity:c.memoryIdentity}:{},...c?{activation:c.activation}:{}});if(d){let u=d;if(d.explicitContent&&d.turn.status==="pending")try{u=await Vt({projectRoot:this.projectRoot,payload:{operation:"commit_explicit",turnId:d.turn.turnId,eventId:d.turn.eventId,sessionId:i,prompt:r.trim().slice(0,4e3),explicitContent:d.explicitContent,createdAt:d.turn.createdAt},memory:await this.getMemoryGate()});}catch(l){this.logRuntime("warn","explicit_memory_commit",{reason:l.message,fallback:"durable_work_queue",turnId:d.turn.turnId},i);}n.push(u.additionalContext),a=u.skipSkillRouting;}}catch(d){a=!!he(r);try{let l=xr(this.projectRoot,{sessionId:i,prompt:r,createdAt:Date.now()});n.push(`DevFlow memory turn status=accepted; durable=true; receiptId=${l}; canonicalMemory=false; SQLite queue replay pending. Do not claim memory success without a canonical receipt.`),this.scheduleMemoryTurnSpoolDrain(250),this.logRuntime("warn","memory_turn_capture",{reason:d.message,fallback:"durable_spool",receiptId:l},i);}catch(l){n.push("DevFlow memory turn status=degraded; durable=false; no canonical receipt exists. Do not claim memory success."),this.logRuntime("error","memory_turn_capture",{reason:l.message,fallback:"none"},i);}}}if(i&&s&&!a){let d=this.startSkillExecution(i,s.skillName,r);d&&n.push(d);}}catch{}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...n.length?{additionalContext:n.join(`
|
|
42
|
-
`)}:{}}}}async handlePreCompact(e){let n;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),r=await me({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=fo(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(e){if(!e||typeof e!="object")throw new Error("memory_turn_payload_invalid");let n=e;if(n.operation!=="capture_prompt"&&n.operation!=="commit_explicit"||typeof n.turnId!="string"||typeof n.eventId!="string"||typeof n.sessionId!="string"||typeof n.prompt!="string"||typeof n.createdAt!="number")throw new Error("memory_turn_payload_invalid");await Vt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(e){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},e),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let e=Er(this.projectRoot);if(!e)return;try{Bt({projectRoot:this.projectRoot,sessionId:e.payload.sessionId,prompt:e.payload.prompt}),Ar(e),this.workRuntime.drainOnce();}catch(n){Tr(e),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(e){if(!e||typeof e!="object"||typeof e.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=e.sessionId,o=await this.getMemoryGate();await o.ensureSession(n,this.projectRoot,"Host session"),await o.releasePendingDistillLeases(n),await this.refreshMemorySnapshot("session_bootstrap");}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=Du&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let n=null,o=false,r;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(n=i.session_id.trim()),o=i.stop_hook_active===!0,typeof i.transcript_path=="string"&&i.transcript_path.trim()&&(r=i.transcript_path.trim());}catch{}if(n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,this.startExplicitIntentFlush(),n){let i=qr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return h({event:"hook.stop.degraded",identity:{projectRoot:this.projectRoot,sessionId:n},level:"warn",timestamp:Date.now(),data:{decision:"block_once",unresolved:i.unresolved.map(a=>a.obligationId)}}),{decision:"block",reason:i.additionalContext};let s=this.runtimeStore.completeExecution(n);if(s?.executionId){let a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),c={};try{let d=a.listSessionMemoryTurnsForReconciliation(this.projectRoot,n);c={...Ct(d),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision};}finally{a.close();}await this.telemetry.sendExecutionComplete(s.executionId,"completed",Date.now(),c),this.deleteContextReceipt(n,s.executionId);}h({event:"hook.stop.completed",identity:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId},level:"info",timestamp:Date.now(),data:{decision:i.decision,unresolvedCount:i.unresolved.length}});}return null}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=Go(this.projectRoot);if(e)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;e.intents.length>0;){let r=e.intents[0];if(r.turnId){let s=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let a=s.getMemoryTurn(r.turnId);if(!a||a.status!=="pending"){this.logRuntime("warn","legacy_memory_intent_drop",{turnId:r.turnId,status:a?.status??"missing"},r.sessionId),Mt(e);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,{actorId:"actor:claude-code",sessionId:r.sessionId},r.eventId);if(o=!0,r.turnId){let s=openGlobalDevFlowDatabase();try{let a=s.commitMemoryTurn({turnId:r.turnId,receiptId:be(r.turnId,"committed",[i.id]),memoryIds:[i.id],source:"explicit_intent",reason:"explicit_user_request_retry"});if(a.receiptId)try{await n.finalizeTurnDecision({turnEventId:a.eventId,sessionId:a.sessionId,turnId:a.turnId,receiptId:a.receiptId,status:"committed",memoryIds:[i.id],reason:"explicit_user_request_retry"});}catch(c){this.logRuntime("warn","memory_lineage_finalize",{reason:c.message,fallback:"session_end_reconciliation",turnId:r.turnId},r.sessionId);}try{await n.enrichExplicitMemoryObservation(i.id);}catch(c){s.enqueueWork({idempotencyKey:`explicit-enrichment:${this.projectRoot}:${i.id}`,kind:"memory.explicit_enrichment",projectRoot:this.projectRoot,sessionId:r.sessionId,turnId:r.turnId,payload:{observationId:i.id},maxAttempts:20}),this.logRuntime("warn","explicit_memory_enrichment",{reason:c.message,fallback:"durable_work_queue",memoryId:i.id,turnId:r.turnId},r.sessionId);}}finally{s.close();}}Mt(e);}o&&await this.refreshMemorySnapshot("legacy_explicit_memory_commit");}catch(n){this.logRuntime("error","legacy_memory_intent_flush",{reason:n.message,fallback:"claim_remains_retryable"});}}deleteContextReceipt(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,e,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(e){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await Ye({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:e})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:e}),zt({projectRoot:this.projectRoot,reason:e,load:async()=>{throw n}})}}async handleMemorySnapshot(){let e=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=e;return {status:n.status==="ready"||n.status==="disabled"?"ok":n.status,enabled:n.status!=="disabled",markdown:n.markdown,memoryIds:n.memoryIds,memoryCount:n.memoryIds.length,conflicts:n.conflicts,snapshot:n,persisted:e.persisted}}async handleSessionEnd(e){let n=null;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let o=n===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(n),r=n?this.runtimeStore.get(n)?.executionId:void 0,i=Ue(e,this.projectRoot,o,r);return i?.workState==="spooled"&&this.scheduleSessionFinalizeSpoolDrain(250),n&&(this.serverManager.removeRef(n),this.activeSessionIds.delete(n),this.eventMap=this.eventMap.filter(s=>s.sessionId!==n)),this.activeSessionIds.size===0&&i?.workState!=="spooled"&&i?.workItemId?setImmediate(()=>{this.workRuntime.drainWorkItemOnce(i.workItemId).finally(()=>{this.shutdown();});}):this.resetIdleTimer(),i??{status:"ok"}}async finalizeSessionWork(e,n){if(!e||typeof e!="object")throw new Error("session_finalize_payload_invalid");let o=e;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await zo(o.inputJson,this.projectRoot,o.cleanupSharedState!==false,{telemetry:this.telemetry,memory:r,executionId:o.executionId});try{await this.refreshMemorySnapshot("session_finalization");}catch(s){this.logRuntime("warn","session_finalize_snapshot",{reason:s.message,fallback:"durable_memory_authoritative"},o.sessionId);}let i=openGlobalDevFlowDatabase();try{i.completeSessionClosure(this.projectRoot,o.sessionId,n);}finally{i.close();}}enqueueLearningAnalysisIfReady(e,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=e.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||e.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=e.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=$u(this.projectRoot);e.enqueueWork({idempotencyKey:`learning-analysis:${r.receiptId}:${a}`,kind:"learning.analyze_session",projectRoot:this.projectRoot,sessionId:n,payload:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId,closureReceipt:r.receiptId,projectRevision:a,createdAt:Date.now()},maxAttempts:5});}scheduleSessionFinalizeSpoolDrain(e){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},e),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let e=vo(this.projectRoot);if(!e)return;try{if(!Ue(e.payload.inputJson,this.projectRoot,e.payload.cleanupSharedState,e.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");_o(e),this.workRuntime.drainOnce();}catch(n){Io(e),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleSessionFinalizeSpoolDrain(1e3);return}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.workRuntime.stop(),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),this.memoryTurnSpoolTimer&&(clearTimeout(this.memoryTurnSpoolTimer),this.memoryTurnSpoolTimer=null),this.sessionFinalizeSpoolTimer&&(clearTimeout(this.sessionFinalizeSpoolTimer),this.sessionFinalizeSpoolTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(n=>{let o=false,r=()=>{o||(o=true,clearTimeout(i),n());},i=setTimeout(r,xu);e.close(r);}))}cleanupOwnedResources(){try{uo(this.projectRoot,process.pid);}catch(e){this.logRuntime("warn","daemon_unregister",{reason:e.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
|
|
43
|
-
`);}};function
|
|
42
|
+
`)}:{}}}}async handlePreCompact(e){let n;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),r=await me({projectRoot:this.projectRoot,sessionId:n,trigger:"pre_compact",memory:o}),i=fo(r);return {hookSpecificOutput:{hookEventName:"PreCompact",...i?{additionalContext:i}:{}}}}async persistMemoryTurnItem(e){if(!e||typeof e!="object")throw new Error("memory_turn_payload_invalid");let n=e;if(n.operation!=="capture_prompt"&&n.operation!=="commit_explicit"||typeof n.turnId!="string"||typeof n.eventId!="string"||typeof n.sessionId!="string"||typeof n.prompt!="string"||typeof n.createdAt!="number")throw new Error("memory_turn_payload_invalid");await Vt({projectRoot:this.projectRoot,payload:n,memory:await this.getMemoryGate()});}scheduleMemoryTurnSpoolDrain(e){this.memoryTurnSpoolTimer||(this.memoryTurnSpoolTimer=setTimeout(()=>{this.memoryTurnSpoolTimer=null,this.drainMemoryTurnSpool();},e),this.memoryTurnSpoolTimer.unref());}async drainMemoryTurnSpool(){for(;;){let e=Er(this.projectRoot);if(!e)return;try{Bt({projectRoot:this.projectRoot,sessionId:e.payload.sessionId,prompt:e.payload.prompt}),Ar(e),this.workRuntime.drainOnce();}catch(n){Tr(e),this.logRuntime("warn","memory_turn_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleMemoryTurnSpoolDrain(1e3);return}}}async bootstrapSessionWork(e){if(!e||typeof e!="object"||typeof e.sessionId!="string")throw new Error("session_bootstrap_payload_invalid");let n=e.sessionId,o=await this.getMemoryGate();await o.ensureSession(n,this.projectRoot,"Host session"),await o.releasePendingDistillLeases(n),await this.refreshMemorySnapshot("session_bootstrap");}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=Cu&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let n=null,o=false,r;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(n=i.session_id.trim()),o=i.stop_hook_active===!0,typeof i.transcript_path=="string"&&i.transcript_path.trim()&&(r=i.transcript_path.trim());}catch{}if(n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,this.startExplicitIntentFlush(),n){let i=qr({projectRoot:this.projectRoot,sessionId:n,transcriptPath:r,stopHookActive:o,runtimeStore:this.runtimeStore});if(i.decision==="block_once")return h({event:"hook.stop.degraded",identity:{projectRoot:this.projectRoot,sessionId:n},level:"warn",timestamp:Date.now(),data:{decision:"block_once",unresolved:i.unresolved.map(a=>a.obligationId)}}),{decision:"block",reason:i.additionalContext};let s=this.runtimeStore.completeExecution(n);if(s?.executionId){let a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50}),c={};try{let d=a.listSessionMemoryTurnsForReconciliation(this.projectRoot,n);c={...Ct(d),evidenceDegradations:s.evidenceDegradations,evidenceContractOutcomes:s.evidenceOutcomes,unresolvedObligations:i.unresolved,terminalState:i.decision};}finally{a.close();}await this.telemetry.sendExecutionComplete(s.executionId,"completed",Date.now(),c),this.deleteContextReceipt(n,s.executionId);}h({event:"hook.stop.completed",identity:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId},level:"info",timestamp:Date.now(),data:{decision:i.decision,unresolvedCount:i.unresolved.length}});}return null}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=Go(this.projectRoot);if(e)try{let n=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);await n.forceWarmUp();let o=!1;for(;e.intents.length>0;){let r=e.intents[0];if(r.turnId){let s=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});try{let a=s.getMemoryTurn(r.turnId);if(!a||a.status!=="pending"){this.logRuntime("warn","legacy_memory_intent_drop",{turnId:r.turnId,status:a?.status??"missing"},r.sessionId),Mt(e);continue}}finally{s.close();}}let i=await n.saveExplicitMemoryIntent(r.content,{actorId:"actor:claude-code",sessionId:r.sessionId},r.eventId);if(o=!0,r.turnId){let s=openGlobalDevFlowDatabase();try{let a=s.commitMemoryTurn({turnId:r.turnId,receiptId:be(r.turnId,"committed",[i.id]),memoryIds:[i.id],source:"explicit_intent",reason:"explicit_user_request_retry"});if(a.receiptId)try{await n.finalizeTurnDecision({turnEventId:a.eventId,sessionId:a.sessionId,turnId:a.turnId,receiptId:a.receiptId,status:"committed",memoryIds:[i.id],reason:"explicit_user_request_retry"});}catch(c){this.logRuntime("warn","memory_lineage_finalize",{reason:c.message,fallback:"session_end_reconciliation",turnId:r.turnId},r.sessionId);}try{await n.enrichExplicitMemoryObservation(i.id);}catch(c){s.enqueueWork({idempotencyKey:`explicit-enrichment:${this.projectRoot}:${i.id}`,kind:"memory.explicit_enrichment",projectRoot:this.projectRoot,sessionId:r.sessionId,turnId:r.turnId,payload:{observationId:i.id},maxAttempts:20}),this.logRuntime("warn","explicit_memory_enrichment",{reason:c.message,fallback:"durable_work_queue",memoryId:i.id,turnId:r.turnId},r.sessionId);}}finally{s.close();}}Mt(e);}o&&await this.refreshMemorySnapshot("legacy_explicit_memory_commit");}catch(n){this.logRuntime("error","legacy_memory_intent_flush",{reason:n.message,fallback:"claim_remains_retryable"});}}deleteContextReceipt(e,n){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),o.deleteContextReceipt(this.projectRoot,e,n);}catch{}finally{o?.close();}}async refreshMemorySnapshot(e){try{let n=loadConfig(this.projectRoot).sessionStart?.injectMemories??!0,o=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return await Ye({projectRoot:this.projectRoot,memory:o,injectConfig:n,reason:e})}catch(n){return this.logRuntime("warn","memory_snapshot_refresh",{reason:n.message,fallback:"cached_snapshot",trigger:e}),zt({projectRoot:this.projectRoot,reason:e,load:async()=>{throw n}})}}async handleMemorySnapshot(){let e=await this.refreshMemorySnapshot("memory_snapshot_request"),{snapshot:n}=e;return {status:n.status==="ready"||n.status==="disabled"?"ok":n.status,enabled:n.status!=="disabled",markdown:n.markdown,memoryIds:n.memoryIds,memoryCount:n.memoryIds.length,conflicts:n.conflicts,snapshot:n,persisted:e.persisted}}async handleSessionEnd(e){let n=null;try{let s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(n=s.session_id.trim());}catch{}n??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let o=n===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(n),r=n?this.runtimeStore.get(n)?.executionId:void 0,i=Ue(e,this.projectRoot,o,r);return i?.workState==="spooled"&&this.scheduleSessionFinalizeSpoolDrain(250),n&&(this.serverManager.removeRef(n),this.activeSessionIds.delete(n),this.eventMap=this.eventMap.filter(s=>s.sessionId!==n)),this.activeSessionIds.size===0&&i?.workState!=="spooled"&&i?.workItemId?setImmediate(()=>{this.workRuntime.drainWorkItemOnce(i.workItemId).finally(()=>{this.shutdown();});}):this.resetIdleTimer(),i??{status:"ok"}}async finalizeSessionWork(e,n){if(!e||typeof e!="object")throw new Error("session_finalize_payload_invalid");let o=e;if(typeof o.inputJson!="string"||typeof o.sessionId!="string")throw new Error("session_finalize_payload_invalid");let r=await this.getMemoryGate();await zo(o.inputJson,this.projectRoot,o.cleanupSharedState!==false,{telemetry:this.telemetry,memory:r,executionId:o.executionId});try{await this.refreshMemorySnapshot("session_finalization");}catch(s){this.logRuntime("warn","session_finalize_snapshot",{reason:s.message,fallback:"durable_memory_authoritative"},o.sessionId);}let i=openGlobalDevFlowDatabase();try{i.completeSessionClosure(this.projectRoot,o.sessionId,n);}finally{i.close();}}enqueueLearningAnalysisIfReady(e,n){if(resolveCapabilityRollout(this.projectRoot).config.learningOverlays==="off")return;let r=e.getSessionClosure(this.projectRoot,n);if(!r||r.state!=="closed"||r.pendingWorkCount!==0||e.listSessionObligations(this.projectRoot,n).some(c=>c.state==="open"||c.state==="degraded"))return;let s=e.getLatestSkillExecutionForSession(n);if(s&&s.status==="running")return;let a=Fu(this.projectRoot);e.enqueueWork({idempotencyKey:`learning-analysis:${r.receiptId}:${a}`,kind:"learning.analyze_session",projectRoot:this.projectRoot,sessionId:n,payload:{projectRoot:this.projectRoot,sessionId:n,executionId:s?.executionId,closureReceipt:r.receiptId,projectRevision:a,createdAt:Date.now()},maxAttempts:5});}scheduleSessionFinalizeSpoolDrain(e){this.sessionFinalizeSpoolTimer||(this.sessionFinalizeSpoolTimer=setTimeout(()=>{this.sessionFinalizeSpoolTimer=null,this.drainSessionFinalizeSpool();},e),this.sessionFinalizeSpoolTimer.unref());}async drainSessionFinalizeSpool(){for(;;){let e=vo(this.projectRoot);if(!e)return;try{if(!Ue(e.payload.inputJson,this.projectRoot,e.payload.cleanupSharedState,e.payload.executionId,!1))throw new Error("session_finalize_spool_rejected");_o(e),this.workRuntime.drainOnce();}catch(n){Io(e),this.logRuntime("warn","session_finalize_spool_replay",{reason:n.message,fallback:"bounded_retry"},e.payload.sessionId),this.scheduleSessionFinalizeSpoolDrain(1e3);return}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.workRuntime.stop(),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),this.memoryTurnSpoolTimer&&(clearTimeout(this.memoryTurnSpoolTimer),this.memoryTurnSpoolTimer=null),this.sessionFinalizeSpoolTimer&&(clearTimeout(this.sessionFinalizeSpoolTimer),this.sessionFinalizeSpoolTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(n=>{let o=false,r=()=>{o||(o=true,clearTimeout(i),n());},i=setTimeout(r,Eu);e.close(r);}))}cleanupOwnedResources(){try{uo(this.projectRoot,process.pid);}catch(e){this.logRuntime("warn","daemon_unregister",{reason:e.message});}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
|
|
43
|
+
`);}};function $u(t){if(t)try{let e=JSON.parse(t);return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():void 0}catch{return}}function Fu(t){try{return execFileSync("git",["rev-parse","HEAD"],{cwd:t,encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return `unversioned:${createHash("sha256").update(t).digest("hex").slice(0,16)}`}}if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let t=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new In(t,process.argv[3]);process.once("SIGTERM",()=>{e.shutdown();}),process.once("SIGINT",()=>{e.shutdown();}),e.start().catch(n=>{console.error("[devflow-daemon] Failed to start:",n),process.exit(1);});}export{In as HookDaemon,ju as injectProjectRootIfMissing};
|