@devflow-tools/cli 0.18.25 → 0.18.27
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/init.d.ts.map +1 -1
- package/dist/commands/init.js +3 -18
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/setup.js +1 -1
- package/dist/commands/setup.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/plugin-setup.d.ts +0 -6
- package/dist/lib/plugin-setup.d.ts.map +1 -1
- package/dist/lib/plugin-setup.js +1 -29
- package/dist/lib/plugin-setup.js.map +1 -1
- package/dist/plugin-files/.claude-plugin/plugin.json +1 -1
- package/dist/plugin-files/.mcp.json +12 -0
- package/dist/plugin-files/dist/command-registry.json +6 -6
- package/dist/plugin-files/dist/hooks/hook-daemon.js +27 -27
- package/dist/plugin-files/dist/hooks/post-tool-use.js +6 -6
- package/dist/plugin-files/hooks/session-start +3 -1
- package/dist/plugin-files/package.json +14 -13
- package/package.json +28 -28
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {existsSync,readFileSync,rmSync,mkdirSync,writeFileSync,linkSync,readdirSync,renameSync,unlinkSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {getLogWriter,emitSemanticControlLog,SemanticRuntimeEventProjector,rotateDiagnosticLogFile}from'@devflow-tools/telemetry';import {request}from'node:http';import {mkdirSync as mkdirSync$1,appendFileSync,existsSync as existsSync$1,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1,readdirSync as readdirSync$1}from'node:fs';import {join,dirname,relative,resolve,isAbsolute,sep}from'node:path';import {getLocalApiKey,getDevFlowStateRoot,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase,retrievalLedgerTransitionId}from'@devflow-tools/database';import {randomUUID,createHash}from'crypto';import {fileURLToPath}from'url';import {TaskKernel,TaskEventStore}from'@devflow-tools/task-runtime';import {createHash as createHash$1}from'node:crypto';import {classifyWorkflowFailure}from'@devflow-tools/workflow-engine/failure-classifier';function
|
|
2
|
-
`;rotateDiagnosticLogFile({path:e,maxBytes:50*1024*1024,maxFiles:5,incomingBytes:Buffer.byteLength(o)}),appendFileSync(e,o);}catch{}}function bt(n){return new Promise(t=>setTimeout(t,n))}var m=emitSemanticControlLog;function Z(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function w(n){return getProjectStateDir(Z(n))}function be(n){return Buffer.from(n,"utf8").toString("base64url")}function xt(n,t,e){let o=t?.trim();if(o){let i=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${i}`}return `${n}:legacy-${e}-${randomUUID().slice(0,8)}`}function xe(n){return `${n}:legacy-journal`}var R=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(w(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 i=Date.now(),r={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:i,lastActivityAt:i};return this.sessions.set(e,r),this.persist(r),r}startExecution(t,e,o){let i=this.registerSession(t);return (!i.executionId||i.skillName!==e)&&(i.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),i.skillName=e,i.requiredMcpTools=[...new Set(o)],delete i.contextInitialization,i.lastActivityAt=Date.now(),this.persist(i),i}beginContextInitialization(t,e){let o=this.registerSession(t);return o.contextInitialization={startedAt:Date.now(),...e?{toolUseId:e}:{}},o.lastActivityAt=Date.now(),this.persist(o),o}completeContextInitialization(t,e){let o=this.get(t);return o?(e&&o.contextInitialization?.toolUseId&&o.contextInitialization.toolUseId!==e||(delete o.contextInitialization,o.lastActivityAt=Date.now(),this.persist(o)),o):null}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 i=this.snapshotPath(e);if(!existsSync(i))return null;try{let r=JSON.parse(readFileSync(i,"utf8"));return r.sessionId!==e||r.projectRoot!==this.projectRoot?null:(r.requiredMcpTools=Array.isArray(r.requiredMcpTools)?r.requiredMcpTools:[],r.evidenceObligations=ve(r.evidenceObligations),r.evidenceDegradations=Ie(r.evidenceDegradations),r.evidenceOutcomes=_e(r.evidenceOutcomes),this.replayEvidenceJournal(r),this.sessions.set(e,r),r)}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,delete e.contextInitialization,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),o}addEvidenceObligation(t,e,o=Date.now(),i){let r=this.registerSession(t),a=(i?void 0:r.evidenceObligations.find(l=>l.contractId===e.id))?.obligationId??xt(e.id,i,o);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:o,contract:e},`add\0${a}`),this.replayEvidenceJournal(r);let c=r.evidenceObligations.find(l=>l.obligationId===a);return c?(r.lastActivityAt=Date.now(),this.persist(r),structuredClone(c)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,o,i,r=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(i)?i:"";if(!c)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:r,fingerprint:c,violations:o.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,this.persist(s);let l=s.evidenceObligations.find(d=>d.obligationId===e);return l?structuredClone(l):null}resolveEvidenceObligation(t,e){let o=this.get(t);if(!o)return false;let i=o.evidenceObligations.find(s=>s.obligationId===e);if(!i)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:r},`resolve\0${e}`),this.replayEvidenceJournal(o),o.lastActivityAt=r,this.persist(o),true}resolveDegradedEvidence(t,e){let o=this.get(t),i=o?.evidenceDegradations.find(s=>s.obligationId===e);if(!o||!i)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:r},`resolve-degraded\0${e}\0${r}`),this.replayEvidenceJournal(o),o.lastActivityAt=r,this.persist(o),true}degradeEvidenceObligation(t,e,o,i=Date.now()){let r=this.get(t),s=r?.evidenceObligations.find(c=>c.obligationId===e);if(!r||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:i,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),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,`${be(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",be(t))}appendEvidenceEvent(t,e,o){let i=this.evidenceJournalDir(t);mkdirSync(i,{recursive:true,mode:448});let r=createHash("sha256").update(o).digest("hex"),s=join$1(i,`${e.kind}-${r}.json`);if(existsSync(s))return;let a=join$1(i,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=ve(t.evidenceObligations),t.evidenceDegradations=Ie(t.evidenceDegradations),t.evidenceOutcomes=_e(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let o;try{o=readdirSync(e).filter(r=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(r)).slice(0,4096);}catch{return}let i=o.flatMap(r=>{try{let s=readFileSync(join$1(e,r),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=kt(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||we(r.kind)-we(s.kind));for(let r of i)this.applyEvidenceEvent(t,r);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 i=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!i||o||i.correctionFingerprint===e.fingerprint)return;i.attempt+=1,i.correctionRequested=true,i.correctionRequestedAt=e.at,i.correctionFingerprint=e.fingerprint,i.violations=e.violations;return}let r=i?.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:r,contract:i?.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:r,...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 ve(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)||!ke(e.contract))return [];let o=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:xe(e.contractId),i=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,r=e.correctionFingerprint??i;return r!==void 0&&!/^[a-f0-9]{64}$/.test(r)?[]:[{...e,obligationId:o,correctionFingerprint:r}]}).slice(-8):[]}function Ie(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 _e(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 kt(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 i={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:xe(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return ke(t.contract)?{kind:e,...i,contract:t.contract}:null;if(e==="correction"){let r=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...i,fingerprint:r,violations:t.violations}:null}return e==="resolve"?{kind:e,...i}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...i,reason:t.reason}:null}function we(n){return n==="add"?0:n==="correction"?1:2}function ke(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(i=>typeof i=="string"&&i.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 Q(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 i=t[o];if(i==null)continue;e[o]=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0;}return e}function St(n,t){return n.lastMcpCall===t.lastMcpCall&&n.bypassCount===t.bypassCount}function Et(n,t,e){let o=e instanceof Error?e.message:String(e);m({event:"hook.runtime.degraded",identity:{projectRoot:n},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:o,fallback:"fail_open"}});}function Se(n,t,e){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let i={},r=o.updateHookReceipt(n,a=>(i=Q(a),Q(t(i)))),s=Q(r);return {receipt:s,applied:!0,changed:!St(i,s)}}catch(i){return Et(n,e,i),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function te(n,t){return Se(n,()=>t,"write").applied}function ne(n,t){return Se(n,t,"update")}var ee={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},At=new Set(["Write","Edit","NotebookEdit"]),Ct=new Set(["failed","timeout","unavailable"]);function Dt(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 P=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 o=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(o&&o.expiresAt>Date.now())return "context_ready";o&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}let e=new R(this.projectRoot).get(this.sessionId);return e?.executionId===this.executionId&&e.contextInitialization?"context_initializing":"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_initializing"&&ee[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_INITIALIZING",reason:`DevFlow context initialization is in progress. Wait for mcp__devflow__get_project_context to complete, then retry ${t}.`};if(o==="context_gathering"&&ee[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(At.has(t)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let i=ee[t];if(!i)return {permissionDecision:"allow"};let r=ne(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!r.applied)return {permissionDecision:"allow"};let s=r.receipt.bypassCount??0,a=Dt(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${i} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){te(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,o,i){if(!this.sessionId||!this.executionId)return false;let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=r.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let a=Date.now(),c=i?.trim()?`${i.trim()}:${e}`:`${t}:${e}:${a}`,l=s.actionAttempts??[];return r.upsertContextReceipt({...s,actionAttempts:l.some(d=>d.id===c||i&&d.toolUseId===i&&d.status===e)?l:[...l,{id:c,tool:t,status:e,attemptedAt:a,toolUseId:i,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{r?.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 i=(t.actionAttempts??[]).filter(r=>r.tool===e.tool&&Ct.has(r.status));if(i.length>0){let r=i.at(-1),s={missedTool:e.tool,failedAttemptCount:i.length,reason:`${r.status}:${r.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} ${r.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 i=o.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!i||i.contextHash!==t.contextHash||i.actionDegradation)return;o.upsertContextReceipt({...i,actionDegradation:e});let r=o.getSkillExecution(t.executionId);if(!r)return;let s=r.metadata&&typeof r.metadata=="object"?r.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...r.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(r.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(r.fallbackCount??0)+1,fallbackReasons:[...new Set([...r.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...a,e]}});}catch{}finally{try{o?.close();}catch{}}}};var De=1e4,$t=3e4,$=500,q=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,i,r=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:o,startedAt:i,projectRoot:r,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",o=Date.now(),i){let r={executionId:t,status:e,finishedAt:o,metadata:i},s=this.commitOrCache("execution_complete",r);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",r),s}async sendSessionStart(t,e,o){let i={id:t,projectRoot:e,startedAt:o,label:e.split("/").pop()??"unknown"},r=this.commitOrCache("session_start",i);return r&&this.postHttp("/api/telemetry/sessions",i),r}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},i=this.commitOrCache("session_end",o);return i&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),i}async flushCache(){try{let e=this.getDatabase(),o=e.listTelemetryFailures({unresolvedOnly:!0,limit:$}).reverse();for(let i of o)try{this.applyOperation(i.operation,i.payload),e.resolveTelemetryFailure(i.id);}catch{}e.trimTelemetryFailures($);}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:qt(JSON.parse(readFileSync(o,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,o)=>e.envelope.timestamp-o.envelope.timestamp||Oe(e.envelope.operation)-Oe(o.envelope.operation));for(let{cacheFile:e,envelope:o}of t)try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),i.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:Te(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(Te(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 i=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:i,label:i==="unknown"?void 0:i.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,o){let i=Date.now(),r={id:`failure:${i}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:o instanceof Error?o.message:String(o),timestamp:i};try{let s=this.getDatabase();s.insertTelemetryFailure({id:r.id,operation:t,payload:e,error:r.failure,createdAt:i}),s.trimTelemetryFailures($),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${i}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(r,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-$)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},$t).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){T(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=De?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,De)}...`}}};function Oe(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function Te(n){return `hook-run:${n}`}function qt(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}var Ut=2,Vt=1;function zt(){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 je(n=zt()){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!==Ut&&o.version!==Vt||!Bt(o.commands)){m({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){m({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 Bt(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 L(e.mcpTools)&&L(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||L(e.runtimePackages))&&(e.hostTools===void 0||Wt(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Wt(n){return !!n&&typeof n=="object"&&!Array.isArray(n)&&Object.entries(n).every(([t,e])=>t.length>0&&L(e))}function L(n){return Array.isArray(n)&&n.every(t=>typeof t=="string"&&t.length>0)}function Pe(n){let t=je();return t?t[n]?.mcpTools??[]:[]}function Fe(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 $e(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)}`}function E(n){let{projectRoot:t,...e}=n;try{return new ie(t).dispatchBoundary(e).snapshot??null}catch(o){return m({event:"hook.runtime.degraded",identity:{projectRoot:t,sessionId:n.sessionId,...n.turnId?{turnId:n.turnId}:{},...n.requestId?{requestId:n.requestId}:{},...n.executionId?{executionId:n.executionId}:{}},level:"error",timestamp:Date.now(),data:{stage:n.kind,reason:o instanceof Error?o.message:String(o),tool:n.producer}}),null}}var ie=class{constructor(t){this.projectRoot=t;}dispatchBoundary(t){let e=Yt(t.kind,t.payload??{});if(!e)return {handled:false};let o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let i=Xt(o,{projectRoot:this.projectRoot,sessionId:t.sessionId,...t.turnId?{turnId:t.turnId}:{},...t.requestId?{requestId:t.requestId}:{},...t.executionId?{executionId:t.executionId}:{}});return i?{handled:!0,snapshot:new TaskKernel(new TaskEventStore(o),new SemanticRuntimeEventProjector).dispatch({definition:i.definition,kind:e.kind,payload:e.payload,idempotencyKey:`host:${i.definition.definitionHash}:${t.dedupeKey}`,producer:t.producer}).snapshot}:{handled:!1}}finally{o.close();}}};function Xt(n,t){let e=t.executionId?n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId):null,o=t.turnId??e?.canonicalAction?.binding.turnId,i=t.requestId??e?.requestId;if(!o&&!i)return null;let r=n.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId).find(c=>o?c.turnId===o:c.requestId===i);if(!r)return null;let s=n.getTaskAggregateSnapshot(t.projectRoot,t.sessionId,r.turnId,r.version);if(!s)return null;let a=n.getTaskDefinitionV2(s.taskDefinitionHash);return !a||a.revision!==r.version?null:{definition:a,snapshot:s}}function Yt(n,t){switch(n){case "action.lease.issued":return {kind:"action_lease_issued",payload:t};case "action.succeeded":return {kind:"action_completed",payload:t};case "action.failed":return {kind:"action_failed",payload:t};case "verification.succeeded":return {kind:"verification_completed",payload:t};case "verification.failed":return {kind:"verification_failed",payload:t};case "memory.committed":return {kind:"memory_episode_persisted",payload:t};case "memory.skipped":return {kind:"memory_decision_completed",payload:t};case "memory.pending":return {kind:"memory_extraction_queued",payload:t};case "memory.failed":return {kind:"memory_extraction_failed",payload:t};case "durable_work.owned":return {kind:"durable_work_leased",payload:{...t,fencingToken:Number.isSafeInteger(t.fencingToken)?t.fencingToken:0}};case "durable_work.completed":return {kind:"durable_work_completed",payload:t};case "durable_work.dead_lettered":return {kind:"durable_work_dead_lettered",payload:t};default:return null}}var en=256*1024,tn=48*1024;var nn=5,M=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function on(n){return n==="react_audit_performance"||n.endsWith("__react_audit_performance")}function rn(n){let t=D(n,0,new Set);return t?an(t.contract,t.canonicalReport):null}function Le(n){if(!n.sessionId||!on(n.toolName))return null;let t=rn(n.toolResponse);if(!t)return null;let e=Date.now(),o=n.runtimeStore.addEvidenceObligation(n.sessionId,t,e,n.toolUseId),i=n.runtimeStore.get(n.sessionId);if(o&&i){let r=openGlobalDevFlowDatabase();try{r.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:i.projectRoot,sessionId:n.sessionId,executionId:i.executionId,kind:"evidence_contract",state:"open",payload:{contract:t,runtimeObligationId:o.obligationId},createdAt:e,updatedAt:e});}finally{r.close();}m({event:"verification.completed",identity:{projectRoot:i.projectRoot,sessionId:n.sessionId,executionId:i.executionId},level:"info",timestamp:e,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:t.id,obligationId:o.obligationId,detectorCoverage:N(n.toolResponse),runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,toolUseId:n.toolUseId}});}return sn(t)}function sn(n){return [`DevFlow performance evidence contract ${n.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${n.requiredSections.join(" / ")}.`,n.runtimeProfilingOccurred?"Only claims directly supported by the returned runtime measurements may be stated as measured facts.":"No runtime profiling occurred. Treat every finding as a static candidate: do not assign P0/high-risk severity, claim a confirmed bottleneck/jank/frame drop/CPU hotspot, quantify performance or benefit, or recommend requestAnimationFrame as generic throttling without sampling evidence.",`samplingEvidenceOccurred=${n.samplingEvidenceOccurred}. RAF recommendations are permitted only when this structured contract field is true; answer text cannot self-declare sampling evidence.`,"Use the canonical report below directly or preserve its evidence boundaries. Stop will request one correction for unsupported claims, then fail open with degradation telemetry.",n.canonicalReport].join(`
|
|
1
|
+
import {existsSync,readFileSync,rmSync,mkdirSync,writeFileSync,linkSync,readdirSync,renameSync,unlinkSync}from'fs';import {join as join$1,dirname as dirname$1}from'path';import {getLogWriter,emitSemanticControlLog,SemanticRuntimeEventProjector,rotateDiagnosticLogFile}from'@devflow-tools/telemetry';import {request}from'node:http';import {mkdirSync as mkdirSync$1,appendFileSync,existsSync as existsSync$1,readFileSync as readFileSync$1,writeFileSync as writeFileSync$1,renameSync as renameSync$1,readdirSync as readdirSync$1}from'node:fs';import {join,dirname,relative,resolve,isAbsolute,sep}from'node:path';import {getLocalApiKey,getDevFlowStateRoot,acquireRuntimeHttpCircuit,registerRuntimeHttpSuccess,registerRuntimeHttpFailure,getProjectStateDir,readRuntimeState}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase,retrievalLedgerTransitionId}from'@devflow-tools/database';import {randomUUID,createHash}from'crypto';import {fileURLToPath}from'url';import {TaskKernel,TaskEventStore}from'@devflow-tools/task-runtime';import {createHash as createHash$1}from'node:crypto';import {classifyWorkflowFailure}from'@devflow-tools/workflow-engine/failure-classifier';function J(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 pt=getLocalApiKey(),K=join(getDevFlowStateRoot(),"errors");async function T(n,t,e={}){let o=e.endpoint??process.env.DEVFLOW_SERVER_URL?.trim()??gt();if(!o)return {delivered:false,suppressed:false,fallbackReason:"runtime_not_ready"};let i=e.timeout??1500,r=e.durableMirror??true,s=e.maxRetries??(r?0:2),a=e.circuitBreaker??true,c=acquireRuntimeHttpCircuit(o,n);if(a&&!c.allowed)return {delivered:false,suppressed:true,fallbackReason:c.state.fallbackReason};let l;for(let u=0;u<=s;u+=1)try{return await mt(o,n,t,i),a&®isterRuntimeHttpSuccess(o,n).transitioned&&J("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:c.state.status,status:"closed",failures:0}),{delivered:!0,suppressed:!1}}catch(f){l=f instanceof Error?f:new Error(String(f)),u<s&&await yt(Math.min(100*2**u,1e3));}if(!l)return {delivered:false,suppressed:false,fallbackReason:"unknown_http_failure"};if(!a)return ue(n,l),{delivered:false,suppressed:false,fallbackReason:l.message};let d=registerRuntimeHttpFailure(o,n,e.fallbackReason??(r?"local_durable_mirror":"http_delivery_failed"));return d.transitioned&&(ue(n,l),J("http_circuit_transition",{endpoint:o,path:new URL(n,o).pathname,previous:c.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 gt(){let n=readRuntimeState();return n?.status==="ready"&&n.dashboardAvailable?n.url:void 0}function mt(n,t,e,o){return new Promise((i,r)=>{let s=JSON.stringify(e),a=new URL(t,n),c=false,l=u=>{c||(c=true,u?r(u):i());},d=request({hostname:a.hostname,port:a.port,path:a.pathname+a.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":pt,"Content-Length":Buffer.byteLength(s)},timeout:o},u=>{u.on("error",l),u.on("end",()=>{let f=u.statusCode??0;l(f>=200&&f<300?void 0:new Error(`HTTP ${f}`));}),u.resume();});d.on("error",l),d.on("timeout",()=>d.destroy(new Error(`HTTP mirror timed out after ${o}ms`))),d.write(s),d.end();})}function ue(n,t){try{existsSync$1(K)||mkdirSync$1(K,{recursive:!0});let e=join(K,"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 yt(n){return new Promise(t=>setTimeout(t,n))}var m=emitSemanticControlLog;function G(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function w(n){return getProjectStateDir(G(n))}function ye(n){return Buffer.from(n,"utf8").toString("base64url")}function wt(n,t,e){let o=t?.trim();if(o){let i=/^[a-zA-Z0-9:._-]{1,192}$/.test(o)?o:`tool-${createHash("sha256").update(o.slice(0,1024)).digest("hex").slice(0,32)}`;return `${n}:${i}`}return `${n}:legacy-${e}-${randomUUID().slice(0,8)}`}function we(n){return `${n}:legacy-journal`}var R=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join$1(w(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 i=Date.now(),r={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],evidenceObligations:[],evidenceDegradations:[],evidenceOutcomes:[],startedAt:i,lastActivityAt:i};return this.sessions.set(e,r),this.persist(r),r}startExecution(t,e,o){let i=this.registerSession(t);return (!i.executionId||i.skillName!==e)&&(i.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),i.skillName=e,i.requiredMcpTools=[...new Set(o)],delete i.contextInitialization,i.lastActivityAt=Date.now(),this.persist(i),i}beginContextInitialization(t,e){let o=this.registerSession(t);return o.contextInitialization={startedAt:Date.now(),...e?{toolUseId:e}:{}},o.lastActivityAt=Date.now(),this.persist(o),o}completeContextInitialization(t,e){let o=this.get(t);return o?(e&&o.contextInitialization?.toolUseId&&o.contextInitialization.toolUseId!==e||(delete o.contextInitialization,o.lastActivityAt=Date.now(),this.persist(o)),o):null}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 i=this.snapshotPath(e);if(!existsSync(i))return null;try{let r=JSON.parse(readFileSync(i,"utf8"));return r.sessionId!==e||r.projectRoot!==this.projectRoot?null:(r.requiredMcpTools=Array.isArray(r.requiredMcpTools)?r.requiredMcpTools:[],r.evidenceObligations=he(r.evidenceObligations),r.evidenceDegradations=be(r.evidenceDegradations),r.evidenceOutcomes=ve(r.evidenceOutcomes),this.replayEvidenceJournal(r),this.sessions.set(e,r),r)}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,delete e.contextInitialization,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),o}addEvidenceObligation(t,e,o=Date.now(),i){let r=this.registerSession(t),a=(i?void 0:r.evidenceObligations.find(l=>l.contractId===e.id))?.obligationId??wt(e.id,i,o);this.appendEvidenceEvent(t,{kind:"add",obligationId:a,contractId:e.id,at:o,contract:e},`add\0${a}`),this.replayEvidenceJournal(r);let c=r.evidenceObligations.find(l=>l.obligationId===a);return c?(r.lastActivityAt=Date.now(),this.persist(r),structuredClone(c)):null}listEvidenceObligations(t){return (this.get(t)?.evidenceObligations??[]).map(e=>structuredClone(e))}markEvidenceCorrection(t,e,o,i,r=Date.now()){let s=this.get(t),a=s?.evidenceObligations.find(d=>d.obligationId===e);if(!s||!a)return null;let c=/^[a-f0-9]{64}$/.test(i)?i:"";if(!c)return null;this.appendEvidenceEvent(t,{kind:"correction",obligationId:e,contractId:a.contractId,at:r,fingerprint:c,violations:o.slice(0,16).map(d=>d.slice(0,240))},`correction\0${e}\0${c}`),this.replayEvidenceJournal(s),s.lastActivityAt=r,this.persist(s);let l=s.evidenceObligations.find(d=>d.obligationId===e);return l?structuredClone(l):null}resolveEvidenceObligation(t,e){let o=this.get(t);if(!o)return false;let i=o.evidenceObligations.find(s=>s.obligationId===e);if(!i)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:r},`resolve\0${e}`),this.replayEvidenceJournal(o),o.lastActivityAt=r,this.persist(o),true}resolveDegradedEvidence(t,e){let o=this.get(t),i=o?.evidenceDegradations.find(s=>s.obligationId===e);if(!o||!i)return false;let r=Date.now();return this.appendEvidenceEvent(t,{kind:"resolve",obligationId:e,contractId:i.contractId,at:r},`resolve-degraded\0${e}\0${r}`),this.replayEvidenceJournal(o),o.lastActivityAt=r,this.persist(o),true}degradeEvidenceObligation(t,e,o,i=Date.now()){let r=this.get(t),s=r?.evidenceObligations.find(c=>c.obligationId===e);if(!r||!s)return false;let a=o.slice(0,240);return this.appendEvidenceEvent(t,{kind:"degrade",obligationId:e,contractId:s.contractId,at:i,reason:a},`degrade\0${e}\0${a}`),this.replayEvidenceJournal(r),r.lastActivityAt=i,this.persist(r),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,`${ye(t)}.json`)}evidenceJournalDir(t){return join$1(this.sessionsDir,"evidence-journal",ye(t))}appendEvidenceEvent(t,e,o){let i=this.evidenceJournalDir(t);mkdirSync(i,{recursive:true,mode:448});let r=createHash("sha256").update(o).digest("hex"),s=join$1(i,`${e.kind}-${r}.json`);if(existsSync(s))return;let a=join$1(i,`.${process.pid}.${randomUUID()}.tmp`);writeFileSync(a,JSON.stringify(e),{mode:384});try{linkSync(a,s);}catch(c){if(c.code!=="EEXIST")throw c}finally{rmSync(a,{force:true});}}replayEvidenceJournal(t){t.evidenceObligations=he(t.evidenceObligations),t.evidenceDegradations=be(t.evidenceDegradations),t.evidenceOutcomes=ve(t.evidenceOutcomes);let e=this.evidenceJournalDir(t.sessionId);if(!existsSync(e))return;let o;try{o=readdirSync(e).filter(r=>/^(?:add|correction|resolve|degrade)-[a-f0-9]{64}\.json$/.test(r)).slice(0,4096);}catch{return}let i=o.flatMap(r=>{try{let s=readFileSync(join$1(e,r),"utf8");if(Buffer.byteLength(s,"utf8")>64*1024)return [];let a=Rt(JSON.parse(s));return a?[a]:[]}catch{return []}}).sort((r,s)=>r.at-s.at||Ie(r.kind)-Ie(s.kind));for(let r of i)this.applyEvidenceEvent(t,r);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 i=t.evidenceObligations.find(s=>s.obligationId===e.obligationId);if(e.kind==="correction"){if(!i||o||i.correctionFingerprint===e.fingerprint)return;i.attempt+=1,i.correctionRequested=true,i.correctionRequestedAt=e.at,i.correctionFingerprint=e.fingerprint,i.violations=e.violations;return}let r=i?.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:r,contract:i?.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:r,...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 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)||!Re(e.contract))return [];let o=typeof e.obligationId=="string"&&e.obligationId.length>0&&e.obligationId.length<=384?e.obligationId:we(e.contractId),i=typeof e.correctionTranscriptHash=="string"?e.correctionTranscriptHash:void 0,r=e.correctionFingerprint??i;return r!==void 0&&!/^[a-f0-9]{64}$/.test(r)?[]:[{...e,obligationId:o,correctionFingerprint:r}]}).slice(-8):[]}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"&&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 Rt(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 i={obligationId:typeof t.obligationId=="string"&&t.obligationId.length>0&&t.obligationId.length<=384?t.obligationId:we(t.contractId),contractId:t.contractId,at:t.at};if(e==="add")return Re(t.contract)?{kind:e,...i,contract:t.contract}:null;if(e==="correction"){let r=typeof t.fingerprint=="string"?t.fingerprint:t.transcriptHash;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)&&Array.isArray(t.violations)&&t.violations.every(s=>typeof s=="string"&&s.length<=240)?{kind:e,...i,fingerprint:r,violations:t.violations}:null}return e==="resolve"?{kind:e,...i}:typeof t.reason=="string"&&t.reason.length<=240?{kind:e,...i,reason:t.reason}:null}function Ie(n){return n==="add"?0:n==="correction"?1:2}function Re(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(i=>typeof i=="string"&&i.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 Y(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 i=t[o];if(i==null)continue;e[o]=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0;}return e}function xt(n,t){return n.lastMcpCall===t.lastMcpCall&&n.bypassCount===t.bypassCount}function kt(n,t,e){let o=e instanceof Error?e.message:String(e);m({event:"hook.runtime.degraded",identity:{projectRoot:n},level:"warn",timestamp:Date.now(),data:{stage:"enforcement_receipt",operation:t,reason:o,fallback:"fail_open"}});}function xe(n,t,e){let o;try{o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let i={},r=o.updateHookReceipt(n,a=>(i=Y(a),Y(t(i)))),s=Y(r);return {receipt:s,applied:!0,changed:!xt(i,s)}}catch(i){return kt(n,e,i),{receipt:{},applied:false,changed:false}}finally{try{o?.close();}catch{}}}function ee(n,t){return xe(n,()=>t,"write").applied}function St(n,t){return xe(n,t,"update")}var Q={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"},Et=new Set(["Write","Edit","NotebookEdit"]),At=new Set(["failed","timeout","unavailable"]);function Dt(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 P=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 o=t.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(o&&o.expiresAt>Date.now())return "context_ready";o&&t.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{t?.close();}catch{}}let e=new R(this.projectRoot).get(this.sessionId);return e?.executionId===this.executionId&&e.contextInitialization?"context_initializing":"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_initializing"&&Q[t])return {permissionDecision:"deny",reasonCode:"DEVFLOW_CONTEXT_INITIALIZING",reason:`DevFlow context initialization is in progress. Wait for mcp__devflow__get_project_context to complete, then retry ${t}.`};if(o==="context_gathering"&&Q[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(Et.has(t)){let c=this.evaluateRequiredAction();if(c)return c}return {permissionDecision:"allow"}}let i=Q[t];if(!i)return {permissionDecision:"allow"};let r=St(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!r.applied)return {permissionDecision:"allow"};let s=r.receipt.bypassCount??0,a=Dt(t);return s>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \u6B21\u76F4\u63A5\u4F7F\u7528 ${t}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${i} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){ee(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}recordDomainActionOutcome(t,e,o,i){if(!this.sessionId||!this.executionId)return false;let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let s=r.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(!s||s.expiresAt<=Date.now()||s.canonicalAction?.tool!==t)return !1;let a=Date.now(),c=i?.trim()?`${i.trim()}:${e}`:`${t}:${e}:${a}`,l=s.actionAttempts??[];return r.upsertContextReceipt({...s,actionAttempts:l.some(d=>d.id===c||i&&d.toolUseId===i&&d.status===e)?l:[...l,{id:c,tool:t,status:e,attemptedAt:a,toolUseId:i,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{r?.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 i=(t.actionAttempts??[]).filter(r=>r.tool===e.tool&&At.has(r.status));if(i.length>0){let r=i.at(-1),s={missedTool:e.tool,failedAttemptCount:i.length,reason:`${r.status}:${r.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} ${r.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 i=o.getContextReceipt(t.projectRoot,t.sessionId,t.executionId);if(!i||i.contextHash!==t.contextHash||i.actionDegradation)return;o.upsertContextReceipt({...i,actionDegradation:e});let r=o.getSkillExecution(t.executionId);if(!r)return;let s=r.metadata&&typeof r.metadata=="object"?r.metadata:{},a=Array.isArray(s.requiredActionDegradations)?s.requiredActionDegradations:[];o.updateSkillExecution(t.executionId,{missedMcpTools:[...new Set([...r.missedMcpTools??[],e.missedTool])],failedToolCalls:Math.max(r.failedToolCalls??0,e.failedAttemptCount),fallbackCount:(r.fallbackCount??0)+1,fallbackReasons:[...new Set([...r.fallbackReasons??[],`required_action_${e.reason}`])],metadata:{...s,requiredActionDegradations:[...a,e]}});}catch{}finally{try{o?.close();}catch{}}}};var Ae=1e4,Ft=3e4,$=500,q=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,i,r=process.env.CLAUDE_PROJECT_DIR??process.cwd(),s=[]){let a={executionId:t,sessionId:e,skillName:o,startedAt:i,projectRoot:r,requiredMcpTools:s};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",o=Date.now(),i){let r={executionId:t,status:e,finishedAt:o,metadata:i},s=this.commitOrCache("execution_complete",r);return s&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",r),s}async sendSessionStart(t,e,o){let i={id:t,projectRoot:e,startedAt:o,label:e.split("/").pop()??"unknown"},r=this.commitOrCache("session_start",i);return r&&this.postHttp("/api/telemetry/sessions",i),r}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},i=this.commitOrCache("session_end",o);return i&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),i}async flushCache(){try{let e=this.getDatabase(),o=e.listTelemetryFailures({unresolvedOnly:!0,limit:$}).reverse();for(let i of o)try{this.applyOperation(i.operation,i.payload),e.resolveTelemetryFailure(i.id);}catch{}e.trimTelemetryFailures($);}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:$t(JSON.parse(readFileSync(o,"utf8")))}}catch{return null}}).filter(e=>e!==null).sort((e,o)=>e.envelope.timestamp-o.envelope.timestamp||De(e.envelope.operation)-De(o.envelope.operation));for(let{cacheFile:e,envelope:o}of t)try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),i.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:Ce(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(Ce(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 i=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:i,label:i==="unknown"?void 0:i.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}cacheOperation(t,e,o){let i=Date.now(),r={id:`failure:${i}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:o instanceof Error?o.message:String(o),timestamp:i};try{let s=this.getDatabase();s.insertTelemetryFailure({id:r.id,operation:t,payload:e,error:r.failure,createdAt:i}),s.trimTelemetryFailures($),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join$1(this.cacheDir,`${i}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(r,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-$)))unlinkSync(join$1(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Ft).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){T(t,e,{endpoint:this.apiUrl,fallbackReason:"telemetry_already_committed_locally"});}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=Ae?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,Ae)}...`}}};function De(n){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(n)}function Ce(n){return `hook-run:${n}`}function $t(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}var Ht=2,Ut=1;function Vt(){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 Oe(n=Vt()){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!==Ht&&o.version!==Ut||!zt(o.commands)){m({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){m({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 zt(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 L(e.mcpTools)&&L(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.runtimePackages===void 0||L(e.runtimePackages))&&(e.hostTools===void 0||Bt(e.hostTools))&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function Bt(n){return !!n&&typeof n=="object"&&!Array.isArray(n)&&Object.entries(n).every(([t,e])=>t.length>0&&L(e))}function L(n){return Array.isArray(n)&&n.every(t=>typeof t=="string"&&t.length>0)}function Te(n){let t=Oe();return t?t[n]?.mcpTools??[]:[]}function je(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 Pe(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)}`}function E(n){let{projectRoot:t,...e}=n;try{return new ne(t).dispatchBoundary(e).snapshot??null}catch(o){return m({event:"hook.runtime.degraded",identity:{projectRoot:t,sessionId:n.sessionId,...n.turnId?{turnId:n.turnId}:{},...n.requestId?{requestId:n.requestId}:{},...n.executionId?{executionId:n.executionId}:{}},level:"error",timestamp:Date.now(),data:{stage:n.kind,reason:o instanceof Error?o.message:String(o),tool:n.producer}}),null}}var ne=class{constructor(t){this.projectRoot=t;}dispatchBoundary(t){let e=Xt(t.kind,t.payload??{});if(!e)return {handled:false};let o=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let i=Zt(o,{projectRoot:this.projectRoot,sessionId:t.sessionId,...t.turnId?{turnId:t.turnId}:{},...t.requestId?{requestId:t.requestId}:{},...t.executionId?{executionId:t.executionId}:{}});return i?{handled:!0,snapshot:new TaskKernel(new TaskEventStore(o),new SemanticRuntimeEventProjector).dispatch({definition:i.definition,kind:e.kind,payload:e.payload,idempotencyKey:`host:${i.definition.definitionHash}:${t.dedupeKey}`,producer:t.producer}).snapshot}:{handled:!1}}finally{o.close();}}};function Zt(n,t){let e=t.executionId?n.getActiveContextReceipt(t.projectRoot,t.sessionId,t.executionId):null,o=t.turnId??e?.canonicalAction?.binding.turnId,i=t.requestId??e?.requestId;if(!o&&!i)return null;let r=n.listLatestTaskIntentArtifacts(t.projectRoot,t.sessionId).find(c=>o?c.turnId===o:c.requestId===i);if(!r)return null;let s=n.getTaskAggregateSnapshot(t.projectRoot,t.sessionId,r.turnId,r.version);if(!s)return null;let a=n.getTaskDefinitionV2(s.taskDefinitionHash);return !a||a.revision!==r.version?null:{definition:a,snapshot:s}}function Xt(n,t){switch(n){case "action.lease.issued":return {kind:"action_lease_issued",payload:t};case "action.succeeded":return {kind:"action_completed",payload:t};case "action.failed":return {kind:"action_failed",payload:t};case "verification.succeeded":return {kind:"verification_completed",payload:t};case "verification.failed":return {kind:"verification_failed",payload:t};case "memory.committed":return {kind:"memory_episode_persisted",payload:t};case "memory.skipped":return {kind:"memory_decision_completed",payload:t};case "memory.pending":return {kind:"memory_extraction_queued",payload:t};case "memory.failed":return {kind:"memory_extraction_failed",payload:t};case "durable_work.owned":return {kind:"durable_work_leased",payload:{...t,fencingToken:Number.isSafeInteger(t.fencingToken)?t.fencingToken:0}};case "durable_work.completed":return {kind:"durable_work_completed",payload:t};case "durable_work.dead_lettered":return {kind:"durable_work_dead_lettered",payload:t};default:return null}}var Qt=256*1024,en=48*1024;var tn=5,M=["\u5DE5\u5177\u53D1\u73B0","\u6A21\u578B\u5047\u8BBE","\u9700\u8981\u8FD0\u884C\u65F6\u9A8C\u8BC1"];function nn(n){return n==="react_audit_performance"||n.endsWith("__react_audit_performance")}function on(n){let t=C(n,0,new Set);return t?sn(t.contract,t.canonicalReport):null}function $e(n){if(!n.sessionId||!nn(n.toolName))return null;let t=on(n.toolResponse);if(!t)return null;let e=Date.now(),o=n.runtimeStore.addEvidenceObligation(n.sessionId,t,e,n.toolUseId),i=n.runtimeStore.get(n.sessionId);if(o&&i){let r=openGlobalDevFlowDatabase();try{r.upsertSessionObligation({obligationId:`evidence:${o.obligationId}`,projectRoot:i.projectRoot,sessionId:n.sessionId,executionId:i.executionId,kind:"evidence_contract",state:"open",payload:{contract:t,runtimeObligationId:o.obligationId},createdAt:e,updatedAt:e});}finally{r.close();}m({event:"verification.completed",identity:{projectRoot:i.projectRoot,sessionId:n.sessionId,executionId:i.executionId},level:"info",timestamp:e,data:{stage:"performance_detector_coverage",status:"obligation_opened",contractId:t.id,obligationId:o.obligationId,detectorCoverage:N(n.toolResponse),runtimeProfilingOccurred:t.runtimeProfilingOccurred,samplingEvidenceOccurred:t.samplingEvidenceOccurred,toolUseId:n.toolUseId}});}return rn(t)}function rn(n){return [`DevFlow performance evidence contract ${n.id} is active.`,`The final performance answer MUST contain these three sections exactly: ${n.requiredSections.join(" / ")}.`,n.runtimeProfilingOccurred?"Only claims directly supported by the returned runtime measurements may be stated as measured facts.":"No runtime profiling occurred. Treat every finding as a static candidate: do not assign P0/high-risk severity, claim a confirmed bottleneck/jank/frame drop/CPU hotspot, quantify performance or benefit, or recommend requestAnimationFrame as generic throttling without sampling evidence.",`samplingEvidenceOccurred=${n.samplingEvidenceOccurred}. RAF recommendations are permitted only when this structured contract field is true; answer text cannot self-declare sampling evidence.`,"Use the canonical report below directly or preserve its evidence boundaries. Stop will request one correction for unsupported claims, then fail open with degradation telemetry.",n.canonicalReport].join(`
|
|
3
3
|
|
|
4
|
-
`)}function N(n,t=0){if(t>6||n==null)return [];if(typeof n=="string")try{return N(JSON.parse(n),t+1)}catch{return []}if(Array.isArray(n)){for(let o of n){let i=N(o,t+1);if(i.length>0)return i}return []}if(typeof n!="object")return [];let e=n;if(Array.isArray(e.detectorCoverage))return e.detectorCoverage.filter(o=>typeof o=="string").slice(0,32);for(let o of Object.values(e)){let i=N(o,t+1);if(i.length>0)return i}return []}function
|
|
5
|
-
`)||null}finally{e.close();}}function
|
|
6
|
-
`,{encoding:"utf8",mode:384}),m({event:"canonical.action.validated",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:t.executionId,contextReceipt:t.contextReceipt},level:n.success?"info":"warn",timestamp:e,data:{stage:"host_file_state_completed",valid:n.success,operation:t.operation,targetPath:relative(n.projectRoot,t.path),beforeHash:t.before.hash,afterHash:o.after.hash,beforeExists:t.before.exists,afterExists:o.after.exists,reason:o.error,toolUseId:t.toolUseId}}),o}function Ln(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 Be(n){return join(w(n),"file-state")}function We(n){return join(Be(n),"pending.json")}function Mn(n){return join(Be(n),"observations.jsonl")}function Nn(n){try{return JSON.parse(readFileSync$1(We(n),"utf8"))}catch{return {}}}function Hn(n,t){let e=We(n),o=Nn(n),i=o[t];if(i)return delete o[t],Un(e,JSON.stringify(o)),i}function Un(n,t){let e=`${n}.${process.pid}.${Date.now()}.tmp`;writeFileSync$1(e,t,{encoding:"utf8",mode:384}),renameSync$1(e,n);}var zn={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 Bn(n){return Wn(n)}function Wn(n){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let e=Zn(t,n.artifact);if(Xn(e.toState))return e;let o=t.getContextReceiptForRequest(n.artifact.projectRoot,n.artifact.sessionId,n.artifact.requestId),i=t.getMemoryTurn(n.artifact.turnId),r=n.artifact.intent==="memory"||i?.source==="explicit_intent";if(!o&&!r)return e;let s=o?Jn(n.artifact,o):"context_ready";e.toState==="intent_bound"&&(e=y(t,e,n,s,r?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Kn(n.artifact,o):"action_not_required";if((e.toState==="context_ready"||e.toState==="context_degraded")&&(a==="action_not_required"?e=y(t,e,n,"action_not_required","task_action_not_required"):e=y(t,e,n,"action_required","canonical_action_obligation_present")),e.toState==="action_required"){if(a==="action_required")return e;if(a==="action_failed")return y(t,e,n,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?e=y(t,e,n,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(e=y(t,e,n,"action_satisfied","canonical_action_succeeded"));}if(e.toState==="action_failed")if(a==="action_satisfied")e=y(t,e,n,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")e=y(t,e,n,"action_degraded","canonical_action_retry_degraded");else return e;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(e.toState)&&(e=y(t,e,n,n.memoryStatus==="pending"?"memory_quarantined":"memory_decided",n.memoryStatus==="pending"?n.reason:`canonical_memory_${n.memoryStatus}`)),e.toState==="memory_decided"?y(t,e,n,c?"closed_with_degradation":"closed",n.reason):e.toState==="memory_quarantined"?y(t,e,n,n.retryOwned?"closed_with_retry_work":"closed_with_degradation",n.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):e}finally{t.close();}}function Ke(n){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let e=t.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId),o=typeof e?.canonicalAction?.binding.turnId=="string"?e.canonicalAction.binding.turnId:void 0;if(!o)return null;let i=t.listLatestTaskIntentArtifacts(n.projectRoot,n.sessionId).find(s=>s.turnId===o),r=t.getMemoryTurn(o);return !i||!r?null:Bn({artifact:i,memoryStatus:r.status,memoryReceiptId:r.receiptId,reason:n.reason})}finally{t.close();}}function Jn(n,t){return n.intent==="memory"||n.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Kn(n,t){let e=t.canonicalAction,i=(e?(t.actionAttempts??[]).filter(r=>r.tool===e.tool):[]).at(-1);return t.actionSatisfiedAt||i?.status==="succeeded"?"action_satisfied":i&&["failed","timeout","unavailable"].includes(i.status)?"action_failed":t.actionDegradation||e?.status==="degraded"||e?.status==="unsupported"?"action_degraded":e?.required||Gn(n)?"action_required":"action_not_required"}function Gn(n){return ["create","modify","debug","test","format"].includes(n.action)||["feature","refactor","performance"].includes(n.intent)}function Zn(n,t){let e=n.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!e)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return e}function y(n,t,e,o,i){if(!zn[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let r=t.sequence+1,s=`terminal:${createHash$1("sha256").update(`${e.artifact.artifactHash}\0${r}\0${o}`).digest("hex").slice(0,24)}`,a=n.appendTerminalTransition({projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,executionId:e.artifact.executionId,sequence:r,fromState:t.toState,toState:o,receiptId:s,sourceReceiptId:e.memoryReceiptId??t.receiptId,reason:i,payload:{memoryStatus:e.memoryStatus,retryOwned:e.retryOwned??false,sourceIntentHash:e.artifact.artifactHash},createdAt:Date.now()});return m({event:"terminal.state.transitioned",identity:{projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,...e.artifact.executionId?{executionId:e.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:i}}),a}function Xn(n){return n==="closed"||n==="closed_with_degradation"||n==="closed_with_retry_work"}function Ge(n){let t=n.hook==="post_tool_use_failure"||!!n.error?.trim()||Yn(n.response),e=t?"not_consumed":n.hook==="post_tool_use"?"consumed":"unknown",o=t?Qn(n.error,n.response):e==="consumed"?"host_reported_success":"host_outcome_unknown";return {schemaVersion:"host-tool-outcome.v1",toolName:n.toolName,...n.toolUseId?{toolUseId:n.toolUseId}:{},consumption:e,reasonCode:o,receiptId:n.toolUseId??`host-tool:${n.toolName}:${o}`}}function Yn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let t=n;return t.isError===true||t.error?true:typeof t.status=="string"&&["failed","error","rejected","timeout","unavailable"].includes(t.status.toLowerCase())}function Qn(n,t){let e=`${n??""} ${JSON.stringify(t??"")}`;return /timeout|timed out|deadline/iu.test(e)?"host_tool_timeout":/unavailable|not found|not registered|unsupported/iu.test(e)?"host_tool_unavailable":"host_tool_failed"}var ao=new Set(["Agent","Bash","Glob","Grep","WebSearch","WebFetch"]);function Ze(n){if(!n)return;let t=typeof n.status=="string"?n.status:void 0;if(!(n.ok===false||n.success===false||n.isError===true||t==="failed"||t==="rejected"||!!n.error))return;let o=n.error;if(typeof o=="string"&&o.trim())return o;if(o&&typeof o=="object"){let i=o;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return t?`Tool response status: ${t}`:"Tool response reported failure"}function co(n,t,e,o){try{let i=join$1(w(n),"event-map.json");if(!existsSync(i))return null;let r=JSON.parse(readFileSync(i,"utf-8")),s=r.filter(l=>l.toolName===e&&(!l.sessionId||l.sessionId===t));if(s.length===0)return null;let a=o?s.find(l=>l.toolUseId===o):s.sort((l,d)=>l.timestamp-d.timestamp)[0];if(!a)return null;let c=r.findIndex(l=>l.eventId===a.eventId);return c!==-1&&r.splice(c,1),writeFileSync(i,JSON.stringify(r)),{eventId:a.eventId,timestamp:a.timestamp}}catch{return null}}function Xe(n){if(!n)return 0;let t=n;if(typeof n=="string")try{t=JSON.parse(n);}catch{return 1}let e=t,o=["files","results","data","result","memories","nodes","chunks","findings","symbols","keySymbols"],i=["reasoning","riskHints","nextActions"],r=Array.isArray(e.data)?e.data:e.structuredContent??e;if(Array.isArray(r))return r.length;if(typeof r=="object"&&r!==null){let s=r,a=0,c=false;for(let d of o)Array.isArray(s[d])&&(c=true,a+=s[d].length);for(let d of i)Array.isArray(s[d])&&(a+=s[d].length);for(let[,d]of Object.entries(s))d&&typeof d=="object"&&!Array.isArray(d)&&(a+=Xe(d));let l=!!(s._devflow||s._devflow_unique||s.taskType);return a===0&&l&&!c?1:a>0?a:c?0:Object.keys(s).length>0?1:0}return 0}function lo(n,t){if(!ao.has(t))return null;let e=ne(n,i=>({...i,bypassCount:(i.bypassCount??0)+1}));if(!e.applied)return null;let o=e.receipt.bypassCount??0;return o>20&&o%10===0?`MCP \u5DE5\u5177\u4F7F\u7528\u7387\u4F4E\uFF1A${o} \u6B21\u76F4\u63A5\u5DE5\u5177\u8C03\u7528\u3002\u5EFA\u8BAE\u4F7F\u7528 get_project_context \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`:null}async function uo(n){if(!n)return null;let t;try{t=JSON.parse(n);}catch{return null}let e=t.tool_name||"",o=Z(),i=t.tool_input||{},r=t.tool_response||{},s=t.session_id?.trim()||null,a=new R(o);if(s&&a.registerSession(s),s&&e==="mcp__devflow__get_project_context"&&a.completeContextInitialization(s,t.tool_use_id),e==="Skill"){let p=typeof i=="object"&&i.skill?i.skill:"",g=Fe(p);s&&g&&(a.startExecution(s,g,Pe(g)),te(o,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}let c=s?a.get(s):null;if(e.startsWith("mcp__")){let p=new P(o,s??void 0,c?.executionId??s??void 0);p.recordMcpCall();let g=Ze(typeof r=="object"&&r!==null?r:null),b=e.replace(/^mcp__[^_]+__/,""),J=p.getContextReceipt?.()?.canonicalAction?.tool===b;if((p.recordDomainActionOutcome(b,g?fo(g):"succeeded",g,t.tool_use_id)||J)&&s){let k=Ge({hook:"post_tool_use",toolName:b,...t.tool_use_id?{toolUseId:t.tool_use_id}:{},response:r,...g?{error:g}:{}});E({projectRoot:o,sessionId:s,executionId:c?.executionId??s,kind:k.consumption==="consumed"?"action.succeeded":"action.failed",payload:{receiptId:k.receiptId,reasonCode:k.reasonCode,consumption:k.consumption,tool:b},dedupeKey:`${k.receiptId}:${k.consumption}`,producer:"devflow-post-tool-use"});try{Ke({projectRoot:o,sessionId:s,executionId:c?.executionId??s,reason:g?"post_tool_action_failed":"post_tool_action_succeeded"});}catch{}}}s&&Ne({projectRoot:o,sessionId:s,executionId:c?.executionId,toolName:e,toolInput:i,toolResponse:r,toolUseId:t.tool_use_id});let l=s?co(o,s,e,t.tool_use_id):null,d=s&&t.tool_use_id&&!l?(()=>{try{let p=openGlobalDevFlowDatabase();try{return p.getToolCallEventByToolUseId(s,t.tool_use_id)}finally{p.close();}}catch{return null}})():null,u=l??d,f=typeof r=="object"&&r!==null?r:null,U=JSON.stringify(r),x=Buffer.byteLength(U,"utf8"),A=Xe(r),V=Ze(f);if(s&&ze({projectRoot:o,sessionId:s,toolUseId:t.tool_use_id,success:!V,error:V}),c?.executionId!==void 0||e.startsWith("mcp__devflow__")||e==="Skill"){let p=getLogWriter(o),g=c?.executionId??`auto-${s??Date.now()}`;p.toolCall({tool:e,runId:g,stepId:`step-${g}`,input:i,output:r,duration:u?Math.max(0,Date.now()-u.timestamp):0,success:!f?.error,resultCount:A,resultSizeBytes:x,error:f?.error});}if(u&&s){let p=typeof r=="string"?r:JSON.stringify(r),g=p.length>5e3?{_truncated:true,_originalSize:p.length,text:p.slice(0,5e3)}:r,b=V,J=b?classifyWorkflowFailure({stepId:e,toolName:e,output:r,error:new Error(b),errorStack:b}).category:void 0;await new q().completeEvent({eventId:u.eventId,sessionId:s,output:g,error:b,failureCategory:J,duration:u?Math.max(0,Date.now()-u.timestamp):0,completedAt:Date.now()});}let fe=typeof i=="object"&&i.command?i.command:"",z=f?.exitCode,Ye=f?.stderr,Qe=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,I,_,B=true;if(e.startsWith("mcp__"))I="mcp_call",_={mcpTool:e.replace(/^mcp__[^_]+__/,""),query:typeof i=="object"&&i.query?i.query:null,resultCount:A,resultSizeBytes:x};else if(e==="Read"||e==="Write"||e==="Edit")I=e==="Read"?"file_read":"file_write",_={filePath:typeof i=="object"&&i.file_path?i.file_path:null,fileContentSize:x};else if(e==="Bash"){let p=Qe.test(fe),g=z!==void 0&&z!==0;B=!p||g,I=g?"bash_error":"bash_command",_={command:fe||e,exitCode:z??null,stderr:Ye??null};}else e==="Agent"?(I="subagent",_={subagentType:typeof i=="object"&&i.subagent_type?i.subagent_type:null,description:typeof i=="object"&&i.description?String(i.description).slice(0,200):null}):e==="WebSearch"||e==="WebFetch"?(I=e==="WebSearch"?"web_search":"web_fetch",_={query:typeof i=="object"&&i.query?String(i.query).slice(0,200):null}):(B=false,I="tool_use",_={});if(B){let p={id:t.tool_use_id?`memory:${$e(s??"",t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s??"",tool:e,kind:I,payload:{..._,durationMs:u?Math.max(0,Date.now()-u.timestamp):0},createdAt:Date.now()};s&&T(`/api/memory/session-events?rootPath=${encodeURIComponent(o)}`,p);}let et=Le({toolName:e,toolResponse:r,sessionId:s,toolUseId:t.tool_use_id,runtimeStore:a}),tt=s?He({projectRoot:o,sessionId:s,executionId:c?.executionId,toolName:e,toolInput:i,toolResponse:r,toolUseId:t.tool_use_id}):null,W=lo(o,e);return W&&m({event:"hook.runtime.degraded",identity:{projectRoot:o,sessionId:s,executionId:c?.executionId},level:"warn",timestamp:Date.now(),data:{stage:"post_tool_enforcement",tool:e,reason:W}}),[et,tt,W].filter(p=>!!p).join(`
|
|
4
|
+
`)}function N(n,t=0){if(t>6||n==null)return [];if(typeof n=="string")try{return N(JSON.parse(n),t+1)}catch{return []}if(Array.isArray(n)){for(let o of n){let i=N(o,t+1);if(i.length>0)return i}return []}if(typeof n!="object")return [];let e=n;if(Array.isArray(e.detectorCoverage))return e.detectorCoverage.filter(o=>typeof o=="string").slice(0,32);for(let o of Object.values(e)){let i=N(o,t+1);if(i.length>0)return i}return []}function C(n,t,e){if(t>tn||n===null||n===void 0)return null;if(typeof n=="string"){if(Buffer.byteLength(n,"utf8")>Qt)return null;try{return C(JSON.parse(n),t+1,e)}catch{return null}}if(typeof n!="object"||e.has(n))return null;if(e.add(n),Array.isArray(n)){for(let i of n.slice(0,16)){let r=C(i,t+1,e);if(r)return r}return null}let o=n;if("evidenceContract"in o)return {contract:o.evidenceContract,canonicalReport:o.canonicalReport};for(let i of ["structuredContent","data","result"])if(i in o){let r=C(o[i],t+1,e);if(r)return r}if(Array.isArray(o.content))for(let i of o.content.slice(0,16)){let r=i&&typeof i=="object"&&"text"in i?i.text:i,s=C(r,t+1,e);if(s)return s}return null}function sn(n,t){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;if(e.version!=="1.0"||typeof e.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/.test(e.id)||typeof e.runtimeProfilingOccurred!="boolean"||typeof e.samplingEvidenceOccurred!="boolean"||!Array.isArray(e.requiredSections)||e.requiredSections.length!==M.length)return null;let o=e.requiredSections.filter(c=>typeof c=="string");if(o.length!==M.length||M.some((c,l)=>o[l]!==c)||!Array.isArray(e.prohibitedClaims)||e.prohibitedClaims.length>16)return null;let i=e.prohibitedClaims.filter(c=>typeof c=="string"&&c.length<=128);if(i.length!==e.prohibitedClaims.length)return null;let r=e.correctionPolicy;if(!r||typeof r!="object"||Array.isArray(r))return null;let s=r;if(s.maxAttempts!==1||s.repeatedViolation!=="fail_open")return null;let a=typeof e.canonicalReport=="string"?e.canonicalReport:t;return typeof a!="string"||Buffer.byteLength(a,"utf8")>en||M.some(c=>!a.includes(c))?null:{version:"1.0",id:e.id,runtimeProfilingOccurred:e.runtimeProfilingOccurred,samplingEvidenceOccurred:e.samplingEvidenceOccurred,requiredSections:o,prohibitedClaims:i,correctionPolicy:{maxAttempts:1,repeatedViolation:"fail_open"},canonicalReport:a}}function Le(n){let t;try{if(mn(n.toolResponse))return null;t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:50});let e=t.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId);if(!e)return null;let o=un(n.toolInput);if(o.length===0)return null;let i=n.toolName==="Read"?fn(n.toolInput):void 0,r=i?e.selectedFiles?.find(d=>pn(n.projectRoot,d,i)):void 0,s=gn(n.toolName),a=r?"code":e.canonicalNextAction===s?"action":null,c=r&&o.includes(r)?r:a==="action"&&o.includes(s)?s:void 0;if(a&&c){let d=[e.contextHash,e.requestId??"",a,c,n.toolUseId??`${n.sessionId}:${n.executionId??e.executionId}`].join("\0");t.recordContextSelectionEvent({id:`ctxsel:${createHash$1("sha256").update(d).digest("hex").slice(0,32)}`,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:e.executionId,requestId:e.requestId,selectionType:a,candidateId:c,toolName:n.toolName,toolUseId:n.toolUseId,selectedAt:Date.now()});}let l=t.listRetrievalLedgerEvents({projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:e.executionId,requestId:e.requestId}).filter(d=>d.stage==="selected"&&o.includes(d.sourceId));for(let d of l)t.appendRetrievalLedgerEvent({...d,id:retrievalLedgerTransitionId(d.id,"consumed",n.toolUseId??n.toolName),stage:"consumed",toolEvidence:[n.toolUseId??n.toolName],evidenceIds:o,actor:n.toolName,reasonCode:"structural_evidence_ref",payload:{...d.payload,consumedByTool:n.toolName},createdAt:Date.now()});return l.length>0&&qe({event:"retrieval.attribution.transitioned",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:e.executionId,requestId:e.requestId,contextReceipt:e.contextHash},level:"info",timestamp:Date.now(),data:{stage:"consumed",actor:n.toolName,consumedCount:l.length,evidenceRefCount:o.length}}),a}catch(e){throw qe({event:"hook.runtime.degraded",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,requestId:n.requestId},level:"warn",timestamp:Date.now(),data:{stage:"retrieval_attribution",actor:n.toolName,reason:e instanceof Error?e.message:String(e)}}),e}finally{try{t?.close();}catch{}}}function un(...n){let t=new Set,e=(o,i=0)=>{if(!(i>6||o==null)){if(typeof o=="string"){try{e(JSON.parse(o),i+1);}catch{}return}if(Array.isArray(o)){for(let r of o)e(r,i+1);return}if(typeof o=="object")for(let[r,s]of Object.entries(o))if((r==="evidenceRefs"||r==="_devflow_evidence_refs")&&Array.isArray(s))for(let a of s)typeof a=="string"&&a.trim()&&t.add(a.trim());else e(s,i+1);}};for(let o of n)e(o);return [...t]}function fn(n){for(let t of ["file_path","path"]){let e=n[t];if(typeof e=="string"&&e.trim())return e.trim()}}function pn(n,t,e){let o=resolve(n,t),i=isAbsolute(e)?resolve(e):resolve(n,e);return o===i}function gn(n){return n.startsWith("mcp__")?n.split("__").at(-1)??n:n}function mn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let t=n;return t.ok===false||t.success===false||t.isError===true||!!t.error||["failed","rejected","unavailable"].includes(String(t.status??""))}function qe(n){try{m(n);}catch{}}var In=new Set(["Write","Edit","NotebookEdit"]);function Me(n){if(!In.has(n.toolName)||xn(n.toolResponse))return null;let t=wn(n.projectRoot,n.toolInput);if(!t)return null;let e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let o=e.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId),i=o?.canonicalAction?.verificationPlan??[];if(!o||i.length===0)return null;let r=[],s=[];for(let c of i){let l=_n({projectRoot:n.projectRoot,targetFile:t,kind:c.kind,mode:c.mode==="write"?"write":"check",required:c.required===!0,contextReceipt:o.contextHash}),d=`${o.contextHash}\0${n.toolUseId??t}\0${c.kind}\0${t}`,u=`policy-verification:${createHash$1("sha256").update(d).digest("hex")}`,f=Date.now();if(!l){let A=`verification_unavailable:${c.kind}`;e.upsertSessionObligation({obligationId:u,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,kind:"evidence_contract",state:"degraded",payload:{subtype:"policy_verification",status:"unknown",verificationKind:c.kind,targetFile:t,contextReceipt:o.contextHash},reason:A,createdAt:f,updatedAt:f,resolvedAt:f}),s.push(c.kind),c.required===!0&&E({projectRoot:n.projectRoot,sessionId:n.sessionId,requestId:o.requestId,executionId:n.executionId,kind:"verification.failed",payload:{receiptId:u,reasonCode:A},dedupeKey:`${u}:unavailable`,producer:"devflow-verification-scheduler"});continue}let U={...l,obligationId:u,sessionId:n.sessionId,executionId:n.executionId,requestId:o.requestId};e.upsertSessionObligation({obligationId:u,projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:n.executionId,kind:"evidence_contract",state:"open",payload:{subtype:"policy_verification",status:"scheduled",verificationKind:c.kind,command:l.display,targetFile:t,contextReceipt:o.contextHash,required:c.required===!0},createdAt:f,updatedAt:f});let x=e.enqueueWork({idempotencyKey:u,kind:"verification.policy",projectRoot:n.projectRoot,sessionId:n.sessionId,payload:U,maxAttempts:2,nextAttemptAt:f});E({projectRoot:n.projectRoot,sessionId:n.sessionId,requestId:o.requestId,executionId:n.executionId,kind:"durable_work.owned",payload:{workId:x.id,obligation:"verification"},dedupeKey:`${x.id}:owned`,producer:"devflow-verification-scheduler"}),r.push(l.display);}return [r.length>0?`DevFlow scheduled policy verification: ${r.join(" && ")}`:"",s.length>0?`Verification unavailable and recorded as unknown: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
5
|
+
`)||null}finally{e.close();}}function _n(n){let t=kn(n.projectRoot),e=Sn(n.projectRoot),o=t?.scripts??{},i={...t?.dependencies,...t?.devDependencies},r=null;if(n.kind==="formatter"&&(i.prettier||En(n.projectRoot)))r=H(e,"prettier",[n.mode==="write"?"--write":"--check",n.targetFile],6e4);else if(n.kind==="typecheck"){let s=re(o,["typecheck","type-check","check:types"]);s?r=ie(e,s,12e4):i.typescript&&existsSync$1(join(n.projectRoot,"tsconfig.json"))&&(r=H(e,"tsc",["--noEmit","--pretty","false"],12e4));}else if(n.kind==="lint"){let s=re(o,["lint"]);s&&(r=ie(e,s,12e4));}else if(n.kind==="test"){let s=An(n.projectRoot,n.targetFile);s&&i.vitest?r=H(e,"vitest",["run",s],12e4):s&&(i.jest||i["@jest/core"])&&(r=H(e,"jest",["--runTestsByPath",s],12e4));}else if(n.kind==="build"){let s=re(o,["build"]);s&&(r=ie(e,s,18e4));}else n.kind==="generated_files"&&(r={command:"git",args:["diff","--check","--",n.targetFile],timeoutMs:3e4});return r?{kind:n.kind,...r,display:[r.command,...r.args].map(Dn).join(" "),required:n.required,targetFile:n.targetFile,contextReceipt:n.contextReceipt}:null}function ie(n,t,e){return n==="yarn"?{command:"yarn",args:["run",t],timeoutMs:e}:n==="pnpm"?{command:"pnpm",args:["run",t],timeoutMs:e}:n==="bun"?{command:"bun",args:["run",t],timeoutMs:e}:{command:"npm",args:["run",t],timeoutMs:e}}function H(n,t,e,o){return n==="pnpm"?{command:"pnpm",args:["exec",t,...e],timeoutMs:o}:n==="yarn"?{command:"yarn",args:[t,...e],timeoutMs:o}:n==="bun"?{command:"bunx",args:[t,...e],timeoutMs:o}:{command:"npx",args:["--no-install",t,...e],timeoutMs:o}}function wn(n,t){let e=t.file_path??t.notebook_path;if(typeof e!="string"||!e.trim())return null;let o=isAbsolute(e)?resolve(e):resolve(n,e);return Rn(n,o)?relative(n,o).split(sep).join("/"):null}function Rn(n,t){let e=isAbsolute(t)?resolve(t):resolve(n,t),o=relative(resolve(n),e);return o!==""&&o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}function xn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let t=n;return t.ok===false||t.success===false||t.isError===true||!!t.error}function kn(n){try{return JSON.parse(readFileSync$1(join(n,"package.json"),"utf8"))}catch{return null}}function Sn(n){return existsSync$1(join(n,"pnpm-lock.yaml"))?"pnpm":existsSync$1(join(n,"yarn.lock"))?"yarn":existsSync$1(join(n,"bun.lockb"))||existsSync$1(join(n,"bun.lock"))?"bun":"npm"}function En(n){return [".prettierrc",".prettierrc.json",".prettierrc.js",".prettierrc.cjs","prettier.config.js","prettier.config.cjs"].some(t=>existsSync$1(join(n,t)))}function re(n,t){return t.find(e=>typeof n[e]=="string"&&n[e].trim())??null}function An(n,t){let e=t.replace(/\.[^.]+$/u,""),o=[".test.ts",".test.tsx",".spec.ts",".spec.tsx",".test.js",".spec.js"];for(let s of o){let a=`${e}${s}`;if(existsSync$1(join(n,a)))return a}let i=join(n,t.split("/").slice(0,-1).join("/")),r=t.split("/").at(-1)?.replace(/\.[^.]+$/u,"");if(!r||!existsSync$1(i))return null;try{return readdirSync$1(i).filter(s=>s.startsWith(`${r}.`)&&/\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(s)).map(s=>relative(n,join(i,s)).split(sep).join("/"))[0]??null}catch{return null}}function Dn(n){return /^[A-Za-z0-9_./:@=-]+$/u.test(n)?n:JSON.stringify(n)}function Ue(n){if(!n.toolUseId)return null;let t=Nn(n.projectRoot,n.toolUseId);if(!t||t.sessionId!==n.sessionId)return null;let e=Date.now(),o={...t,id:createHash$1("sha256").update(`${t.sessionId}\0${t.toolUseId}\0${t.path}\0${e}`).digest("hex"),phase:"completed",success:n.success,after:qn(t.path),completedAt:e,error:n.error?.slice(0,500)},i=Ln(n.projectRoot);return mkdirSync$1(dirname(i),{recursive:true}),appendFileSync(i,`${JSON.stringify(o)}
|
|
6
|
+
`,{encoding:"utf8",mode:384}),m({event:"canonical.action.validated",identity:{projectRoot:n.projectRoot,sessionId:n.sessionId,executionId:t.executionId,contextReceipt:t.contextReceipt},level:n.success?"info":"warn",timestamp:e,data:{stage:"host_file_state_completed",valid:n.success,operation:t.operation,targetPath:relative(n.projectRoot,t.path),beforeHash:t.before.hash,afterHash:o.after.hash,beforeExists:t.before.exists,afterExists:o.after.exists,reason:o.error,toolUseId:t.toolUseId}}),o}function qn(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 Ve(n){return join(w(n),"file-state")}function ze(n){return join(Ve(n),"pending.json")}function Ln(n){return join(Ve(n),"observations.jsonl")}function Mn(n){try{return JSON.parse(readFileSync$1(ze(n),"utf8"))}catch{return {}}}function Nn(n,t){let e=ze(n),o=Mn(n),i=o[t];if(i)return delete o[t],Hn(e,JSON.stringify(o)),i}function Hn(n,t){let e=`${n}.${process.pid}.${Date.now()}.tmp`;writeFileSync$1(e,t,{encoding:"utf8",mode:384}),renameSync$1(e,n);}var Vn={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 zn(n){return Bn(n)}function Bn(n){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let e=Gn(t,n.artifact);if(Zn(e.toState))return e;let o=t.getContextReceiptForRequest(n.artifact.projectRoot,n.artifact.sessionId,n.artifact.requestId),i=t.getMemoryTurn(n.artifact.turnId),r=n.artifact.intent==="memory"||i?.source==="explicit_intent";if(!o&&!r)return e;let s=o?Wn(n.artifact,o):"context_ready";e.toState==="intent_bound"&&(e=y(t,e,n,s,r?"task_context_not_required":s==="context_ready"?"canonical_context_receipt_ready":"canonical_context_receipt_degraded"));let a=o?Jn(n.artifact,o):"action_not_required";if((e.toState==="context_ready"||e.toState==="context_degraded")&&(a==="action_not_required"?e=y(t,e,n,"action_not_required","task_action_not_required"):e=y(t,e,n,"action_required","canonical_action_obligation_present")),e.toState==="action_required"){if(a==="action_required")return e;if(a==="action_failed")return y(t,e,n,"action_failed","canonical_action_attempt_failed");a==="action_degraded"?e=y(t,e,n,"action_degraded","canonical_action_unavailable_or_degraded"):a==="action_satisfied"&&(e=y(t,e,n,"action_satisfied","canonical_action_succeeded"));}if(e.toState==="action_failed")if(a==="action_satisfied")e=y(t,e,n,"action_satisfied","canonical_action_retry_succeeded");else if(a==="action_degraded")e=y(t,e,n,"action_degraded","canonical_action_retry_degraded");else return e;let c=s==="context_degraded"||a==="action_degraded";return ["action_not_required","action_satisfied","action_degraded"].includes(e.toState)&&(e=y(t,e,n,n.memoryStatus==="pending"?"memory_quarantined":"memory_decided",n.memoryStatus==="pending"?n.reason:`canonical_memory_${n.memoryStatus}`)),e.toState==="memory_decided"?y(t,e,n,c?"closed_with_degradation":"closed",n.reason):e.toState==="memory_quarantined"?y(t,e,n,n.retryOwned?"closed_with_retry_work":"closed_with_degradation",n.retryOwned?"durable_retry_owner_confirmed":"terminal_obligation_unowned"):e}finally{t.close();}}function We(n){let t=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});try{let e=t.getActiveContextReceipt(n.projectRoot,n.sessionId,n.executionId),o=typeof e?.canonicalAction?.binding.turnId=="string"?e.canonicalAction.binding.turnId:void 0;if(!o)return null;let i=t.listLatestTaskIntentArtifacts(n.projectRoot,n.sessionId).find(s=>s.turnId===o),r=t.getMemoryTurn(o);return !i||!r?null:zn({artifact:i,memoryStatus:r.status,memoryReceiptId:r.receiptId,reason:n.reason})}finally{t.close();}}function Wn(n,t){return n.intent==="memory"||n.intent==="knowledge"||(t.selectedFiles?.length??0)>0?"context_ready":"context_degraded"}function Jn(n,t){let e=t.canonicalAction,i=(e?(t.actionAttempts??[]).filter(r=>r.tool===e.tool):[]).at(-1);return t.actionSatisfiedAt||i?.status==="succeeded"?"action_satisfied":i&&["failed","timeout","unavailable"].includes(i.status)?"action_failed":t.actionDegradation||e?.status==="degraded"||e?.status==="unsupported"?"action_degraded":e?.required||Kn(n)?"action_required":"action_not_required"}function Kn(n){return ["create","modify","debug","test","format"].includes(n.action)||["feature","refactor","performance"].includes(n.intent)}function Gn(n,t){let e=n.getLatestTerminalTransition(t.projectRoot,t.sessionId,t.turnId);if(!e)throw new Error(`TERMINAL_INTENT_STATE_MISSING:${t.turnId}`);return e}function y(n,t,e,o,i){if(!Vn[t.toState]?.includes(o))throw new Error(`TERMINAL_PATH_UNAVAILABLE:${t.toState}->${o}`);let r=t.sequence+1,s=`terminal:${createHash$1("sha256").update(`${e.artifact.artifactHash}\0${r}\0${o}`).digest("hex").slice(0,24)}`,a=n.appendTerminalTransition({projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,executionId:e.artifact.executionId,sequence:r,fromState:t.toState,toState:o,receiptId:s,sourceReceiptId:e.memoryReceiptId??t.receiptId,reason:i,payload:{memoryStatus:e.memoryStatus,retryOwned:e.retryOwned??false,sourceIntentHash:e.artifact.artifactHash},createdAt:Date.now()});return m({event:"terminal.state.transitioned",identity:{projectRoot:e.artifact.projectRoot,projectId:e.artifact.projectId,hostId:e.artifact.hostId,sessionId:e.artifact.sessionId,turnId:e.artifact.turnId,requestId:e.artifact.requestId,...e.artifact.executionId?{executionId:e.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:i}}),a}function Zn(n){return n==="closed"||n==="closed_with_degradation"||n==="closed_with_retry_work"}function Je(n){let t=n.hook==="post_tool_use_failure"||!!n.error?.trim()||Xn(n.response),e=t?"not_consumed":n.hook==="post_tool_use"?"consumed":"unknown",o=t?Yn(n.error,n.response):e==="consumed"?"host_reported_success":"host_outcome_unknown";return {schemaVersion:"host-tool-outcome.v1",toolName:n.toolName,...n.toolUseId?{toolUseId:n.toolUseId}:{},consumption:e,reasonCode:o,receiptId:n.toolUseId??`host-tool:${n.toolName}:${o}`}}function Xn(n){if(!n||typeof n!="object"||Array.isArray(n))return false;let t=n;return t.isError===true||t.error?true:typeof t.status=="string"&&["failed","error","rejected","timeout","unavailable"].includes(t.status.toLowerCase())}function Yn(n,t){let e=`${n??""} ${JSON.stringify(t??"")}`;return /timeout|timed out|deadline/iu.test(e)?"host_tool_timeout":/unavailable|not found|not registered|unsupported/iu.test(e)?"host_tool_unavailable":"host_tool_failed"}function Ke(n){if(!n)return;let t=typeof n.status=="string"?n.status:void 0;if(!(n.ok===false||n.success===false||n.isError===true||t==="failed"||t==="rejected"||!!n.error))return;let o=n.error;if(typeof o=="string"&&o.trim())return o;if(o&&typeof o=="object"){let i=o;if(typeof i.message=="string"&&i.message.trim())return i.message;if(typeof i.code=="string"&&i.code.trim())return i.code}return t?`Tool response status: ${t}`:"Tool response reported failure"}function so(n,t,e,o){try{let i=join$1(w(n),"event-map.json");if(!existsSync(i))return null;let r=JSON.parse(readFileSync(i,"utf-8")),s=r.filter(l=>l.toolName===e&&(!l.sessionId||l.sessionId===t));if(s.length===0)return null;let a=o?s.find(l=>l.toolUseId===o):s.sort((l,d)=>l.timestamp-d.timestamp)[0];if(!a)return null;let c=r.findIndex(l=>l.eventId===a.eventId);return c!==-1&&r.splice(c,1),writeFileSync(i,JSON.stringify(r)),{eventId:a.eventId,timestamp:a.timestamp}}catch{return null}}function Ge(n){if(!n)return 0;let t=n;if(typeof n=="string")try{t=JSON.parse(n);}catch{return 1}let e=t,o=["files","results","data","result","memories","nodes","chunks","findings","symbols","keySymbols"],i=["reasoning","riskHints","nextActions"],r=Array.isArray(e.data)?e.data:e.structuredContent??e;if(Array.isArray(r))return r.length;if(typeof r=="object"&&r!==null){let s=r,a=0,c=false;for(let d of o)Array.isArray(s[d])&&(c=true,a+=s[d].length);for(let d of i)Array.isArray(s[d])&&(a+=s[d].length);for(let[,d]of Object.entries(s))d&&typeof d=="object"&&!Array.isArray(d)&&(a+=Ge(d));let l=!!(s._devflow||s._devflow_unique||s.taskType);return a===0&&l&&!c?1:a>0?a:c?0:Object.keys(s).length>0?1:0}return 0}async function ao(n){if(!n)return null;let t;try{t=JSON.parse(n);}catch{return null}let e=t.tool_name||"",o=G(),i=t.tool_input||{},r=t.tool_response||{},s=t.session_id?.trim()||null,a=new R(o);if(s&&a.registerSession(s),s&&e==="mcp__devflow__get_project_context"&&a.completeContextInitialization(s,t.tool_use_id),e==="Skill"){let p=typeof i=="object"&&i.skill?i.skill:"",g=je(p);s&&g&&(a.startExecution(s,g,Te(g)),ee(o,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}let c=s?a.get(s):null;if(e.startsWith("mcp__")){let p=new P(o,s??void 0,c?.executionId??s??void 0);p.recordMcpCall();let g=Ke(typeof r=="object"&&r!==null?r:null),b=e.replace(/^mcp__[^_]+__/,""),W=p.getContextReceipt?.()?.canonicalAction?.tool===b;if((p.recordDomainActionOutcome(b,g?co(g):"succeeded",g,t.tool_use_id)||W)&&s){let k=Je({hook:"post_tool_use",toolName:b,...t.tool_use_id?{toolUseId:t.tool_use_id}:{},response:r,...g?{error:g}:{}});E({projectRoot:o,sessionId:s,executionId:c?.executionId??s,kind:k.consumption==="consumed"?"action.succeeded":"action.failed",payload:{receiptId:k.receiptId,reasonCode:k.reasonCode,consumption:k.consumption,tool:b},dedupeKey:`${k.receiptId}:${k.consumption}`,producer:"devflow-post-tool-use"});try{We({projectRoot:o,sessionId:s,executionId:c?.executionId??s,reason:g?"post_tool_action_failed":"post_tool_action_succeeded"});}catch{}}}s&&Le({projectRoot:o,sessionId:s,executionId:c?.executionId,toolName:e,toolInput:i,toolResponse:r,toolUseId:t.tool_use_id});let l=s?so(o,s,e,t.tool_use_id):null,d=s&&t.tool_use_id&&!l?(()=>{try{let p=openGlobalDevFlowDatabase();try{return p.getToolCallEventByToolUseId(s,t.tool_use_id)}finally{p.close();}}catch{return null}})():null,u=l??d,f=typeof r=="object"&&r!==null?r:null,U=JSON.stringify(r),x=Buffer.byteLength(U,"utf8"),A=Ge(r),V=Ke(f);if(s&&Ue({projectRoot:o,sessionId:s,toolUseId:t.tool_use_id,success:!V,error:V}),c?.executionId!==void 0||e.startsWith("mcp__devflow__")||e==="Skill"){let p=getLogWriter(o),g=c?.executionId??`auto-${s??Date.now()}`;p.toolCall({tool:e,runId:g,stepId:`step-${g}`,input:i,output:r,duration:u?Math.max(0,Date.now()-u.timestamp):0,success:!f?.error,resultCount:A,resultSizeBytes:x,error:f?.error});}if(u&&s){let p=typeof r=="string"?r:JSON.stringify(r),g=p.length>5e3?{_truncated:true,_originalSize:p.length,text:p.slice(0,5e3)}:r,b=V,W=b?classifyWorkflowFailure({stepId:e,toolName:e,output:r,error:new Error(b),errorStack:b}).category:void 0;await new q().completeEvent({eventId:u.eventId,sessionId:s,output:g,error:b,failureCategory:W,duration:u?Math.max(0,Date.now()-u.timestamp):0,completedAt:Date.now()});}let le=typeof i=="object"&&i.command?i.command:"",z=f?.exitCode,Ze=f?.stderr,Xe=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,I,_,B=true;if(e.startsWith("mcp__"))I="mcp_call",_={mcpTool:e.replace(/^mcp__[^_]+__/,""),query:typeof i=="object"&&i.query?i.query:null,resultCount:A,resultSizeBytes:x};else if(e==="Read"||e==="Write"||e==="Edit")I=e==="Read"?"file_read":"file_write",_={filePath:typeof i=="object"&&i.file_path?i.file_path:null,fileContentSize:x};else if(e==="Bash"){let p=Xe.test(le),g=z!==void 0&&z!==0;B=!p||g,I=g?"bash_error":"bash_command",_={command:le||e,exitCode:z??null,stderr:Ze??null};}else e==="Agent"?(I="subagent",_={subagentType:typeof i=="object"&&i.subagent_type?i.subagent_type:null,description:typeof i=="object"&&i.description?String(i.description).slice(0,200):null}):e==="WebSearch"||e==="WebFetch"?(I=e==="WebSearch"?"web_search":"web_fetch",_={query:typeof i=="object"&&i.query?String(i.query).slice(0,200):null}):(B=false,I="tool_use",_={});if(B){let p={id:t.tool_use_id?`memory:${Pe(s??"",t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:s??"",tool:e,kind:I,payload:{..._,durationMs:u?Math.max(0,Date.now()-u.timestamp):0},createdAt:Date.now()};s&&T(`/api/memory/session-events?rootPath=${encodeURIComponent(o)}`,p);}let Ye=$e({toolName:e,toolResponse:r,sessionId:s,toolUseId:t.tool_use_id,runtimeStore:a}),Qe=s?Me({projectRoot:o,sessionId:s,executionId:c?.executionId,toolName:e,toolInput:i,toolResponse:r,toolUseId:t.tool_use_id}):null;return [Ye,Qe].filter(p=>!!p).join(`
|
|
7
7
|
|
|
8
|
-
`)||null}function
|
|
8
|
+
`)||null}function co(n){return /timeout|timed out|deadline|warming/i.test(n)?"timeout":/unavailable|not active|unknown tool|not found|not registered|route not found/i.test(n)?"unavailable":"failed"}if(process.argv[1]?.endsWith("post-tool-use")||process.argv[1]?.endsWith("post-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 ao(t.trim()||process.argv[2]||"");n(JSON.stringify(e?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}}:{status:"ok"}));}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),5e3).unref();}export{ao as handlePostToolUse};
|
|
@@ -62,7 +62,9 @@ fi
|
|
|
62
62
|
# Append Gateway status to summary
|
|
63
63
|
GATEWAY_STATUS=$'\n\n━━━━━━ DevFlow Gateway ━━━━━━\n'
|
|
64
64
|
# Check if devflow MCP server is configured (token will be auto-generated by ensureSessionToken)
|
|
65
|
-
if [ -f
|
|
65
|
+
if [ -f "$PLUGIN_ROOT/.mcp.json" ] && grep -q '"devflow"' "$PLUGIN_ROOT/.mcp.json" 2>/dev/null; then
|
|
66
|
+
GATEWAY_STATUS="${GATEWAY_STATUS}Status: 🟢 DevFlow MCP 已配置(插件级)"$'\n'"Gate 层数: ${GATE_COUNT} (${GATE_DETAIL})"$'\n'
|
|
67
|
+
elif [ -f ~/.claude/.mcp.json ] && grep -q '"devflow"' ~/.claude/.mcp.json 2>/dev/null; then
|
|
66
68
|
GATEWAY_STATUS="${GATEWAY_STATUS}Status: 🟢 DevFlow MCP 已配置"$'\n'"Gate 层数: ${GATE_COUNT} (${GATE_DETAIL})"$'\n'
|
|
67
69
|
elif [ -f .mcp.json ] && grep -q '"devflow"' .mcp.json 2>/dev/null; then
|
|
68
70
|
GATEWAY_STATUS="${GATEWAY_STATUS}Status: 🟢 DevFlow MCP 已配置(项目级)"$'\n'"Gate 层数: ${GATE_COUNT} (${GATE_DETAIL})"$'\n'
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devflow-tools/claude-code-plugin",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.27",
|
|
4
4
|
"description": "Claude Code hooks and skills for the DevFlow development intelligence runtime.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -12,20 +12,20 @@
|
|
|
12
12
|
"verify:runtime-dependencies": "node --import tsx scripts/verify-runtime-dependencies.ts"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@devflow-tools/benchmark": "0.18.
|
|
16
|
-
"@devflow-tools/context-engine": "0.18.
|
|
17
|
-
"@devflow-tools/database": "0.18.
|
|
18
|
-
"@devflow-tools/mcp-server": "0.18.
|
|
19
|
-
"@devflow-tools/memory-engine": "0.18.
|
|
20
|
-
"@devflow-tools/sdk": "0.18.
|
|
21
|
-
"@devflow-tools/semantic-engine": "0.18.
|
|
22
|
-
"@devflow-tools/server": "0.18.
|
|
23
|
-
"@devflow-tools/task-runtime": "0.18.
|
|
24
|
-
"@devflow-tools/telemetry": "0.18.
|
|
25
|
-
"@devflow-tools/workflow-engine": "0.18.
|
|
15
|
+
"@devflow-tools/benchmark": "0.18.27",
|
|
16
|
+
"@devflow-tools/context-engine": "0.18.27",
|
|
17
|
+
"@devflow-tools/database": "0.18.27",
|
|
18
|
+
"@devflow-tools/mcp-server": "0.18.27",
|
|
19
|
+
"@devflow-tools/memory-engine": "0.18.27",
|
|
20
|
+
"@devflow-tools/sdk": "0.18.27",
|
|
21
|
+
"@devflow-tools/semantic-engine": "0.18.27",
|
|
22
|
+
"@devflow-tools/server": "0.18.27",
|
|
23
|
+
"@devflow-tools/task-runtime": "0.18.27",
|
|
24
|
+
"@devflow-tools/telemetry": "0.18.27",
|
|
25
|
+
"@devflow-tools/workflow-engine": "0.18.27"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@devflow-tools/devflow": "0.18.
|
|
28
|
+
"@devflow-tools/devflow": "0.18.27"
|
|
29
29
|
},
|
|
30
30
|
"allowScripts": {
|
|
31
31
|
"better-sqlite3@12.11.1": true,
|
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
]
|
|
45
45
|
},
|
|
46
46
|
"files": [
|
|
47
|
+
".mcp.json",
|
|
47
48
|
".claude-plugin",
|
|
48
49
|
"CLAUDE.md",
|
|
49
50
|
"dist",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devflow-tools/cli",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"devflow": "./bin/devflow.cjs"
|
|
@@ -14,38 +14,38 @@
|
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@colbymchenry/codegraph": "^1.1.1",
|
|
17
|
-
"@devflow-tools/adapters": "0.18.
|
|
18
|
-
"@devflow-tools/benchmark": "0.18.
|
|
19
|
-
"@devflow-tools/context-engine": "0.18.
|
|
20
|
-
"@devflow-tools/database": "0.18.
|
|
21
|
-
"@devflow-tools/delivery-line": "0.18.
|
|
22
|
-
"@devflow-tools/knowledge-engine": "0.18.
|
|
23
|
-
"@devflow-tools/mcp-server": "0.18.
|
|
24
|
-
"@devflow-tools/memory-engine": "0.18.
|
|
25
|
-
"@devflow-tools/plugin-animation": "0.18.
|
|
26
|
-
"@devflow-tools/plugin-css": "0.18.
|
|
27
|
-
"@devflow-tools/plugin-docker": "0.18.
|
|
28
|
-
"@devflow-tools/plugin-electron": "0.18.
|
|
29
|
-
"@devflow-tools/plugin-git": "0.18.
|
|
30
|
-
"@devflow-tools/plugin-graphql": "0.18.
|
|
31
|
-
"@devflow-tools/plugin-nest": "0.18.
|
|
32
|
-
"@devflow-tools/plugin-nextjs": "0.18.
|
|
33
|
-
"@devflow-tools/plugin-performance": "0.18.
|
|
34
|
-
"@devflow-tools/plugin-react": "0.18.
|
|
35
|
-
"@devflow-tools/plugin-tailwind": "0.18.
|
|
36
|
-
"@devflow-tools/plugin-taro": "0.18.
|
|
37
|
-
"@devflow-tools/plugin-ui-layout": "0.18.
|
|
38
|
-
"@devflow-tools/plugin-vue": "0.18.
|
|
39
|
-
"@devflow-tools/sdk": "0.18.
|
|
40
|
-
"@devflow-tools/server": "0.18.
|
|
41
|
-
"@devflow-tools/telemetry": "0.18.
|
|
42
|
-
"@devflow-tools/workflow-engine": "0.18.
|
|
17
|
+
"@devflow-tools/adapters": "0.18.27",
|
|
18
|
+
"@devflow-tools/benchmark": "0.18.27",
|
|
19
|
+
"@devflow-tools/context-engine": "0.18.27",
|
|
20
|
+
"@devflow-tools/database": "0.18.27",
|
|
21
|
+
"@devflow-tools/delivery-line": "0.18.27",
|
|
22
|
+
"@devflow-tools/knowledge-engine": "0.18.27",
|
|
23
|
+
"@devflow-tools/mcp-server": "0.18.27",
|
|
24
|
+
"@devflow-tools/memory-engine": "0.18.27",
|
|
25
|
+
"@devflow-tools/plugin-animation": "0.18.27",
|
|
26
|
+
"@devflow-tools/plugin-css": "0.18.27",
|
|
27
|
+
"@devflow-tools/plugin-docker": "0.18.27",
|
|
28
|
+
"@devflow-tools/plugin-electron": "0.18.27",
|
|
29
|
+
"@devflow-tools/plugin-git": "0.18.27",
|
|
30
|
+
"@devflow-tools/plugin-graphql": "0.18.27",
|
|
31
|
+
"@devflow-tools/plugin-nest": "0.18.27",
|
|
32
|
+
"@devflow-tools/plugin-nextjs": "0.18.27",
|
|
33
|
+
"@devflow-tools/plugin-performance": "0.18.27",
|
|
34
|
+
"@devflow-tools/plugin-react": "0.18.27",
|
|
35
|
+
"@devflow-tools/plugin-tailwind": "0.18.27",
|
|
36
|
+
"@devflow-tools/plugin-taro": "0.18.27",
|
|
37
|
+
"@devflow-tools/plugin-ui-layout": "0.18.27",
|
|
38
|
+
"@devflow-tools/plugin-vue": "0.18.27",
|
|
39
|
+
"@devflow-tools/sdk": "0.18.27",
|
|
40
|
+
"@devflow-tools/server": "0.18.27",
|
|
41
|
+
"@devflow-tools/telemetry": "0.18.27",
|
|
42
|
+
"@devflow-tools/workflow-engine": "0.18.27",
|
|
43
43
|
"@inquirer/prompts": "^7.10.1",
|
|
44
44
|
"chalk": "^5.3.0",
|
|
45
45
|
"commander": "^12.0.0"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@devflow-tools/devflow": "0.18.
|
|
48
|
+
"@devflow-tools/devflow": "0.18.27",
|
|
49
49
|
"typescript": "^5.5.0",
|
|
50
50
|
"vitest": "^2.0.0"
|
|
51
51
|
},
|