@devflow-tools/cli 0.18.11 → 0.18.12
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/commands/delivery.d.ts +1 -1
- package/dist/commands/delivery.d.ts.map +1 -1
- package/dist/commands/delivery.js +1 -0
- package/dist/commands/delivery.js.map +1 -1
- package/dist/plugin-files/.claude-plugin/plugin.json +1 -1
- package/dist/plugin-files/dist/command-registry.json +8 -6
- package/dist/plugin-files/dist/hooks/hook-daemon.js +1 -1
- package/dist/plugin-files/dist/hooks/pre-tool-use.js +4 -4
- package/dist/plugin-files/dist/hooks/session-end.js +5 -5
- package/dist/plugin-files/dist/hooks/stop.js +3 -3
- package/dist/plugin-files/dist/skills/devflow:delivery/SKILL.md +7 -2
- package/dist/plugin-files/hooks/pre-tool-use +4 -4
- package/dist/plugin-files/package.json +13 -13
- package/dist/plugin-files/skills/delivery/SKILL.md +3 -0
- package/package.json +28 -28
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
2
|
import { DeliveryLineFacade } from '@devflow-tools/delivery-line';
|
|
3
|
-
export type DeliveryFacade = Pick<DeliveryLineFacade, 'createCase' | 'status' | 'answer' | 'revise' | 'compareOptions' | 'approve' | 'reject' | 'resume' | 'retryTask' | 'export' | 'cancel'>;
|
|
3
|
+
export type DeliveryFacade = Pick<DeliveryLineFacade, 'createCase' | 'status' | 'answer' | 'revise' | 'compareOptions' | 'approve' | 'reject' | 'resume' | 'retryTask' | 'importExternalChange' | 'export' | 'cancel'>;
|
|
4
4
|
export type DeliveryFacadeResolver = (projectRoot: string) => DeliveryFacade | Promise<DeliveryFacade>;
|
|
5
5
|
export declare function deliveryCliError(error: unknown): {
|
|
6
6
|
ok: false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delivery.d.ts","sourceRoot":"","sources":["../../src/commands/delivery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,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AM,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,KAAK,OAAO,CAAC;IAAE,MAAM,EAAE,cAAc,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAgC,GAC7K,OAAO,CAwBT"}
|
|
@@ -71,6 +71,7 @@ export function createDeliveryCommand(facade, resolveFacade = async () => {
|
|
|
71
71
|
writeOptions(command.command('resume').argument('<caseId>').option('--continue', 'Resume the same recoverable case')).action(async (caseId, opts) => { await run(withFacade(opts.project, selectedFacade => selectedFacade.resume(caseId, identity(opts, opts.idempotencyKey))), opts.json); });
|
|
72
72
|
writeOptions(command.command('cancel').argument('<caseId>').requiredOption('--reason <reason>')).action(async (caseId, opts) => { await run(withFacade(opts.project, selectedFacade => selectedFacade.cancel(caseId, { ...identity(opts, opts.idempotencyKey), reason: opts.reason })), opts.json); });
|
|
73
73
|
writeOptions(command.command('retry-task').argument('<caseId>').requiredOption('--task-id <taskId>')).action(async (caseId, opts) => { await run(withFacade(opts.project, selectedFacade => selectedFacade.retryTask(caseId, { ...identity(opts, opts.idempotencyKey), taskId: opts.taskId })), opts.json); });
|
|
74
|
+
writeOptions(command.command('import-external').argument('<caseId>').requiredOption('--task-id <taskId>').requiredOption('--candidate <revision>').requiredOption('--reason <reason>')).action(async (caseId, opts) => { await run(withFacade(opts.project, selectedFacade => selectedFacade.importExternalChange(caseId, { ...identity(opts, opts.idempotencyKey), taskId: opts.taskId, candidateRevision: opts.candidate, reason: opts.reason })), opts.json); });
|
|
74
75
|
writeOptions(command.command('export').argument('<caseId>').requiredOption('--path <path>')).action(async (caseId, opts) => { await run(withFacade(opts.project, selectedFacade => selectedFacade.export(caseId, { ...identity(opts, opts.idempotencyKey), path: opts.path })), opts.json); });
|
|
75
76
|
return command;
|
|
76
77
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delivery.js","sourceRoot":"","sources":["../../src/commands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X,IAAI,CAAC,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CACnC,CAAC;AACJ,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "devflow",
|
|
3
3
|
"description": "DevFlow — Developer Intelligence Platform: project context, code graph, knowledge base, memory engine, and workflow automation with 14 domain plugins",
|
|
4
|
-
"version": "0.18.
|
|
4
|
+
"version": "0.18.12",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "DevFlow"
|
|
7
7
|
},
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"WebFetch"
|
|
20
20
|
],
|
|
21
21
|
"source": "core",
|
|
22
|
-
"sourceVersion": "0.18.
|
|
22
|
+
"sourceVersion": "0.18.12",
|
|
23
23
|
"requiresContext": true,
|
|
24
24
|
"evidenceMode": "mixed",
|
|
25
25
|
"skillPath": "skills/devflow:context/SKILL.md",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"Explore"
|
|
45
45
|
],
|
|
46
46
|
"source": "core",
|
|
47
|
-
"sourceVersion": "0.18.
|
|
47
|
+
"sourceVersion": "0.18.12",
|
|
48
48
|
"requiresContext": true,
|
|
49
49
|
"evidenceMode": "mixed",
|
|
50
50
|
"skillPath": "skills/devflow:graph/SKILL.md",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"WebFetch"
|
|
64
64
|
],
|
|
65
65
|
"source": "core",
|
|
66
|
-
"sourceVersion": "0.18.
|
|
66
|
+
"sourceVersion": "0.18.12",
|
|
67
67
|
"requiresContext": true,
|
|
68
68
|
"evidenceMode": "mixed",
|
|
69
69
|
"skillPath": "skills/devflow:knowledge/SKILL.md",
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"Explore"
|
|
88
88
|
],
|
|
89
89
|
"source": "core",
|
|
90
|
-
"sourceVersion": "0.18.
|
|
90
|
+
"sourceVersion": "0.18.12",
|
|
91
91
|
"requiresContext": true,
|
|
92
92
|
"evidenceMode": "mixed",
|
|
93
93
|
"skillPath": "skills/devflow:memory/SKILL.md",
|
|
@@ -103,7 +103,7 @@
|
|
|
103
103
|
],
|
|
104
104
|
"blockedNative": [],
|
|
105
105
|
"source": "core",
|
|
106
|
-
"sourceVersion": "0.18.
|
|
106
|
+
"sourceVersion": "0.18.12",
|
|
107
107
|
"requiresContext": true,
|
|
108
108
|
"evidenceMode": "mixed",
|
|
109
109
|
"skillPath": "skills/devflow:workflow/SKILL.md",
|
|
@@ -125,12 +125,13 @@
|
|
|
125
125
|
"delivery_resume",
|
|
126
126
|
"delivery_advance",
|
|
127
127
|
"delivery_retry_task",
|
|
128
|
+
"delivery_import_external_change",
|
|
128
129
|
"delivery_export",
|
|
129
130
|
"delivery_cancel"
|
|
130
131
|
],
|
|
131
132
|
"blockedNative": [],
|
|
132
133
|
"source": "core",
|
|
133
|
-
"sourceVersion": "0.18.
|
|
134
|
+
"sourceVersion": "0.18.12",
|
|
134
135
|
"requiresContext": true,
|
|
135
136
|
"evidenceMode": "mixed",
|
|
136
137
|
"skillPath": "skills/devflow:delivery/SKILL.md",
|
|
@@ -146,6 +147,7 @@
|
|
|
146
147
|
"mcp__devflow__delivery_resume",
|
|
147
148
|
"mcp__devflow__delivery_advance",
|
|
148
149
|
"mcp__devflow__delivery_retry_task",
|
|
150
|
+
"mcp__devflow__delivery_import_external_change",
|
|
149
151
|
"mcp__devflow__delivery_export",
|
|
150
152
|
"mcp__devflow__delivery_cancel"
|
|
151
153
|
]
|
|
@@ -14,7 +14,7 @@ import {createServer,createConnection}from'net';import {createHash,randomUUID as
|
|
|
14
14
|
`)+1)));let d=c.split(/\r?\n/).slice(-ea),u=t.length>0?Math.min(...t.map(p=>p.promptedAt)):0,l=ya(d,u),f=[...l].reverse().find(p=>ga(p.text,t))??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 ga(e,t){let n=new Set(t.flatMap(r=>r.contract.requiredSections)),o=xo(So(e.split(/\r?\n/u)).headingLines);return [...n].every(r=>o.found.has(r))}function We(e){return wt(e,[]).answer}function ya(e,t){let n=[];for(let o=0;o<e.length;o++){let r=e[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=ha(i.timestamp);if(c>0&&c+5e3<t)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
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 ha(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")return 0;let t=Date.parse(e);return Number.isFinite(t)?t:0}function xo(e){let t=new Set,n=new Map,o;for(let r=0;r<e.length;r++){let i=e[r].trim().replace(/^#{1,6}\s*/,"").replace(/^\*\*(.*)\*\*$/,"$1").replace(/^(?:[一二三123][、..]\s*)/,"").replace(/[::]\s*$/,"").trim(),s=pe.find(a=>i===a);s&&(o=s,t.add(s)),n.set(r,o);}return {found:t,byLine:n}}function To(e){let t;try{if(Ra(e.toolResponse))return null;t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let n=t.getActiveContextReceipt(e.projectRoot,e.sessionId,e.executionId);if(!n)return null;let o=Ia(e.toolInput);if(o.length===0)return null;let r=e.toolName==="Read"?wa(e.toolInput):void 0,i=r?n.selectedFiles?.find(u=>ka(e.projectRoot,u,r)):void 0,s=ba(e.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,e.toolUseId??`${e.sessionId}:${e.executionId??n.executionId}`].join("\0");t.recordContextSelectionEvent({id:`ctxsel:${createHash("sha256").update(u).digest("hex").slice(0,32)}`,projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,selectionType:a,candidateId:c,toolName:e.toolName,toolUseId:e.toolUseId,selectedAt:Date.now()});}let d=t.listRetrievalLedgerEvents({projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId}).filter(u=>u.stage==="selected"&&o.includes(u.sourceId));for(let u of d)t.appendRetrievalLedgerEvent({...u,id:retrievalLedgerTransitionId(u.id,"consumed",e.toolUseId??e.toolName),stage:"consumed",toolEvidence:[e.toolUseId??e.toolName],evidenceIds:o,actor:e.toolName,reasonCode:"structural_evidence_ref",payload:{...u.payload,consumedByTool:e.toolName},createdAt:Date.now()});return d.length>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n.executionId,requestId:n.requestId,contextReceipt:n.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:e.toolName,consumedCount:d.length,evidenceRefCount:o.length}}),a}catch(n){throw ge({event:"hook.runtime.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:e.toolName,reason:n instanceof Error?n.message:String(n)}}),n}finally{try{t?.close();}catch{}}}function Co(e){let t=openGlobalDevFlowDatabase();try{let n=t.listRetrievalLedgerEvents(e),o=new Map(n.filter(l=>l.stage==="selected").map(l=>[Eo(l),l])),r=new Map(n.filter(l=>l.stage==="consumed").map(l=>[Eo(l),l])),i=0,s=0,a=0;for(let[l,m]of o){let f=r.get(l);f&&e.verificationReceipt&&t.appendRetrievalLedgerEvent({...f,id:retrievalLedgerTransitionId(f.id,"verified",e.verificationReceipt),stage:"verified",verificationReceipt:e.verificationReceipt,reasonCode:"same_task_verification_receipt",createdAt:e.finishedAt??Date.now()});let p=f&&e.verificationReceipt&&e.outcome!=="unknown"?e.outcome:"unknown",g=p==="positive"?"positive_outcome":p==="negative"?"negative_outcome":"unknown_outcome";t.appendRetrievalLedgerEvent({...m,id:retrievalLedgerTransitionId(m.id,g,e.verificationReceipt??e.sessionId),stage:g,reason:f?e.outcomeReason:"selected_not_consumed",toolEvidence:f?.toolEvidence??[],verificationReceipt:p==="unknown"?void 0:e.verificationReceipt,payload:{...m.payload,consumed:!!f},createdAt:e.finishedAt??Date.now()}),g==="positive_outcome"?i+=1:g==="negative_outcome"?s+=1:a+=1;}let c=e.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:e.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 e.verificationReceipt&&r.size>0&&ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:"info",timestamp:e.finishedAt??Date.now(),data:{stage:"verified",verifiedCount:r.size}}),ge({event:"task.proof.completed",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:d.status==="complete"?"info":"warn",timestamp:e.finishedAt??Date.now(),data:d}),ge({event:"retrieval.attribution.transitioned",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:e.executionId,requestId:e.requestId},level:a>0?"warn":"info",timestamp:e.finishedAt??Date.now(),data:{stage:"session_outcome",selectedCount:o.size,consumedCount:r.size,verifiedCount:e.verificationReceipt?r.size:0,positiveCount:i,negativeCount:s,unknownCount:a}}),u}finally{t.close();}}function Ia(...e){let t=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()&&t.add(a.trim());else n(s,r+1);}};for(let o of e)n(o);return [...t]}function wa(e){for(let t of ["file_path","path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n.trim()}}function ka(e,t,n){let o=resolve(e,t),r=isAbsolute(n)?resolve(n):resolve(e,n);return o===r}function ba(e){return e.startsWith("mcp__")?e.split("__").at(-1)??e:e}function Ra(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return t.ok===false||t.success===false||t.isError===true||!!t.error||["failed","rejected","unavailable"].includes(String(t.status??""))}function Eo(e){return [e.requestId,e.contextReceipt,e.sourceType,e.sourceId].join("\0")}function ge(e){try{h(e);}catch{}}var Ma=8*1024*1024;function Oo(e){if(!e.transcriptPath||!existsSync(e.transcriptPath))return {status:"unavailable",eventsRead:0,failuresFound:0,failuresRecorded:0,reason:"transcript_path_unavailable"};let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=t.getLatestTranscriptCheckpoint({projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath}),o=statSync(e.transcriptPath).size,r=Math.min(n?.byteOffset??0,o),i=Math.min(Ma,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(e.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=t.listLatestTaskIntentArtifacts(e.projectRoot,e.sessionId),u=new Map,l=new Set,m=0,f=0;for(let k of c){let b;try{b=JSON.parse(k);}catch{continue}for(let R of Rt(b,u)){let I=claudeCodeRuntimeAdapter.normalizeToolResult(R,{projectRoot:e.projectRoot});if(I.success||!I.error)continue;let F=I.toolUseId??I.sourceHash;if(l.has(F))continue;l.add(F),m++;let A=I.toolUseId?t.getToolCallEventByToolUseId(e.sessionId,I.toolUseId):null,M=Mo(A?.input,"_devflow_turn_id"),L=Mo(A?.input,"_devflow_request_id"),S=M?d.find(E=>E.turnId===M):[...d].reverse().find(E=>(!A?.executionId||E.executionId===A.executionId)&&E.createdAt<=(A?.timestamp??I.timestamp))??d.at(-1),T=`host-failure:${I.sourceHash}`;t.insertEvent({kind:"host_transcript_tool_failure",timestamp:I.timestamp,success:!1,toolName:I.canonicalName??I.requestedName,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,sourceId:T,toolUseId:I.toolUseId,correlatedEventId:A?.eventId,requestedName:I.requestedName,canonicalName:I.canonicalName,failureCategory:I.failureCategory,error:I.error.slice(0,1e3)}}),h({event:"host.tool.result.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,turnId:M??S?.turnId,requestId:L??S?.requestId,executionId:A?.executionId},level:"warn",timestamp:Date.now(),data:{toolUseId:I.toolUseId,toolName:I.canonicalName??I.requestedName,failureCategory:I.failureCategory,correlation:A?"tool_use_id":"timestamp_fallback"}}),f++;}}let p=createHash("sha256").update(s).digest("hex"),g=`transcript:${createHash("sha256").update(`${e.projectRoot}\0${e.sessionId}\0${e.transcriptPath}\0${r+i}\0${p}`).digest("hex").slice(0,24)}`;return t.appendTranscriptCheckpoint({id:g,projectRoot:e.projectRoot,hostId:"claude-code",sessionId:e.sessionId,sourcePath:e.transcriptPath,sourceHash:p,byteOffset:r+i,eventCount:c.length,createdAt:Date.now()}),h({event:"session.reconciled",identity:{projectRoot:e.projectRoot,sessionId:e.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{t.close();}}function Mo(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Rt(e,t,n=0){if(n>7||e===null||e===void 0)return [];if(Array.isArray(e))return e.flatMap(s=>Rt(s,t,n+1));if(typeof e!="object")return [];let o=e,r=typeof o.type=="string"?o.type:"";r==="tool_use"&&typeof o.id=="string"&&typeof o.name=="string"&&t.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?t.get(s)??"unknown":"unknown",tool_use_id:s,tool_response:o.content,is_error:o.is_error===true,...o.is_error===true?{error:St(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(...Rt(a,t,n+1));return i}function St(e){if(typeof e=="string")return e.slice(0,4e3);if(Array.isArray(e))return e.map(St).filter(Boolean).join(`
|
|
16
16
|
`).slice(0,4e3);if(!e||typeof e!="object")return "";let t=e;return [t.text,t.content,t.message].map(St).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 Po(e){return $a(e)}function $a(e){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Na(t,e.artifact);if(qa(n.toState))return n;let o=t.getContextReceiptForRequest(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.requestId),r=t.getMemoryTurn(e.artifact.turnId),i=e.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Fa(e.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=j(t,n,e,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Ha(e.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=j(t,n,e,"action_not_required","task_action_not_required"):n=j(t,n,e,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return j(t,n,e,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=j(t,n,e,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=j(t,n,e,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=j(t,n,e,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=j(t,n,e,"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=j(t,n,e,e.memoryStatus==="pending"?"memory_quarantined":"memory_decided",e.memoryStatus==="pending"?e.reason:`canonical_memory_${e.memoryStatus}`)),n.toState==="memory_decided"?j(t,n,e,c?"closed_with_degradation":"closed",e.reason):n.toState==="memory_quarantined"?j(t,n,e,e.retryOwned?"closed_with_retry_work":"closed_with_degradation",e.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{t.close();}}function Fa(e,t){return e.intent==="memory"||e.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ha(e,t){let n=t.canonicalAction,r=(n?(t.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return t.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":t.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||La(e)?"action_required":"action_not_required"}function La(e){return ["create","modify","debug","test","format"].includes(e.action)||["feature","refactor","performance"].includes(e.intent)}function Na(e,t){let n=e.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return n}function j(e,t,n,o,r){if(!ja[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let i=t.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=e.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:t.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??t.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:t.toState,nextState:o,receiptId:s,reason:r}}),a}function qa(e){return e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function jo(e,t){let n=join(e,".devflow","delivery-line","state.db");if(!existsSync(n)||!t.trim())return 0;let o;try{o=new DatabaseSync(n,{timeout:250});let r=o.prepare("SELECT id FROM delivery_cases WHERE id = ? OR json_extract(payload, '$.sessionId') = ?").all(t,t),i=0;for(let s of r)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(s.id).changes);return i}catch{return 0}finally{o?.close();}}function xt(e){let t={committed:0,skipped:0,pending:0},n=[];for(let o of e)t[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function $(e){return (e instanceof Error?e.message:String(e)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(t,n){super(`session_finalize_${t}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function ye(e){let t;try{t=openGlobalDevFlowDatabase();let n=(e.executionId?t.getSkillExecution(e.executionId):null)??t.getLatestSkillExecutionForSession(e.sessionId),o={stage:e.stage,reason:e.reason,degradedAt:Date.now()};n&&t.mergeSkillExecutionMetadata(n.executionId,{...e.metadata,sessionFinalizationDegradations:[o]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId,...o}}),h({event:"hook.session_end.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:e.stage,reason:e.reason}});}catch{}finally{t?.close();}}function Ue(e,t=Te(),n=true,o,r=true){let i;try{i=JSON.parse(e);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:e,sessionId:s,cleanupSharedState:n,executionId:o};try{jo(t,s);}catch{}let d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:t,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:t,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 fo(t,{receiptId:a,...c}),h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:$(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function Fo(e,t=Te(),n=true,o){let r;try{r=JSON.parse(e);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new q(t),a=s.get(i),c=Oo({projectRoot:t,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,k;try{let _=openGlobalDevFlowDatabase();try{k=_.listSessionMemoryTurnsForReconciliation(t,i);for(let y of k){let w=`memory:${y.turnId}`,v=_.getSessionObligation(t,i,w);v?v.state==="open"&&y.status!=="pending"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:w,state:"satisfied",receiptId:y.receiptId,reason:y.reason,resolvedAt:y.decidedAt}):_.upsertSessionObligation({obligationId:w,projectRoot:t,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=$(_),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"turn_load",reason:y,metadata:w}),new K("turn_load",y)}let b=xt(k),R=o?.memory??(f=new MemoryGate(t)),I={status:"completed"};try{I=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(k)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let y=$(_);throw I={status:"degraded",reason:y},ye({projectRoot:t,sessionId:i,executionId:g,stage:"memory_lineage",reason:y,metadata:{...b,...d,memoryLineageReconciliation:I}}),new K("memory_lineage",y)}let F={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=We(r.transcript_path),y=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",de,H,N,Y=[],at=[];try{let z=y.listHostActionsForSession(t,i,g),hn=z.filter(D=>D.state==="verified"),ct=z.filter(D=>["failed","cancelled","degraded"].includes(D.state));ct.length>0?(w="negative",v=`terminal_host_action_${ct[0].state}`):hn.length>0&&(w="positive",v="host_action_verified");let xe=ct[0]??hn.at(-1);if(de=xe?.runId,H=xe?.contextReceipt,N=xe?.evidenceHash,at=z.flatMap(D=>{let X=D.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!xe&&g){let D=y.getSkillExecution(g),X=D?.metadata&&typeof D.metadata=="object"&&Array.isArray(D.metadata.policyVerificationOutcomes)?D.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),dt=X.filter(B=>B.status==="passed");le?(w="negative",v="policy_verification_failed",N=typeof le.receiptId=="string"?le.receiptId:void 0):dt.length>0&&(w="positive",v="policy_verification_passed",N=typeof dt.at(-1)?.receiptId=="string"?String(dt.at(-1).receiptId):void 0),H=y.getActiveContextReceipt(t,i,g)?.contextHash,at=X.map(B=>B.command).filter(B=>typeof B=="string");}H&&(Y=y.getSemanticExecutionContextByHash(H)?.dispositions.filter(D=>D.requirement==="required").map(D=>D.channel)??[]);}finally{y.close();}let yn=Co({projectRoot:t,sessionId:i,executionId:g,outcome:w,outcomeReason:v,verificationReceipt:N,requiredChannels:Y,finishedAt:p}),ci=await R.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:w,outcomeReason:v,workflowRunId:de,contextReceipt:H,toolEvidence:at,verificationReceipt:N,consumedSourceIds:yn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});F={status:_?"evaluated":"unknown",...ci,retrievalLedger:yn};}catch(_){F={...F,status:"degraded",reason:$(_)};}let A;try{A=await R.reconcileDecidedTurnEventWindows(i,k,p);}catch(_){let y=$(_),w={...b,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"event_reconciliation",reason:y,metadata:w}),new K("event_reconciliation",y)}let M;try{M=await me({projectRoot:t,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:A},strictPersistence:!0});}catch(_){let y=$(_),w={...b,...d,memoryEventReconciliation:{status:"completed",...A,checkpointPending:null},memoryCheckpointDegradation:y};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"checkpoint",reason:y,metadata:w}),new K("checkpoint",y)}let L={memoryLineageReconciliation:I,memoryBenefitAttribution:F,memoryEventReconciliation:{status:"completed",...A,checkpointPending:M.pendingEvents},memoryDistillCheckpoint:M};try{let _=openGlobalDevFlowDatabase();try{let y=`session-finalize:${i}:events`,w=Math.max(Number(M.pendingEvents??0),Number(A.remainingUndecided??0)),v=_.getSessionObligation(t,i,y);w>0?_.upsertSessionObligation({obligationId:y,projectRoot:t,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:A,checkpointId:M.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:y,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:$(_)}});}try{await R.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let y=$(_),w={...b,...d,...L,memorySessionCloseDegradation:y};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"memory_close",reason:y,metadata:w}),new K("memory_close",y)}let S={...b,...d,...L},T=[];try{let _=openGlobalDevFlowDatabase();try{let y=new Map(_.listLatestTaskIntentArtifacts(t,i).map(w=>[w.turnId,w]));for(let w of k){let v=y.get(w.turnId);if(!v)continue;let H=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),N=Po({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:H,reason:w.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});T.push({turnId:w.turnId,state:N.toState,receiptId:N.receiptId});}}finally{_.close();}}catch(_){T.push({state:"terminal_integrity_failure",reason:$(_)});}S.terminalOutcomes=T,m=!0;let E;try{E=openGlobalDevFlowDatabase();let _=g;if(_)try{E.reconcileSkillExecution(_,"completed",p,S);let v=E.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=E.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 w=E.getLatestSkillExecutionForSession(i);if(w&&!y.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,S),n){E.deleteHookReceipt(t);let v=P(t),de=createHash("sha256").update(t).digest("hex").slice(0,12);for(let H of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,H),{force:!0});}E.deleteContextReceipt(t,i);}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:$(_),fallback:"fail_open"}});}finally{E?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:$(_),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:t,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 e=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n;}),process.stdin.on("end",async()=>{let n=Ue(t.trim()||process.argv[2]||"");n&&e(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var Za=/^\/(?:devflow:)?[\w-]+\b\s*/iu,ec=/\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,tc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,nc=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function he(e){let t=e.trim().replace(Za,"").trim();return !t||ec.test(t)?null:(nc.exec(t)??tc.exec(t))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function oc(e){return join(getProjectStateDir(e),"memory-intents.jsonl")}function rc(e){try{return readFileSync$1(e,"utf8").split(`
|
|
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 Po(e){return $a(e)}function $a(e){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let n=Na(t,e.artifact);if(qa(n.toState))return n;let o=t.getContextReceiptForRequest(e.artifact.projectRoot,e.artifact.sessionId,e.artifact.requestId),r=t.getMemoryTurn(e.artifact.turnId),i=e.artifact.intent==="memory"||r?.source==="explicit_intent";if(!o&&!i)return n;let s=o?Fa(e.artifact,o):"context_ready";n.toState==="intent_bound"&&(n=j(t,n,e,s,i?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Ha(e.artifact,o):"action_not_required";if((n.toState==="context_ready"||n.toState==="context_degraded")&&(a==="action_not_required"?n=j(t,n,e,"action_not_required","task_action_not_required"):n=j(t,n,e,"action_required","canonical_action_obligation_present")),n.toState==="action_required"){if(a==="action_required")return n;if(a==="action_failed")return j(t,n,e,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?n=j(t,n,e,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(n=j(t,n,e,"action_satisfied","canonical_action_succeeded"));}if(n.toState==="action_failed")if(a==="action_satisfied")n=j(t,n,e,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")n=j(t,n,e,"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=j(t,n,e,e.memoryStatus==="pending"?"memory_quarantined":"memory_decided",e.memoryStatus==="pending"?e.reason:`canonical_memory_${e.memoryStatus}`)),n.toState==="memory_decided"?j(t,n,e,c?"closed_with_degradation":"closed",e.reason):n.toState==="memory_quarantined"?j(t,n,e,e.retryOwned?"closed_with_retry_work":"closed_with_degradation",e.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):n}finally{t.close();}}function Fa(e,t){return e.intent==="memory"||e.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Ha(e,t){let n=t.canonicalAction,r=(n?(t.actionAttempts??[]).filter(i=>i.tool===n.tool):[]).at(-1);return t.actionSatisfiedAt||r?.status==="succeeded"?"action_satisfied":r&&["failed","timeout","unavailable"].includes(r.status)?"action_failed":t.actionDegradation||n?.status==="degraded"||n?.status==="unsupported"?"action_degraded":n?.required||La(e)?"action_required":"action_not_required"}function La(e){return ["create","modify","debug","test","format"].includes(e.action)||["feature","refactor","performance"].includes(e.intent)}function Na(e,t){let n=e.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!n)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return n}function j(e,t,n,o,r){if(!ja[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let i=t.sequence+1,s=`terminal:${createHash("sha256").update(`${n.artifact.artifactHash}\0${i}\0${o}`).digest("hex").slice(0,24)}`,a=e.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:t.toState,toState:o,receiptId:s,sourceReceiptId:n.memoryReceiptId??t.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:t.toState,nextState:o,receiptId:s,reason:r}}),a}function qa(e){return e==="closed"||e==="closed_with_degradation"||e==="closed_with_retry_work"}function jo(e,t){let n=join(e,".devflow","delivery-line","state.db");if(!existsSync(n)||!t.trim())return 0;let o;try{o=new DatabaseSync(n,{timeout:250});let r=o.prepare("SELECT id FROM delivery_cases WHERE id = ? OR json_extract(payload, '$.sessionId') = ?").all(t,t),i=0,s=!!o.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'delivery_events'").get();for(let a of r)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 c=`session.closed:${a.id}:${t}`;o.prepare("INSERT OR IGNORE INTO delivery_events (id,case_id,idempotency_key,actor,type,payload,created_at,processed_at) VALUES (?,?,?,?,?,?,?,NULL)").run(c,a.id,c,JSON.stringify({id:"devflow:session-end",kind:"system"}),"session.closed",JSON.stringify({sessionId:t,releasedLeases:i}),Date.now());}return i}catch{return 0}finally{o?.close();}}function xt(e){let t={committed:0,skipped:0,pending:0},n=[];for(let o of e)t[o.status]+=1,o.receiptId&&n.push(o.receiptId);return {memoryReceiptIds:[...new Set(n)],missingMemoryDecisionCount:t.pending,memoryTurnOutcomes:t}}function $(e){return (e instanceof Error?e.message:String(e)).trim().slice(0,240)||"memory_lifecycle_unavailable"}var K=class extends Error{constructor(t,n){super(`session_finalize_${t}:${n}`),this.name="SessionFinalizationRetryableError",this.category=`session_finalize_${t}`;}};function ye(e){let t;try{t=openGlobalDevFlowDatabase();let n=(e.executionId?t.getSkillExecution(e.executionId):null)??t.getLatestSkillExecutionForSession(e.sessionId),o={stage:e.stage,reason:e.reason,degradedAt:Date.now()};n&&t.mergeSkillExecutionMetadata(n.executionId,{...e.metadata,sessionFinalizationDegradations:[o]}),t.insertEvent({kind:"session_finalize_degraded",timestamp:o.degradedAt,success:!1,metadata:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId,...o}}),h({event:"hook.session_end.degraded",identity:{projectRoot:e.projectRoot,sessionId:e.sessionId,executionId:n?.executionId},level:"warn",timestamp:o.degradedAt,data:{stage:e.stage,reason:e.reason}});}catch{}finally{t?.close();}}function Ue(e,t=Te(),n=true,o,r=true){let i;try{i=JSON.parse(e);}catch{return null}let s=i.session_id?.trim();if(!s)return null;let a=`session-close:${createHash("sha256").update(`${t}\0${s}`).digest("hex").slice(0,24)}`,c={inputJson:e,sessionId:s,cleanupSharedState:n,executionId:o};try{jo(t,s);}catch{}let d;try{d=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let u=d.requestSessionClosure({receiptId:a,projectRoot:t,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:t,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 fo(t,{receiptId:a,...c}),h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:s,executionId:o,terminalReceipt:a},level:"warn",timestamp:Date.now(),data:{stage:"enqueue",reason:$(u),fallback:"durable_spool"}}),{status:"accepted",receiptId:a,workState:"spooled",closureState:"closing",pendingWorkCount:1}}finally{d?.close();}}async function Fo(e,t=Te(),n=true,o){let r;try{r=JSON.parse(e);}catch{return}let i=r.session_id?.trim();if(!i)return;let s=new q(t),a=s.get(i),c=Oo({projectRoot:t,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,k;try{let _=openGlobalDevFlowDatabase();try{k=_.listSessionMemoryTurnsForReconciliation(t,i);for(let y of k){let w=`memory:${y.turnId}`,v=_.getSessionObligation(t,i,w);v?v.state==="open"&&y.status!=="pending"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:w,state:"satisfied",receiptId:y.receiptId,reason:y.reason,resolvedAt:y.decidedAt}):_.upsertSessionObligation({obligationId:w,projectRoot:t,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=$(_),w={...d,memoryEventReconciliation:{status:"degraded",stage:"turn_load",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"turn_load",reason:y,metadata:w}),new K("turn_load",y)}let b=xt(k),R=o?.memory??(f=new MemoryGate(t)),I={status:"completed"};try{I=typeof R.reconcileTurnObservationLineage=="function"?{status:"completed",...await R.reconcileTurnObservationLineage(k)}:{status:"unsupported_adapter",committed:0,skipped:0,quarantined:0,unlinked:0};}catch(_){let y=$(_);throw I={status:"degraded",reason:y},ye({projectRoot:t,sessionId:i,executionId:g,stage:"memory_lineage",reason:y,metadata:{...b,...d,memoryLineageReconciliation:I}}),new K("memory_lineage",y)}let F={status:"unknown",selected:0,consumed:0,unknown:0,positive:0,negative:0};try{let _=We(r.transcript_path),y=openGlobalDevFlowDatabase(),w="unknown",v="no_terminal_host_action_evidence",de,H,N,Y=[],at=[];try{let z=y.listHostActionsForSession(t,i,g),hn=z.filter(D=>D.state==="verified"),ct=z.filter(D=>["failed","cancelled","degraded"].includes(D.state));ct.length>0?(w="negative",v=`terminal_host_action_${ct[0].state}`):hn.length>0&&(w="positive",v="host_action_verified");let xe=ct[0]??hn.at(-1);if(de=xe?.runId,H=xe?.contextReceipt,N=xe?.evidenceHash,at=z.flatMap(D=>{let X=D.report.toolUseIds;return Array.isArray(X)?X.filter(le=>typeof le=="string"):[]}),!xe&&g){let D=y.getSkillExecution(g),X=D?.metadata&&typeof D.metadata=="object"&&Array.isArray(D.metadata.policyVerificationOutcomes)?D.metadata.policyVerificationOutcomes:[],le=X.find(B=>B.status==="failed"),dt=X.filter(B=>B.status==="passed");le?(w="negative",v="policy_verification_failed",N=typeof le.receiptId=="string"?le.receiptId:void 0):dt.length>0&&(w="positive",v="policy_verification_passed",N=typeof dt.at(-1)?.receiptId=="string"?String(dt.at(-1).receiptId):void 0),H=y.getActiveContextReceipt(t,i,g)?.contextHash,at=X.map(B=>B.command).filter(B=>typeof B=="string");}H&&(Y=y.getSemanticExecutionContextByHash(H)?.dispositions.filter(D=>D.requirement==="required").map(D=>D.channel)??[]);}finally{y.close();}let yn=Co({projectRoot:t,sessionId:i,executionId:g,outcome:w,outcomeReason:v,verificationReceipt:N,requiredChannels:Y,finishedAt:p}),ci=await R.attributeRetrievalBenefits({sessionId:i,executionId:g,outcome:w,outcomeReason:v,workflowRunId:de,contextReceipt:H,toolEvidence:at,verificationReceipt:N,consumedSourceIds:yn.consumedSources.filter(z=>z.sourceType==="memory").map(z=>z.sourceId)});F={status:_?"evaluated":"unknown",...ci,retrievalLedger:yn};}catch(_){F={...F,status:"degraded",reason:$(_)};}let A;try{A=await R.reconcileDecidedTurnEventWindows(i,k,p);}catch(_){let y=$(_),w={...b,...d,memoryEventReconciliation:{status:"degraded",stage:"event_reconciliation",reason:y,committedProcessed:0,skippedDiscarded:0,remainingUndecided:null,checkpointPending:null}};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"event_reconciliation",reason:y,metadata:w}),new K("event_reconciliation",y)}let M;try{M=await me({projectRoot:t,sessionId:i,trigger:"session_end",memory:R,details:{eventReconciliation:A},strictPersistence:!0});}catch(_){let y=$(_),w={...b,...d,memoryEventReconciliation:{status:"completed",...A,checkpointPending:null},memoryCheckpointDegradation:y};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"checkpoint",reason:y,metadata:w}),new K("checkpoint",y)}let L={memoryLineageReconciliation:I,memoryBenefitAttribution:F,memoryEventReconciliation:{status:"completed",...A,checkpointPending:M.pendingEvents},memoryDistillCheckpoint:M};try{let _=openGlobalDevFlowDatabase();try{let y=`session-finalize:${i}:events`,w=Math.max(Number(M.pendingEvents??0),Number(A.remainingUndecided??0)),v=_.getSessionObligation(t,i,y);w>0?_.upsertSessionObligation({obligationId:y,projectRoot:t,sessionId:i,executionId:g,kind:"session_finalize",state:"open",payload:{pendingEvents:w,reconciliation:A,checkpointId:M.id},reason:"active_unprocessed_session_events",createdAt:v?.createdAt??p,updatedAt:p}):v?.state==="open"&&_.resolveSessionObligation({projectRoot:t,sessionId:i,obligationId:y,state:"satisfied",reason:"session_events_reconciled",resolvedAt:p});}finally{_.close();}}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"obligation_persistence",reason:$(_)}});}try{await R.closeSession(i),f&&(f.close(),f=void 0);}catch(_){let y=$(_),w={...b,...d,...L,memorySessionCloseDegradation:y};throw ye({projectRoot:t,sessionId:i,executionId:g,stage:"memory_close",reason:y,metadata:w}),new K("memory_close",y)}let S={...b,...d,...L},T=[];try{let _=openGlobalDevFlowDatabase();try{let y=new Map(_.listLatestTaskIntentArtifacts(t,i).map(w=>[w.turnId,w]));for(let w of k){let v=y.get(w.turnId);if(!v)continue;let H=[_.getWorkByIdempotencyKey(`memory-turn:capture_prompt:${w.turnId}`),_.getWorkByIdempotencyKey(`memory-turn:commit_explicit:${w.turnId}`)].filter(Boolean).some(Y=>Y.state==="pending"||Y.state==="leased"||Y.state==="failed"),N=Po({artifact:v,memoryStatus:w.status,memoryReceiptId:w.receiptId,retryOwned:H,reason:w.status==="pending"?"session_end_memory_pending":"session_end_reconciled"});T.push({turnId:w.turnId,state:N.toState,receiptId:N.receiptId});}}finally{_.close();}}catch(_){T.push({state:"terminal_integrity_failure",reason:$(_)});}S.terminalOutcomes=T,m=!0;let E;try{E=openGlobalDevFlowDatabase();let _=g;if(_)try{E.reconcileSkillExecution(_,"completed",p,S);let v=E.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=E.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 w=E.getLatestSkillExecutionForSession(i);if(w&&!y.some(v=>v.executionId===w.executionId)&&E.mergeSkillExecutionMetadata(w.executionId,S),n){E.deleteHookReceipt(t);let v=P(t),de=createHash("sha256").update(t).digest("hex").slice(0,12);for(let H of [`session-id-${de}`,"current-execution-id","current-skill.json","event-map.json"])rmSync$1(join(v,H),{force:!0});}E.deleteContextReceipt(t,i);}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"lifecycle_telemetry",reason:$(_),fallback:"fail_open"}});}finally{E?.close();}try{await u.endSession(i),await u.flushAndAggregate();}catch(_){h({event:"hook.session_end.degraded",identity:{projectRoot:t,sessionId:i,executionId:g},level:"warn",timestamp:Date.now(),data:{stage:"telemetry_flush",reason:$(_),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:t,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 e=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n;}),process.stdin.on("end",async()=>{let n=Ue(t.trim()||process.argv[2]||"");n&&e(JSON.stringify(n)),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var Za=/^\/(?:devflow:)?[\w-]+\b\s*/iu,ec=/\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,tc=/(?:^|[.!?]\s*)(?:(?:please|kindly)\s+)?(?:remember|memorize|save\s+this|store\s+this|note\s+that)(?:\s+(?:that|to))?[\s:,-]*(.+)$/iu,nc=/(?:^|[。!?;,,]\s*)(?:(?:请|麻烦|务必|一定要|帮我|帮忙|需要)\s*)?(?:记住|记一下|记下来|记|记录一下|记录下来|保存一下|保存下来)(?:这(?:件事|一点|个信息|些内容))?[\s::,,]*(.+)$/iu;function he(e){let t=e.trim().replace(Za,"").trim();return !t||ec.test(t)?null:(nc.exec(t)??tc.exec(t))?.[1]?.trim().replace(/^[::,,\s]+/u,"")||null}function oc(e){return join(getProjectStateDir(e),"memory-intents.jsonl")}function rc(e){try{return readFileSync$1(e,"utf8").split(`
|
|
18
18
|
`).filter(Boolean).flatMap(t=>{try{let n=JSON.parse(t);return typeof n.content=="string"&&typeof n.createdAt=="number"?[n]:[]}catch{return []}})}catch{return []}}function Wo(e){let t=oc(e),n=`${t}.claim-`,o=`${basename(t)}.claim-`,r=(()=>{try{return readdirSync$1(dirname$1(t)).filter(a=>a.startsWith(o)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),i=r?join(dirname$1(t),r):`${n}${Date.now()}-${process.pid}`;if(!r)try{renameSync(t,i);}catch{return null}let s=rc(i);if(s.length===0){try{unlinkSync$1(i);}catch{}return null}return {path:i,intents:s}}function Et(e){if(e.intents.shift(),e.intents.length===0){try{unlinkSync$1(e.path);}catch{}return}let t=`${e.path}.tmp-${process.pid}`;writeFileSync$1(t,e.intents.map(n=>JSON.stringify(n)).join(`
|
|
19
19
|
`)+`
|
|
20
20
|
`,{mode:384}),renameSync(t,e.path);}function ze(e){let t=e.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let n=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(n)?`devflow:${n.toLowerCase()}`:null}function Uo(e){let t=e.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let n=ze(t[1]);return n?{rawName:t[1],skillName:n}:null}function ve(e,t){return t?`evt_tool_${createHash$1("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var Ie=1,Pt="memory-snapshot-v1.json",tr=512*1024,nr=256*1024,or=2e3,mc=500,pc=10,fc=240,gc=300*1e3,yc=720*60*60*1e3,rr=2147483647,hc=100,Jo=250,vc=3e4,_c=10,Be=new Map;function ir(e){return e.currentUid===void 0?{ownerSafe:true,modeSafe:true}:{ownerSafe:e.ownerUid===e.currentUid,modeSafe:(e.mode&18)===0}}function G(e){return resolve(e)}function re(e){return createHash("sha256").update(G(e)).digest("hex").slice(0,16)}function jt(e,t={}){let n=re(e),o=t.stateRoot?join(t.stateRoot,n):getProjectStateDir(G(e));return join(o,Pt)}function Je(e,t){let o=(e instanceof Error?e.message:"").replace(/[\r\n\t]+/gu," ").trim().slice(0,160);return o?`${t}:${o}`:t}function $t(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=512)}function Ic(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&t.id.length<=512&&typeof t.kind=="string"&&t.kind.length>0&&t.kind.length<=128&&(t.family===void 0||typeof t.family=="string"&&t.family.length>0&&t.family.length<=256)&&(t.entity===void 0||typeof t.entity=="string"&&t.entity.length>0&&t.entity.length<=256)&&$t(t.memoryIds,100)&&(t.status==="withheld"||t.status==="resolved")&&(t.summary===void 0||typeof t.summary=="string"&&t.summary.length<=2e3)}function wc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.reason=="string"&&t.reason.length>0&&t.reason.length<=512&&(t.stale===void 0||typeof t.stale=="boolean")}function Ft(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e,r=G(t),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")>nr||!$t(o.memoryIds,or)||!Array.isArray(o.conflicts)||o.conflicts.length>mc||!o.conflicts.every(Ic)||typeof o.generatedAt!="number"||!Number.isFinite(o.generatedAt)||o.generatedAt<0||o.generatedAt>n+gc||!Number.isInteger(s)||s<0||s>rr||!["ready","pending","degraded","disabled"].includes(String(o.status))||o.degradation!==void 0&&!wc(o.degradation)?null:{...o,generation:s}}function Ht(e,t,n,o,r=0){let i=G(e);return {version:Ie,projectRoot:i,projectHash:re(i),markdown:"",memoryIds:[],conflicts:[],generatedAt:o,generation:r,status:t,degradation:{reason:n}}}function ne(e,t={}){let n=t.now??Date.now(),o=jt(e,t),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>tr)throw new Error("cache_size_invalid");let s=ir({...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=Ft(a,e,n);if(!c)throw new Error("cache_schema_invalid");return c.status==="ready"&&n-c.generatedAt>yc?{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:Ht(e,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 Ko(e){if(!Number.isInteger(e)||e<0||e>=rr)throw new Error("memory_snapshot_generation_exhausted");return e+1}function kc(e){let t=dirname$1(e);mkdirSync$1(t,{recursive:true,mode:448}),chmodSync(t,448);}function bc(e){kc(e);let t=`${e}.lock`,n={pid:process.pid,createdAt:Date.now(),token:randomUUID$1()},o=JSON.stringify(n),r;try{return r=openSync$1(t,"wx",384),writeFileSync$1(r,o),fsyncSync(r),{fd:r,path:t,contents:o}}catch(i){if(r!==void 0){try{closeSync$1(r);}catch{}try{unlinkSync$1(t);}catch{}}if(i.code==="EEXIST")return null;throw i}}function Rc(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)&&typeof t.token=="string"&&t.token.length>0}function Sc(e){try{return process.kill(e,0),!1}catch(t){return t.code==="ESRCH"}}function xc(e){return !e.canonicalCachePath||!e.directoryIsSafe||!e.lockIsRegularFile||!e.metadataValid||!e.contentsUnchanged||!e.ownerDead&&!e.stale?false:e.currentUid!==void 0?e.directoryUid===e.currentUid&&e.lockUid===e.currentUid:true}function Ec(e){return isAbsolute(e)&&resolve(e)===e&&basename(e)===Pt&&/^[a-f0-9]{16}$/u.test(basename(dirname$1(e)))}function Ac(e,t){let n=`${e}.lock`;try{let o=lstatSync$1(dirname$1(e)),r=lstatSync$1(n),i=readFileSync$1(n,"utf8"),s=null;try{let f=JSON.parse(i);Rc(f)&&(s=f);}catch{}let a=s?.createdAt??r.mtimeMs,c=Date.now()-a>t,d=s?Sc(s.pid):!1,u=readFileSync$1(n,"utf8")===i,l=typeof process.getuid=="function"?process.getuid():void 0,m=ir({...l!==void 0?{currentUid:l}:{},ownerUid:o.uid,mode:o.mode});return xc({canonicalCachePath:Ec(e),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 Tc(e){try{closeSync$1(e.fd);}catch{}try{readFileSync$1(e.path,"utf8")===e.contents&&unlinkSync$1(e.path);}catch{}}function Cc(e){return new Promise(t=>setTimeout(t,e))}function At(e,t,n,o){let r=Number.isFinite(e)?Math.floor(e):t;return Math.min(o,Math.max(n,r))}async function Dc(e,t){let n=At(t.lockTimeoutMs,hc,0,Jo),o=At(t.lockRetryMs,_c,1,Jo),r=At(t.lockStaleMs,vc,0,Number.MAX_SAFE_INTEGER),i=Date.now()+n;for(;;){let s=bc(e);if(s)return s;if(Ac(e,r))continue;let a=i-Date.now();if(a<=0)throw new Error("memory_snapshot_cache_lock_timeout");await Cc(Math.min(o,a));}}async function Go(e,t,n){let o=await Dc(e,t);try{return await n()}finally{Tc(o);}}function Yo(e,t,n,o){let r=o.now??Date.now(),i=G(e),s={version:Ie,projectRoot:i,projectHash:re(i),markdown:t.markdown,memoryIds:t.memoryIds??[],conflicts:t.conflicts??[],generatedAt:r,generation:n,status:t.status??"ready",...t.degradation?{degradation:t.degradation}:{}};if(!Ft(s,e,r))throw new Error("memory_snapshot_payload_invalid");let a=JSON.stringify(s);if(Buffer.byteLength(a,"utf8")>tr)throw new Error("memory_snapshot_cache_too_large");let c=jt(e,o),d=dirname$1(c);mkdirSync$1(d,{recursive:true,mode:448}),chmodSync(d,448);let u=join(d,`.${Pt}.${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 Mc(e,t){let o=(Be.get(e)??Promise.resolve()).catch(()=>{}).then(t),r=o.then(()=>{},()=>{});return Be.set(e,r),o.finally(()=>{Be.get(e)===r&&Be.delete(e);})}function Tt(e,t,n,o,r){return e.valid?e.snapshot.generation>r?{...e,persisted:false}:{...e,snapshot:{...e.snapshot,status:"degraded",degradation:{reason:n,stale:e.stale||void 0}},persisted:false}:{snapshot:Ht(t,"degraded",n,o,r),source:"none",valid:false,stale:false,persisted:false}}async function Lt(e){let t=jt(e.projectRoot,e.cacheOptions);return Mc(t,async()=>{let n=ne(e.projectRoot,e.cacheOptions),o=n.valid?n.snapshot.generation:0,r;try{r=await e.load();}catch(i){let s=Je(i,`refresh_failed:${e.reason}`);try{return await Go(t,e.cacheOptions??{},()=>{let a=ne(e.projectRoot,e.cacheOptions);if(a.valid)return Tt(a,e.projectRoot,s,e.cacheOptions?.now??Date.now(),o);let c=Ko(o),d=Ht(e.projectRoot,"degraded",s,e.cacheOptions?.now??Date.now(),c);return {snapshot:Yo(e.projectRoot,d,c,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(a){let c=ne(e.projectRoot,e.cacheOptions);return Tt(c,e.projectRoot,Je(a,s),e.cacheOptions?.now??Date.now(),o)}}try{return await Go(t,e.cacheOptions??{},()=>{let i=ne(e.projectRoot,e.cacheOptions);if(i.valid&&i.snapshot.generation>o)return {...i,persisted:!1};let s=Ko(Math.max(o,i.valid?i.snapshot.generation:0));return {snapshot:Yo(e.projectRoot,r,s,e.cacheOptions??{}),source:"cache",valid:!0,stale:!1,persisted:!0}})}catch(i){let s=ne(e.projectRoot,e.cacheOptions);return Tt(s,e.projectRoot,Je(i,`refresh_commit_failed:${e.reason}`),e.cacheOptions?.now??Date.now(),o)}})}async function Ye(e){return Lt({projectRoot:e.projectRoot,reason:e.reason,cacheOptions:e.cacheOptions,load:async()=>{if(e.injectConfig===false)return {status:"disabled",markdown:"",memoryIds:[],conflicts:[]};let t=typeof e.injectConfig=="object"?e.injectConfig:{},n=Number.isFinite(t.topN)?Math.max(0,Math.floor(t.topN)):4,o=Number.isFinite(t.budgetTokens)?Math.max(1,Math.floor(t.budgetTokens)):400,r=await e.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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync,rmSync,linkSync,renameSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey,getDevFlowStateRoot,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {request}from'node:http';import {existsSync as existsSync$1,mkdirSync as mkdirSync$1,appendFileSync,chmodSync,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1}from'node:fs';import {join,resolve,basename,relative,sep,dirname,isAbsolute,normalize}from'node:path';import {maybeRunDiagnosticLogCleanup,rotateDiagnosticLogFile,emitSemanticControlLog}from'@devflow-tools/telemetry';import {fileURLToPath}from'url';import {createHash as createHash$1}from'node:crypto';import {homedir}from'node:os';import {randomUUID,createHash}from'crypto';import {DatabaseSync}from'node:sqlite';function
|
|
2
|
-
`;rotateDiagnosticLogFile({path:e,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(r)}),appendFileSync(e,r);}catch{}}function ot(n){return new Promise(t=>setTimeout(t,n))}var ee=1e4,dt=3e4,S=500,O=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,r,o,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:r,startedAt:o,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",r=Date.now(),o){let i={executionId:t,status:e,finishedAt:r,metadata:o},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(t,e,r){let o={id:t,projectRoot:e,startedAt:r,label:e.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",o);return i&&this.postHttp("/api/telemetry/sessions",o),i}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let r={sessionId:t,finishedAt:e},o=this.commitOrCache("session_end",r);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),o}async flushCache(){try{let e=this.getDatabase(),r=e.listTelemetryFailures({unresolvedOnly:!0,limit:S}).reverse();for(let o of r)try{this.applyOperation(o.operation,o.payload),e.resolveTelemetryFailure(o.id);}catch{}e.trimTelemetryFailures(S);}catch{}let t=(existsSync(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(e=>e.endsWith(".json")).map(e=>{let r=join$1(this.cacheDir,e);try{return {cacheFile:r,envelope:ut(JSON.parse(readFileSync(r,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,r)=>e.envelope.timestamp-r.envelope.timestamp||te(e.envelope.operation)-te(r.envelope.operation));for(let{cacheFile:e,envelope:r}of t)try{let o=this.getDatabase();o.insertTelemetryFailure({id:r.id,operation:r.operation,payload:r.payload,error:r.failure,createdAt:r.timestamp}),this.applyOperation(r.operation,r.payload),o.resolveTelemetryFailure(r.id),unlinkSync(e);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(r){return this.cacheOperation(t,e,r),false}}applyOperation(t,e){let r=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(r,e),r.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(r,e),r.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":r.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":r.ensureSession(e),r.insertRun({id:ne(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!r.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":r.closeSession(e.sessionId,e.finishedAt),r.updateRun(ne(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let r=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!r)throw new Error("Canonical session ID is required for telemetry");let o=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:r,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,r){let o=Date.now(),i={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:r instanceof Error?r.message:String(r),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:t,payload:e,error:i.failure,createdAt:o}),s.trimTelemetryFailures(S),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(i,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-S)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},dt).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){Y(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=ee?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,ee)}...`}}};function te(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function ne(n){return `hook-run:${n}`}function ut(n){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.id!="string"||typeof t.operation!="string"||t.payload===void 0||typeof t.failure!="string"||typeof t.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return t}function A(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function y(n){return getProjectStateDir(A(n))}var v=emitSemanticControlLog;var vt=2,bt=1;function _t(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join$1(dirname$1(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function re(n=_t()){let t=[join$1(n,"dist","command-registry.json"),join$1(n,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let r=JSON.parse(readFileSync(e,"utf8"));if(r.version!==vt&&r.version!==bt||!Rt(r.commands)){v({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:"contract_mismatch",registryPath:e}});continue}return r.commands}catch(r){v({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:r.message,fallback:"next_registry_candidate"}});}return null}function Rt(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return C(e.mcpTools)&&C(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||C(e.runtimePackages))&&(e.hostTools===void 0||Et(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Et(n){return !!n&&typeof n=="object"&&!Array.isArray(n)&&Object.entries(n).every(([t,e])=>t.length>0&&C(e))}function C(n){return Array.isArray(n)&&n.every(t=>typeof t=="string"&&t.length>0)}function oe(n){let t=re();return t?t[n]?.mcpTools??[]:[]}function T(n){if(!n||typeof n!="object"||Array.isArray(n))return {};let t=n,e={};for(let r of ["lastMcpCall","bypassCount"])if(r in t){let o=t[r];if(o==null)continue;e[r]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return e}function wt(n,t){return n.lastMcpCall===t.lastMcpCall&&n.bypassCount===t.bypassCount}function se(n,t,e){let r=e instanceof Error?e.message:String(e);v({event:"hook.runtime.degraded",identity:{projectRoot:n},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:r,fallback:"fail_open"}});}function ae(n,t,e){let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o={},i=r.updateHookReceipt(n,a=>(o=T(a),T(t(o)))),s=T(i);return {receipt:s,applied:!0,changed:!wt(o,s)}}catch(o){return se(n,e,o),{receipt:{},applied:false,changed:false}}finally{try{r?.close();}catch{}}}function ce(n){let t;try{return t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),T(t.getHookReceipt(n))}catch(e){return se(n,"update",e),{}}finally{try{t?.close();}catch{}}}function Dt(n,t){return ae(n,()=>t,"write").applied}function It(n,t){return ae(n,t,"update")}var ie={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},xt=new Set(["Write","Edit","NotebookEdit"]),kt=new Set(["failed","timeout","unavailable"]);function St(n){switch(n){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var F=class{constructor(t,e,r){this.projectRoot=t;this.sessionId=e;this.executionId=r;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(e&&e.expiresAt>Date.now())return "context_ready";e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return e&&e.expiresAt>Date.now()?e:(e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,e){let r=this.getPhase();if(e||t==="Skill")return {permissionDecision:"allow"};if(r==="context_gathering"&&ie[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${t}.`};if(r==="context_ready"){if(xt.has(t)){let l=this.evaluateRequiredAction();if(l)return l}return {permissionDecision:"allow"}}let o=ie[t];if(!o)return {permissionDecision:"allow"};let i=It(this.projectRoot,l=>({...l,bypassCount:(l.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=St(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${o} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Dt(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,r,o){if(!this.sessionId||!this.executionId)return false;let i;try{i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=i.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let a=Date.now(),l=o?.trim()?`${o.trim()}:${e}`:`${t}:${e}:${a}`,c=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:c.some(d=>d.id===l||o&&d.toolUseId===o&&d.status===e)?c:[...c,{id:l,tool:t,status:e,attemptedAt:a,toolUseId:o,reason:r?.slice(0,500)}].slice(-20),actionSatisfiedAt:e==="succeeded"?a:s.actionSatisfiedAt,actionDegradation:e==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{i?.close();}catch{}}}evaluateRequiredAction(){let t=this.getContextReceipt(),e=t?.canonicalAction;if(!t||!e||!e.required||e.status!=="required")return null;let r=e.binding;if(r.requiredContextReceipt!==t.contextHash||r.projectRoot!==this.projectRoot||r.sessionId!==this.sessionId||r.requestId!==t.requestId||r.executionId&&r.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:"DevFlow canonical action binding is stale or mismatched. Call mcp__devflow__get_project_context again before writing."};if(t.actionSatisfiedAt)return null;if(t.actionDegradation?.authorizedByContextReceipt===t.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${t.contextHash}: ${t.actionDegradation.reason}`};let o=(t.actionAttempts??[]).filter(i=>i.tool===e.tool&&kt.has(i.status));if(o.length>0){let i=o.at(-1),s={missedTool:e.tool,failedAttemptCount:o.length,reason:`${i.status}:${i.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${e.tool} ${i.status}; degraded direct write authorized by context receipt ${t.contextHash}. Preserve the action contract and verification plan.`}}return {permissionDecision:"deny",reasonCode:"DEVFLOW_REQUIRED_ACTION",reason:`DevFlow required action not completed. Call mcp__devflow__${e.tool} using context receipt ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,e){let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let o=r.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!o||o.contextHash!==t.contextHash||o.actionDegradation)return;r.upsertContextReceipt({...o,actionDegradation:e});let i=r.getSkillExecution(t.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];r.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...i.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(i.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(i.fallbackCount??0)+1,fallbackReasons:[...new Set([...i.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...a,e]}});}catch{}finally{try{r?.close();}catch{}}}};var Mt=10*1024*1024,$t=5;function Nt(n){return createHash$1("sha256").update(n).digest("hex").slice(0,16)}function le(n){return join(homedir(),".devflow","logs","hook-debug",`${Nt(n)}.jsonl`)}function de(n,t,e={}){let r=e.maxBytes??Mt,o=e.maxFiles??$t;mkdirSync$1(dirname(n),{recursive:true,mode:448});let i=Buffer.byteLength(t);rotateDiagnosticLogFile({path:n,maxBytes:r,maxFiles:o,incomingBytes:i}),appendFileSync(n,t,{mode:384}),chmodSync(n,384);}var U="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function ue(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function me(n){return Buffer.from(n,"utf8").toString("base64url")}function Wt(n,t,e){let r=t?.trim();if(r){let o=/^[a-zA-Z0-9:._-]{1,192}$/.test(r)?r:`tool-${createHash("sha256").update(r.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${o}`}return `${n}:legacy-${e}-${randomUUID().slice(0,8)}`}function Re(n){return `${n}:legacy-journal`}var L=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(y(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let r=this.get(e);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let o=Date.now(),i={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:o,lastActivityAt:o};return this.sessions.set(e,i),this.persist(i),i}startExecution(t,e,r){let o=this.registerSession(t);return (!o.executionId||o.skillName!==e)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=e,o.requiredMcpTools=[...new Set(r)],o.lastActivityAt=Date.now(),this.persist(o),o}bindTaskIdentity(t,e){let r=this.registerSession(t);return r.activeTurnId=e.turnId,r.activeRequestId=e.requestId,r.intentArtifactHash=e.intentArtifactHash,r.lastActivityAt=Date.now(),this.persist(r),r}get(t){let e=t.trim();if(!e)return null;let r=this.sessions.get(e);if(r)return this.replayEvidenceJournal(r),r;let o=this.snapshotPath(e);if(!existsSync(o))return null;try{let i=JSON.parse(readFileSync(o,"utf8"));return i.sessionId!==e||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=he(i.evidenceObligations),i.evidenceDegradations=ye(i.evidenceDegradations),i.evidenceOutcomes=ve(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(e,i),i)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let r=structuredClone(e);return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),r}addEvidenceObligation(t,e,r=Date.now(),o){let i=this.registerSession(t),a=(o?void 0:i.evidenceObligations.find(c=>c.contractId===e.id))?.obligationId??Wt(e.id,o,r);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:r,contract:e},`add\0${a}`),this.replayEvidenceJournal(i);let l=i.evidenceObligations.find(c=>c.obligationId===a);return l?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(l)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,r,o,i=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!a)return null;let l=/^[a-f0-9]{64}$/.test(o)?o:"";if(!l)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:i,fingerprint:l,violations:r.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let c=s.evidenceObligations.find(d=>d.obligationId===e);return c?structuredClone(c):null}resolveEvidenceObligation(t,e){let r=this.get(t);if(!r)return false;let o=r.evidenceObligations.find(s=>s.obligationId===e);if(!o)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:i},`resolve\0${e}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),true}resolveDegradedEvidence(t,e){let r=this.get(t),o=r?.evidenceDegradations.find(s=>s.obligationId===e);if(!r||!o)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:o.contractId,at:i},`resolve-degraded\0${e}\0${i}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),true}degradeEvidenceObligation(t,e,r,o=Date.now()){let i=this.get(t),s=i?.evidenceObligations.find(l=>l.obligationId===e);if(!i||!s)return false;let a=r.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:o,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=o,this.persist(i),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}),rmSync(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${me(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",me(t))}appendEvidenceEvent(t,e,r){let o=this.evidenceJournalDir(t);mkdirSync(o,{recursive:true,mode:448});let i=createHash("sha256").update(r).digest("hex"),s=join$1(o,`${e.kind}-${i}.json`);if(existsSync(s))return;let a=join$1(o,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(l){if(l.code!=="EEXIST")throw l}finally{rmSync(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=he(t.evidenceObligations),t.evidenceDegradations=ye(t.evidenceDegradations),t.evidenceOutcomes=ve(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let r;try{r=readdirSync(e).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let o=r.flatMap(i=>{try{let s=readFileSync(join$1(e,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Jt(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||be(i.kind)-be(s.kind));for(let i of o)this.applyEvidenceEvent(t,i);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let r=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(r)return;let s=t.evidenceObligations.find(a=>a.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let o=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!o||r||o.correctionFingerprint===e.fingerprint)return;o.attempt+=1,o.correctionRequested=true,o.correctionRequestedAt=e.at,o.correctionFingerprint=e.fingerprint,o.violations=e.violations;return}let i=o?.attempt??r?.attempt??0;if(e.kind==="resolve"&&r?.status==="degraded")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==e.obligationId);else if(r)return;e.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:i,contract:o?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:i,...e.kind==="degrade"?{reason:e.reason}:{}});}persist(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),r=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(r,JSON.stringify(t),{mode:384}),renameSync(r,e);}};function he(n){return Array.isArray(n)?n.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!Ee(e.contract))return [];let r=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:Re(e.contractId),o=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,i=e.correctionFingerprint??o;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...e,obligationId:r,correctionFingerprint:i}]}).slice(-8):[]}function ye(n){return Array.isArray(n)?n.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function ve(n){return Array.isArray(n)?n.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Jt(n){if(!n||typeof n!="object")return null;let t=n,e=t.kind;if(e!=="add"&&e!=="correction"&&e!=="resolve"&&e!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let o={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:Re(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return Ee(t.contract)?{kind:e,...o,contract:t.contract}:null;if(e==="correction"){let i=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...o,fingerprint:i,violations:t.violations}:null}return e==="resolve"?{kind:e,...o}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...o,reason:t.reason}:null}function be(n){return n==="add"?0:n==="correction"?1:2}function Ee(n){if(!n||typeof n!="object")return false;let t=n,e=t.requiredSections,r=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(r)&&r.length<=16&&r.every(o=>typeof o=="string"&&o.length<=128)&&typeof t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function we(n){let t=n.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function De(n,t){return t?`evt_tool_${createHash("sha256").update(`${n}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var zt=new Set(["Write","Edit","NotebookEdit"]),Ie="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 Ae(n){if(!zt.has(n.toolName))return null;let t=Kt(n.toolInput);if(!t)return null;let e=Yt(t,n.projectRoot),r=resolve(n.projectRoot,".claude");if(xe(e,r)&&basename(e).toLocaleUpperCase("en-US")==="MEMORY.MD")return Ie;let o=resolve(n.home??homedir(),".claude","projects");return xe(e,o)&&relative(o,e).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?Ie:null}function Kt(n){for(let t of ["file_path","notebook_path","path"]){let e=n[t];if(typeof e=="string"&&e.trim())return e.trim()}return null}function Yt(n,t){return resolve(isAbsolute(n)?n:resolve(t,n))}function xe(n,t){let e=relative(t,n);return e===""||!e.startsWith(`..${sep}`)&&e!==".."&&!isAbsolute(e)}function je(n){let t=on(n.toolName,n.toolInput),e=t?sn(n.projectRoot,n.toolName,n.toolInput):void 0;if(!t||!e||!n.toolUseId)return {allowed:true};let r=cn(e),o,i=0,s,a;try{a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100,readonly:!0});let c=a.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId);o=c?.contextHash,i=c?.issuedAt??0,s=c?.canonicalAction?.binding.operationTargets?.find(d=>ln(n.projectRoot,d.path,e));}catch{}finally{try{a?.close();}catch{}}let l={toolUseId:n.toolUseId,sessionId:n.sessionId,executionId:n.executionId,operation:t,path:e,before:r,contextReceipt:o,observedAt:Date.now()};if(pn(n.projectRoot,l),t==="edit"||t==="write"||t==="delete"){let c=gn(n.projectRoot,e),d=c?.success&&c.operation==="delete"&&!c.after.exists&&c.completedAt>=i,u=s?.expectedState==="existing"&&!r.exists||s?.expectedState==="missing"&&r.exists||!!(s?.contentHash&&r.hash!==s.contentHash);if(d||s?.expectedState==="existing"&&!r.exists)return Ce(n,l,"DEVFLOW_FILE_STATE_DELETED","The target was deleted after the active Context receipt. Refresh project context before editing or recreating it.");if(u)return Ce(n,l,"DEVFLOW_FILE_STATE_STALE","The target state no longer matches the active Context receipt. Refresh project context before overwriting it.")}return Le(n,l,true),{allowed:true,pending:l}}function Ce(n,t,e,r){return Le(n,t,false,e),{allowed:false,reasonCode:e,reason:r,pending:t}}function Le(n,t,e,r){v({event:"canonical.action.validated",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,contextReceipt:t.contextReceipt},level:e?"info":"warn",timestamp:Date.now(),data:{stage:"host_file_state_precondition",valid:e,operation:t.operation,targetPath:relative(n.projectRoot,t.path),targetExists:t.before.exists,targetHash:t.before.hash,reason:r,toolUseId:t.toolUseId}});}function on(n,t){if(n==="Read")return "read";if(n==="Edit"||n==="NotebookEdit")return "edit";if(n==="Write")return "write";if(n==="Delete"||n==="Bash"&&Pe(t.command))return "delete"}function sn(n,t,e){let r=an(e,["file_path","filePath","notebook_path","path","targetPath"])??(t==="Bash"?Pe(e.command):void 0);if(!r)return;let o=isAbsolute(r)?normalize(r):resolve(n,r),i=relative(n,o);return i.startsWith("..")||isAbsolute(i)?void 0:o}function Pe(n){return typeof n!="string"?void 0:/(?:^|[;&|]\s*)\s*(?:rm|unlink)\s+(?:-[A-Za-z]+\s+)*(?:--\s+)?(["']?)([^\s;&|"']+)\1/u.exec(n)?.[2]}function an(n,t){for(let e of t){let r=n[e];if(typeof r=="string"&&r.trim())return r.trim()}}function cn(n){if(!existsSync$1(n))return {exists:false};try{return {exists:!0,hash:createHash$1("sha256").update(readFileSync$1(n)).digest("hex")}}catch{return {exists:true}}}function ln(n,t,e){return (isAbsolute(t)?normalize(t):resolve(n,t))===normalize(e)}function Me(n){return join(y(n),"file-state")}function $e(n){return join(Me(n),"pending.json")}function dn(n){return join(Me(n),"observations.jsonl")}function un(n){try{return JSON.parse(readFileSync$1($e(n),"utf8"))}catch{return {}}}function pn(n,t){let e=$e(n);mkdirSync$1(dirname(e),{recursive:true});let r=un(n);r[t.toolUseId]=t,fn(e,JSON.stringify(r));}function gn(n,t){try{let e=readFileSync$1(dn(n),"utf8").trim().split(`
|
|
3
|
-
`);for(let
|
|
4
|
-
`);}catch{}return g}catch{
|
|
1
|
+
import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync,rmSync,linkSync,renameSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey,getDevFlowStateRoot,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {request}from'node:http';import {existsSync as existsSync$1,mkdirSync as mkdirSync$1,appendFileSync,chmodSync,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1}from'node:fs';import {join,resolve,basename,relative,sep,dirname,isAbsolute,normalize}from'node:path';import {maybeRunDiagnosticLogCleanup,rotateDiagnosticLogFile,emitSemanticControlLog}from'@devflow-tools/telemetry';import {fileURLToPath}from'url';import {createHash as createHash$1}from'node:crypto';import {homedir}from'node:os';import {randomUUID,createHash}from'crypto';import {DatabaseSync}from'node:sqlite';function k(n,t,e){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:n,timestamp:Date.now(),duration:e,success:t.success!==!1,metadata:t});}finally{o.close();}}catch{}}var tt=getLocalApiKey(),$=join(getDevFlowStateRoot(),"errors");async function X(n,t,e={}){let o=e.endpoint??process.env.DEVFLOW_SERVER_URL?.trim()??nt();if(!o)return {delivered:false,suppressed:false,fallbackReason:"runtime_not_ready"};let r=e.timeout??1500,i=e.durableMirror??true,s=e.maxRetries??(i?0:2),a=e.circuitBreaker??true,l=acquireRuntimeHttpCircuit(o,n);if(a&&!l.allowed)return {delivered:false,suppressed:true,fallbackReason:l.state.fallbackReason};let c;for(let u=0;u<=s;u+=1)try{return await ot(o,n,t,r),a&®isterRuntimeHttpSuccess(o,n).transitioned&&k("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:l.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(p){c=p instanceof Error?p:new Error(String(p)),u<s&&await rt(Math.min(100*2**u,1e3));}if(!c)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return K(n,c),{delivered:false,suppressed:false,fallbackReason:c.message};let d=registerRuntimeHttpFailure(o,n,e.fallbackReason??(i?"local_durable_mirror":"http_delivery_failed"));return d.transitioned&&(K(n,c),k("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:l.state.status,status:"open",failures:d.state.failures,openUntil:d.state.openUntil,fallbackReason:d.state.fallbackReason})),{delivered:false,suppressed:false,fallbackReason:d.state.fallbackReason}}function nt(){let n=readRuntimeState();return n?.status==="ready"&&n.dashboardAvailable?n.url:void 0}function ot(n,t,e,o){return new Promise((r,i)=>{let s=JSON.stringify(e),a=new URL(t,n),l=false,c=u=>{l||(l=true,u?i(u):r());},d=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":tt,"Content-Length":Buffer.byteLength(s)},timeout:o},u=>{u.on("error",c),u.on("end",()=>{let p=u.statusCode??0;c(p>=200&&p<300?void 0:new Error(`HTTP ${p}`));}),u.resume();});d.on("error",c),d.on("timeout",()=>d.destroy(new Error(`HTTP mirror timed out after ${o}ms`))),d.write(s),d.end();})}function K(n,t){try{existsSync$1($)||mkdirSync$1($,{recursive:!0});let e=join($,"http-errors.log"),o=`${new Date().toISOString()} | ${n} | ${t.message}
|
|
2
|
+
`;rotateDiagnosticLogFile({path:e,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(o)}),appendFileSync(e,o);}catch{}}function rt(n){return new Promise(t=>setTimeout(t,n))}var te=1e4,dt=3e4,O=500,A=class{constructor(t){this.retryScheduled=false;this.metricAggregationScheduled=false;this.apiUrl=t?.apiUrl,this.cacheDir=t?.cacheDir??join$1(getDevFlowStateRoot(),"global","telemetry-cache"),this.database=t?.database??null,this.ownsDatabase=!t?.database;let e=t?.busyTimeoutMs??Number(process.env.DEVFLOW_TELEMETRY_DB_BUSY_TIMEOUT_MS);this.busyTimeoutMs=Number.isSafeInteger(e)&&e>=0?e:100;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,o,r,i=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:o,startedAt:r,projectRoot:i,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",o=Date.now(),r){let i={executionId:t,status:e,finishedAt:o,metadata:r},s=this.commitOrCache("execution_complete",i);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",i),s}async sendSessionStart(t,e,o){let r={id:t,projectRoot:e,startedAt:o,label:e.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",r);return i&&this.postHttp("/api/telemetry/sessions",r),i}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),e}async endSession(t,e=Date.now()){let o={sessionId:t,finishedAt:e},r=this.commitOrCache("session_end",o);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),r}async flushCache(){try{let e=this.getDatabase(),o=e.listTelemetryFailures({unresolvedOnly:!0,limit:O}).reverse();for(let r of o)try{this.applyOperation(r.operation,r.payload),e.resolveTelemetryFailure(r.id);}catch{}e.trimTelemetryFailures(O);}catch{}let t=(existsSync(this.cacheDir)?readdirSync(this.cacheDir):[]).filter(e=>e.endsWith(".json")).map(e=>{let o=join$1(this.cacheDir,e);try{return {cacheFile:o,envelope:ut(JSON.parse(readFileSync(o,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,o)=>e.envelope.timestamp-o.envelope.timestamp||ne(e.envelope.operation)-ne(o.envelope.operation));for(let{cacheFile:e,envelope:o}of t)try{let r=this.getDatabase();r.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id),unlinkSync(e);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:this.busyTimeoutMs}),this.database}commitOrCache(t,e){try{return this.applyOperation(t,e),!0}catch(o){return this.cacheOperation(t,e,o),false}}applyOperation(t,e){let o=this.getDatabase();switch(t){case "tool_call":this.ensureParentSession(o,e),o.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(o,e),o.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":o.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":o.ensureSession(e),o.insertRun({id:oe(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!o.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,failureCategory:e.failureCategory,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":o.closeSession(e.sessionId,e.finishedAt),o.updateRun(oe(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let o=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!o)throw new Error("Canonical session ID is required for telemetry");let r=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:o,projectRoot:r,label:r==="unknown"?void 0:r.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,o){let r=Date.now(),i={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:o instanceof Error?o.message:String(o),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:t,payload:e,error:i.failure,createdAt:r}),s.trimTelemetryFailures(O),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${r}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(i,null,2),{mode:384}),this.trimRetryCache(),this.scheduleRetry();}catch{}}trimRetryCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-O)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},dt).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){X(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=te?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,te)}...`}}};function ne(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function oe(n){return `hook-run:${n}`}function ut(n){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.id!="string"||typeof t.operation!="string"||t.payload===void 0||typeof t.failure!="string"||typeof t.timestamp!="number")throw new Error("Invalid telemetry cache envelope");return t}function w(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function y(n){return getProjectStateDir(w(n))}var v=emitSemanticControlLog;var vt=2,bt=1;function _t(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join$1(dirname$1(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function re(n=_t()){let t=[join$1(n,"dist","command-registry.json"),join$1(n,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let o=JSON.parse(readFileSync(e,"utf8"));if(o.version!==vt&&o.version!==bt||!Rt(o.commands)){v({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:"contract_mismatch",registryPath:e}});continue}return o.commands}catch(o){v({event:"hook.runtime.degraded",identity:{projectRoot:process.env.CLAUDE_PROJECT_DIR||process.cwd()},level:"warn",timestamp:Date.now(),data:{stage:"command_registry",reason:o.message,fallback:"next_registry_candidate"}});}return null}function Rt(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return C(e.mcpTools)&&C(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||C(e.runtimePackages))&&(e.hostTools===void 0||Et(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Et(n){return !!n&&typeof n=="object"&&!Array.isArray(n)&&Object.entries(n).every(([t,e])=>t.length>0&&C(e))}function C(n){return Array.isArray(n)&&n.every(t=>typeof t=="string"&&t.length>0)}function ie(n){let t=re();return t?t[n]?.mcpTools??[]:[]}function T(n){if(!n||typeof n!="object"||Array.isArray(n))return {};let t=n,e={};for(let o of ["lastMcpCall","bypassCount"])if(o in t){let r=t[o];if(r==null)continue;e[o]=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;}return e}function wt(n,t){return n.lastMcpCall===t.lastMcpCall&&n.bypassCount===t.bypassCount}function ae(n,t,e){let o=e instanceof Error?e.message:String(e);v({event:"hook.runtime.degraded",identity:{projectRoot:n},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:o,fallback:"fail_open"}});}function ce(n,t,e){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r={},i=o.updateHookReceipt(n,a=>(r=T(a),T(t(r)))),s=T(i);return {receipt:s,applied:!0,changed:!wt(r,s)}}catch(r){return ae(n,e,r),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function le(n){let t;try{return t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),T(t.getHookReceipt(n))}catch(e){return ae(n,"update",e),{}}finally{try{t?.close();}catch{}}}function Dt(n,t){return ce(n,()=>t,"write").applied}function It(n,t){return ce(n,t,"update")}var se={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},xt=new Set(["Write","Edit","NotebookEdit"]),kt=new Set(["failed","timeout","unavailable"]);function St(n){switch(n){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var F=class{constructor(t,e,o){this.projectRoot=t;this.sessionId=e;this.executionId=o;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(e&&e.expiresAt>Date.now())return "context_ready";e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}return "context_gathering"}getContextReceipt(){if(!this.sessionId||!this.executionId)return null;let t;try{t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let e=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);return e&&e.expiresAt>Date.now()?e:(e&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId),null)}catch{return null}finally{try{t?.close();}catch{}}}evaluate(t,e){let o=this.getPhase();if(e||t==="Skill")return {permissionDecision:"allow"};if(o==="context_gathering"&&se[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_REQUIRED",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${t}.`};if(o==="context_ready"){if(xt.has(t)){let l=this.evaluateRequiredAction();if(l)return l}return {permissionDecision:"allow"}}let r=se[t];if(!r)return {permissionDecision:"allow"};let i=It(this.projectRoot,l=>({...l,bypassCount:(l.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,a=St(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${r} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){Dt(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,o,r){if(!this.sessionId||!this.executionId)return false;let i;try{i=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=i.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let a=Date.now(),l=r?.trim()?`${r.trim()}:${e}`:`${t}:${e}:${a}`,c=s.actionAttempts??[];return i.upsertContextReceipt({...s,actionAttempts:c.some(d=>d.id===l||r&&d.toolUseId===r&&d.status===e)?c:[...c,{id:l,tool:t,status:e,attemptedAt:a,toolUseId:r,reason:o?.slice(0,500)}].slice(-20),actionSatisfiedAt:e==="succeeded"?a:s.actionSatisfiedAt,actionDegradation:e==="succeeded"?void 0:s.actionDegradation}),!0}catch{return false}finally{try{i?.close();}catch{}}}evaluateRequiredAction(){let t=this.getContextReceipt(),e=t?.canonicalAction;if(!t||!e||!e.required||e.status!=="required")return null;let o=e.binding;if(o.requiredContextReceipt!==t.contextHash||o.projectRoot!==this.projectRoot||o.sessionId!==this.sessionId||o.requestId!==t.requestId||o.executionId&&o.executionId!==this.executionId)return {permissionDecision:"deny",reasonCode:"DEVFLOW_ACTION_BINDING_STALE",reason:"DevFlow canonical action binding is stale or mismatched. Call mcp__devflow__get_project_context again before writing."};if(t.actionSatisfiedAt)return null;if(t.actionDegradation?.authorizedByContextReceipt===t.contextHash)return {permissionDecision:"allow",additionalContext:`DevFlow degraded fallback authorized by context receipt ${t.contextHash}: ${t.actionDegradation.reason}`};let r=(t.actionAttempts??[]).filter(i=>i.tool===e.tool&&kt.has(i.status));if(r.length>0){let i=r.at(-1),s={missedTool:e.tool,failedAttemptCount:r.length,reason:`${i.status}:${i.reason??"canonical domain action did not complete"}`,authorizedByContextReceipt:t.contextHash,authorizedAt:Date.now()};return this.persistDegradation(t,s),{permissionDecision:"allow",additionalContext:`DevFlow canonical tool mcp__devflow__${e.tool} ${i.status}; degraded direct write authorized by context receipt ${t.contextHash}. Preserve the action contract and verification plan.`}}return {permissionDecision:"deny",reasonCode:"DEVFLOW_REQUIRED_ACTION",reason:`DevFlow required action not completed. Call mcp__devflow__${e.tool} using context receipt ${t.contextHash}, then retry the write. Direct fallback is allowed only after unavailable, failed, or timeout evidence.`}}persistDegradation(t,e){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let r=o.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!r||r.contextHash!==t.contextHash||r.actionDegradation)return;o.upsertContextReceipt({...r,actionDegradation:e});let i=o.getSkillExecution(t.executionId);if(!i)return;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...i.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(i.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(i.fallbackCount??0)+1,fallbackReasons:[...new Set([...i.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...a,e]}});}catch{}finally{try{o?.close();}catch{}}}};var Mt=10*1024*1024,$t=5;function Nt(n){return createHash$1("sha256").update(n).digest("hex").slice(0,16)}function de(n){return join(homedir(),".devflow","logs","hook-debug",`${Nt(n)}.jsonl`)}function ue(n,t,e={}){let o=e.maxBytes??Mt,r=e.maxFiles??$t;mkdirSync$1(dirname(n),{recursive:true,mode:448});let i=Buffer.byteLength(t);rotateDiagnosticLogFile({path:n,maxBytes:o,maxFiles:r,incomingBytes:i}),appendFileSync(n,t,{mode:384}),chmodSync(n,384);}var U="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function pe(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function he(n){return Buffer.from(n,"utf8").toString("base64url")}function Wt(n,t,e){let o=t?.trim();if(o){let r=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${r}`}return `${n}:legacy-${e}-${randomUUID().slice(0,8)}`}function Ee(n){return `${n}:legacy-journal`}var j=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(y(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let o=this.get(e);if(o)return o.lastActivityAt=Date.now(),this.persist(o),o;let r=Date.now(),i={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:r,lastActivityAt:r};return this.sessions.set(e,i),this.persist(i),i}startExecution(t,e,o){let r=this.registerSession(t);return (!r.executionId||r.skillName!==e)&&(r.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),r.skillName=e,r.requiredMcpTools=[...new Set(o)],r.lastActivityAt=Date.now(),this.persist(r),r}bindTaskIdentity(t,e){let o=this.registerSession(t);return o.activeTurnId=e.turnId,o.activeRequestId=e.requestId,o.intentArtifactHash=e.intentArtifactHash,o.lastActivityAt=Date.now(),this.persist(o),o}get(t){let e=t.trim();if(!e)return null;let o=this.sessions.get(e);if(o)return this.replayEvidenceJournal(o),o;let r=this.snapshotPath(e);if(!existsSync(r))return null;try{let i=JSON.parse(readFileSync(r,"utf8"));return i.sessionId!==e||i.projectRoot!==this.projectRoot?null:(i.requiredMcpTools=Array.isArray(i.requiredMcpTools)?i.requiredMcpTools:[],i.evidenceObligations=ye(i.evidenceObligations),i.evidenceDegradations=ve(i.evidenceDegradations),i.evidenceOutcomes=be(i.evidenceOutcomes),this.replayEvidenceJournal(i),this.sessions.set(e,i),i)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let o=structuredClone(e);return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),o}addEvidenceObligation(t,e,o=Date.now(),r){let i=this.registerSession(t),a=(r?void 0:i.evidenceObligations.find(c=>c.contractId===e.id))?.obligationId??Wt(e.id,r,o);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:o,contract:e},`add\0${a}`),this.replayEvidenceJournal(i);let l=i.evidenceObligations.find(c=>c.obligationId===a);return l?(i.lastActivityAt=Date.now(),this.persist(i),structuredClone(l)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,o,r,i=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!a)return null;let l=/^[a-f0-9]{64}$/.test(r)?r:"";if(!l)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:i,fingerprint:l,violations:o.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${l}`),this.replayEvidenceJournal(s),s.lastActivityAt=i,this.persist(s);let c=s.evidenceObligations.find(d=>d.obligationId===e);return c?structuredClone(c):null}resolveEvidenceObligation(t,e){let o=this.get(t);if(!o)return false;let r=o.evidenceObligations.find(s=>s.obligationId===e);if(!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:r.contractId,at:i},`resolve\0${e}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}resolveDegradedEvidence(t,e){let o=this.get(t),r=o?.evidenceDegradations.find(s=>s.obligationId===e);if(!o||!r)return false;let i=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:r.contractId,at:i},`resolve-degraded\0${e}\0${i}`),this.replayEvidenceJournal(o),o.lastActivityAt=i,this.persist(o),true}degradeEvidenceObligation(t,e,o,r=Date.now()){let i=this.get(t),s=i?.evidenceObligations.find(l=>l.obligationId===e);if(!i||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:r,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(i),i.lastActivityAt=r,this.persist(i),true}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}),rmSync(this.evidenceJournalDir(e),{recursive:true,force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join$1(this.sessionsDir,`${he(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",he(t))}appendEvidenceEvent(t,e,o){let r=this.evidenceJournalDir(t);mkdirSync(r,{recursive:true,mode:448});let i=createHash("sha256").update(o).digest("hex"),s=join$1(r,`${e.kind}-${i}.json`);if(existsSync(s))return;let a=join$1(r,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(l){if(l.code!=="EEXIST")throw l}finally{rmSync(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=ye(t.evidenceObligations),t.evidenceDegradations=ve(t.evidenceDegradations),t.evidenceOutcomes=be(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let o;try{o=readdirSync(e).filter(i=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(i)).slice(0,4096);}catch{return}let r=o.flatMap(i=>{try{let s=readFileSync(join$1(e,i),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Jt(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((i,s)=>i.at-s.at||_e(i.kind)-_e(s.kind));for(let i of r)this.applyEvidenceEvent(t,i);t.evidenceObligations=t.evidenceObligations.slice(-8),t.evidenceDegradations=t.evidenceDegradations.slice(-20),t.evidenceOutcomes=t.evidenceOutcomes.slice(-20);}applyEvidenceEvent(t,e){let o=t.evidenceOutcomes.find(s=>s.obligationId===e.obligationId);if(e.kind==="add"){if(o)return;let s=t.evidenceObligations.find(a=>a.obligationId===e.obligationId);s?(s.contract=e.contract,s.promptedAt=Math.min(s.promptedAt,e.at)):t.evidenceObligations.push({obligationId:e.obligationId,contractId:e.contractId,contract:e.contract,promptedAt:e.at,attempt:0,correctionRequested:false,violations:[]});return}let r=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!r||o||r.correctionFingerprint===e.fingerprint)return;r.attempt+=1,r.correctionRequested=true,r.correctionRequestedAt=e.at,r.correctionFingerprint=e.fingerprint,r.violations=e.violations;return}let i=r?.attempt??o?.attempt??0;if(e.kind==="resolve"&&o?.status==="degraded")t.evidenceOutcomes=t.evidenceOutcomes.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations=t.evidenceDegradations.filter(s=>s.obligationId!==e.obligationId);else if(o)return;e.kind==="degrade"?(t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceDegradations.push({obligationId:e.obligationId,contractId:e.contractId,reason:e.reason,degradedAt:e.at,attempt:i,contract:r?.contract})):t.evidenceObligations=t.evidenceObligations.filter(s=>s.obligationId!==e.obligationId),t.evidenceOutcomes.push({obligationId:e.obligationId,contractId:e.contractId,status:e.kind==="resolve"?"resolved":"degraded",completedAt:e.at,attempt:i,...e.kind==="degrade"?{reason:e.reason}:{}});}persist(t){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),o=`${e}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(t),{mode:384}),renameSync(o,e);}};function ye(n){return Array.isArray(n)?n.flatMap(t=>{if(!t||typeof t!="object")return [];let e=t;if(typeof e.contractId!="string"||e.contractId.length===0||e.contractId.length>128||typeof e.promptedAt!="number"||typeof e.attempt!="number"||typeof e.correctionRequested!="boolean"||!Array.isArray(e.violations)||!we(e.contract))return [];let o=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:Ee(e.contractId),r=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,i=e.correctionFingerprint??r;return i!==void 0&&!/^[a-f0-9]{64}$/.test(i)?[]:[{...e,obligationId:o,correctionFingerprint:i}]}).slice(-8):[]}function ve(n){return Array.isArray(n)?n.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&typeof e.reason=="string"&&typeof e.degradedAt=="number"&&typeof e.attempt=="number"}).slice(-20):[]}function be(n){return Array.isArray(n)?n.filter(t=>{if(!t||typeof t!="object")return false;let e=t;return typeof e.obligationId=="string"&&typeof e.contractId=="string"&&(e.status==="resolved"||e.status==="degraded")&&typeof e.completedAt=="number"&&typeof e.attempt=="number"&&(e.reason===void 0||typeof e.reason=="string")}).slice(-20):[]}function Jt(n){if(!n||typeof n!="object")return null;let t=n,e=t.kind;if(e!=="add"&&e!=="correction"&&e!=="resolve"&&e!=="degrade"||typeof t.contractId!="string"||t.contractId.length>128||typeof t.at!="number")return null;let r={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:Ee(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return we(t.contract)?{kind:e,...r,contract:t.contract}:null;if(e==="correction"){let i=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof i=="string"&&/^[a-f0-9]{64}$/.test(i)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...r,fingerprint:i,violations:t.violations}:null}return e==="resolve"?{kind:e,...r}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...r,reason:t.reason}:null}function _e(n){return n==="add"?0:n==="correction"?1:2}function we(n){if(!n||typeof n!="object")return false;let t=n,e=t.requiredSections,o=t.prohibitedClaims;return t.version==="1.0"&&typeof t.id=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(t.id)&&typeof t.runtimeProfilingOccurred=="boolean"&&typeof t.samplingEvidenceOccurred=="boolean"&&Array.isArray(e)&&e.length===3&&e[0]==="\u5DE5\u5177\u53D1\u73B0"&&e[1]==="\u6A21\u578B\u5047\u8BBE"&&e[2]==="\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"&&Array.isArray(o)&&o.length<=16&&o.every(r=>typeof r=="string"&&r.length<=128)&&typeof t.canonicalReport=="string"&&Buffer.byteLength(t.canonicalReport,"utf8")<=48*1024&&!!t.correctionPolicy&&t.correctionPolicy.maxAttempts===1&&t.correctionPolicy.repeatedViolation==="fail_open"}function De(n){let t=n.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function Ie(n,t){return t?`evt_tool_${createHash("sha256").update(`${n}\0${t}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var zt=new Set(["Write","Edit","NotebookEdit"]),xe="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 Ce(n){if(!zt.has(n.toolName))return null;let t=Kt(n.toolInput);if(!t)return null;let e=Yt(t,n.projectRoot),o=resolve(n.projectRoot,".claude");if(ke(e,o)&&basename(e).toLocaleUpperCase("en-US")==="MEMORY.MD")return xe;let r=resolve(n.home??homedir(),".claude","projects");return ke(e,r)&&relative(r,e).split(sep).some(s=>s.toLocaleLowerCase("en-US")==="memory")?xe:null}function Kt(n){for(let t of ["file_path","notebook_path","path"]){let e=n[t];if(typeof e=="string"&&e.trim())return e.trim()}return null}function Yt(n,t){return resolve(isAbsolute(n)?n:resolve(t,n))}function ke(n,t){let e=relative(t,n);return e===""||!e.startsWith(`..${sep}`)&&e!==".."&&!isAbsolute(e)}function je(n){let t=rn(n.toolName,n.toolInput),e=t?sn(n.projectRoot,n.toolName,n.toolInput):void 0;if(!t||!e||!n.toolUseId)return {allowed:true};let o=cn(e),r,i=0,s,a;try{a=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:100,readonly:!0});let c=a.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId);r=c?.contextHash,i=c?.issuedAt??0,s=c?.canonicalAction?.binding.operationTargets?.find(d=>ln(n.projectRoot,d.path,e));}catch{}finally{try{a?.close();}catch{}}let l={toolUseId:n.toolUseId,sessionId:n.sessionId,executionId:n.executionId,operation:t,path:e,before:o,contextReceipt:r,observedAt:Date.now()};if(pn(n.projectRoot,l),t==="edit"||t==="write"||t==="delete"){let c=gn(n.projectRoot,e),d=c?.success&&c.operation==="delete"&&!c.after.exists&&c.completedAt>=i,u=s?.expectedState==="existing"&&!o.exists||s?.expectedState==="missing"&&o.exists||!!(s?.contentHash&&o.hash!==s.contentHash);if(d||s?.expectedState==="existing"&&!o.exists)return Te(n,l,"DEVFLOW_FILE_STATE_DELETED","The target was deleted after the active Context receipt. Refresh project context before editing or recreating it.");if(u)return Te(n,l,"DEVFLOW_FILE_STATE_STALE","The target state no longer matches the active Context receipt. Refresh project context before overwriting it.")}return Pe(n,l,true),{allowed:true,pending:l}}function Te(n,t,e,o){return Pe(n,t,false,e),{allowed:false,reasonCode:e,reason:o,pending:t}}function Pe(n,t,e,o){v({event:"canonical.action.validated",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,contextReceipt:t.contextReceipt},level:e?"info":"warn",timestamp:Date.now(),data:{stage:"host_file_state_precondition",valid:e,operation:t.operation,targetPath:relative(n.projectRoot,t.path),targetExists:t.before.exists,targetHash:t.before.hash,reason:o,toolUseId:t.toolUseId}});}function rn(n,t){if(n==="Read")return "read";if(n==="Edit"||n==="NotebookEdit")return "edit";if(n==="Write")return "write";if(n==="Delete"||n==="Bash"&&Me(t.command))return "delete"}function sn(n,t,e){let o=an(e,["file_path","filePath","notebook_path","path","targetPath"])??(t==="Bash"?Me(e.command):void 0);if(!o)return;let r=isAbsolute(o)?normalize(o):resolve(n,o),i=relative(n,r);return i.startsWith("..")||isAbsolute(i)?void 0:r}function Me(n){return typeof n!="string"?void 0:/(?:^|[;&|]\s*)\s*(?:rm|unlink)\s+(?:-[A-Za-z]+\s+)*(?:--\s+)?(["']?)([^\s;&|"']+)\1/u.exec(n)?.[2]}function an(n,t){for(let e of t){let o=n[e];if(typeof o=="string"&&o.trim())return o.trim()}}function cn(n){if(!existsSync$1(n))return {exists:false};try{return {exists:!0,hash:createHash$1("sha256").update(readFileSync$1(n)).digest("hex")}}catch{return {exists:true}}}function ln(n,t,e){return (isAbsolute(t)?normalize(t):resolve(n,t))===normalize(e)}function $e(n){return join(y(n),"file-state")}function Ne(n){return join($e(n),"pending.json")}function dn(n){return join($e(n),"observations.jsonl")}function un(n){try{return JSON.parse(readFileSync$1(Ne(n),"utf8"))}catch{return {}}}function pn(n,t){let e=Ne(n);mkdirSync$1(dirname(e),{recursive:true});let o=un(n);o[t.toolUseId]=t,fn(e,JSON.stringify(o));}function gn(n,t){try{let e=readFileSync$1(dn(n),"utf8").trim().split(`
|
|
3
|
+
`);for(let o=e.length-1;o>=0;o-=1){let r=JSON.parse(e[o]);if(r.path===t)return r}}catch{}}function fn(n,t){let e=`${n}.${process.pid}.${Date.now()}.tmp`;writeFileSync$1(e,t,{encoding:"utf8",mode:384}),renameSync$1(e,n);}var vn=new Set(["delivered","cancelled","rejected"]),bn=new Set(["Write","Edit","NotebookEdit","Bash"]);function G(n,t,e,o){if(!bn.has(e)||!t.trim())return null;let r=join(n,".devflow","delivery-line","state.db");if(!existsSync$1(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 l=JSON.parse(a.payload),c=typeof l.stage=="string"?l.stage:"unknown";if(!vn.has(c)){if(o&&c==="executing"&&i.prepare("SELECT id FROM delivery_tasks WHERE case_id = ? AND lease_expires_at > ? AND lease_owner = ? AND fencing_token > 0 LIMIT 1").get(a.id,Date.now(),`${a.id}:execution`)?.id&&t===a.id)return null;if(l.sessionId===t||t===a.id)return {code:"DELIVERY_AUTHORITY_REQUIRED",caseId:a.id,stage:c,message:`Delivery case ${a.id} is ${c}; 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 D(){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}function Ue(n){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:n}}}function In(n){let t=y(n);return existsSync(t)||mkdirSync(t,{recursive:true}),t}function xn(n,t,e,o,r,i){let s=join$1(In(n),"event-map.json"),a=[];try{existsSync(s)&&(a=JSON.parse(readFileSync(s,"utf-8")));}catch{}a.push({sessionId:t,toolName:e,toolUseId:o,eventId:r,timestamp:i}),writeFileSync(s,JSON.stringify(a));}function kn(n){switch(n){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"}}async function Sn(n){let t=pe();try{if(!n||n.trim()==="")return D();let e=JSON.parse(n),o=Date.now();try{maybeRunDiagnosticLogCleanup(w(),{now:o});}catch{}let r=w(),i=new A;e.tool_name.startsWith("mcp__devflow__")&&(typeof e.tool_input.projectRoot!="string"||!e.tool_input.projectRoot.trim())&&(e.tool_input.projectRoot=r);let s=e.session_id?.trim();if(!s)return Ue(U);let a=new j(r),l=a.get(s)!==null;if(a.registerSession(s),l||await i.sendSessionStart(s,r,Date.now()),e.tool_name==="Skill"){let m=e.tool_input?.skill,f=m?De(m):null;if(f){let h=a.get(s)?.executionId,E=a.startExecution(s,f,ie(f));E.executionId&&E.executionId!==h&&await i.sendExecutionStart(E.executionId,s,f,E.lastActivityAt,r,E.requiredMcpTools);}}let c=a.get(s);e.tool_name.startsWith("mcp__devflow__")&&(e.tool_input._devflow_session_id=s,e.tool_input._devflow_execution_id=c?.executionId??s,c?.activeTurnId&&(e.tool_input._devflow_turn_id=c.activeTurnId),c?.activeRequestId&&(e.tool_input._devflow_request_id=c.activeRequestId),c?.intentArtifactHash&&(e.tool_input._devflow_intent_artifact_hash=c.intentArtifactHash),c?.skillName&&(e.tool_input._devflow_active_skill=c.skillName),e.tool_use_id&&(e.tool_input._devflow_tool_use_id=e.tool_use_id));let d=e.tool_name.startsWith("mcp__"),u=d?e.tool_name.replace(/^mcp__[^_]+__/,""):void 0,p=new F(r,s,c?.executionId),z=p.getPhase(),g,I,M=G(r,s,e.tool_name,c?.executionId);if(M)I=M.code,g={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${M.message} Resolve the case blocker or obtain an authorized task lease before retrying.`}};else {let m=Ce({toolName:e.tool_name,toolInput:e.tool_input,projectRoot:r}),f=je({projectRoot:r,sessionId:s,executionId:c?.executionId,toolUseId:e.tool_use_id,toolName:e.tool_name,toolInput:e.tool_input}),h=m?{permissionDecision:"deny",reason:m}:f.allowed?p.evaluate(e.tool_name,d):{permissionDecision:"deny",reason:f.reason,reasonCode:f.reasonCode};h.permissionDecision==="deny"?(I=m?"DEVFLOW_CANONICAL_MEMORY_REQUIRED":h.reasonCode??"DEVFLOW_CONTEXT_REQUIRED",g={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:h.reason??"MCP context required"}}):h.additionalContext?g=Ue(h.additionalContext):g=D();}e.tool_name.startsWith("mcp__devflow__")&&(g.hookSpecificOutput.updatedInput=e.tool_input),t&&g.hookSpecificOutput.permissionDecision==="allow"&&(g.hookSpecificOutput.additionalContext=U);let qe=c?.executionId??s,R={eventId:Ie(s,e.tool_use_id),executionId:qe,sessionId:s,projectRoot:r,toolUseId:e.tool_use_id,timestamp:Date.now(),toolName:e.tool_name,toolType:d?"mcp":e.tool_name==="Agent"?"subagent":"direct",isMcpTool:d,mcpToolName:u,mcpEnforced:d&&z==="context_gathering",mcpFallback:!d&&z==="context_gathering",kind:kn(e.tool_name),input:e.tool_input,duration:0,blocked:g.hookSpecificOutput.permissionDecision==="deny",blockReason:g.hookSpecificOutput.permissionDecision==="deny"?I??"DEVFLOW_CONTEXT_REQUIRED":void 0},x=await i.sendEvent(R);x&&!R.blocked&&xn(r,s,e.tool_name,e.tool_use_id,x,R.timestamp),x&&R.blocked&&await i.completeEvent({eventId:x,sessionId:s,error:I??"DEVFLOW_CONTEXT_REQUIRED",duration:Date.now()-R.timestamp,completedAt:Date.now()});try{let m=le(r),f={ts:o,tool:e.tool_name,sessionId:s,skill:c?.skillName??"(none)",requiredTools:c?.requiredMcpTools??[],isMcp:d,enforce:c?.executionId!==void 0,stateless:c?.executionId===void 0&&!d&&e.tool_name!=="Skill",bypassCount:m.bypassCount??0,decision:g.hookSpecificOutput.permissionDecision,env_CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd()};ue(de(r),`${JSON.stringify(f)}
|
|
4
|
+
`);}catch{}return g}catch{try{let e=JSON.parse(n),o=w(),r=G(o,String(e.session_id??""),String(e.tool_name??""),void 0);if(r)return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:r.message}}}catch{}return D()}}if(process.argv[1]?.endsWith("pre-tool-use")||process.argv[1]?.endsWith("pre-tool-use.js")){let n=console.log.bind(console);console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{let e=await Sn(t);n(JSON.stringify(e));}),process.stdin.on("error",()=>{n(JSON.stringify(D())),process.exit(0);}),setTimeout(()=>{n(JSON.stringify(D())),process.exit(0);},4e3).unref();}export{Sn as handlePreToolUse};
|