MCPcopy Create free account
hub / github.com/ChinaSiro/claude-code-sourcemap / WWK

Function WWK

package/cli.js:4118–4171  ·  view source on GitHub ↗
(q,K,_)

Source from the content-addressed store, hash-verified

4116Check this list before writing — update an existing file rather than creating a duplicate.`:"";return[`You are now acting as the memory extraction subagent. Analyze the most recent ~${q} messages above and use them to update your persistent memory systems.`,"",`Available tools: ${Cq}, ${n3}, ${i9}, read-only ${_q} (ls/find/cat/stat/wc/head/tail and similar), and ${X4}/${tK} for paths inside the memory directory only. ${_q} rm is not permitted. All other tools — MCP, Agent, write-capable ${_q}, etc — will be denied.`,"",`You have a limited turn budget. ${X4} requires a prior ${Cq} of the same file, so the efficient strategy is: turn 1 — issue all ${Cq} calls in parallel for every file you might update; turn 2 — issue all ${tK}/${X4} calls in parallel. Do not interleave reads and writes across multiple turns.`,"",`You MUST only use content from the last ~${q} messages to update your persistent memories. Do not waste any turns attempting to investigate or verify that content further — no grepping source files, no reading code to confirm a pattern exists, no git commands.`+_].join(`
4117`)}function OWK(q,K,_=!1){let z=_?["## How to save memories","","Write each memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:","",...jp,"","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."]:["## How to save memories","","Saving a memory is a two-step process:","","**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:","",...jp,"","**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: `- [Title](file.md) — one-line hook`. It has no frontmatter. Never write memory content directly into `MEMORY.md`.","","- `MEMORY.md` is always loaded into your system prompt — lines after 200 will be truncated, so keep the index concise","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."];return[AWK(q,K),"","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","",...Jp8,...XH6,"",...z].join(`
4118`)}function wWK(q,K,_=!1){let z=_?["## How to save memories","","Write each memory to its own file in the chosen directory (private or team, per the type's scope guidance) using this frontmatter format:","",...jp,"","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."]:["## How to save memories","","Saving a memory is a two-step process:","","**Step 1** — write the memory to its own file in the chosen directory (private or team, per the type's scope guidance) using this frontmatter format:","",...jp,"","**Step 2** — add a pointer to that file in the same directory's `MEMORY.md`. Each directory (private and team) has its own `MEMORY.md` index — each entry should be one line, under ~150 characters: `- [Title](file.md) — one-line hook`. They have no frontmatter. Never write memory content directly into a `MEMORY.md`.","","- Both `MEMORY.md` indexes are loaded into your system prompt — lines after 200 will be truncated, so keep them concise","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."];return[AWK(q,K),"","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","",...Hp8,...XH6,"- You MUST avoid saving sensitive data within shared team memories. For example, never save API keys or user credentials.","",...z].join(`
4119`)}var jWK=y(()=>{j18();IY();E2();qM()});var fp8={};T8(fp8,{initExtractMemories:()=>t5Y,executeExtractMemories:()=>e5Y,drainPendingExtraction:()=>q3Y,createAutoMemCanUseTool:()=>Dp8});import{basename as r5Y}from"path";function W87(q){return q.type==="user"||q.type==="assistant"}function o5Y(q,K){if(K===null||K===void 0)return $7(q,W87);let _=!1,z=0;for(let Y of q){if(!_){if(Y.uuid===K)_=!0;continue}if(W87(Y))z++}if(!_)return $7(q,W87);return z}function a5Y(q,K){let _=K===void 0;for(let z of q){if(!_){if(z.uuid===K)_=!0;continue}if(z.type!=="assistant")continue;let Y=z.message.content;if(!Array.isArray(Y))continue;for(let $ of Y){let A=MWK($);if(A!==void 0&&f16(A))return!0}}return!1}function JWK(q,K){return N(`[autoMem] denied ${q.name}: ${K}`),d("tengu_auto_mem_tool_denied",{tool_name:wK(q.name)}),{behavior:"deny",message:K,decisionReason:{type:"other",reason:K}}}function Dp8(q){return async(K,_)=>{if(K.name===FS)return{behavior:"allow",updatedInput:_};if(K.name===Cq||K.name===n3||K.name===i9)return{behavior:"allow",updatedInput:_};if(K.name===_q){let z=K.inputSchema.safeParse(_);if(z.success&&K.isReadOnly(z.data))return{behavior:"allow",updatedInput:_};return JWK(K,"Only read-only shell commands are permitted in this context (ls, find, grep, cat, stat, wc, head, tail, and similar)")}if((K.name===X4||K.name===tK)&&"file_path"in _){let z=_.file_path;if(typeof z==="string"&&f16(z))return{behavior:"allow",updatedInput:_}}return JWK(K,`only ${Cq}, ${n3}, ${i9}, read-only ${_q}, and ${X4}/${tK} within ${q} are allowed`)}}function MWK(q){if(q.type!=="tool_use"||q.name!==X4&&q.name!==tK)return;let K=q.input;if(typeof K==="object"&&K!==null&&"file_path"in K){let _=K.file_path;return typeof _==="string"?_:void 0}return}function s5Y(q){let K=[];for(let _ of q){if(_.type!=="assistant")continue;let z=_.message.content;if(!Array.isArray(z))continue;for(let Y of z){let $=MWK(Y);if($!==void 0)K.push($)}}return cJ(K)}function t5Y(){let q=new Set,K,_=!1,z=!1,Y=0,$;async function A({context:w,appendSystemMessage:j,isTrailingRun:H}){let{messages:J}=w,M=Vj(),X=o5Y(J,K);if(a5Y(J,K)){N("[extractMemories] skipping — conversation already wrote to memory files");let Z=J.at(-1);if(Z?.uuid)K=Z.uuid;d("tengu_extract_memories_skipped_direct_write",{message_count:X});return}let P=HWK.isTeamMemoryEnabled(),W=g8("tengu_moth_copse",!1),D=Dp8(M),f=hL(w);if(!H){if(Y++,Y<(g8("tengu_bramble_lintel",null)??1))return}Y=0,z=!0;let G=Date.now();try{N(`[extractMemories] starting — ${X} new messages, memoryDir=${M}`);let Z=Pp8(await Xp8(M,P3().signal)),T=P?wWK(X,Z,W):OWK(X,Z,W),v=await hG({promptMessages:[U8({content:T})],cacheSafeParams:f,canUseTool:D,querySource:"extract_memories",forkLabel:"extract_memories",skipTranscript:!0,maxTurns:5}),V=J.at(-1);if(V?.uuid)K=V.uuid;let E=s5Y(v.messages),S=$7(v.messages,(p)=>p.type==="assistant"),R=v.totalUsage.input_tokens+v.totalUsage.cache_creation_input_tokens+v.totalUsage.cache_read_input_tokens,x=R>0?(v.totalUsage.cache_read_input_tokens/R*100).toFixed(1):"0.0";if(N(`[extractMemories] finished — ${E.length} files written, cache: read=${v.totalUsage.cache_read_input_tokens} create=${v.totalUsage.cache_creation_input_tokens} input=${v.totalUsage.input_tokens} (${x}% hit)`),E.length>0)N(`[extractMemories] memories saved: ${E.join(", ")}`);else N("[extractMemories] no memories saved this run");let I=E.filter((p)=>r5Y(p)!==oP),B=$7(I,HWK.isTeamMemPath);if(d("tengu_extract_memories_extraction",{input_tokens:v.totalUsage.input_tokens,output_tokens:v.totalUsage.output_tokens,cache_read_input_tokens:v.totalUsage.cache_read_input_tokens,cache_creation_input_tokens:v.totalUsage.cache_creation_input_tokens,message_count:X,turn_count:S,files_written:E.length,memories_saved:I.length,team_memories_saved:B,duration_ms:Date.now()-G}),N(`[extractMemories] writtenPaths=${E.length} memoryPaths=${I.length} appendSystemMessage defined=${j!=null}`),I.length>0){let p=Zp8(I);p.teamCount=B,j?.(p)}}catch(Z){N(`[extractMemories] error: ${Z}`),d("tengu_extract_memories_error",{duration_ms:Date.now()-G})}finally{z=!1;let Z=$;if($=void 0,Z)N("[extractMemories] running trailing extraction for stashed context"),await A({context:Z.context,appendSystemMessage:Z.appendSystemMessage,isTrailingRun:!0})}}async function O(w,j){if(w.toolUseContext.agentId)return;if(!g8("tengu_passport_quail",!1))return;if(!l3())return;if(z5())return;if(z){N("[extractMemories] extraction in progress — stashing for trailing run"),d("tengu_extract_memories_coalesced",{}),$={context:w,appendSystemMessage:j};return}await A({context:w,appendSystemMessage:j})}XWK=async(w,j)=>{let H=O(w,j);q.add(H);try{await H}finally{q.delete(H)}},PWK=async(w=60000)=>{if(q.size===0)return;await Promise.race([Promise.all(q).catch(()=>{}),new Promise((j)=>setTimeout(j,w).unref())])}}async function e5Y(q,K){await XWK?.(q,K)}async function q3Y(q){await PWK(q)}var HWK,XWK=null,PWK=async()=>{};var H18=y(()=>{v8();n76();P87();rw();IY();E2();qM();k16();B2();_8();nv();i1();o1();k8();kj();jWK();HWK=(YL(),Eq(Pi))});function WWK(q,K,_){return`# Dream: Memory Consolidation
4120
4121You are performing a dream — a reflective pass over your memory files. Synthesize what you've learned recently into durable, well-organized memories so that future sessions can orient quickly.
4122
4123Memory directory: \`${q}\`
4124${D87}
4125
4126Session transcripts: \`${K}\` (large JSONL files — grep narrowly, don't read whole files)
4127
4128---
4129
4130## Phase 1 — Orient
4131
4132- \`ls\` the memory directory to see what already exists
4133- Read \`${oP}\` to understand the current index
4134- Skim existing topic files so you improve them rather than creating duplicates
4135- If \`logs/\` or \`sessions/\` subdirectories exist (assistant-mode layout), review recent entries there
4136
4137## Phase 2 — Gather recent signal
4138
4139Look for new information worth persisting. Sources in rough priority order:
4140
41411. **Daily logs** (\`logs/YYYY/MM/YYYY-MM-DD.md\`) if present — these are the append-only stream
41422. **Existing memories that drifted** — facts that contradict something you see in the codebase now
41433. **Transcript search** — if you need specific context (e.g., "what was the error message from yesterday's build failure?"), grep the JSONL transcripts for narrow terms:
4144 \`grep -rn "<narrow term>" ${K}/ --include="*.jsonl" | tail -50\`
4145
4146Don't exhaustively read transcripts. Look only for things you already suspect matter.
4147
4148## Phase 3 — Consolidate
4149
4150For each thing worth remembering, write or update a memory file at the top level of the memory directory. Use the memory file format and type conventions from your system prompt's auto-memory section — it's the source of truth for what to save, how to structure it, and what NOT to save.
4151
4152Focus on:
4153- Merging new signal into existing topic files rather than creating near-duplicates
4154- Converting relative dates ("yesterday", "last week") to absolute dates so they remain interpretable after time passes
4155- Deleting contradicted facts — if today's investigation disproves an old memory, fix it at the source
4156
4157## Phase 4 — Prune and index
4158
4159Update \`${oP}\` so it stays under ${nK6} lines AND under ~25KB. It's an **index**, not a dump — each entry should be one line under ~150 characters: \`- [Title](file.md) — one-line hook\`. Never write memory content directly into it.
4160
4161- Remove pointers to memories that are now stale, wrong, or superseded
4162- Demote verbose entries: if an index line is over ~200 chars, it's carrying content that belongs in the topic file — shorten the line, move the detail
4163- Add pointers to newly important memories
4164- Resolve contradictions — if two files disagree, fix the wrong one
4165
4166---
4167
4168Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.${_?`
4169
4170## Additional context
4171
4172${_}`:""}`}var DWK=y(()=>{n76()});function _3Y(){let q=g8("tengu_onyx_plover",null);return{minHours:typeof q?.minHours==="number"&&Number.isFinite(q.minHours)&&q.minHours>0?q.minHours:fWK.minHours,minSessions:typeof q?.minSessions==="number"&&Number.isFinite(q.minSessions)&&q.minSessions>0?q.minSessions:fWK.minSessions}}function z3Y(){if(xk())return!1;if(z5())return!1;if(!l3())return!1;return jp8()}function Y3Y(){return!1}function GWK(){let q=0;ZWK=async function(_,z){let Y=_3Y(),$=Y3Y();if(!$&&!z3Y())return;let A;try{A=await Am8()}catch(W){N(`[autoDream] readLastConsolidatedAt failed: ${W.message}`);return}let O=(Date.now()-A)/3600000;if(!$&&O<Y.minHours)return;let w=Date.now()-q;if(!$&&w<K3Y){N(`[autoDream] scan throttle — time-gate passed but last scan was ${Math.round(w/1000)}s ago`);return}q=Date.now();let j;try{j=await PjK(A)}catch(W){N(`[autoDream] listSessionsTouchedSince failed: ${W.message}`);return}let H=N8();if(j=j.filter((W)=>W!==H),!$&&j.length<Y.minSessions){N(`[autoDream] skip — ${j.length} sessions since last consolidation, need ${Y.minSessions}`);return}let J;if($)J=A;else{try{J=await XjK()}catch(W){N(`[autoDream] lock acquire failed: ${W.message}`);return}if(J===null)return}N(`[autoDream] firing — ${O.toFixed(1)}h since last, ${j.length} sessions to review`),d("tengu_auto_dream_fired",{hours_since:Math.round(O),sessions_since:j.length});let M=_.toolUseContext.setAppStateForTasks??_.toolUseContext.setAppState,X=new AbortController,P=DjK(M,{sessionsReviewing:j.length,priorMtime:J,abortController:X});try{let W=Vj(),D=_2(r1()),f=`
4173
4174**Tool constraints for this run:** Bash is restricted to read-only commands (\`ls\`, \`find\`, \`grep\`, \`cat\`, \`stat\`, \`wc\`, \`head\`, \`tail\`, and similar). Anything that writes, redirects to a file, or modifies state will be denied. Plan your exploration with this in mind — no need to probe.

Callers 1

GWKFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected