@holoscript/holoscript-agent 2.1.4 → 2.1.5

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runner.ts","../src/holomesh-client.ts","../src/cael-builder.ts","../src/tools.ts","../src/cognitive-verbs.ts"],"sourcesContent":["import type { ILLMProvider, LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport { embedAcrossFleet, cosineSimilarity } from '@holoscript/llm-provider';\nimport type { CostGuard } from './cost-guard.js';\nimport type { HolomeshClient } from './holomesh-client.js';\nimport { pickClaimableTask } from './holomesh-client.js';\nimport type { AuditLog } from './audit-log.js';\nimport { buildCaelRecord } from './cael-builder.js';\nimport { resolveActiveTools, runTool, summarizeToolProductivity } from './tools.js';\nimport { augmentWithOnTaskCognition } from './cognitive-verbs.js';\nimport { DelegatedAuthorityHandler } from './delegated-authority.js';\nimport type {\n AgentIdentity,\n BoardTask,\n ExecutionResult,\n RuntimeBrainConfig,\n TickResult,\n} from './types.js';\n\n// Bumped when the CAEL record schema or layer-hash semantics change. Lives\n// in the version_vector_fingerprint of every emitted record so consumers\n// can partition the corpus by runtime version.\nconst RUNTIME_VERSION = '1.0.0';\n\nexport interface AgentRunnerOptions {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n provider: ILLMProvider;\n costGuard: CostGuard;\n mesh: HolomeshClient;\n logger?: (event: Record<string, unknown>) => void;\n onTaskExecuted?: (result: ExecutionResult, task: BoardTask) => Promise<void>;\n auditLog?: AuditLog;\n /** Optional delegated-authority handler for governance message processing (E4). */\n messageHandler?: DelegatedAuthorityHandler;\n /**\n * Optional hardware-receipt signer (index.ts wires the seat wallet). When\n * present, emit_hardware_receipt seals its content hash with a wallet signature\n * so the hardware-provenance artifact is verifiable, not plain JSON. Absent →\n * the receipt is content-hashed but self-reports `signed:false` (honest).\n */\n signReceipt?: (canonical: string) => Promise<{ alg: string; signer: string; signature: string }>;\n}\n\nexport class AgentRunner {\n private stopped = false;\n // CAEL audit hash chain — survives across ticks within a single runner\n // process. On process restart it resets to null; the first post-restart\n // record breaks the chain, which is honest (the runner has no memory of\n // its prior chain state and shouldn't fake continuity). prev_hash=null\n // is a valid value the audit-store accepts.\n private prevCaelChain: string | null = null;\n // Self-recovery flag for the auto-rejoin path (task_1777112258989_eeyp).\n // When the heartbeat returns 403 \"Not a member of this team\" — typical of\n // a fresh Vast.ai worker whose provisioning didn't atomically /join, or of\n // a worker whose membership was reaped — the runner calls mesh.joinTeam()\n // ONCE per process and retries the heartbeat. After a successful rejoin\n // we set this flag so subsequent 403s on the same process don't loop back\n // into joinTeam (avoiding a retry storm if the team-cap is full or the\n // join itself is permanently rejected). On process restart the flag\n // resets, which is the correct semantics: a fresh process gets one fresh\n // chance to self-rejoin. Discovered 2026-04-25 SSH-probing 5 fleet\n // workers stuck in indefinite 403→tick-error→sleep→retry loops; without\n // this, a fresh-deploy of an unjoined agent stays silent forever.\n private joinedThisProcess = false;\n\n constructor(private readonly opts: AgentRunnerOptions) {}\n\n async tick(): Promise<TickResult> {\n const { identity, brain, mesh, costGuard, provider, logger } = this.opts;\n const log = logger ?? (() => undefined);\n\n await this.heartbeatWithAutoRejoin();\n\n // ── Delegated-authority message processing (E4) ──────────────────────────\n // Run before budget/task claiming so governance requests are handled\n // even when the agent is over-budget or has no claimable tasks.\n if (this.opts.messageHandler) {\n try {\n const receipts = await this.opts.messageHandler.processMessages();\n if (receipts.length > 0) {\n log({\n ev: 'messages-processed',\n count: receipts.length,\n statuses: receipts.map((r) => r.status),\n });\n // If this agent has no board-task capability tags (Brittney is\n // governance-only), return early so the tick result reflects message\n // work rather than falling through to no-claimable-task.\n if (\n brain.capabilityTags.length === 0 ||\n brain.capabilityTags.every((t) => t.startsWith('delegated'))\n ) {\n return {\n action: 'messages-processed',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n receipts: receipts.map((r) => ({\n status: r.status,\n action: r.action,\n reason: r.reason,\n })),\n };\n }\n }\n } catch (err) {\n log({\n ev: 'message-handler-error',\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (costGuard.isOverBudget()) {\n const state = costGuard.getState();\n log({ ev: 'over-budget', spentUsd: state.spentUsd, budget: identity.budgetUsdPerDay });\n return {\n action: 'over-budget',\n spentUsd: state.spentUsd,\n remainingUsd: 0,\n message: `daily budget $${identity.budgetUsdPerDay} exhausted`,\n };\n }\n\n const tasks = await mesh.getOpenTasks();\n const target = pickClaimableTask(tasks, brain.capabilityTags);\n if (!target) {\n log({ ev: 'no-claimable-task', open: tasks.length });\n return {\n action: 'no-claimable-task',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n };\n }\n\n log({ ev: 'claim', taskId: target.id, title: target.title });\n await mesh.claim(target.id);\n\n const start = Date.now();\n // Tool-use loop. The model gets MESH_TOOLS (read_file, list_dir,\n // write_file, bash) and can iterate read→reason→read→write until it\n // emits a final text response. Without this loop the model could only\n // reason from prompt+brain alone — no filesystem access, no kernel\n // checks, no inspection of inputs scp'd to the instance. With it,\n // lean-theorist can actually `cat MSC/Invariants.lean`, `lake build`,\n // and `write_file /root/agent-output/Invariants.lean` per its brain rules.\n // ── On-task cognition (Phase 2.2 — cognitive-verbs.ts) ───────────────────\n // Execute the brain's authored `behavior on_task` verbs (llm_call / rag_query\n // / recall / plan) and accumulate their outputs onto the system prompt before\n // the tool loop. Provider + mesh only (no engine/@holoscript/core dep) so the\n // edge package keeps its clean publish closure. `reflect` runs post-artifact.\n const systemContent = await augmentWithOnTaskCognition({\n systemPrompt: brain.systemPrompt,\n onTaskActions: brain.onTaskActions ?? [],\n task: { id: target.id, title: target.title },\n queryTeamKnowledge: (q, limit) => mesh.queryTeamKnowledge(q, limit),\n queryPrivateKnowledge: () => mesh.queryPrivateKnowledge(),\n // Phase 2.3 (W.753): codebase GraphRAG via the bearer-gated mesh route.\n // Best-effort: returns [] when the in-process graph isn't loaded → cognitive-verbs\n // falls back to team-knowledge search. No prod impact when graph is cold.\n queryCodebase: (q, topK) => mesh.queryCodebase(q, topK),\n plan: async (prompt) => {\n const resp = await provider.complete(\n { messages: [{ role: 'user', content: prompt }], maxTokens: 512, temperature: 0.3 },\n identity.llmModel\n );\n return resp.content;\n },\n // Semantic `recall` over the private workspace via the fleet nomic (W.753).\n // brainPath from HOLO_LLM_FLEET_BRAIN; if unset/unreachable embedAcrossFleet\n // returns null and cognitive-verbs falls back to the substring filter.\n embed: (text) => embedAcrossFleet(text, { brainPath: process.env.HOLO_LLM_FLEET_BRAIN }),\n similarity: cosineSimilarity,\n log,\n });\n\n const messages: LLMMessage[] = [\n { role: 'system', content: systemContent },\n { role: 'user', content: buildTaskPrompt(target) },\n ];\n let aggUsage: TokenUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\n let finalText = '';\n let iters = 0;\n // 30-iter cap: lean-theorist on Paper 22 needed 13 iters to read MSC files\n // + run lake build + iterate kernel checks. 12 was too tight (cap fired\n // before write_file deliverable). 30 allows ~3x that depth — anything\n // hitting 30 iters is almost certainly stuck and should bail.\n const MAX_TOOL_ITERS = 30;\n let lastResponse;\n // Track which tool names were called during this run so the artifact-grounding\n // gate below can refuse to mark \"executed\" on pure-text or read-only responses.\n // Discovered 2026-04-26 mesh-worker-02 audit: workers were posting CAEL records\n // with tool_iters:1 (zero tools called) declaring \"100 scenes validated\" with\n // no commit / no /room done — fabricated deliverables polluting trust. The\n // gate below short-circuits this class of hallucination at the runner edge.\n const toolsCalled = new Set<string>();\n // Tightened-gate counter (W.107.b 2026-04-26): track *productive* tool calls\n // separately from any tool call. A productive call is one of:\n // - write_file with non-empty content\n // - bash matching a productive prefix (lake build / pnpm --filter / vitest\n // run / lean / pnpm vitest — see tools.ts BASH_PRODUCTIVE_PREFIXES)\n // Read-only bash (cat/grep/ls/echo/git status/etc.) does NOT count even\n // though it's whitelisted for execution. This catches the trivial-bash-bypass\n // class (e.g. `bash echo done`) that the original W.107 gate accepted.\n let productiveCallCount = 0;\n // Last git commit SHA emitted during the tool-loop; forwarded to markDone\n // so the board task records a verifiable commit reference.\n let lastCommitHash: string | undefined;\n // F.126 #1 — the model's tools come from the BRAIN'S DECLARATION (the on_task\n // `llm_call { tools: [...] }` array), not a hardcoded list. resolveActiveTools\n // resolves the declared names against MESH_TOOLS, falls back safely when a brain\n // declares none, and SLIM-trims an oversized set for small local models (W.710\n // num_ctx guard). \"Add a tool\" is now \"declare it in the brain,\" not edit this file.\n const { tools: activeTools, declared: declaredTools, dropped: droppedTools } = resolveActiveTools(brain);\n log({\n ev: 'active-tools',\n taskId: target.id,\n tools: activeTools.map((t) => t.name),\n declared: declaredTools,\n ...(droppedTools.length ? { droppedUnknown: droppedTools } : {}),\n });\n while (true) {\n iters++;\n if (iters > MAX_TOOL_ITERS) {\n log({ ev: 'tool-loop-cap', taskId: target.id, iters });\n finalText = finalText || `[tool-loop hit ${MAX_TOOL_ITERS}-iter cap before final text]`;\n break;\n }\n const resp = await provider.complete(\n {\n messages,\n // 8192 for local thinking models (qwen3:4b uses ~3800 tokens on thinking\n // before the tool-call JSON; 4096 cuts off mid-generation). Frontier\n // models ignore this ceiling and stop naturally earlier.\n maxTokens: 8192,\n temperature: 0.4,\n tools: activeTools,\n },\n identity.llmModel\n );\n lastResponse = resp;\n aggUsage = {\n promptTokens: aggUsage.promptTokens + resp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + resp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + resp.usage.totalTokens,\n };\n // If model called tools, execute them and feed results back.\n if (resp.finishReason === 'tool_use' && resp.toolUses && resp.toolUses.length > 0) {\n log({\n ev: 'tool-call',\n taskId: target.id,\n iter: iters,\n tools: resp.toolUses.map((t) => t.name),\n });\n // Artifact-grounding accounting (W.107.b) via the shared classifier in\n // tools.ts — the SAME function the ablation harness measures, so the gate\n // and its evaluation can never drift (single source of truth).\n const productivity = summarizeToolProductivity(resp.toolUses);\n for (const n of productivity.names) toolsCalled.add(n);\n productiveCallCount += productivity.productiveCount;\n // Append the assistant turn (text + tool_use blocks) so the model\n // sees its own request when we send tool_result back.\n messages.push({\n role: 'assistant',\n content: (resp.assistantBlocks ?? []) as never,\n });\n // Run each tool and collect results.\n const toolResults = await Promise.all(\n resp.toolUses.map((u) =>\n runTool(u, {\n signReceipt: this.opts.signReceipt,\n addTask: (tasks) => mesh.addTasks(tasks),\n })\n )\n );\n // Extract the latest git commit SHA from bash stdout so markDone can\n // record a verifiable reference on the board task. Pattern matches both\n // `git commit -m` output ('[branch abc1234]') and `git rev-parse HEAD`.\n for (let ti = 0; ti < resp.toolUses.length; ti++) {\n const tu = resp.toolUses[ti];\n if (tu.name === 'bash') {\n const tr = toolResults[ti];\n if (tr && !tr.is_error) {\n const shaMatch = tr.content.match(/\\b([0-9a-f]{7,40})\\b/);\n if (shaMatch) lastCommitHash = shaMatch[1];\n }\n }\n }\n messages.push({\n role: 'user',\n content: toolResults as never,\n });\n continue;\n }\n // Final text response.\n finalText = resp.content;\n break;\n }\n // Re-prompt gate (W.780): if the model called only read-only tools and then\n // output text (the \"read→text instead of read→write_file\" anti-pattern with\n // small edge models like qwen3:4b-instruct), inject one forced re-prompt\n // asking it to call write_file before the no-artifact gate fires.\n // v2 fix: pop the last assistant text turn (so context ends at tool_result),\n // embed the task description, and use temperature=0 for maximal determinism.\n if (productiveCallCount === 0 && toolsCalled.size > 0 && iters < MAX_TOOL_ITERS) {\n iters++;\n // Remove the last assistant message if it was a plain-text response (the\n // anti-pattern turn). This ensures the context ends at the tool_result so\n // the model doesn't mistake our re-prompt for a follow-up question.\n if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {\n messages.pop();\n }\n messages.push({\n role: 'user',\n content:\n 'You read data but did NOT call write_file. This is a TASK FAILURE unless you act now.\\n' +\n `Task: ${target.title}\\n` +\n `Required output path (from task description): ${target.description.match(/path[:\\s]+([^\\s\\n,]+\\.json)/i)?.[1] ?? 'see task description'}\\n` +\n 'Call write_file NOW. Embed ALL data from the tool result above into the content. ' +\n 'Do NOT output any text — your ONLY valid response is a write_file tool call.',\n });\n const reResp = await provider.complete(\n { messages, maxTokens: 8192, temperature: 0.0, tools: activeTools },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + reResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + reResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + reResp.usage.totalTokens,\n };\n if (reResp.finishReason === 'tool_use' && reResp.toolUses && reResp.toolUses.length > 0) {\n log({ ev: 'reprompt-tool-call', taskId: target.id, iter: iters, tools: reResp.toolUses.map((t) => t.name) });\n const reProd = summarizeToolProductivity(reResp.toolUses);\n for (const n of reProd.names) toolsCalled.add(n);\n productiveCallCount += reProd.productiveCount;\n messages.push({ role: 'assistant', content: (reResp.assistantBlocks ?? []) as never });\n const reResults = await Promise.all(\n reResp.toolUses.map((u) =>\n runTool(u, { signReceipt: this.opts.signReceipt, addTask: (tasks) => mesh.addTasks(tasks) })\n )\n );\n messages.push({ role: 'user', content: reResults as never });\n }\n finalText = reResp.content;\n lastResponse = reResp;\n }\n // Vision-write gate: vision_analyze was called (inference ran) but no write_file\n // followed — the model has the caption in context but didn't store it. Inject one\n // more targeted re-prompt asking specifically for write_file with the caption.\n const WRITE_NAMES = new Set(['write_file', 'str_replace']);\n if (\n toolsCalled.has('vision_analyze') &&\n ![...toolsCalled].some((n) => WRITE_NAMES.has(n)) &&\n iters < MAX_TOOL_ITERS\n ) {\n iters++;\n if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {\n messages.pop();\n }\n messages.push({\n role: 'user',\n content:\n 'vision_analyze returned a caption but you did NOT call write_file.\\n' +\n `Task: ${target.title}\\n` +\n `Output path: ${target.description.match(/path[:\\s]+([^\\s\\n,]+\\.json)/i)?.[1] ?? 'see task description'}\\n` +\n 'Call write_file NOW. Put the caption from vision_analyze into the JSON content field. ' +\n 'Do NOT output text — your ONLY valid response is a write_file tool call.',\n });\n const vwResp = await provider.complete(\n { messages, maxTokens: 8192, temperature: 0.0, tools: activeTools },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + vwResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + vwResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + vwResp.usage.totalTokens,\n };\n if (vwResp.finishReason === 'tool_use' && vwResp.toolUses && vwResp.toolUses.length > 0) {\n log({ ev: 'vision-write-call', taskId: target.id, iter: iters, tools: vwResp.toolUses.map((t) => t.name) });\n const vwProd = summarizeToolProductivity(vwResp.toolUses);\n for (const n of vwProd.names) toolsCalled.add(n);\n productiveCallCount += vwProd.productiveCount;\n messages.push({ role: 'assistant', content: (vwResp.assistantBlocks ?? []) as never });\n const vwResults = await Promise.all(\n vwResp.toolUses.map((u) =>\n runTool(u, { signReceipt: this.opts.signReceipt, addTask: (tasks) => mesh.addTasks(tasks) })\n )\n );\n messages.push({ role: 'user', content: vwResults as never });\n }\n finalText = vwResp.content;\n lastResponse = vwResp;\n }\n const durationMs = Date.now() - start;\n\n // Artifact-grounding gate (W.107 — fleet event-firing rate is not a productivity\n // metric; only side-effecting tool calls produce real artifacts; 2026-04-26\n // tightened to W.107.b which also closes the trivial-bash bypass: `bash echo\n // done` and `write_file /tmp/x \"\"` no longer pass the gate). The gate now\n // requires AT LEAST ONE productive call:\n // - write_file with non-empty content, OR\n // - bash matching a productive prefix (lake build / pnpm --filter /\n // vitest run / lean / pnpm vitest)\n // Read-only inspection tools (read_file, list_dir) and read-only bash\n // (cat/grep/ls/echo/git status/git log/...) don't satisfy the gate.\n if (productiveCallCount === 0) {\n log({\n ev: 'no-artifact',\n taskId: target.id,\n tool_iters: iters,\n toolsCalled: [...toolsCalled],\n productiveCallCount,\n message:\n 'task execution did not produce a real artifact — refusing to mark executed. ' +\n 'Required: write_file with non-empty content OR bash with a productive prefix ' +\n '(lake build / pnpm --filter / vitest run / lean / pnpm vitest). ' +\n 'Pure-text, read-only inspection, and trivial-bash-bypass (`echo`, `cat`, etc.) do not satisfy the gate.',\n });\n // Best-effort: leave the task in claimed state so the supervisor can either\n // re-tick or release it via heartbeat-rejoin. We deliberately do NOT post\n // a \"fake-done\" message on the board, do NOT post a CAEL record, and do NOT\n // call the cost guard's recordUsage — the run produced no artifact and\n // should not bill the budget for a hallucinated tick.\n return {\n action: 'no-artifact',\n taskId: target.id,\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n message: `no productive tool call observed (toolsCalled=[${[...toolsCalled].join(',')}], productiveCallCount=${productiveCallCount}, iters=${iters})`,\n };\n }\n\n // ── Reflect: cognitive self-evaluation gate (W.736) ──────────────────────\n // If the brain declares a `reflect` verb, run ONE self-evaluation pass over\n // the produced artifact before accepting it — the brain's local_first\n // confidence gate. Uses the same provider (no engine/trait dependency) and\n // mirrors the CognitiveActions reflect prompt shape. The verdict is acted on\n // at the markDone gate below; its tokens fold into aggUsage so cost is honest.\n let reflectVerdict: { pass: boolean; reason: string } | undefined;\n if (brain.reflect) {\n try {\n const reflectResp = await provider.complete(\n {\n messages: [\n {\n role: 'system',\n content:\n 'You are a strict reviewer. Evaluate the work against the criteria; do not rewrite it.',\n },\n {\n role: 'user',\n content:\n `Reflect on the artifact produced for this task. Evaluate it for: ${brain.reflect.criteria}.\\n\\n` +\n `--- artifact / final response ---\\n${finalText.slice(0, 4000)}\\n--- end ---\\n\\n` +\n `Give a one-line reason, then end with exactly \"VERDICT: PASS\" or \"VERDICT: FAIL\".`,\n },\n ],\n maxTokens: 512,\n temperature: 0.1,\n },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + reflectResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + reflectResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + reflectResp.usage.totalTokens,\n };\n const verdictMatch = /VERDICT:\\s*(PASS|FAIL)/i.exec(reflectResp.content);\n // Unparseable verdict = PASS — reflect is a gate, not a tripwire; never\n // block a real artifact on a parser miss (small local models phrase loosely).\n const pass = verdictMatch ? verdictMatch[1].toUpperCase() === 'PASS' : true;\n reflectVerdict = {\n pass,\n reason: reflectResp.content.replace(/VERDICT:\\s*(PASS|FAIL)/i, '').trim().slice(0, 300),\n };\n log({\n ev: 'reflect',\n taskId: target.id,\n pass,\n escalateOnFail: brain.reflect.escalateOnFail,\n reason: reflectVerdict.reason.slice(0, 120),\n });\n } catch (err) {\n log({\n ev: 'reflect-error',\n taskId: target.id,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const cost = costGuard.recordUsage(identity.llmModel, aggUsage);\n log({\n ev: 'executed',\n taskId: target.id,\n costUsd: cost.costUsd.toFixed(4),\n spentUsd: cost.spentUsd.toFixed(4),\n tokens: aggUsage.totalTokens,\n tool_iters: iters,\n });\n const response = {\n ...(lastResponse ?? { content: finalText, usage: aggUsage }),\n content: finalText,\n usage: aggUsage,\n };\n\n const execResult: ExecutionResult = {\n taskId: target.id,\n responseText: response.content,\n usage: response.usage,\n costUsd: cost.costUsd,\n durationMs,\n };\n\n if (this.opts.auditLog) {\n try {\n this.opts.auditLog.recordTaskExecuted({\n identity,\n task: target,\n result: execResult,\n });\n } catch (err) {\n log({ ev: 'audit-log-error', message: err instanceof Error ? err.message : String(err) });\n }\n }\n\n // Phase 1 CAEL audit: post to the HoloMesh audit store so the fleet\n // corpus collector at ai-ecosystem/scripts/fleet-corpus-collector.mjs\n // can read records via GET /api/holomesh/agent/{handle}/audit. Without\n // this POST, the local AuditLog above is the only durable record and\n // Paper 25's gate clock cannot start. See ai-ecosystem task\n // task_1777106535952_atug for the empty-audit investigation.\n try {\n const caelRecord = buildCaelRecord({\n identity,\n brain,\n task: target,\n messages,\n finalText,\n usage: aggUsage,\n costUsd: cost.costUsd,\n spentUsd: cost.spentUsd,\n prevChain: this.prevCaelChain,\n runtimeVersion: RUNTIME_VERSION,\n });\n const posted = await mesh.postAuditRecords(identity.handle, [caelRecord]);\n this.prevCaelChain = caelRecord.fnv1a_chain;\n log({\n ev: 'cael-posted',\n taskId: target.id,\n appended: posted.appended,\n rejected: posted.rejected,\n });\n } catch (err) {\n log({ ev: 'cael-post-error', message: err instanceof Error ? err.message : String(err) });\n }\n\n // Reflect escalation gate: a brain with `reflect { escalate_on_fail: true }`\n // does NOT mark done on a failed self-evaluation — it escalates to the fleet\n // (the local_first directive). Cost + CAEL are already recorded above (the work\n // happened and the self-eval is a verifiable trace); only acceptance/markDone is\n // withheld. Brains without reflect, or with an advisory reflect, fall through.\n if (reflectVerdict && !reflectVerdict.pass && brain.reflect?.escalateOnFail) {\n try {\n await mesh.sendMessageOnTask(\n target.id,\n `[${identity.handle}] reflect gate FAILED — escalating to the fleet instead of marking done. Reason: ${reflectVerdict.reason}`\n );\n } catch {\n /* best-effort escalation notice; the return value is the source of truth */\n }\n log({ ev: 'reflect-escalate', taskId: target.id, reason: reflectVerdict.reason.slice(0, 120) });\n return {\n action: 'reflect-escalate',\n taskId: target.id,\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n message: `reflect self-evaluation failed; escalated to fleet (reason: ${reflectVerdict.reason.slice(0, 120)})`,\n };\n }\n\n if (this.opts.onTaskExecuted) {\n await this.opts.onTaskExecuted(execResult, target);\n } else {\n await mesh.sendMessageOnTask(\n target.id,\n `[${identity.handle}] response (${response.usage.totalTokens} tok, $${cost.costUsd.toFixed(4)}):\\n\\n${response.content}`\n );\n }\n\n // Mark the task done so it doesn't linger in 'claimed' forever.\n // Wrapped in try/catch: a markDone failure (e.g. task already closed by\n // a supervisor, or transient network error) must not prevent the tick\n // return value from reaching the caller.\n try {\n await mesh.markDone(target.id, finalText.slice(0, 500), lastCommitHash);\n log({ ev: 'mark-done', taskId: target.id, commitHash: lastCommitHash });\n } catch (err) {\n log({\n ev: 'mark-done-error',\n taskId: target.id,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n\n // Continuity write-loop: persist this task's outcome to the agent's PRIVATE\n // knowledge so a future `recall` verb has real memory to draw on. This closes\n // the W.752 loop-gap — the edge `recall` verb read /knowledge/private but it\n // was always empty because nothing ever wrote to it. Now markDone feeds it.\n // Best-effort (writePrivateKnowledge swallows its own errors); the task is\n // already done, so a write miss is logged and ignored.\n if (finalText.trim()) {\n const fact =\n `Task \"${target.title}\" (${target.id}) completed. ` +\n `Outcome: ${finalText.trim().slice(0, 600)}` +\n (lastCommitHash ? ` [commit ${lastCommitHash}]` : '');\n const wrote = await mesh.writePrivateKnowledge([\n { content: fact, type: 'task-outcome', tags: ['task-outcome', identity.handle] },\n ]);\n log({ ev: wrote ? 'knowledge-write' : 'knowledge-write-skip', taskId: target.id });\n }\n\n return {\n action: 'executed',\n taskId: target.id,\n spentUsd: cost.spentUsd,\n remainingUsd: cost.remainingUsd,\n };\n }\n\n async runForever(opts: { tickIntervalMs?: number } = {}): Promise<void> {\n const interval = opts.tickIntervalMs ?? 60_000;\n while (!this.stopped) {\n try {\n await this.tick();\n } catch (err) {\n const log = this.opts.logger ?? (() => undefined);\n log({ ev: 'tick-error', message: err instanceof Error ? err.message : String(err) });\n }\n await sleep(interval + jitter(interval));\n }\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n /**\n * Heartbeat with one-shot self-rejoin on 403 \"Not a member of this team\".\n *\n * Pairs with task_1777112258989_eeyp: fresh-deploy fleet workers whose\n * provisioning didn't atomically call /join (or whose membership was\n * reaped) hit 403 every tick and never recover. We detect the specific\n * server error string (see packages/mcp-server/src/holomesh/routes/\n * team-routes.ts:903 → `{ error: 'Not a member' }` for /presence), call\n * mesh.joinTeam() ONCE per runner process, and retry the heartbeat.\n *\n * Strict scope:\n * - Only retries on 403 + \"Not a member\" body. Any other 403 (insufficient\n * permissions, signing failure) re-throws unchanged.\n * - Only retries ONCE per process. If we already rejoined this process and\n * the heartbeat is *still* 403, the team is rejecting us for a reason\n * /join can't fix (e.g. capacity, ban) — surface the error.\n * - If joinTeam() itself throws, we DO mark joinedThisProcess=true before\n * re-throwing so we don't slam the join endpoint on every subsequent\n * tick. The next tick will surface the same heartbeat 403 and the\n * runner-level catch in runForever logs tick-error and sleeps. Operator\n * inspection (SSH/log) is the recovery path at that point.\n */\n private async heartbeatWithAutoRejoin(): Promise<void> {\n const { identity, brain, mesh, logger } = this.opts;\n const log = logger ?? (() => undefined);\n const capabilityTags = brain.capabilityTags.length > 0 ? brain.capabilityTags : undefined;\n try {\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface, capabilityTags });\n } catch (err) {\n if (!this.isNotAMemberError(err) || this.joinedThisProcess) {\n throw err;\n }\n log({ ev: 'auto-rejoin-attempt', reason: 'heartbeat-403-not-a-member' });\n // Mark BEFORE the join call so a thrown joinTeam() can't loop us.\n this.joinedThisProcess = true;\n try {\n const joinResult = await mesh.joinTeam();\n log({ ev: 'auto-rejoin-success', role: joinResult.role, members: joinResult.members });\n } catch (joinErr) {\n log({\n ev: 'auto-rejoin-failed',\n message: joinErr instanceof Error ? joinErr.message : String(joinErr),\n });\n throw joinErr;\n }\n // Retry the heartbeat exactly once. If it still fails (including with\n // another 403), the new error propagates — joinedThisProcess is now\n // true so we won't retry-loop on the next tick.\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface, capabilityTags });\n log({ ev: 'auto-rejoin-heartbeat-recovered' });\n }\n }\n\n /**\n * Detect the server's \"Not a member\" 403 error from HolomeshClient.req().\n * The error message format is: `HoloMesh POST /team/<id>/presence 403: <body>`\n * where body contains `{\"error\":\"Not a member\"}` (or \"Not a member of this team\").\n * Match conservatively: BOTH a \"403\" status marker AND the \"Not a member\"\n * substring must appear, so unrelated 403s (insufficient permissions,\n * signing failures) do NOT trigger a rejoin.\n */\n private isNotAMemberError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return / 403:/.test(msg) && /Not a member/i.test(msg);\n }\n}\n\nfunction buildTaskPrompt(task: BoardTask): string {\n return [\n `Board task to execute: ${task.id}`,\n `Title: ${task.title}`,\n `Priority: ${task.priority}`,\n `Tags: ${(task.tags ?? []).join(', ')}`,\n '',\n 'Description:',\n task.description ?? '(no description)',\n '',\n 'Produce the deliverable: call write_file (or bash with a build command) to create all required output files FIRST. Apply your brain composition rules — anti-patterns, decision loop, and scope tier all bind. After calling the tool(s), return a short plain-text summary of what you did for posting to /room.',\n ].join('\\n');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction jitter(base: number): number {\n return Math.floor((Math.random() - 0.5) * base * 0.2);\n}\n","import { readFile, appendFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { BoardTask } from './types.js';\nimport type { CaelAuditRecord } from './cael-builder.js';\n\n/** Wraps a request body in a signed envelope for strict-mode endpoints (e.g. /team/:id/join). */\nexport type RequestSigner = (\n body: Record<string, unknown>\n) => Promise<Record<string, unknown>>;\n\nexport interface HolomeshClientOptions {\n apiBase: string;\n bearer: string;\n teamId: string;\n fetchImpl?: typeof fetch;\n /** EIP-191 signing function. When present, used on strict endpoints like joinTeam(). */\n signer?: RequestSigner;\n /**\n * Local JSONL path for private knowledge (sovereign edge store).\n * When set, writePrivateKnowledge appends to this file and queryPrivateKnowledge\n * reads from it instead of routing through the remote orchestrator.\n * Bypasses the mcp-orchestrator /knowledge/sync 401 gap for edge nodes.\n * Set via HOLOSCRIPT_AGENT_LOCAL_KNOWLEDGE_PATH env var (index.ts).\n */\n localKnowledgePath?: string;\n}\n\nexport interface TeamMessage {\n id: string;\n fromAgentId: string;\n fromAgentName: string;\n content: string;\n messageType: string;\n createdAt: string;\n}\n\n/** Minimal knowledge-entry shape returned by the mesh knowledge endpoints. */\nexport interface KnowledgeEntry {\n id: string;\n content: string;\n domain?: string;\n type?: string;\n createdAt?: string;\n}\n\nexport class HolomeshClient {\n private readonly apiBase: string;\n private readonly bearer: string;\n private readonly teamId: string;\n private readonly fetchImpl: typeof fetch;\n private readonly signer?: RequestSigner;\n private readonly localKnowledgePath?: string;\n\n constructor(opts: HolomeshClientOptions) {\n this.apiBase = opts.apiBase.replace(/\\/$/, '');\n this.bearer = opts.bearer;\n this.teamId = opts.teamId;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.signer = opts.signer;\n this.localKnowledgePath = opts.localKnowledgePath;\n }\n\n /** Wrap body in a signed envelope when a signer is available (strict-mode endpoints). */\n private async signBody(body: Record<string, unknown>): Promise<Record<string, unknown>> {\n return this.signer ? await this.signer(body) : body;\n }\n\n async heartbeat(payload: { agentName: string; surface: string; capabilityTags?: string[] }): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/presence`, await this.signBody(payload as Record<string, unknown>));\n }\n\n async getOpenTasks(): Promise<BoardTask[]> {\n const data = await this.req<{ tasks?: BoardTask[]; open?: BoardTask[] }>(\n 'GET',\n `/team/${this.teamId}/board`\n );\n return data.tasks ?? data.open ?? [];\n }\n\n async claim(taskId: string): Promise<BoardTask> {\n return this.req<BoardTask>('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'claim' }));\n }\n\n async joinTeam(): Promise<{ success: boolean; role?: string; members?: number }> {\n return this.req<{ success: boolean; role?: string; members?: number }>(\n 'POST',\n `/team/${this.teamId}/join`,\n await this.signBody({})\n );\n }\n\n async sendMessageOnTask(taskId: string, body: string): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, await this.signBody({\n to: 'team',\n subject: `task:${taskId}`,\n content: body,\n }));\n }\n\n async markDone(taskId: string, summary: string, commitHash?: string): Promise<void> {\n await this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({\n action: 'done',\n summary,\n // verification_evidence required by server before task can be closed.\n verification_evidence: summary,\n // Exclude commitHash when undefined — JSON.stringify drops undefined but\n // canonicalizeSigning preserves it as the literal string \"undefined\",\n // causing a signature-mismatch vs what the server sees after JSON.parse.\n ...(commitHash !== undefined ? { commitHash } : {}),\n }));\n }\n\n // POST CAEL audit records for this agent. Server validator at\n // packages/mcp-server/src/holomesh/routes/core-routes.ts:472-533 requires\n // bearer == handle owner OR founder; the per-surface x402 bearer is the\n // handle owner so this resolves correctly. Records that fail shape\n // validation (layer_hashes != 7 elements, missing tick_iso/operation/\n // fnv1a_chain) are silently dropped server-side, not rejected as a batch.\n async postAuditRecords(\n handle: string,\n records: CaelAuditRecord[]\n ): Promise<{ appended: number; rejected: number }> {\n // Audit endpoint uses bearer-only auth — no signed envelope wrapper.\n return this.req<{ appended: number; rejected: number }>(\n 'POST',\n `/agent/${encodeURIComponent(handle)}/audit`,\n { records } as unknown as Record<string, unknown>\n );\n }\n\n async whoAmI(): Promise<{ agentId: string; surface: string; wallet?: string }> {\n // GET /api/holomesh/me returns { agentId, name, wallet, isFounder, teamId, teams, permissions }\n // (see packages/mcp-server/src/holomesh/routes/core-routes.ts §/me handler).\n // It does NOT return a `surface` field — derive it from the seat name on the\n // client side. Seat naming convention (set by the provisioning admin path):\n // claudecode-claude-x402 → claude-code\n // cursor-claude-x402 → claude-cursor\n // gemini-antigravity → gemini-antigravity\n // copilot-vscode → copilot-vscode\n // Founder → unknown (shared key, no surface attribution)\n const raw = await this.req<{\n agentId: string;\n name?: string;\n wallet?: string;\n }>('GET', '/me');\n return {\n agentId: raw.agentId,\n surface: deriveSurface(raw.name),\n wallet: raw.wallet,\n };\n }\n\n // ── Team Message Surface (E4 delegated-authority protocol) ───────────────────\n\n /** Read recent team messages. */\n async getTeamMessages(limit = 20): Promise<TeamMessage[]> {\n const data = await this.req<{ messages?: TeamMessage[]; success?: boolean }>(\n 'GET',\n `/team/${this.teamId}/messages?limit=${limit}`\n );\n return data.messages ?? [];\n }\n\n /** Post a message to the team feed. */\n async sendTeamMessage(content: string, messageType = 'text'): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, await this.signBody({ content, type: messageType }));\n }\n\n // ── Owner-op API wrappers (E4) ─────────────────────────────────────────────\n\n /** Switch team mode. Requires owner or founder role. */\n async setTeamMode(mode: string, reason?: string): Promise<{ mode: string; unchanged?: boolean }> {\n return this.req('POST', `/team/${this.teamId}/mode`, await this.signBody({ mode, reason } as Record<string, unknown>));\n }\n\n /** Update room preferences. Requires config:write permission. */\n async patchRoomPrefs(prefs: { communicationStyle?: string; objective?: string }): Promise<{\n communicationStyle: string;\n objective: string;\n }> {\n return this.req('PATCH', `/team/${this.teamId}/room`, await this.signBody(prefs as Record<string, unknown>));\n }\n\n /** Update a board task. */\n async updateTask(\n taskId: string,\n updates: {\n title?: string;\n description?: string;\n priority?: number;\n tags?: string[];\n }\n ): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'update', ...updates } as Record<string, unknown>));\n }\n\n /** Delete a board task. */\n async deleteTask(taskId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'delete' }));\n }\n\n /** Delegate a board task to another agent. */\n async delegateTask(taskId: string, toAgentId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'delegate', toAgentId }));\n }\n\n /** Add new tasks to the board (used by the delegate_task tool to spawn sub-work). */\n async addTasks(\n tasks: Array<{ title: string; description?: string; priority?: number; source?: string; role?: string; tags?: string[] }>\n ): Promise<{ added: number }> {\n const result = await this.req<{ added?: number }>('POST', `/team/${this.teamId}/board`, await this.signBody({ tasks } as Record<string, unknown>));\n return { added: result.added ?? tasks.length };\n }\n\n // ── Cognitive-verb knowledge surface (Phase 2.2 — recall / rag_query) ────────\n\n /**\n * Query the TEAM knowledge base (the `rag_query` cognitive verb). Bearer-only\n * GET; `q` is the server-side search filter. Returns [] on any failure so a\n * retrieval miss never breaks a tick.\n */\n async queryTeamKnowledge(query: string, limit = 5): Promise<KnowledgeEntry[]> {\n const qs = new URLSearchParams({ q: query, limit: String(limit) }).toString();\n try {\n const data = await this.req<{ entries?: KnowledgeEntry[] }>(\n 'GET',\n `/team/${this.teamId}/knowledge?${qs}`\n );\n return data.entries ?? [];\n } catch {\n return [];\n }\n }\n\n /**\n * Query this agent's PRIVATE workspace knowledge (the `recall` cognitive verb).\n * The endpoint has no server-side search param, so the caller filters by query\n * client-side. Returns [] on any failure.\n */\n async queryPrivateKnowledge(): Promise<KnowledgeEntry[]> {\n if (this.localKnowledgePath) {\n try {\n const raw = await readFile(this.localKnowledgePath, 'utf8');\n return raw.trim().split('\\n').filter(Boolean).map(l => JSON.parse(l) as KnowledgeEntry);\n } catch {\n return [];\n }\n }\n try {\n const data = await this.req<{ entries?: KnowledgeEntry[] }>('GET', `/knowledge/private`);\n return data.entries ?? [];\n } catch {\n return [];\n }\n }\n\n /**\n * Persist facts to this agent's PRIVATE workspace — the WRITE side of `recall`\n * (POST /knowledge/private). The server stamps id / workspaceId (`private:<wallet>`)\n * / author / timestamps; the caller supplies `content` (+ optional type/tags/title).\n * This is what gives `recall` something to recall: without it the private store\n * stays empty and every `recall` returns [] (the W.752 loop-gap). Best-effort —\n * returns false on any failure so a write miss never breaks a tick (the task is\n * already done by the time this runs).\n */\n /**\n * Query the server-side in-process codebase GraphRAG index via the mesh bearer-gated\n * route (POST /api/holomesh/codebase/search). Called by the `rag_query` cognitive verb\n * (Phase 2.3 W.753) so edge agents can reach HoloEmbed semantic search without a direct\n * Absorb-service dep. Returns [] (not an error) when the graph isn't loaded yet — the\n * caller falls back to team-knowledge search.\n *\n * @param query Natural-language search string.\n * @param topK Max results to return (1–20, server-capped).\n */\n async queryCodebase(query: string, topK = 8): Promise<Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>> {\n try {\n const data = await this.req<{\n success?: boolean;\n result?: {\n results?: Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>;\n error?: string;\n };\n error?: string;\n }>('POST', `/codebase/search`, { query, topK });\n if (data.error || data.result?.error) return [];\n return data.result?.results ?? [];\n } catch {\n return [];\n }\n }\n\n async writePrivateKnowledge(\n entries: Array<{ content: string; type?: string; tags?: string[]; title?: string }>\n ): Promise<boolean> {\n if (!entries.length) return false;\n if (this.localKnowledgePath) {\n try {\n await mkdir(dirname(this.localKnowledgePath), { recursive: true });\n const lines = entries.map(e => JSON.stringify({\n id: `local.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`,\n content: e.content,\n type: e.type ?? 'task-outcome',\n tags: e.tags ?? [],\n title: e.title,\n createdAt: new Date().toISOString(),\n })).join('\\n') + '\\n';\n await appendFile(this.localKnowledgePath, lines, 'utf8');\n return true;\n } catch {\n return false;\n }\n }\n try {\n await this.req('POST', `/knowledge/private`, { entries });\n return true;\n } catch {\n return false;\n }\n }\n\n private async req<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.apiBase}${path}`;\n // HoloMesh REST auth: server (packages/mcp-server/src/holomesh/auth-utils.ts\n // resolveRequestingAgent) accepts EITHER `Authorization: Bearer <token>`\n // (HTTP-standard, used here) OR `x-mcp-api-key: <token>` (orchestrator\n // convention). Both resolve through the same key-registry / agent-store /\n // env-fallback chain. Bearer is preferred for new code (W.087 vertex B,\n // task_1777073616424_klls).\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.bearer}`,\n 'content-type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const txt = await res.text().catch(() => '');\n throw new Error(`HoloMesh ${method} ${path} ${res.status}: ${txt.slice(0, 300)}`);\n }\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n\n/**\n * Derive a surface tag from a seat name returned by /me. Mirrors the surface\n * detection in scripts/probe-surface-bearers.mjs and hooks/lib/holomesh-env.mjs\n * so a single agent's surface attribution is consistent across read and write\n * paths. Returns 'unknown' when the seat name doesn't encode a surface\n * (e.g. shared-key resolution to \"Founder\").\n */\nexport function deriveSurface(seatName: string | undefined): string {\n if (!seatName) return 'unknown';\n const n = seatName.toLowerCase();\n if (n.startsWith('claudecode')) return 'claude-code';\n if (n.startsWith('cursor')) return 'claude-cursor';\n if (n.startsWith('claudedesktop')) return 'claude-desktop';\n if (n.startsWith('vscode-claude') || n.startsWith('claude-vscode')) return 'claude-vscode';\n if (n.startsWith('gemini')) return 'gemini-antigravity';\n if (n.startsWith('copilot')) return 'copilot-vscode';\n return 'unknown';\n}\n\nexport function pickClaimableTask(\n tasks: BoardTask[],\n brainCapabilityTags: string[]\n): BoardTask | undefined {\n const wanted = new Set(brainCapabilityTags.map((t) => t.toLowerCase()));\n const open = tasks.filter((t) => t.status === 'open' && !t.claimedBy);\n const scored = open\n .map((t) => ({ task: t, score: scoreTask(t, wanted) }))\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score || priority(a.task) - priority(b.task));\n return scored[0]?.task;\n}\n\nfunction scoreTask(task: BoardTask, wanted: Set<string>): number {\n const tags = (task.tags ?? []).map((t) => t.toLowerCase());\n const text = `${task.title} ${task.description ?? ''}`.toLowerCase();\n let score = 0;\n for (const tag of tags) if (wanted.has(tag)) score += 2;\n for (const w of wanted) if (text.includes(w)) score += 1;\n return score;\n}\n\nfunction priority(t: BoardTask): number {\n if (typeof t.priority === 'number') return t.priority;\n const map: Record<string, number> = { critical: 1, high: 2, medium: 4, low: 6 };\n return map[String(t.priority).toLowerCase()] ?? 5;\n}\n","// CAEL audit record builder for the headless agent runtime.\n//\n// Phase 1: agent ticks emit a CaelAuditRecord shaped to satisfy the\n// HoloMesh audit endpoint validator at packages/mcp-server/src/holomesh/\n// routes/core-routes.ts:512-518 (7-element layer_hashes array, string\n// tick_iso/operation/fnv1a_chain). The 7 layers map to concrete tick\n// stages so a downstream consumer can verify any one layer in isolation:\n//\n// L0 brain_state — sha256(brain.systemPrompt)\n// L1 tick_input — sha256(taskId|title|description)\n// L2 messages — sha256(JSON of final message thread)\n// L3 response — sha256(finalText)\n// L4 usage — sha256(JSON of aggregated TokenUsage)\n// L5 cost — sha256(costUsd|spentUsd)\n// L6 composite — sha256(L0|L1|L2|L3|L4|L5)\n//\n// fnv1a_chain extends across records: chain_n = sha256(chain_{n-1} | L6_n).\n// First tick emits prev_hash=null; subsequent ticks chain from the\n// previous record's fnv1a_chain.\n\nimport { createHash } from 'node:crypto';\nimport type { LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport type { AgentIdentity, BoardTask, ExecutionResult, RuntimeBrainConfig } from './types.js';\n\nexport interface CaelAuditRecord {\n tick_iso: string;\n layer_hashes: string[];\n operation: string;\n prev_hash: string | null;\n fnv1a_chain: string;\n version_vector_fingerprint: string;\n brain_class?: string;\n trial?: number;\n attack_class?: string;\n defense_state?: string;\n /**\n * Trust-epoch tag for downstream consumers (Paper 25 gate clock,\n * fleet-health drift detector, retroactive corpus filters). Set to\n * `'post-w107'` for any record built after the 2026-04-26 W.107\n * artifact-grounding gate landed (HoloScript commit 4aab897ad). Records\n * without this field — i.e. anything in the audit store before the gate\n * was deployed — are implicitly `'pre-w107-untrusted'`. The mesh-worker-02\n * 27.5h hallucination class (fabricated \"100 scenes validated\" CAEL\n * records with no actual artifact) all live in the implicit-untrusted\n * cohort. Consumers should filter by `trust_epoch === 'post-w107'`\n * before treating CAEL records as evidence of real work.\n */\n trust_epoch?: 'post-w107';\n}\n\nexport interface BuildCaelRecordInput {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n task: BoardTask;\n messages: LLMMessage[];\n finalText: string;\n usage: TokenUsage;\n costUsd: number;\n spentUsd: number;\n prevChain: string | null;\n runtimeVersion: string;\n}\n\nfunction sha(input: string): string {\n return createHash('sha256').update(input, 'utf8').digest('hex');\n}\n\n/**\n * Extract the brain class from a runtime brain config. Tries multiple sources\n * because brainPath shape varies across deployment environments:\n * 1. compositions/<class>-brain.hsplus (canonical layout — caught 2026-04-24)\n * 2. <anything>/<class>-brain.hsplus (loose match — Vast.ai box layout)\n * 3. <class>-brain.hsplus basename only\n * 4. brain.domain (loaded from .hsplus identity block by loadBrain())\n * 5. 'unknown' if all sources fail\n *\n * Live evidence (2026-04-25 mesh-worker-01 record): the strict regex returned\n * 'unknown' against the production worker box's brainPath, leaving every CAEL\n * fingerprint useless for fleet attribution. This loosened version recovers\n * brain class even when path layout drifts from the compositions/-rooted form.\n */\nfunction brainClassOf(brain: { brainPath?: string; domain?: string }): string {\n const p = String(brain.brainPath ?? '');\n // Tier 1: canonical compositions/-rooted layout.\n let m = p.match(/compositions[\\\\/]([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 2: any path with `<class>-brain.hsplus` basename.\n m = p.match(/([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 3: bare basename.\n m = p.match(/([\\w-]+)\\.hsplus$/);\n if (m) return m[1];\n // Tier 4: domain field from the loaded brain composition's identity block.\n const domain = String(brain.domain ?? '').trim();\n if (domain && domain !== 'unknown') return domain;\n return 'unknown';\n}\n\nexport function buildCaelRecord(input: BuildCaelRecordInput): CaelAuditRecord {\n const {\n identity,\n brain,\n task,\n messages,\n finalText,\n usage,\n costUsd,\n spentUsd,\n prevChain,\n runtimeVersion,\n } = input;\n\n const l0 = sha(brain.systemPrompt);\n const l1 = sha(`${task.id}|${task.title}|${task.description ?? ''}`);\n const l2 = sha(JSON.stringify(messages));\n const l3 = sha(finalText);\n const l4 = sha(JSON.stringify(usage));\n const l5 = sha(`${costUsd.toFixed(6)}|${spentUsd.toFixed(6)}`);\n const l6 = sha([l0, l1, l2, l3, l4, l5].join('|'));\n\n const fnv1a_chain = sha(`${prevChain ?? ''}|${l6}`);\n\n return {\n tick_iso: new Date().toISOString(),\n layer_hashes: [l0, l1, l2, l3, l4, l5, l6],\n operation: `task-executed:${task.id}`,\n prev_hash: prevChain,\n fnv1a_chain,\n version_vector_fingerprint: `agent@${runtimeVersion}|brain@${brainClassOf(brain)}|provider@${identity.llmProvider}|model@${identity.llmModel}`,\n brain_class: brainClassOf(brain),\n trust_epoch: 'post-w107',\n };\n}\n","/**\n * Tool runner for headless mesh agents.\n *\n * Provides a small, sandboxed set of tools that LLM agents can call during\n * task execution. Anthropic tool-use shape — these specs are passed to\n * `messages.stream({ tools: [...] })`, the model returns `tool_use` blocks,\n * the runner executes them via `runTool()` and feeds results back as\n * `tool_result` blocks until the model emits its final text response.\n *\n * Sandbox model:\n * - read_file / list_dir: restricted to ALLOWED_READ_ROOTS (task inputs +\n * read-only views of the cloned repo). No /etc, no /home, no /root/.ssh.\n * - write_file: restricted to ALLOWED_WRITE_ROOTS (just /root/agent-output/).\n * Creates dir if needed, refuses paths that escape via .. or symlinks.\n * - bash: ONLY whitelisted command prefixes (lake build, lean ..., ls, cat,\n * grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter,\n * vitest run --no-coverage). Hard 60s wall timeout, 1MB stdout cap. Refuses\n * anything else (rm, curl, ssh, sudo, eval, etc.).\n * - http_request: HTTPS GET only, 30s timeout, 200KB cap. Private IP ranges\n * (RFC-1918/loopback/link-local) are blocked to prevent SSRF against the\n * host network. Read-only — does not count as a productive tool call.\n *\n * The sandbox is best-effort host isolation — these instances are dedicated\n * to a single mesh-worker identity, so we trade some flexibility for a clear\n * \"what the LLM can do\" contract that audits cleanly.\n */\n\nimport { readFile, writeFile, readdir, mkdir, stat } from 'node:fs/promises';\nimport { resolve, dirname, delimiter, isAbsolute, sep } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport type { ToolSpec, ToolUseBlock, ToolResultBlock } from '@holoscript/llm-provider';\n\n// ---------------------------------------------------------------------------\n// Sandbox roots — keep narrow. Add only when a task needs more.\n//\n// Env-overridable so the SAME runner serves both deployments:\n// - Vast fleet instance: the /root/* defaults below (clone + scp layout).\n// - Local node (laptop / Jetson): point at the local checkout + a local\n// output dir via HOLOSCRIPT_AGENT_READ_ROOTS / _WRITE_ROOTS.\n// Format: OS-path-separator-delimited list (':' on POSIX, ';' on Windows) —\n// e.g. HOLOSCRIPT_AGENT_READ_ROOTS=\"/home/user/HoloScript:/home/user/agent-output\".\n// Unset → fleet defaults (no behavior change on the existing workers).\n// ---------------------------------------------------------------------------\nconst FLEET_READ_ROOTS = [\n '/root/msc-paper-22', // Paper 22 mechanization inputs (scp'd by deploy)\n '/root/holoscript-mesh', // Read-only repo view (clone path on instance)\n '/root/agent-output', // Read back what we wrote\n];\n\nconst FLEET_WRITE_ROOTS = [\n '/root/agent-output', // Single write sink — keeps deliverables in one place\n];\n\nfunction parseRootsEnv(raw: string | undefined, fallback: string[]): string[] {\n if (!raw) return fallback;\n const roots = raw\n .split(delimiter)\n .map((r) => r.trim())\n .filter((r) => r.length > 0 && isAbsolute(r));\n return roots.length > 0 ? roots : fallback;\n}\n\nconst ALLOWED_READ_ROOTS = parseRootsEnv(\n process.env.HOLOSCRIPT_AGENT_READ_ROOTS,\n FLEET_READ_ROOTS,\n);\n\nconst ALLOWED_WRITE_ROOTS = parseRootsEnv(\n process.env.HOLOSCRIPT_AGENT_WRITE_ROOTS,\n FLEET_WRITE_ROOTS,\n);\n\n// Command-prefix whitelist. Prefix-match is intentional — `lake build MSC`\n// matches `lake build`, `pnpm --filter @holoscript/core build` matches\n// `pnpm --filter`, etc. Refuses anything else (no sudo, rm, curl, ssh, eval).\n//\n// Two-tier classification (W.107 tightening 2026-04-26):\n// READ_ONLY — observation-only commands. Pass execution policy, but do\n// NOT count as artifact-producing for the W.107 gate.\n// PRODUCTIVE — commands that build, test, or otherwise produce a real\n// artifact (compile output, test result, etc.). DO count as\n// artifact-producing for the W.107 gate.\n//\n// Pre-tightening, the gate accepted ANY bash call as side-effecting — so\n// `bash echo done` would falsely pass the gate. Now `echo` is read-only and\n// the worker must call something productive (lake build / pnpm --filter\n// build / vitest run / lean compile / etc.) to claim `executed`.\nconst BASH_READ_ONLY_PREFIXES = [\n 'ls ',\n 'ls\\n',\n 'ls$',\n 'cat ',\n 'grep ',\n 'rg ',\n 'find ',\n 'wc ',\n 'head ',\n 'tail ',\n 'git status',\n 'git log',\n 'git diff',\n 'git show',\n 'pwd',\n 'echo ',\n 'lake env',\n];\n\nconst BASH_PRODUCTIVE_PREFIXES = [\n 'lake build',\n 'lake clean',\n 'lean ',\n 'pnpm --filter',\n 'pnpm vitest',\n 'vitest run',\n // Robotics / edge-node (Jetson) productive commands — without these, every\n // ros2/colcon/tegrastats task fails the W.107 artifact gate and is abandoned\n // as no-artifact. (jetson-orin-01 lane.)\n 'ros2 launch',\n 'ros2 topic pub',\n 'ros2 service call',\n 'colcon build',\n 'tegrastats',\n];\n\nconst BASH_WHITELIST = [...BASH_READ_ONLY_PREFIXES, ...BASH_PRODUCTIVE_PREFIXES];\n\n/**\n * Returns true iff `cmd` matches a productive prefix — i.e. would produce a\n * real artifact (compile/test/build output) rather than just observing state.\n * Used by the W.107 artifact-grounding gate in runner.ts.\n */\nexport function isProductiveBashCommand(cmd: string): boolean {\n const trimmed = String(cmd ?? '').trim();\n if (!trimmed) return false;\n return BASH_PRODUCTIVE_PREFIXES.some((prefix) => trimmed.startsWith(prefix.trim()));\n}\n\n/**\n * True iff a single tool_use is a *productive* (artifact-producing) call for the\n * W.107.b artifact-grounding gate:\n * - write_file with non-empty content,\n * - bash with a productive prefix (isProductiveBashCommand),\n * - emit_hardware_receipt (always writes a receipt file).\n * read_file / list_dir and read-only / trivial bash are NOT productive.\n *\n * This is the SINGLE SOURCE OF TRUTH the runner's gate (runner.ts) and the\n * artifact-gate ablation harness both consume — so the measured gate can never\n * drift from the shipped gate (the ablation measures the real thing, not a copy).\n */\nexport function isProductiveToolUse(use: ToolUseBlock): boolean {\n const input = (use.input ?? {}) as Record<string, unknown>;\n switch (use.name) {\n case 'write_file':\n return String(input.content ?? '').length > 0;\n case 'bash':\n return isProductiveBashCommand(String(input.cmd ?? ''));\n case 'emit_hardware_receipt':\n return true;\n case 'str_replace':\n return true;\n case 'vision_analyze':\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Accumulate the productive-call count + the tool names seen across one model\n * turn's tool_use blocks. The runner adds `names` to its toolsCalled set and\n * `productiveCount` to its gate counter.\n */\nexport function summarizeToolProductivity(uses: readonly ToolUseBlock[]): {\n productiveCount: number;\n names: string[];\n} {\n let productiveCount = 0;\n const names: string[] = [];\n for (const u of uses) {\n names.push(u.name);\n if (isProductiveToolUse(u)) productiveCount++;\n }\n return { productiveCount, names };\n}\n\n// ---------------------------------------------------------------------------\n// Tool specs surfaced to the LLM\n// ---------------------------------------------------------------------------\nexport const MESH_TOOLS: ToolSpec[] = [\n {\n name: 'read_file',\n description:\n `Read a file from the agent sandbox. Allowed roots: ${ALLOWED_READ_ROOTS.join(', ')}. ` +\n 'Returns the file content as text. Use this to inspect task inputs and the ' +\n 'read-only repo view.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'list_dir',\n description:\n 'List entries in a directory under the agent sandbox. Same root restrictions ' +\n 'as read_file. Returns a newline-separated list of entries.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'write_file',\n description:\n `Write a file to the deliverable sink (write roots: ${ALLOWED_WRITE_ROOTS.join(', ')}). ` +\n 'Anything you want to emit as task output (a Lean proof, a markdown report, a JSON ' +\n 'dataset, a .holo scene) goes here. Creates parent directories. Will refuse paths ' +\n 'outside the write root(s).',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: `Absolute path under a write root: ${ALLOWED_WRITE_ROOTS.join(', ')}` },\n content: { type: 'string', description: 'File content to write (UTF-8)' },\n },\n required: ['path', 'content'],\n },\n },\n {\n name: 'bash',\n description:\n 'Run a shell command. Whitelisted prefixes only: lake build, lean, ls, cat, ' +\n 'grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter, vitest run, ' +\n 'pwd, echo, ros2 launch/topic/service, colcon build, tegrastats. ' +\n 'Hard 60s wall timeout, 1MB stdout cap. Use for builds, tests, hardware probes. ' +\n 'Refuses rm, curl, ssh, sudo, eval.',\n input_schema: {\n type: 'object',\n properties: {\n cmd: { type: 'string', description: 'Whitelisted shell command' },\n cwd: { type: 'string', description: 'Optional working directory (defaults to /root)' },\n },\n required: ['cmd'],\n },\n },\n {\n name: 'http_request',\n description:\n 'HTTPS GET a public URL and return the response body as text. ' +\n 'HTTPS only — http:// and private IPs (RFC-1918, loopback, link-local) are blocked. ' +\n '200KB cap, 30s timeout. Read-only: does not satisfy the write_file artifact gate.',\n input_schema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'https:// URL to fetch' },\n headers: {\n type: 'object',\n description: 'Optional request headers (e.g. {\"Accept\": \"application/json\"})',\n },\n },\n required: ['url'],\n },\n },\n {\n name: 'emit_hardware_receipt',\n description:\n 'Emit a portable hardware receipt (PortableHardwareReceiptMetadata v1) capturing ' +\n 'device identity, runtime, and measured performance. Writes a JSON receipt to the ' +\n 'agent output dir. Use after running tegrastats or colcon build to record hardware ' +\n 'evidence for the CAEL audit chain. Accepts either pre-parsed measurements or raw ' +\n 'tegrastats output (the tool parses it automatically).',\n input_schema: {\n type: 'object',\n properties: {\n device_kind: {\n type: 'string',\n description: 'Device identifier, e.g. \"jetson-orin-nano-super\", \"raspberry-pi-5\"',\n },\n accelerator: {\n description: 'Accelerator string, e.g. \"NVIDIA CUDA 8.7\", or null for CPU-only',\n },\n runtime_name: { type: 'string', description: 'Inference runtime, e.g. \"Ollama\", \"llama.cpp\"' },\n runtime_version: { type: 'string', description: 'Runtime version, e.g. \"0.30.8\"' },\n host_os: { type: 'string', description: 'OS + firmware, e.g. \"JetPack 6.2.1 / Ubuntu 22.04\"' },\n composition_id: { type: 'string', description: 'Brain composition reference, e.g. \"jetson-orin-brain\"' },\n measurements: {\n type: 'array',\n description: 'Pre-parsed measurements. Each item: {metric: string, value: number, unit: string}',\n items: { type: 'object' },\n },\n tegrastats_output: {\n type: 'string',\n description: 'Raw tegrastats output line(s) — tool auto-parses GPU%, RAM, temp, power',\n },\n },\n required: ['device_kind', 'runtime_name', 'runtime_version', 'host_os'],\n },\n },\n {\n name: 'str_replace',\n description:\n 'Surgical in-place edit of a file: find an exact string and replace it. ' +\n 'The old string must appear exactly once in the file — if it appears zero or more than once ' +\n 'the tool returns an error with the actual count, letting you refine the search string. ' +\n 'Only files under the write root(s) can be edited. ' +\n 'Counts as a productive tool call (equivalent to write_file).',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: `Absolute path under a write root: ${ALLOWED_WRITE_ROOTS.join(', ')}` },\n old: { type: 'string', description: 'Exact string to find (must occur exactly once)' },\n new: { type: 'string', description: 'Replacement string' },\n },\n required: ['path', 'old', 'new'],\n },\n },\n {\n name: 'delegate_task',\n description:\n 'Post a new task to the team board so another agent can claim and execute it. ' +\n 'Use this to spawn sub-work the current agent cannot or should not do itself ' +\n '(e.g. a vision task for jetson-orin-fara, a cloud compute task for the fleet). ' +\n 'The task appears on the shared board and is claimed by the first agent with matching capability tags.',\n input_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Task title (max 200 chars)' },\n description: { type: 'string', description: 'Detailed task description (max 2000 chars)' },\n priority: { type: 'number', description: 'Priority 1-10 (1 = critical, default 5)' },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Capability tags for routing to the right agent, e.g. [\"vision\",\"edge\"]',\n },\n source: { type: 'string', description: 'Where this subtask came from (e.g. parent task id)' },\n },\n required: ['title'],\n },\n },\n {\n name: 'vision_analyze',\n description:\n 'Analyze an image using the local Fara-7B vision model (Ollama on loopback). ' +\n 'Reads the image file at `image_path`, sends it to fara:7b via the local Ollama API, ' +\n 'and returns the model\\'s text analysis. ' +\n 'Counts as a productive tool call — use for GUI-grounding, visual QA, image captioning, ' +\n 'or any task that requires perceiving image content. ' +\n 'Only available on surfaces with a local Ollama instance running fara:7b.',\n input_schema: {\n type: 'object',\n properties: {\n image_path: {\n type: 'string',\n description: 'Absolute path to the image file (png, jpg, webp, gif)',\n },\n prompt: {\n type: 'string',\n description: 'Instruction for the vision model (default: \"Describe this image in detail.\")',\n },\n model: {\n type: 'string',\n description: 'Ollama model tag to use (default: \"fara:7b\")',\n },\n },\n required: ['image_path'],\n },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Active-tool resolution (F.126 #1 — author behavior as DATA the runtime consumes)\n// ---------------------------------------------------------------------------\n/**\n * Assemble the tool set the model sees from the brain's OWN DECLARATION — the\n * `behavior on_task { llm_call { tools: [...] } }` array — instead of a hardcoded\n * list. This is principle #1 of the native doctrine (F.126): the runtime consumes\n * the brain's authored capability set, so \"add a tool\" becomes \"declare it in the\n * brain,\" not \"edit this TypeScript.\" Fixes the dead-data bug where every brain's\n * declared tools were ignored and local-llm brains were amputated to write_file-only.\n *\n * - Declared names are resolved against the available specs; an unknown name is\n * dropped (the runner logs it) so a typo can't crash the loop.\n * - A brain that declares NO tools falls back to the prior safe default\n * (write_file-only for small local-llm models — the artifact-grounding floor;\n * full menu otherwise) so this is backward-compatible.\n * - W.710 progressive disclosure: a small local model can overflow its num_ctx\n * output budget reasoning over a big menu before it emits a tool call, so a\n * declared set larger than the budget is SLIM-trimmed (write_file kept first)\n * for local-llm brains. Budget via HOLOSCRIPT_AGENT_TOOL_BUDGET (default 6).\n */\nexport function resolveActiveTools(\n brain: { requires: string[]; onTaskActions?: Array<{ verb: string; config?: Record<string, unknown> }> },\n opts: { all?: ToolSpec[]; isLocal?: boolean; budget?: number } = {}\n): { tools: ToolSpec[]; declared: string[]; dropped: string[] } {\n const all = opts.all ?? MESH_TOOLS;\n const isLocal = opts.isLocal ?? brain.requires.includes('local-llm');\n const budget = opts.budget ?? (Number(process.env.HOLOSCRIPT_AGENT_TOOL_BUDGET) || 6);\n\n const declaredRaw = brain.onTaskActions?.find((a) => a.verb === 'llm_call')?.config?.tools;\n const declared = Array.isArray(declaredRaw)\n ? declaredRaw.filter((n): n is string => typeof n === 'string')\n : [];\n\n if (declared.length === 0) {\n // No declaration → prior safe default (backward-compatible).\n const fallback = isLocal ? all.filter((t) => t.name === 'write_file') : all;\n return { tools: fallback, declared: [], dropped: [] };\n }\n\n const dropped = declared.filter((n) => !all.some((t) => t.name === n));\n let resolved = declared\n .map((n) => all.find((t) => t.name === n))\n .filter((t): t is ToolSpec => Boolean(t));\n if (resolved.length === 0) resolved = all.filter((t) => t.name === 'write_file'); // never hand the model an empty toolset\n\n // num_ctx guard for small models: trim a large declared set, keeping write_file (grounding) first.\n if (isLocal && resolved.length > budget) {\n const wf = resolved.filter((t) => t.name === 'write_file');\n const rest = resolved.filter((t) => t.name !== 'write_file');\n resolved = [...wf, ...rest].slice(0, budget);\n }\n return { tools: resolved, declared, dropped };\n}\n\n// ---------------------------------------------------------------------------\n// SSRF guard — block private/loopback/link-local hosts (RFC-1918 + RFC-5735)\n// ---------------------------------------------------------------------------\nconst PRIVATE_IP_RE =\n /^(127\\.|10\\.|192\\.168\\.|172\\.(1[6-9]|2\\d|3[01])\\.|169\\.254\\.|0\\.|::1$|fc[0-9a-f]{2}:|fd[0-9a-f]{2}:)/i;\n\nfunction checkHttpAllowed(rawUrl: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n return `invalid URL: \"${rawUrl}\"`;\n }\n if (parsed.protocol !== 'https:') {\n return `only https:// is allowed, got \"${parsed.protocol}\"`;\n }\n const host = parsed.hostname.toLowerCase();\n if (host === 'localhost' || PRIVATE_IP_RE.test(host)) {\n return `host \"${host}\" is a private/loopback address — blocked to prevent SSRF`;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Path-sandbox helpers\n// ---------------------------------------------------------------------------\nfunction isUnderRoot(absPath: string, root: string): boolean {\n const resolved = resolve(absPath);\n const rootResolved = resolve(root);\n return resolved === rootResolved || resolved.startsWith(rootResolved + sep);\n}\n\nfunction checkReadAllowed(path: string): string | null {\n if (!isAbsolute(path)) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_READ_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `read denied — path \"${path}\" not under allowed roots: ${ALLOWED_READ_ROOTS.join(', ')}`;\n}\n\nfunction checkWriteAllowed(path: string): string | null {\n if (!isAbsolute(path)) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_WRITE_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `write denied — path \"${path}\" not under allowed roots: ${ALLOWED_WRITE_ROOTS.join(', ')}`;\n}\n\nfunction checkBashAllowed(cmd: string): string | null {\n const trimmed = cmd.trim();\n if (trimmed.length === 0) return 'empty command';\n // Reject obvious shell-injection attempts. Whitelist below still applies.\n if (/[;&|`$<>]|>>|\\|\\||&&/.test(trimmed)) {\n return `command contains shell metachars (; & | \\` $ < > >> || &&) — not allowed for safety`;\n }\n for (const prefix of BASH_WHITELIST) {\n if (trimmed.startsWith(prefix.trim())) return null;\n }\n return `command not on whitelist. Allowed prefixes: ${BASH_WHITELIST.join(' / ')}`;\n}\n\n// ---------------------------------------------------------------------------\n// Tool implementations\n// ---------------------------------------------------------------------------\n/** Optional capabilities the caller (runner) can inject into a tool run. */\nexport interface RunToolOptions {\n /**\n * Sign a hardware receipt's canonical body. Injected by index.ts from the seat\n * wallet (ethers EIP-191). Absent → the receipt is content-hashed but unsigned\n * and self-reports `signed:false`, so it can never overclaim.\n */\n signReceipt?: (canonical: string) => Promise<{ alg: string; signer: string; signature: string }>;\n /**\n * Post new tasks to the team board. Injected by runner.ts from mesh.addTasks().\n * Absent → delegate_task returns an error explaining the capability is unavailable.\n */\n addTask?: (tasks: Array<{ title: string; description?: string; priority?: number; source?: string; tags?: string[] }>) => Promise<{ added: number }>;\n}\n\nexport async function runTool(use: ToolUseBlock, opts: RunToolOptions = {}): Promise<ToolResultBlock> {\n try {\n if (use.name === 'read_file') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const text = await readFile(path, 'utf8');\n // Cap at 200KB to avoid context blowups\n const truncated =\n text.length > 200_000\n ? text.slice(0, 200_000) + `\\n…[truncated, full file is ${text.length} bytes]`\n : text;\n return okResult(use.id, truncated);\n }\n\n if (use.name === 'list_dir') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const entries = await readdir(path, { withFileTypes: true });\n const lines = entries.map((e) => `${e.isDirectory() ? 'd' : '-'} ${e.name}`);\n return okResult(use.id, lines.join('\\n'));\n }\n\n if (use.name === 'write_file') {\n const path = use.input.path as string;\n const content = use.input.content as string;\n const denied = checkWriteAllowed(path);\n if (denied) return errResult(use.id, denied);\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n const s = await stat(path);\n return okResult(use.id, `wrote ${s.size} bytes to ${path}`);\n }\n\n if (use.name === 'bash') {\n const cmd = use.input.cmd as string;\n const cwd = (use.input.cwd as string | undefined) ?? '/root';\n const denied = checkBashAllowed(cmd);\n if (denied) return errResult(use.id, denied);\n const result = await runBash(cmd, cwd);\n return result.code === 0\n ? okResult(use.id, result.stdout)\n : errResult(use.id, `exit=${result.code}\\n${result.stderr || result.stdout}`);\n }\n\n if (use.name === 'http_request') {\n const rawUrl = String(use.input.url ?? '');\n const denied = checkHttpAllowed(rawUrl);\n if (denied) return errResult(use.id, denied);\n const userHeaders = (use.input.headers ?? {}) as Record<string, string>;\n const RESPONSE_CAP = 200_000;\n const TIMEOUT_MS = 30_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);\n try {\n const res = await fetch(rawUrl, {\n method: 'GET',\n headers: { 'user-agent': 'holoscript-agent/1.0', ...userHeaders },\n signal: controller.signal,\n });\n clearTimeout(timer);\n const buf = await res.arrayBuffer();\n const text = new TextDecoder('utf-8', { fatal: false }).decode(buf);\n const truncated =\n text.length > RESPONSE_CAP\n ? text.slice(0, RESPONSE_CAP) + `\\n…[truncated, full body is ${text.length} chars]`\n : text;\n if (!res.ok) return errResult(use.id, `HTTP ${res.status} ${res.statusText}\\n${truncated}`);\n return okResult(use.id, truncated);\n } catch (err) {\n clearTimeout(timer);\n const msg = err instanceof Error ? err.message : String(err);\n return errResult(use.id, msg.includes('abort') ? `request timed out after ${TIMEOUT_MS}ms` : msg);\n }\n }\n\n if (use.name === 'emit_hardware_receipt') {\n const deviceKind = String(use.input.device_kind ?? 'unknown-device');\n const accelerator =\n use.input.accelerator === null || use.input.accelerator === 'null'\n ? null\n : String(use.input.accelerator ?? '').trim() || null;\n const runtimeName = String(use.input.runtime_name ?? 'Ollama');\n const runtimeVersion = String(use.input.runtime_version ?? 'unknown');\n const hostOs = String(use.input.host_os ?? 'unknown');\n const compositionId = String(use.input.composition_id ?? 'unknown');\n\n // Collect measurements — from pre-parsed array and/or raw tegrastats output.\n let measurements: Array<{ metric: string; value: number; unit: string; method: string }> = [];\n if (Array.isArray(use.input.measurements)) {\n for (const m of use.input.measurements as Array<Record<string, unknown>>) {\n const metric = String(m.metric ?? '');\n const value = Number(m.value ?? 0);\n const unit = String(m.unit ?? '');\n if (metric && Number.isFinite(value)) {\n measurements.push({ metric, value, unit, method: 'measured' });\n }\n }\n }\n if (typeof use.input.tegrastats_output === 'string' && use.input.tegrastats_output.length > 0) {\n measurements = [...measurements, ...parseTegrastats(use.input.tegrastats_output as string)];\n }\n // Minimum 1 measurement so the schema validator doesn't reject the receipt.\n if (measurements.length === 0) {\n measurements.push({ metric: 'agent-tick', value: 1, unit: 'count', method: 'presence' });\n }\n\n const capturedAt = new Date().toISOString();\n const receipt = {\n schemaVersion: 'holoscript.hardware-receipt-metadata.v1',\n target: {\n id: `${deviceKind}-${Date.now()}`,\n kind: deviceKind,\n architecture: /jetson|orin|nano|agx|xavier/i.test(deviceKind) ? 'arm64' : 'unknown',\n artifactKind: 'measurement-trace',\n },\n device: {\n vendor: /jetson|orin|nvidia/i.test(deviceKind) ? 'nvidia' : 'unknown',\n model: deviceKind,\n accelerator,\n },\n runtime: { name: runtimeName, version: runtimeVersion, hostOS: hostOs },\n compilerVersion: 'holoscript-agent-1.0.0',\n constraints: [],\n measuredResults: measurements,\n replayInputs: [\n { kind: 'composition-ref', uri: `compositions/${compositionId}`, sha256: 'unknown' },\n ],\n provenance: {\n capturedAt,\n sourceCompositionHash: compositionId,\n },\n owner: {\n agent: process.env.HOLOSCRIPT_AGENT_HANDLE ?? 'unknown',\n ...(process.env.HOLOMESH_TEAM_ID ? { team: process.env.HOLOMESH_TEAM_ID } : {}),\n },\n };\n\n // Integrity seal (F.123 — a tamper-evident, not plain-JSON, receipt):\n // a deterministic SHA-256 content hash over the canonical body (keyless\n // content-addressing) plus an OPTIONAL wallet signature when a signer is\n // injected (index.ts wires the seat wallet). `signed` self-reports honestly\n // so an unsigned receipt can never masquerade as signed.\n const canonical = JSON.stringify(receipt);\n const contentHash = createHash('sha256').update(canonical).digest('hex');\n let signature: { alg: string; signer: string; signature: string } | null = null;\n if (opts.signReceipt) {\n try {\n signature = await opts.signReceipt(canonical);\n } catch {\n signature = null; // best-effort: an unsigned receipt is honest, not fatal\n }\n }\n const sealed = {\n ...receipt,\n integrity: { alg: 'sha256', contentHash, signed: Boolean(signature), signature },\n };\n\n // Slug timestamp: \"2026-06-16T07-35-01-000Z\"\n const ts = capturedAt.replace(/[:.]/g, '-');\n const outPath = resolve(ALLOWED_WRITE_ROOTS[0], `hardware-receipt-${ts}.json`);\n const denied = checkWriteAllowed(outPath);\n if (denied) return errResult(use.id, `Cannot write receipt: ${denied}`);\n await mkdir(dirname(outPath), { recursive: true });\n await writeFile(outPath, JSON.stringify(sealed, null, 2), 'utf8');\n return okResult(\n use.id,\n `Hardware receipt written to ${outPath} — ${measurements.length} measurements, ` +\n `contentHash=${contentHash.slice(0, 12)}…, signed=${Boolean(signature)}, accelerator=${accelerator ?? 'none'}`\n );\n }\n\n if (use.name === 'str_replace') {\n const path = use.input.path as string;\n const oldStr = use.input.old as string;\n const newStr = use.input.new as string;\n const denied = checkWriteAllowed(path);\n if (denied) return errResult(use.id, denied);\n const text = await readFile(path, 'utf8');\n // Count occurrences to guarantee exactly-one semantics.\n const count = text.split(oldStr).length - 1;\n if (count === 0) return errResult(use.id, `str_replace: \"old\" string not found in ${path} — 0 occurrences`);\n if (count > 1) return errResult(use.id, `str_replace: \"old\" string is ambiguous in ${path} — ${count} occurrences; add more surrounding context`);\n const updated = text.replace(oldStr, newStr);\n await writeFile(path, updated, 'utf8');\n const s = await stat(path);\n return okResult(use.id, `str_replace: replaced 1 occurrence in ${path} (${s.size} bytes)`);\n }\n\n if (use.name === 'delegate_task') {\n if (!opts.addTask) {\n return errResult(use.id, 'delegate_task: capability not available (no addTask callback injected — board posting requires a mesh connection)');\n }\n const title = String(use.input.title ?? '').trim();\n if (!title) return errResult(use.id, 'delegate_task: title is required');\n const description = use.input.description != null ? String(use.input.description) : undefined;\n const priority = use.input.priority != null ? Number(use.input.priority) : undefined;\n const source = use.input.source != null ? String(use.input.source) : undefined;\n const tags = Array.isArray(use.input.tags) ? (use.input.tags as unknown[]).map(String) : undefined;\n const result = await opts.addTask([{ title, description, priority, source, tags }]);\n return okResult(use.id, `delegate_task: posted \"${title}\" to board — ${result.added} task(s) added`);\n }\n\n if (use.name === 'vision_analyze') {\n const imagePath = String(use.input.image_path ?? '').trim();\n if (!imagePath) return errResult(use.id, 'vision_analyze: image_path is required');\n const denied = checkReadAllowed(imagePath);\n if (denied) return errResult(use.id, `vision_analyze: ${denied}`);\n const prompt = String(use.input.prompt ?? 'Describe this image in detail.');\n const model = String(use.input.model ?? 'fara:7b');\n // Dedicated local-inference tool — /founder ruled 2026-06-18: NOT a bandaid.\n // SSRF guard in http_request is correct and stays; this tool is a different\n // trust boundary (fixed local model endpoint, path-sandboxed input, env-driven\n // URL — no user-controlled URL). D.098 + vision pillar #6.\n const ollamaBase = process.env.HOLOSCRIPT_AGENT_LOCAL_LLM_BASE_URL;\n if (!ollamaBase) {\n return errResult(\n use.id,\n 'vision_analyze: HOLOSCRIPT_AGENT_LOCAL_LLM_BASE_URL is not set — configure it to point to your local Ollama instance (e.g. http://holojetson.local:11434)'\n );\n }\n const TIMEOUT_MS = 120_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);\n try {\n const imageBytes = await readFile(imagePath);\n const imageB64 = imageBytes.toString('base64');\n const res = await fetch(`${ollamaBase}/api/generate`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ model, prompt, images: [imageB64], stream: false }),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (!res.ok) {\n const text = await res.text();\n return errResult(use.id, `vision_analyze: Ollama HTTP ${res.status}: ${text.slice(0, 500)}`);\n }\n const json = (await res.json()) as { response?: string; error?: string };\n if (json.error) return errResult(use.id, `vision_analyze: model error — ${json.error}`);\n return okResult(use.id, json.response ?? '');\n } catch (err) {\n clearTimeout(timer);\n const msg = err instanceof Error ? err.message : String(err);\n return errResult(\n use.id,\n msg.includes('abort') ? `vision_analyze: timed out after ${TIMEOUT_MS}ms` : `vision_analyze: ${msg}`\n );\n }\n }\n\n return errResult(use.id, `unknown tool: ${use.name}`);\n } catch (err) {\n return errResult(use.id, err instanceof Error ? err.message : String(err));\n }\n}\n\n/**\n * Parse a single tegrastats output line into structured measurements.\n * Handles the Jetson Orin / Nano / AGX format emitted by `tegrastats --interval 1000`.\n *\n * Example line:\n * 06-16-2026 07:35:01 RAM 2819/7618MB (lfb 73x4MB) SWAP 0/3809MB CPU [37%@1510,off,off]\n * EMC_FREQ 0% GR3D_FREQ 42% cpu@40.2C tj@41.25C VDD_CPU_CV 570mW VDD_SOC 1380mW\n */\nfunction parseTegrastats(raw: string): Array<{ metric: string; value: number; unit: string; method: string }> {\n const results: Array<{ metric: string; value: number; unit: string; method: string }> = [];\n const m = (pattern: RegExp, metric: string, unit: string, transform?: (v: string) => number) => {\n const match = raw.match(pattern);\n if (match?.[1]) {\n const value = transform ? transform(match[1]) : Number(match[1]);\n if (Number.isFinite(value)) results.push({ metric, value, unit, method: 'tegrastats' });\n }\n };\n\n // RAM: \"RAM 2819/7618MB\"\n const ram = raw.match(/RAM\\s+(\\d+)\\/(\\d+)MB/);\n if (ram) {\n const used = Number(ram[1]);\n const total = Number(ram[2]);\n results.push({ metric: 'ram-used', value: used, unit: 'MB', method: 'tegrastats' });\n results.push({ metric: 'ram-total', value: total, unit: 'MB', method: 'tegrastats' });\n if (total > 0)\n results.push({ metric: 'ram-pct', value: Math.round((used / total) * 100), unit: '%', method: 'tegrastats' });\n }\n\n m(/GR3D_FREQ\\s+(\\d+)%/, 'gpu-util', '%');\n m(/EMC_FREQ\\s+(\\d+)%/, 'emc-freq-pct', '%');\n m(/tj@([\\d.]+)C/, 'temp-tj', 'C', parseFloat);\n m(/cpu@([\\d.]+)C/, 'temp-cpu', 'C', parseFloat);\n m(/gpu@([\\d.]+)C/, 'temp-gpu', 'C', parseFloat);\n m(/VDD_SOC\\s+(\\d+)mW/, 'power-soc', 'mW');\n m(/VDD_CPU_CV\\s+(\\d+)mW/, 'power-cpu-cv', 'mW');\n m(/VDD_IN\\s+(\\d+)mW/, 'power-total', 'mW');\n\n // CPU first-core utilisation: \"CPU [37%@1510,...\"\n m(/CPU\\s+\\[(\\d+)%/, 'cpu-util-core0', '%');\n\n return results;\n}\n\ninterface BashResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runBash(cmd: string, cwd: string): Promise<BashResult> {\n // Test short-circuit (task_1778113854009_x6p3): under vitest, return a\n // fast synthetic exit instead of spawning bash. Without this, mocks that\n // emit a \"vitest run\" tool_use cause runner.test.ts to recursively spawn\n // vitest startup per tick (~1.7s each), pushing 3-tick tests over the\n // 5000ms timeout. Production paths (NODE_ENV != 'test', VITEST unset)\n // are unchanged and still spawn the real shell.\n if (process.env.VITEST === 'true' || process.env.NODE_ENV === 'test') {\n return Promise.resolve({\n code: 0,\n stdout: `[mock-bash under vitest] cmd=\"${cmd}\" cwd=\"${cwd}\"`,\n stderr: '',\n });\n }\n return new Promise((resolveProm) => {\n const child = spawn('bash', ['-c', cmd], { cwd, env: process.env });\n let stdout = '';\n let stderr = '';\n let killed = false;\n const STDOUT_CAP = 1_000_000;\n const TIMEOUT_MS = 60_000;\n const killer = setTimeout(() => {\n killed = true;\n child.kill('SIGKILL');\n }, TIMEOUT_MS);\n child.stdout.on('data', (d: Buffer) => {\n if (stdout.length < STDOUT_CAP) stdout += d.toString('utf8');\n });\n child.stderr.on('data', (d: Buffer) => {\n if (stderr.length < STDOUT_CAP) stderr += d.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(killer);\n resolveProm({ code: 1, stdout, stderr: stderr + '\\nspawn-error: ' + err.message });\n });\n child.on('exit', (code) => {\n clearTimeout(killer);\n const finalStdout =\n stdout.length >= STDOUT_CAP\n ? stdout + `\\n…[stdout truncated at ${STDOUT_CAP} bytes]`\n : stdout;\n const note = killed ? `\\n[bash killed after ${TIMEOUT_MS}ms timeout]` : '';\n resolveProm({ code: code ?? 1, stdout: finalStdout + note, stderr });\n });\n });\n}\n\nfunction okResult(id: string, content: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content };\n}\n\nfunction errResult(id: string, message: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content: message, is_error: true };\n}\n","/**\n * On-task cognitive verbs — the edge executor (Phase 2.2).\n *\n * A brain's `behavior on_task { … }` block parses into an ordered sequence of\n * cognitive verbs (brain.ts extractOnTaskActions). The lightweight AgentRunner\n * executes them WITHOUT a @holoscript/core / engine dependency — provider + mesh\n * only — so the edge package keeps its clean publish dep-closure:\n *\n * - `llm_call { prompt }` → append the prompt as a domain directive (was the\n * only wired verb before this; W.736).\n * - `rag_query { query }` → retrieve from TEAM knowledge → inject as context.\n * - `recall { query }` → retrieve from the agent's PRIVATE workspace →\n * filter by query client-side → inject.\n * - `plan { goal|prompt }` → one provider call producing a short plan → inject.\n *\n * Each verb is best-effort: a retrieval/plan failure is logged and skipped, never\n * breaking the tick. The verbs run in authored order and their outputs accumulate\n * onto the system prompt the tool-loop sees. `reflect` is handled separately\n * (post-artifact gate in runner.ts), not here.\n *\n * @module holoscript-agent/cognitive-verbs\n */\nimport type { KnowledgeEntry } from './holomesh-client.js';\nimport type { OnTaskAction } from './types.js';\n\nexport interface CognitiveVerbDeps {\n /** The brain's base system prompt to augment. */\n systemPrompt: string;\n /** Parsed `behavior on_task` verbs, in authored order. */\n onTaskActions: OnTaskAction[];\n /** Task being executed (for `plan` goal fallback + logging). */\n task: { id: string; title: string };\n /** TEAM knowledge retrieval (rag_query, keyword/semantic). */\n queryTeamKnowledge: (query: string, limit: number) => Promise<KnowledgeEntry[]>;\n /**\n * Codebase GraphRAG semantic search (rag_query Phase 2.3, W.753).\n * Optional — when absent OR it returns [] (graph not loaded), rag_query falls\n * back to team-knowledge search. Wires the in-process HoloEmbed index via the\n * bearer-gated mesh route POST /api/holomesh/codebase/search.\n */\n queryCodebase?: (query: string, topK: number) => Promise<Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>>;\n /** PRIVATE workspace retrieval (recall). */\n queryPrivateKnowledge: () => Promise<KnowledgeEntry[]>;\n /** One-shot provider planner (plan). Optional — when absent, `plan` is skipped. */\n plan?: (prompt: string) => Promise<string>;\n /**\n * Embed text for SEMANTIC `recall` (the fleet nomic model). Optional — when absent\n * OR it returns null (no fleet/registry reachable), `recall` falls back to the\n * substring filter. Pairs with `similarity`. (W.753: recall should rank via the\n * semantic stack, not keyword-match the private workspace.)\n */\n embed?: (text: string) => Promise<number[] | null>;\n /** Cosine similarity for ranking recalled entries (required alongside `embed`). */\n similarity?: (a: number[], b: number[]) => number;\n /** Structured logger. */\n log: (ev: Record<string, unknown>) => void;\n}\n\nconst DEFAULT_LIMIT = 5;\n/** Cap injected context so the edge model's num_ctx isn't blown (qwen3:4b). */\nconst MAX_ENTRY_CHARS = 320;\nconst MAX_INJECTED_CHARS = 2400;\n/** Cap entries embedded per recall so a large private store can't stall a tick. */\nconst MAX_RECALL_EMBED = 40;\n\nfunction strField(config: Record<string, unknown>, ...keys: string[]): string {\n for (const k of keys) {\n const v = config[k];\n if (typeof v === 'string' && v.trim()) return v.trim();\n }\n return '';\n}\n\nfunction numField(config: Record<string, unknown>, key: string, fallback: number): number {\n const v = config[key];\n return typeof v === 'number' && Number.isFinite(v) ? v : fallback;\n}\n\nfunction formatEntries(entries: KnowledgeEntry[]): string {\n let out = '';\n for (const e of entries) {\n const line = `- ${(e.content ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_ENTRY_CHARS)}`;\n if (out.length + line.length > MAX_INJECTED_CHARS) break;\n out += (out ? '\\n' : '') + line;\n }\n return out;\n}\n\n/**\n * Execute a brain's on_task cognitive verbs and return the augmented system\n * prompt the tool-loop should use. Pure-ish: all I/O is injected via deps.\n */\nexport async function augmentWithOnTaskCognition(deps: CognitiveVerbDeps): Promise<string> {\n let content = deps.systemPrompt;\n if (!deps.onTaskActions || deps.onTaskActions.length === 0) return content;\n\n for (const action of deps.onTaskActions) {\n try {\n switch (action.verb) {\n case 'llm_call': {\n const prompt = strField(action.config, 'prompt');\n if (prompt) {\n content += `\\n\\n[Brain on_task directive]\\n${prompt}`;\n deps.log({ ev: 'on-task-llm-call', taskId: deps.task.id, promptLen: prompt.length });\n }\n break;\n }\n case 'rag_query': {\n const query = strField(action.config, 'query', 'q') || deps.task.title;\n const limit = numField(action.config, 'limit', DEFAULT_LIMIT);\n // Phase 2.3 (W.753): try codebase GraphRAG (in-process HoloEmbed via the mesh bearer\n // route) first — returns ranked symbols (name/file/score). Falls back to team-knowledge\n // search when the graph isn't loaded or the dep isn't wired.\n let mode = 'team-knowledge';\n let injected = '';\n if (deps.queryCodebase) {\n const symbols = await deps.queryCodebase(query, limit);\n if (symbols.length > 0) {\n mode = 'codebase-graphrag';\n const lines = symbols\n .slice(0, limit)\n .map(\n (s) =>\n `- ${s.name} (${s.type}) ${s.file}${s.line != null ? `:${s.line}` : ''}` +\n (s.signature ? ` — ${s.signature.slice(0, 80)}` : '') +\n ` [score:${s.score.toFixed(2)}]`\n )\n .join('\\n');\n injected = `\\n\\n[Codebase search for \"${query}\"]\\n${lines}`;\n }\n }\n if (!injected) {\n // Fallback: team knowledge store (already semantic via HoloEmbed ranking, bb28ecc25).\n const entries = await deps.queryTeamKnowledge(query, limit);\n if (entries.length > 0) {\n injected = `\\n\\n[Retrieved knowledge for \"${query}\"]\\n${formatEntries(entries)}`;\n }\n }\n if (injected) content += injected;\n deps.log({ ev: 'on-task-rag-query', taskId: deps.task.id, query, mode, retrieved: injected ? limit : 0 });\n break;\n }\n case 'recall': {\n const query = strField(action.config, 'query', 'q');\n const limit = numField(action.config, 'limit', DEFAULT_LIMIT);\n const all = await deps.queryPrivateKnowledge();\n let matched: KnowledgeEntry[] | null = null;\n let mode = 'substring';\n // SEMANTIC recall (W.753): rank the private workspace by embedding-cosine\n // when an embed route resolves. Best-effort — any miss (no embed dep, fleet\n // unreachable, null vectors) drops to the substring filter below; never breaks the tick.\n if (deps.embed && deps.similarity && query && all.length > 0) {\n const qv = await deps.embed(query);\n if (qv) {\n const scored: Array<{ e: KnowledgeEntry; score: number }> = [];\n for (const e of all.slice(0, MAX_RECALL_EMBED)) {\n const ev = await deps.embed(e.content ?? '');\n if (ev) scored.push({ e, score: deps.similarity(qv, ev) });\n }\n if (scored.length > 0) {\n scored.sort((a, b) => b.score - a.score);\n matched = scored.slice(0, limit).map((s) => s.e);\n mode = 'semantic';\n }\n }\n }\n if (!matched) {\n const needle = query.toLowerCase();\n matched = (\n needle\n ? all.filter((e) => `${e.id ?? ''} ${e.content ?? ''}`.toLowerCase().includes(needle))\n : all\n ).slice(0, limit);\n }\n if (matched.length > 0) {\n content += `\\n\\n[Recalled memory${query ? ` for \"${query}\"` : ''}]\\n${formatEntries(matched)}`;\n }\n deps.log({ ev: 'on-task-recall', taskId: deps.task.id, query, recalled: matched.length, mode });\n break;\n }\n case 'plan': {\n if (!deps.plan) break;\n const goal = strField(action.config, 'goal', 'prompt', 'of') || deps.task.title;\n const planText = await deps.plan(\n `Produce a short numbered plan (max 6 steps) to accomplish this task. Be concrete and specific to the goal; do not execute it.\\n\\nGoal: ${goal}`\n );\n const trimmed = planText.trim().slice(0, MAX_INJECTED_CHARS);\n if (trimmed) {\n content += `\\n\\n[Plan]\\n${trimmed}`;\n deps.log({ ev: 'on-task-plan', taskId: deps.task.id, planLen: trimmed.length });\n }\n break;\n }\n // `reflect` is handled post-artifact in runner.ts, not here.\n default:\n break;\n }\n } catch (err) {\n deps.log({\n ev: 'on-task-verb-error',\n taskId: deps.task.id,\n verb: action.verb,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return content;\n}\n"],"mappings":";AACA,SAAS,kBAAkB,wBAAwB;;;ACDnD,SAAS,UAAU,YAAY,aAAa;AAC5C,SAAS,eAAe;AA4WjB,SAAS,kBACd,OACA,qBACuB;AACvB,QAAM,SAAS,IAAI,IAAI,oBAAoB,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACtE,QAAM,OAAO,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,SAAS;AACpE,QAAM,SAAS,KACZ,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,UAAU,GAAG,MAAM,EAAE,EAAE,EACrD,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EACzB,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,SAAS,EAAE,IAAI,IAAI,SAAS,EAAE,IAAI,CAAC;AAC1E,SAAO,OAAO,CAAC,GAAG;AACpB;AAEA,SAAS,UAAU,MAAiB,QAA6B;AAC/D,QAAM,QAAQ,KAAK,QAAQ,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC;AACzD,QAAM,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,eAAe,EAAE,GAAG,YAAY;AACnE,MAAI,QAAQ;AACZ,aAAW,OAAO,KAAM,KAAI,OAAO,IAAI,GAAG,EAAG,UAAS;AACtD,aAAW,KAAK,OAAQ,KAAI,KAAK,SAAS,CAAC,EAAG,UAAS;AACvD,SAAO;AACT;AAEA,SAAS,SAAS,GAAsB;AACtC,MAAI,OAAO,EAAE,aAAa,SAAU,QAAO,EAAE;AAC7C,QAAM,MAA8B,EAAE,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,KAAK,EAAE;AAC9E,SAAO,IAAI,OAAO,EAAE,QAAQ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AAW,GAAG,EAAE,CAAC;AAC7C;AAEA,SAAS,OAAO,MAAsB;AACpC,SAAO,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,OAAO,GAAG;AACtD;","names":["readFile","mkdir","dirname","createHash","priority","tasks"]}
1
+ {"version":3,"sources":["../src/runner.ts","../src/holomesh-client.ts","../src/cael-builder.ts","../src/tools.ts","../src/cognitive-verbs.ts"],"sourcesContent":["import type { ILLMProvider, LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport { embedAcrossFleet, cosineSimilarity } from '@holoscript/llm-provider';\nimport type { CostGuard } from './cost-guard.js';\nimport type { HolomeshClient } from './holomesh-client.js';\nimport { pickClaimableTask } from './holomesh-client.js';\nimport type { AuditLog } from './audit-log.js';\nimport { buildCaelRecord } from './cael-builder.js';\nimport { resolveActiveTools, runTool, summarizeToolProductivity } from './tools.js';\nimport { augmentWithOnTaskCognition } from './cognitive-verbs.js';\nimport { DelegatedAuthorityHandler } from './delegated-authority.js';\nimport type {\n AgentIdentity,\n BoardTask,\n ExecutionResult,\n RuntimeBrainConfig,\n TickResult,\n} from './types.js';\n\n// Bumped when the CAEL record schema or layer-hash semantics change. Lives\n// in the version_vector_fingerprint of every emitted record so consumers\n// can partition the corpus by runtime version.\nconst RUNTIME_VERSION = '1.0.0';\n\nexport interface AgentRunnerOptions {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n provider: ILLMProvider;\n costGuard: CostGuard;\n mesh: HolomeshClient;\n logger?: (event: Record<string, unknown>) => void;\n onTaskExecuted?: (result: ExecutionResult, task: BoardTask) => Promise<void>;\n auditLog?: AuditLog;\n /** Optional delegated-authority handler for governance message processing (E4). */\n messageHandler?: DelegatedAuthorityHandler;\n /**\n * Optional hardware-receipt signer (index.ts wires the seat wallet). When\n * present, emit_hardware_receipt seals its content hash with a wallet signature\n * so the hardware-provenance artifact is verifiable, not plain JSON. Absent →\n * the receipt is content-hashed but self-reports `signed:false` (honest).\n */\n signReceipt?: (canonical: string) => Promise<{ alg: string; signer: string; signature: string }>;\n}\n\nexport class AgentRunner {\n private stopped = false;\n // CAEL audit hash chain — survives across ticks within a single runner\n // process. On process restart it resets to null; the first post-restart\n // record breaks the chain, which is honest (the runner has no memory of\n // its prior chain state and shouldn't fake continuity). prev_hash=null\n // is a valid value the audit-store accepts.\n private prevCaelChain: string | null = null;\n // Self-recovery flag for the auto-rejoin path (task_1777112258989_eeyp).\n // When the heartbeat returns 403 \"Not a member of this team\" — typical of\n // a fresh Vast.ai worker whose provisioning didn't atomically /join, or of\n // a worker whose membership was reaped — the runner calls mesh.joinTeam()\n // ONCE per process and retries the heartbeat. After a successful rejoin\n // we set this flag so subsequent 403s on the same process don't loop back\n // into joinTeam (avoiding a retry storm if the team-cap is full or the\n // join itself is permanently rejected). On process restart the flag\n // resets, which is the correct semantics: a fresh process gets one fresh\n // chance to self-rejoin. Discovered 2026-04-25 SSH-probing 5 fleet\n // workers stuck in indefinite 403→tick-error→sleep→retry loops; without\n // this, a fresh-deploy of an unjoined agent stays silent forever.\n private joinedThisProcess = false;\n\n constructor(private readonly opts: AgentRunnerOptions) {}\n\n async tick(): Promise<TickResult> {\n const { identity, brain, mesh, costGuard, provider, logger } = this.opts;\n const log = logger ?? (() => undefined);\n\n await this.heartbeatWithAutoRejoin();\n\n // ── Delegated-authority message processing (E4) ──────────────────────────\n // Run before budget/task claiming so governance requests are handled\n // even when the agent is over-budget or has no claimable tasks.\n if (this.opts.messageHandler) {\n try {\n const receipts = await this.opts.messageHandler.processMessages();\n if (receipts.length > 0) {\n log({\n ev: 'messages-processed',\n count: receipts.length,\n statuses: receipts.map((r) => r.status),\n });\n // If this agent has no board-task capability tags (Brittney is\n // governance-only), return early so the tick result reflects message\n // work rather than falling through to no-claimable-task.\n if (\n brain.capabilityTags.length === 0 ||\n brain.capabilityTags.every((t) => t.startsWith('delegated'))\n ) {\n return {\n action: 'messages-processed',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n receipts: receipts.map((r) => ({\n status: r.status,\n action: r.action,\n reason: r.reason,\n })),\n };\n }\n }\n } catch (err) {\n log({\n ev: 'message-handler-error',\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (costGuard.isOverBudget()) {\n const state = costGuard.getState();\n log({ ev: 'over-budget', spentUsd: state.spentUsd, budget: identity.budgetUsdPerDay });\n return {\n action: 'over-budget',\n spentUsd: state.spentUsd,\n remainingUsd: 0,\n message: `daily budget $${identity.budgetUsdPerDay} exhausted`,\n };\n }\n\n const tasks = await mesh.getOpenTasks();\n const target = pickClaimableTask(tasks, brain.capabilityTags);\n if (!target) {\n log({ ev: 'no-claimable-task', open: tasks.length });\n return {\n action: 'no-claimable-task',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n };\n }\n\n log({ ev: 'claim', taskId: target.id, title: target.title });\n await mesh.claim(target.id);\n\n const start = Date.now();\n // Tool-use loop. The model gets MESH_TOOLS (read_file, list_dir,\n // write_file, bash) and can iterate read→reason→read→write until it\n // emits a final text response. Without this loop the model could only\n // reason from prompt+brain alone — no filesystem access, no kernel\n // checks, no inspection of inputs scp'd to the instance. With it,\n // lean-theorist can actually `cat MSC/Invariants.lean`, `lake build`,\n // and `write_file /root/agent-output/Invariants.lean` per its brain rules.\n // ── On-task cognition (Phase 2.2 — cognitive-verbs.ts) ───────────────────\n // Execute the brain's authored `behavior on_task` verbs (llm_call / rag_query\n // / recall / plan) and accumulate their outputs onto the system prompt before\n // the tool loop. Provider + mesh only (no engine/@holoscript/core dep) so the\n // edge package keeps its clean publish closure. `reflect` runs post-artifact.\n const systemContent = await augmentWithOnTaskCognition({\n systemPrompt: brain.systemPrompt,\n onTaskActions: brain.onTaskActions ?? [],\n task: { id: target.id, title: target.title },\n queryTeamKnowledge: (q, limit) => mesh.queryTeamKnowledge(q, limit),\n queryPrivateKnowledge: () => mesh.queryPrivateKnowledge(),\n // Phase 2.3 (W.753): codebase GraphRAG via the bearer-gated mesh route.\n // Best-effort: returns [] when the in-process graph isn't loaded → cognitive-verbs\n // falls back to team-knowledge search. No prod impact when graph is cold.\n queryCodebase: (q, topK) => mesh.queryCodebase(q, topK),\n plan: async (prompt) => {\n const resp = await provider.complete(\n { messages: [{ role: 'user', content: prompt }], maxTokens: 512, temperature: 0.3 },\n identity.llmModel\n );\n return resp.content;\n },\n // Semantic `recall` over the private workspace via the fleet nomic (W.753).\n // brainPath from HOLO_LLM_FLEET_BRAIN; if unset/unreachable embedAcrossFleet\n // returns null and cognitive-verbs falls back to the substring filter.\n embed: (text) => embedAcrossFleet(text, { brainPath: process.env.HOLO_LLM_FLEET_BRAIN }),\n similarity: cosineSimilarity,\n log,\n });\n\n const messages: LLMMessage[] = [\n { role: 'system', content: systemContent },\n { role: 'user', content: buildTaskPrompt(target) },\n ];\n let aggUsage: TokenUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\n let finalText = '';\n let iters = 0;\n // 30-iter cap: lean-theorist on Paper 22 needed 13 iters to read MSC files\n // + run lake build + iterate kernel checks. 12 was too tight (cap fired\n // before write_file deliverable). 30 allows ~3x that depth — anything\n // hitting 30 iters is almost certainly stuck and should bail.\n const MAX_TOOL_ITERS = 30;\n let lastResponse;\n // Track which tool names were called during this run so the artifact-grounding\n // gate below can refuse to mark \"executed\" on pure-text or read-only responses.\n // Discovered 2026-04-26 mesh-worker-02 audit: workers were posting CAEL records\n // with tool_iters:1 (zero tools called) declaring \"100 scenes validated\" with\n // no commit / no /room done — fabricated deliverables polluting trust. The\n // gate below short-circuits this class of hallucination at the runner edge.\n const toolsCalled = new Set<string>();\n // Tightened-gate counter (W.107.b 2026-04-26): track *productive* tool calls\n // separately from any tool call. A productive call is one of:\n // - write_file with non-empty content\n // - bash matching a productive prefix (lake build / pnpm --filter / vitest\n // run / lean / pnpm vitest — see tools.ts BASH_PRODUCTIVE_PREFIXES)\n // Read-only bash (cat/grep/ls/echo/git status/etc.) does NOT count even\n // though it's whitelisted for execution. This catches the trivial-bash-bypass\n // class (e.g. `bash echo done`) that the original W.107 gate accepted.\n let productiveCallCount = 0;\n // Last git commit SHA emitted during the tool-loop; forwarded to markDone\n // so the board task records a verifiable commit reference.\n let lastCommitHash: string | undefined;\n // F.126 #1 — the model's tools come from the BRAIN'S DECLARATION (the on_task\n // `llm_call { tools: [...] }` array), not a hardcoded list. resolveActiveTools\n // resolves the declared names against MESH_TOOLS, falls back safely when a brain\n // declares none, and SLIM-trims an oversized set for small local models (W.710\n // num_ctx guard). \"Add a tool\" is now \"declare it in the brain,\" not edit this file.\n const { tools: activeTools, declared: declaredTools, dropped: droppedTools } = resolveActiveTools(brain);\n log({\n ev: 'active-tools',\n taskId: target.id,\n tools: activeTools.map((t) => t.name),\n declared: declaredTools,\n ...(droppedTools.length ? { droppedUnknown: droppedTools } : {}),\n });\n while (true) {\n iters++;\n if (iters > MAX_TOOL_ITERS) {\n log({ ev: 'tool-loop-cap', taskId: target.id, iters });\n finalText = finalText || `[tool-loop hit ${MAX_TOOL_ITERS}-iter cap before final text]`;\n break;\n }\n const resp = await provider.complete(\n {\n messages,\n // 8192 for local thinking models (qwen3:4b uses ~3800 tokens on thinking\n // before the tool-call JSON; 4096 cuts off mid-generation). Frontier\n // models ignore this ceiling and stop naturally earlier.\n maxTokens: 8192,\n temperature: 0.4,\n tools: activeTools,\n },\n identity.llmModel\n );\n lastResponse = resp;\n aggUsage = {\n promptTokens: aggUsage.promptTokens + resp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + resp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + resp.usage.totalTokens,\n };\n // If model called tools, execute them and feed results back.\n if (resp.finishReason === 'tool_use' && resp.toolUses && resp.toolUses.length > 0) {\n log({\n ev: 'tool-call',\n taskId: target.id,\n iter: iters,\n tools: resp.toolUses.map((t) => t.name),\n });\n // Artifact-grounding accounting (W.107.b) via the shared classifier in\n // tools.ts — the SAME function the ablation harness measures, so the gate\n // and its evaluation can never drift (single source of truth).\n const productivity = summarizeToolProductivity(resp.toolUses);\n for (const n of productivity.names) toolsCalled.add(n);\n productiveCallCount += productivity.productiveCount;\n // Append the assistant turn (text + tool_use blocks) so the model\n // sees its own request when we send tool_result back.\n messages.push({\n role: 'assistant',\n content: (resp.assistantBlocks ?? []) as never,\n });\n // Run each tool and collect results.\n const toolResults = await Promise.all(\n resp.toolUses.map((u) =>\n runTool(u, {\n signReceipt: this.opts.signReceipt,\n addTask: (tasks) => mesh.addTasks(tasks),\n })\n )\n );\n // Extract the latest git commit SHA from bash stdout so markDone can\n // record a verifiable reference on the board task. Pattern matches both\n // `git commit -m` output ('[branch abc1234]') and `git rev-parse HEAD`.\n for (let ti = 0; ti < resp.toolUses.length; ti++) {\n const tu = resp.toolUses[ti];\n if (tu.name === 'bash') {\n const tr = toolResults[ti];\n if (tr && !tr.is_error) {\n const shaMatch = tr.content.match(/\\b([0-9a-f]{7,40})\\b/);\n if (shaMatch) lastCommitHash = shaMatch[1];\n }\n }\n }\n messages.push({\n role: 'user',\n content: toolResults as never,\n });\n continue;\n }\n // Final text response.\n finalText = resp.content;\n break;\n }\n // Re-prompt gate (W.780): if the model called only read-only tools and then\n // output text (the \"read→text instead of read→write_file\" anti-pattern with\n // small edge models like qwen3:4b-instruct), inject one forced re-prompt\n // asking it to call write_file before the no-artifact gate fires.\n // v2 fix: pop the last assistant text turn (so context ends at tool_result),\n // embed the task description, and use temperature=0 for maximal determinism.\n if (productiveCallCount === 0 && toolsCalled.size > 0 && iters < MAX_TOOL_ITERS) {\n iters++;\n // Remove the last assistant message if it was a plain-text response (the\n // anti-pattern turn). This ensures the context ends at the tool_result so\n // the model doesn't mistake our re-prompt for a follow-up question.\n if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {\n messages.pop();\n }\n messages.push({\n role: 'user',\n content:\n 'You read data but did NOT call write_file. This is a TASK FAILURE unless you act now.\\n' +\n `Task: ${target.title}\\n` +\n `Required output path (from task description): ${target.description.match(/path[:\\s]+([^\\s\\n,]+\\.json)/i)?.[1] ?? 'see task description'}\\n` +\n 'Call write_file NOW. Embed ALL data from the tool result above into the content. ' +\n 'Do NOT output any text — your ONLY valid response is a write_file tool call.',\n });\n const reResp = await provider.complete(\n { messages, maxTokens: 8192, temperature: 0.0, tools: activeTools },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + reResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + reResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + reResp.usage.totalTokens,\n };\n if (reResp.finishReason === 'tool_use' && reResp.toolUses && reResp.toolUses.length > 0) {\n log({ ev: 'reprompt-tool-call', taskId: target.id, iter: iters, tools: reResp.toolUses.map((t) => t.name) });\n const reProd = summarizeToolProductivity(reResp.toolUses);\n for (const n of reProd.names) toolsCalled.add(n);\n productiveCallCount += reProd.productiveCount;\n messages.push({ role: 'assistant', content: (reResp.assistantBlocks ?? []) as never });\n const reResults = await Promise.all(\n reResp.toolUses.map((u) =>\n runTool(u, { signReceipt: this.opts.signReceipt, addTask: (tasks) => mesh.addTasks(tasks) })\n )\n );\n messages.push({ role: 'user', content: reResults as never });\n }\n finalText = reResp.content;\n lastResponse = reResp;\n }\n // Vision-write gate: vision_analyze was called (inference ran) but no write_file\n // followed — the model has the caption in context but didn't store it. Inject one\n // more targeted re-prompt asking specifically for write_file with the caption.\n const WRITE_NAMES = new Set(['write_file', 'str_replace']);\n if (\n toolsCalled.has('vision_analyze') &&\n ![...toolsCalled].some((n) => WRITE_NAMES.has(n)) &&\n iters < MAX_TOOL_ITERS\n ) {\n iters++;\n if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {\n messages.pop();\n }\n messages.push({\n role: 'user',\n content:\n 'vision_analyze returned a caption but you did NOT call write_file.\\n' +\n `Task: ${target.title}\\n` +\n `Output path: ${target.description.match(/path[:\\s]+([^\\s\\n,]+\\.json)/i)?.[1] ?? 'see task description'}\\n` +\n 'Call write_file NOW. Put the caption from vision_analyze into the JSON content field. ' +\n 'Do NOT output text — your ONLY valid response is a write_file tool call.',\n });\n const vwResp = await provider.complete(\n { messages, maxTokens: 8192, temperature: 0.0, tools: activeTools },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + vwResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + vwResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + vwResp.usage.totalTokens,\n };\n if (vwResp.finishReason === 'tool_use' && vwResp.toolUses && vwResp.toolUses.length > 0) {\n log({ ev: 'vision-write-call', taskId: target.id, iter: iters, tools: vwResp.toolUses.map((t) => t.name) });\n const vwProd = summarizeToolProductivity(vwResp.toolUses);\n for (const n of vwProd.names) toolsCalled.add(n);\n productiveCallCount += vwProd.productiveCount;\n messages.push({ role: 'assistant', content: (vwResp.assistantBlocks ?? []) as never });\n const vwResults = await Promise.all(\n vwResp.toolUses.map((u) =>\n runTool(u, { signReceipt: this.opts.signReceipt, addTask: (tasks) => mesh.addTasks(tasks) })\n )\n );\n messages.push({ role: 'user', content: vwResults as never });\n }\n finalText = vwResp.content;\n lastResponse = vwResp;\n }\n const durationMs = Date.now() - start;\n\n // Artifact-grounding gate (W.107 — fleet event-firing rate is not a productivity\n // metric; only side-effecting tool calls produce real artifacts; 2026-04-26\n // tightened to W.107.b which also closes the trivial-bash bypass: `bash echo\n // done` and `write_file /tmp/x \"\"` no longer pass the gate). The gate now\n // requires AT LEAST ONE productive call:\n // - write_file with non-empty content, OR\n // - bash matching a productive prefix (lake build / pnpm --filter /\n // vitest run / lean / pnpm vitest)\n // Read-only inspection tools (read_file, list_dir) and read-only bash\n // (cat/grep/ls/echo/git status/git log/...) don't satisfy the gate.\n if (productiveCallCount === 0) {\n log({\n ev: 'no-artifact',\n taskId: target.id,\n tool_iters: iters,\n toolsCalled: [...toolsCalled],\n productiveCallCount,\n message:\n 'task execution did not produce a real artifact — refusing to mark executed. ' +\n 'Required: write_file with non-empty content OR bash with a productive prefix ' +\n '(lake build / pnpm --filter / vitest run / lean / pnpm vitest). ' +\n 'Pure-text, read-only inspection, and trivial-bash-bypass (`echo`, `cat`, etc.) do not satisfy the gate.',\n });\n // Best-effort: leave the task in claimed state so the supervisor can either\n // re-tick or release it via heartbeat-rejoin. We deliberately do NOT post\n // a \"fake-done\" message on the board, do NOT post a CAEL record, and do NOT\n // call the cost guard's recordUsage — the run produced no artifact and\n // should not bill the budget for a hallucinated tick.\n return {\n action: 'no-artifact',\n taskId: target.id,\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n message: `no productive tool call observed (toolsCalled=[${[...toolsCalled].join(',')}], productiveCallCount=${productiveCallCount}, iters=${iters})`,\n };\n }\n\n // ── Reflect: cognitive self-evaluation gate (W.736) ──────────────────────\n // If the brain declares a `reflect` verb, run ONE self-evaluation pass over\n // the produced artifact before accepting it — the brain's local_first\n // confidence gate. Uses the same provider (no engine/trait dependency) and\n // mirrors the CognitiveActions reflect prompt shape. The verdict is acted on\n // at the markDone gate below; its tokens fold into aggUsage so cost is honest.\n let reflectVerdict: { pass: boolean; reason: string } | undefined;\n if (brain.reflect) {\n try {\n const reflectResp = await provider.complete(\n {\n messages: [\n {\n role: 'system',\n content:\n 'You are a strict reviewer. Evaluate the work against the criteria; do not rewrite it.',\n },\n {\n role: 'user',\n content:\n `Reflect on the artifact produced for this task. Evaluate it for: ${brain.reflect.criteria}.\\n\\n` +\n `--- artifact / final response ---\\n${finalText.slice(0, 4000)}\\n--- end ---\\n\\n` +\n `Give a one-line reason, then end with exactly \"VERDICT: PASS\" or \"VERDICT: FAIL\".`,\n },\n ],\n maxTokens: 512,\n temperature: 0.1,\n },\n identity.llmModel\n );\n aggUsage = {\n promptTokens: aggUsage.promptTokens + reflectResp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + reflectResp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + reflectResp.usage.totalTokens,\n };\n const verdictMatch = /VERDICT:\\s*(PASS|FAIL)/i.exec(reflectResp.content);\n // Unparseable verdict = PASS — reflect is a gate, not a tripwire; never\n // block a real artifact on a parser miss (small local models phrase loosely).\n const pass = verdictMatch ? verdictMatch[1].toUpperCase() === 'PASS' : true;\n reflectVerdict = {\n pass,\n reason: reflectResp.content.replace(/VERDICT:\\s*(PASS|FAIL)/i, '').trim().slice(0, 300),\n };\n log({\n ev: 'reflect',\n taskId: target.id,\n pass,\n escalateOnFail: brain.reflect.escalateOnFail,\n reason: reflectVerdict.reason.slice(0, 120),\n });\n } catch (err) {\n log({\n ev: 'reflect-error',\n taskId: target.id,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const cost = costGuard.recordUsage(identity.llmModel, aggUsage);\n log({\n ev: 'executed',\n taskId: target.id,\n costUsd: cost.costUsd.toFixed(4),\n spentUsd: cost.spentUsd.toFixed(4),\n tokens: aggUsage.totalTokens,\n tool_iters: iters,\n });\n const response = {\n ...(lastResponse ?? { content: finalText, usage: aggUsage }),\n content: finalText,\n usage: aggUsage,\n };\n\n const execResult: ExecutionResult = {\n taskId: target.id,\n responseText: response.content,\n usage: response.usage,\n costUsd: cost.costUsd,\n durationMs,\n };\n\n if (this.opts.auditLog) {\n try {\n this.opts.auditLog.recordTaskExecuted({\n identity,\n task: target,\n result: execResult,\n });\n } catch (err) {\n log({ ev: 'audit-log-error', message: err instanceof Error ? err.message : String(err) });\n }\n }\n\n // Phase 1 CAEL audit: post to the HoloMesh audit store so the fleet\n // corpus collector at ai-ecosystem/scripts/fleet-corpus-collector.mjs\n // can read records via GET /api/holomesh/agent/{handle}/audit. Without\n // this POST, the local AuditLog above is the only durable record and\n // Paper 25's gate clock cannot start. See ai-ecosystem task\n // task_1777106535952_atug for the empty-audit investigation.\n try {\n const caelRecord = buildCaelRecord({\n identity,\n brain,\n task: target,\n messages,\n finalText,\n usage: aggUsage,\n costUsd: cost.costUsd,\n spentUsd: cost.spentUsd,\n prevChain: this.prevCaelChain,\n runtimeVersion: RUNTIME_VERSION,\n });\n const posted = await mesh.postAuditRecords(identity.handle, [caelRecord]);\n this.prevCaelChain = caelRecord.fnv1a_chain;\n log({\n ev: 'cael-posted',\n taskId: target.id,\n appended: posted.appended,\n rejected: posted.rejected,\n });\n } catch (err) {\n log({ ev: 'cael-post-error', message: err instanceof Error ? err.message : String(err) });\n }\n\n // Reflect escalation gate: a brain with `reflect { escalate_on_fail: true }`\n // does NOT mark done on a failed self-evaluation — it escalates to the fleet\n // (the local_first directive). Cost + CAEL are already recorded above (the work\n // happened and the self-eval is a verifiable trace); only acceptance/markDone is\n // withheld. Brains without reflect, or with an advisory reflect, fall through.\n if (reflectVerdict && !reflectVerdict.pass && brain.reflect?.escalateOnFail) {\n try {\n await mesh.sendMessageOnTask(\n target.id,\n `[${identity.handle}] reflect gate FAILED — escalating to the fleet instead of marking done. Reason: ${reflectVerdict.reason}`\n );\n } catch {\n /* best-effort escalation notice; the return value is the source of truth */\n }\n log({ ev: 'reflect-escalate', taskId: target.id, reason: reflectVerdict.reason.slice(0, 120) });\n return {\n action: 'reflect-escalate',\n taskId: target.id,\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n message: `reflect self-evaluation failed; escalated to fleet (reason: ${reflectVerdict.reason.slice(0, 120)})`,\n };\n }\n\n if (this.opts.onTaskExecuted) {\n await this.opts.onTaskExecuted(execResult, target);\n } else {\n await mesh.sendMessageOnTask(\n target.id,\n `[${identity.handle}] response (${response.usage.totalTokens} tok, $${cost.costUsd.toFixed(4)}):\\n\\n${response.content}`\n );\n }\n\n // Mark the task done so it doesn't linger in 'claimed' forever.\n // Wrapped in try/catch: a markDone failure (e.g. task already closed by\n // a supervisor, or transient network error) must not prevent the tick\n // return value from reaching the caller.\n try {\n await mesh.markDone(target.id, finalText.slice(0, 500), lastCommitHash);\n log({ ev: 'mark-done', taskId: target.id, commitHash: lastCommitHash });\n } catch (err) {\n log({\n ev: 'mark-done-error',\n taskId: target.id,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n\n // Continuity write-loop: persist this task's outcome to the agent's PRIVATE\n // knowledge so a future `recall` verb has real memory to draw on. This closes\n // the W.752 loop-gap — the edge `recall` verb read /knowledge/private but it\n // was always empty because nothing ever wrote to it. Now markDone feeds it.\n // Best-effort (writePrivateKnowledge swallows its own errors); the task is\n // already done, so a write miss is logged and ignored.\n if (finalText.trim()) {\n const fact =\n `Task \"${target.title}\" (${target.id}) completed. ` +\n `Outcome: ${finalText.trim().slice(0, 600)}` +\n (lastCommitHash ? ` [commit ${lastCommitHash}]` : '');\n const wrote = await mesh.writePrivateKnowledge([\n { content: fact, type: 'task-outcome', tags: ['task-outcome', identity.handle] },\n ]);\n log({ ev: wrote ? 'knowledge-write' : 'knowledge-write-skip', taskId: target.id });\n }\n\n return {\n action: 'executed',\n taskId: target.id,\n spentUsd: cost.spentUsd,\n remainingUsd: cost.remainingUsd,\n };\n }\n\n async runForever(opts: { tickIntervalMs?: number } = {}): Promise<void> {\n const interval = opts.tickIntervalMs ?? 60_000;\n while (!this.stopped) {\n try {\n await this.tick();\n } catch (err) {\n const log = this.opts.logger ?? (() => undefined);\n log({ ev: 'tick-error', message: err instanceof Error ? err.message : String(err) });\n }\n await sleep(interval + jitter(interval));\n }\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n /**\n * Heartbeat with one-shot self-rejoin on 403 \"Not a member of this team\".\n *\n * Pairs with task_1777112258989_eeyp: fresh-deploy fleet workers whose\n * provisioning didn't atomically call /join (or whose membership was\n * reaped) hit 403 every tick and never recover. We detect the specific\n * server error string (see packages/mcp-server/src/holomesh/routes/\n * team-routes.ts:903 → `{ error: 'Not a member' }` for /presence), call\n * mesh.joinTeam() ONCE per runner process, and retry the heartbeat.\n *\n * Strict scope:\n * - Only retries on 403 + \"Not a member\" body. Any other 403 (insufficient\n * permissions, signing failure) re-throws unchanged.\n * - Only retries ONCE per process. If we already rejoined this process and\n * the heartbeat is *still* 403, the team is rejecting us for a reason\n * /join can't fix (e.g. capacity, ban) — surface the error.\n * - If joinTeam() itself throws, we DO mark joinedThisProcess=true before\n * re-throwing so we don't slam the join endpoint on every subsequent\n * tick. The next tick will surface the same heartbeat 403 and the\n * runner-level catch in runForever logs tick-error and sleeps. Operator\n * inspection (SSH/log) is the recovery path at that point.\n */\n private async heartbeatWithAutoRejoin(): Promise<void> {\n const { identity, brain, mesh, logger } = this.opts;\n const log = logger ?? (() => undefined);\n const capabilityTags = brain.capabilityTags.length > 0 ? brain.capabilityTags : undefined;\n try {\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface, capabilityTags });\n } catch (err) {\n if (!this.isNotAMemberError(err) || this.joinedThisProcess) {\n throw err;\n }\n log({ ev: 'auto-rejoin-attempt', reason: 'heartbeat-403-not-a-member' });\n // Mark BEFORE the join call so a thrown joinTeam() can't loop us.\n this.joinedThisProcess = true;\n try {\n const joinResult = await mesh.joinTeam();\n log({ ev: 'auto-rejoin-success', role: joinResult.role, members: joinResult.members });\n } catch (joinErr) {\n log({\n ev: 'auto-rejoin-failed',\n message: joinErr instanceof Error ? joinErr.message : String(joinErr),\n });\n throw joinErr;\n }\n // Retry the heartbeat exactly once. If it still fails (including with\n // another 403), the new error propagates — joinedThisProcess is now\n // true so we won't retry-loop on the next tick.\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface, capabilityTags });\n log({ ev: 'auto-rejoin-heartbeat-recovered' });\n }\n }\n\n /**\n * Detect the server's \"Not a member\" 403 error from HolomeshClient.req().\n * The error message format is: `HoloMesh POST /team/<id>/presence 403: <body>`\n * where body contains `{\"error\":\"Not a member\"}` (or \"Not a member of this team\").\n * Match conservatively: BOTH a \"403\" status marker AND the \"Not a member\"\n * substring must appear, so unrelated 403s (insufficient permissions,\n * signing failures) do NOT trigger a rejoin.\n */\n private isNotAMemberError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return / 403:/.test(msg) && /Not a member/i.test(msg);\n }\n}\n\nfunction buildTaskPrompt(task: BoardTask): string {\n return [\n `Board task to execute: ${task.id}`,\n `Title: ${task.title}`,\n `Priority: ${task.priority}`,\n `Tags: ${(task.tags ?? []).join(', ')}`,\n '',\n 'Description:',\n task.description ?? '(no description)',\n '',\n 'Produce the deliverable: call write_file (or bash with a build command) to create all required output files FIRST. Apply your brain composition rules — anti-patterns, decision loop, and scope tier all bind. After calling the tool(s), return a short plain-text summary of what you did for posting to /room.',\n ].join('\\n');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction jitter(base: number): number {\n return Math.floor((Math.random() - 0.5) * base * 0.2);\n}\n","import { readFile, appendFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { BoardTask } from './types.js';\nimport type { CaelAuditRecord } from './cael-builder.js';\n\n/** Wraps a request body in a signed envelope for strict-mode endpoints (e.g. /team/:id/join). */\nexport type RequestSigner = (\n body: Record<string, unknown>\n) => Promise<Record<string, unknown>>;\n\nexport interface HolomeshClientOptions {\n apiBase: string;\n bearer: string;\n teamId: string;\n fetchImpl?: typeof fetch;\n /** EIP-191 signing function. When present, used on strict endpoints like joinTeam(). */\n signer?: RequestSigner;\n /**\n * Local JSONL path for private knowledge (sovereign edge store).\n * When set, writePrivateKnowledge appends to this file and queryPrivateKnowledge\n * reads from it instead of routing through the remote orchestrator.\n * Bypasses the mcp-orchestrator /knowledge/sync 401 gap for edge nodes.\n * Set via HOLOSCRIPT_AGENT_LOCAL_KNOWLEDGE_PATH env var (index.ts).\n */\n localKnowledgePath?: string;\n}\n\nexport interface TeamMessage {\n id: string;\n fromAgentId: string;\n fromAgentName: string;\n content: string;\n messageType: string;\n createdAt: string;\n}\n\n/** Minimal knowledge-entry shape returned by the mesh knowledge endpoints. */\nexport interface KnowledgeEntry {\n id: string;\n content: string;\n domain?: string;\n type?: string;\n createdAt?: string;\n}\n\nexport class HolomeshClient {\n private readonly apiBase: string;\n private readonly bearer: string;\n private readonly teamId: string;\n private readonly fetchImpl: typeof fetch;\n private readonly signer?: RequestSigner;\n private readonly localKnowledgePath?: string;\n\n constructor(opts: HolomeshClientOptions) {\n this.apiBase = opts.apiBase.replace(/\\/$/, '');\n this.bearer = opts.bearer;\n this.teamId = opts.teamId;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.signer = opts.signer;\n this.localKnowledgePath = opts.localKnowledgePath;\n }\n\n /** Wrap body in a signed envelope when a signer is available (strict-mode endpoints). */\n private async signBody(body: Record<string, unknown>): Promise<Record<string, unknown>> {\n return this.signer ? await this.signer(body) : body;\n }\n\n async heartbeat(payload: { agentName: string; surface: string; capabilityTags?: string[] }): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/presence`, await this.signBody(payload as Record<string, unknown>));\n }\n\n async getOpenTasks(): Promise<BoardTask[]> {\n const data = await this.req<{ tasks?: BoardTask[]; open?: BoardTask[] }>(\n 'GET',\n `/team/${this.teamId}/board`\n );\n return data.tasks ?? data.open ?? [];\n }\n\n async claim(taskId: string): Promise<BoardTask> {\n return this.req<BoardTask>('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'claim' }));\n }\n\n async joinTeam(): Promise<{ success: boolean; role?: string; members?: number }> {\n return this.req<{ success: boolean; role?: string; members?: number }>(\n 'POST',\n `/team/${this.teamId}/join`,\n await this.signBody({})\n );\n }\n\n async sendMessageOnTask(taskId: string, body: string): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, await this.signBody({\n to: 'team',\n subject: `task:${taskId}`,\n content: body,\n }));\n }\n\n async markDone(taskId: string, summary: string, commitHash?: string): Promise<void> {\n await this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({\n action: 'done',\n summary,\n // verification_evidence required by server before task can be closed.\n verification_evidence: summary,\n // Exclude commitHash when undefined — JSON.stringify drops undefined but\n // canonicalizeSigning preserves it as the literal string \"undefined\",\n // causing a signature-mismatch vs what the server sees after JSON.parse.\n ...(commitHash !== undefined ? { commitHash } : {}),\n }));\n }\n\n // POST CAEL audit records for this agent. Server validator at\n // packages/mcp-server/src/holomesh/routes/core-routes.ts:472-533 requires\n // bearer == handle owner OR founder; the per-surface x402 bearer is the\n // handle owner so this resolves correctly. Records that fail shape\n // validation (layer_hashes != 7 elements, missing tick_iso/operation/\n // fnv1a_chain) are silently dropped server-side, not rejected as a batch.\n async postAuditRecords(\n handle: string,\n records: CaelAuditRecord[]\n ): Promise<{ appended: number; rejected: number }> {\n // Audit endpoint uses bearer-only auth — no signed envelope wrapper.\n return this.req<{ appended: number; rejected: number }>(\n 'POST',\n `/agent/${encodeURIComponent(handle)}/audit`,\n { records } as unknown as Record<string, unknown>\n );\n }\n\n async whoAmI(): Promise<{ agentId: string; surface: string; wallet?: string }> {\n // GET /api/holomesh/me returns { agentId, name, wallet, isFounder, teamId, teams, permissions }\n // (see packages/mcp-server/src/holomesh/routes/core-routes.ts §/me handler).\n // It does NOT return a `surface` field — derive it from the seat name on the\n // client side. Seat naming convention (set by the provisioning admin path):\n // claudecode-claude-x402 → claude-code\n // cursor-claude-x402 → claude-cursor\n // gemini-antigravity → gemini-antigravity\n // copilot-vscode → copilot-vscode\n // Founder → unknown (shared key, no surface attribution)\n const raw = await this.req<{\n agentId: string;\n name?: string;\n wallet?: string;\n }>('GET', '/me');\n return {\n agentId: raw.agentId,\n surface: deriveSurface(raw.name),\n wallet: raw.wallet,\n };\n }\n\n // ── Team Message Surface (E4 delegated-authority protocol) ───────────────────\n\n /** Read recent team messages. */\n async getTeamMessages(limit = 20): Promise<TeamMessage[]> {\n const data = await this.req<{ messages?: TeamMessage[]; success?: boolean }>(\n 'GET',\n `/team/${this.teamId}/messages?limit=${limit}`\n );\n return data.messages ?? [];\n }\n\n /** Post a message to the team feed. */\n async sendTeamMessage(content: string, messageType = 'text'): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, await this.signBody({ content, type: messageType }));\n }\n\n // ── Owner-op API wrappers (E4) ─────────────────────────────────────────────\n\n /** Switch team mode. Requires owner or founder role. */\n async setTeamMode(mode: string, reason?: string): Promise<{ mode: string; unchanged?: boolean }> {\n return this.req('POST', `/team/${this.teamId}/mode`, await this.signBody({ mode, reason } as Record<string, unknown>));\n }\n\n /** Update room preferences. Requires config:write permission. */\n async patchRoomPrefs(prefs: { communicationStyle?: string; objective?: string }): Promise<{\n communicationStyle: string;\n objective: string;\n }> {\n return this.req('PATCH', `/team/${this.teamId}/room`, await this.signBody(prefs as Record<string, unknown>));\n }\n\n /** Update a board task. */\n async updateTask(\n taskId: string,\n updates: {\n title?: string;\n description?: string;\n priority?: number;\n tags?: string[];\n }\n ): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'update', ...updates } as Record<string, unknown>));\n }\n\n /** Delete a board task. */\n async deleteTask(taskId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'delete' }));\n }\n\n /** Delegate a board task to another agent. */\n async delegateTask(taskId: string, toAgentId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, await this.signBody({ action: 'delegate', toAgentId }));\n }\n\n /** Add new tasks to the board (used by the delegate_task tool to spawn sub-work). */\n async addTasks(\n tasks: Array<{ title: string; description?: string; priority?: number; source?: string; role?: string; tags?: string[] }>\n ): Promise<{ added: number }> {\n const result = await this.req<{ added?: number }>('POST', `/team/${this.teamId}/board`, await this.signBody({ tasks } as Record<string, unknown>));\n return { added: result.added ?? tasks.length };\n }\n\n // ── Cognitive-verb knowledge surface (Phase 2.2 — recall / rag_query) ────────\n\n /**\n * Query the TEAM knowledge base (the `rag_query` cognitive verb). Bearer-only\n * GET; `q` is the server-side search filter. Returns [] on any failure so a\n * retrieval miss never breaks a tick.\n */\n async queryTeamKnowledge(query: string, limit = 5): Promise<KnowledgeEntry[]> {\n const qs = new URLSearchParams({ q: query, limit: String(limit) }).toString();\n try {\n const data = await this.req<{ entries?: KnowledgeEntry[] }>(\n 'GET',\n `/team/${this.teamId}/knowledge?${qs}`\n );\n return data.entries ?? [];\n } catch {\n return [];\n }\n }\n\n /**\n * Query this agent's PRIVATE workspace knowledge (the `recall` cognitive verb).\n * The endpoint has no server-side search param, so the caller filters by query\n * client-side. Returns [] on any failure.\n */\n async queryPrivateKnowledge(): Promise<KnowledgeEntry[]> {\n if (this.localKnowledgePath) {\n try {\n const raw = await readFile(this.localKnowledgePath, 'utf8');\n return raw.trim().split('\\n').filter(Boolean).map(l => JSON.parse(l) as KnowledgeEntry);\n } catch {\n return [];\n }\n }\n try {\n const data = await this.req<{ entries?: KnowledgeEntry[] }>('GET', `/knowledge/private`);\n return data.entries ?? [];\n } catch {\n return [];\n }\n }\n\n /**\n * Persist facts to this agent's PRIVATE workspace — the WRITE side of `recall`\n * (POST /knowledge/private). The server stamps id / workspaceId (`private:<wallet>`)\n * / author / timestamps; the caller supplies `content` (+ optional type/tags/title).\n * This is what gives `recall` something to recall: without it the private store\n * stays empty and every `recall` returns [] (the W.752 loop-gap). Best-effort —\n * returns false on any failure so a write miss never breaks a tick (the task is\n * already done by the time this runs).\n */\n /**\n * Query the server-side in-process codebase GraphRAG index via the mesh bearer-gated\n * route (POST /api/holomesh/codebase/search). Called by the `rag_query` cognitive verb\n * (Phase 2.3 W.753) so edge agents can reach HoloEmbed semantic search without a direct\n * Absorb-service dep. Returns [] (not an error) when the graph isn't loaded yet — the\n * caller falls back to team-knowledge search.\n *\n * @param query Natural-language search string.\n * @param topK Max results to return (1–20, server-capped).\n */\n async queryCodebase(query: string, topK = 8): Promise<Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>> {\n try {\n const data = await this.req<{\n success?: boolean;\n result?: {\n results?: Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>;\n error?: string;\n };\n error?: string;\n }>('POST', `/codebase/search`, { query, topK });\n if (data.error || data.result?.error) return [];\n return data.result?.results ?? [];\n } catch {\n return [];\n }\n }\n\n async writePrivateKnowledge(\n entries: Array<{ content: string; type?: string; tags?: string[]; title?: string }>\n ): Promise<boolean> {\n if (!entries.length) return false;\n if (this.localKnowledgePath) {\n try {\n await mkdir(dirname(this.localKnowledgePath), { recursive: true });\n const lines = entries.map(e => JSON.stringify({\n id: `local.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`,\n content: e.content,\n type: e.type ?? 'task-outcome',\n tags: e.tags ?? [],\n title: e.title,\n createdAt: new Date().toISOString(),\n })).join('\\n') + '\\n';\n await appendFile(this.localKnowledgePath, lines, 'utf8');\n return true;\n } catch {\n return false;\n }\n }\n try {\n await this.req('POST', `/knowledge/private`, { entries });\n return true;\n } catch {\n return false;\n }\n }\n\n private async req<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.apiBase}${path}`;\n // HoloMesh REST auth: server (packages/mcp-server/src/holomesh/auth-utils.ts\n // resolveRequestingAgent) accepts EITHER `Authorization: Bearer <token>`\n // (HTTP-standard, used here) OR `x-mcp-api-key: <token>` (orchestrator\n // convention). Both resolve through the same key-registry / agent-store /\n // env-fallback chain. Bearer is preferred for new code (W.087 vertex B,\n // task_1777073616424_klls).\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.bearer}`,\n 'content-type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const txt = await res.text().catch(() => '');\n throw new Error(`HoloMesh ${method} ${path} ${res.status}: ${txt.slice(0, 300)}`);\n }\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n\n/**\n * Derive a surface tag from a seat name returned by /me. Mirrors the surface\n * detection in scripts/probe-surface-bearers.mjs and hooks/lib/holomesh-env.mjs\n * so a single agent's surface attribution is consistent across read and write\n * paths. Returns 'unknown' when the seat name doesn't encode a surface\n * (e.g. shared-key resolution to \"Founder\").\n */\nexport function deriveSurface(seatName: string | undefined): string {\n if (!seatName) return 'unknown';\n const n = seatName.toLowerCase();\n if (n.startsWith('claudecode')) return 'claude-code';\n if (n.startsWith('cursor')) return 'claude-cursor';\n if (n.startsWith('claudedesktop')) return 'claude-desktop';\n if (n.startsWith('vscode-claude') || n.startsWith('claude-vscode')) return 'claude-vscode';\n if (n.startsWith('gemini')) return 'gemini-antigravity';\n if (n.startsWith('copilot')) return 'copilot-vscode';\n return 'unknown';\n}\n\nexport function pickClaimableTask(\n tasks: BoardTask[],\n brainCapabilityTags: string[]\n): BoardTask | undefined {\n const wanted = new Set(brainCapabilityTags.map((t) => t.toLowerCase()));\n const open = tasks.filter((t) => t.status === 'open' && !t.claimedBy);\n const scored = open\n .map((t) => ({ task: t, score: scoreTask(t, wanted) }))\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score || priority(a.task) - priority(b.task));\n return scored[0]?.task;\n}\n\nfunction scoreTask(task: BoardTask, wanted: Set<string>): number {\n const tags = (task.tags ?? []).map((t) => t.toLowerCase());\n const text = `${task.title} ${task.description ?? ''}`.toLowerCase();\n let score = 0;\n for (const tag of tags) if (wanted.has(tag)) score += 2;\n for (const w of wanted) if (text.includes(w)) score += 1;\n return score;\n}\n\nfunction priority(t: BoardTask): number {\n if (typeof t.priority === 'number') return t.priority;\n const map: Record<string, number> = { critical: 1, high: 2, medium: 4, low: 6 };\n return map[String(t.priority).toLowerCase()] ?? 5;\n}\n","// CAEL audit record builder for the headless agent runtime.\n//\n// Phase 1: agent ticks emit a CaelAuditRecord shaped to satisfy the\n// HoloMesh audit endpoint validator at packages/mcp-server/src/holomesh/\n// routes/core-routes.ts:512-518 (7-element layer_hashes array, string\n// tick_iso/operation/fnv1a_chain). The 7 layers map to concrete tick\n// stages so a downstream consumer can verify any one layer in isolation:\n//\n// L0 brain_state — sha256(brain.systemPrompt)\n// L1 tick_input — sha256(taskId|title|description)\n// L2 messages — sha256(JSON of final message thread)\n// L3 response — sha256(finalText)\n// L4 usage — sha256(JSON of aggregated TokenUsage)\n// L5 cost — sha256(costUsd|spentUsd)\n// L6 composite — sha256(L0|L1|L2|L3|L4|L5)\n//\n// fnv1a_chain extends across records: chain_n = sha256(chain_{n-1} | L6_n).\n// First tick emits prev_hash=null; subsequent ticks chain from the\n// previous record's fnv1a_chain.\n\nimport { createHash } from 'node:crypto';\nimport type { LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport type { AgentIdentity, BoardTask, ExecutionResult, RuntimeBrainConfig } from './types.js';\n\nexport interface CaelAuditRecord {\n tick_iso: string;\n layer_hashes: string[];\n operation: string;\n prev_hash: string | null;\n fnv1a_chain: string;\n version_vector_fingerprint: string;\n brain_class?: string;\n trial?: number;\n attack_class?: string;\n defense_state?: string;\n /**\n * Trust-epoch tag for downstream consumers (Paper 25 gate clock,\n * fleet-health drift detector, retroactive corpus filters). Set to\n * `'post-w107'` for any record built after the 2026-04-26 W.107\n * artifact-grounding gate landed (HoloScript commit 4aab897ad). Records\n * without this field — i.e. anything in the audit store before the gate\n * was deployed — are implicitly `'pre-w107-untrusted'`. The mesh-worker-02\n * 27.5h hallucination class (fabricated \"100 scenes validated\" CAEL\n * records with no actual artifact) all live in the implicit-untrusted\n * cohort. Consumers should filter by `trust_epoch === 'post-w107'`\n * before treating CAEL records as evidence of real work.\n */\n trust_epoch?: 'post-w107';\n}\n\nexport interface BuildCaelRecordInput {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n task: BoardTask;\n messages: LLMMessage[];\n finalText: string;\n usage: TokenUsage;\n costUsd: number;\n spentUsd: number;\n prevChain: string | null;\n runtimeVersion: string;\n}\n\nfunction sha(input: string): string {\n return createHash('sha256').update(input, 'utf8').digest('hex');\n}\n\n/**\n * Extract the brain class from a runtime brain config. Tries multiple sources\n * because brainPath shape varies across deployment environments:\n * 1. compositions/<class>-brain.hsplus (canonical layout — caught 2026-04-24)\n * 2. <anything>/<class>-brain.hsplus (loose match — Vast.ai box layout)\n * 3. <class>-brain.hsplus basename only\n * 4. brain.domain (loaded from .hsplus identity block by loadBrain())\n * 5. 'unknown' if all sources fail\n *\n * Live evidence (2026-04-25 mesh-worker-01 record): the strict regex returned\n * 'unknown' against the production worker box's brainPath, leaving every CAEL\n * fingerprint useless for fleet attribution. This loosened version recovers\n * brain class even when path layout drifts from the compositions/-rooted form.\n */\nfunction brainClassOf(brain: { brainPath?: string; domain?: string }): string {\n const p = String(brain.brainPath ?? '');\n // Tier 1: canonical compositions/-rooted layout.\n let m = p.match(/compositions[\\\\/]([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 2: any path with `<class>-brain.hsplus` basename.\n m = p.match(/([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 3: bare basename.\n m = p.match(/([\\w-]+)\\.hsplus$/);\n if (m) return m[1];\n // Tier 4: domain field from the loaded brain composition's identity block.\n const domain = String(brain.domain ?? '').trim();\n if (domain && domain !== 'unknown') return domain;\n return 'unknown';\n}\n\nexport function buildCaelRecord(input: BuildCaelRecordInput): CaelAuditRecord {\n const {\n identity,\n brain,\n task,\n messages,\n finalText,\n usage,\n costUsd,\n spentUsd,\n prevChain,\n runtimeVersion,\n } = input;\n\n const l0 = sha(brain.systemPrompt);\n const l1 = sha(`${task.id}|${task.title}|${task.description ?? ''}`);\n const l2 = sha(JSON.stringify(messages));\n const l3 = sha(finalText);\n const l4 = sha(JSON.stringify(usage));\n const l5 = sha(`${costUsd.toFixed(6)}|${spentUsd.toFixed(6)}`);\n const l6 = sha([l0, l1, l2, l3, l4, l5].join('|'));\n\n const fnv1a_chain = sha(`${prevChain ?? ''}|${l6}`);\n\n return {\n tick_iso: new Date().toISOString(),\n layer_hashes: [l0, l1, l2, l3, l4, l5, l6],\n operation: `task-executed:${task.id}`,\n prev_hash: prevChain,\n fnv1a_chain,\n version_vector_fingerprint: `agent@${runtimeVersion}|brain@${brainClassOf(brain)}|provider@${identity.llmProvider}|model@${identity.llmModel}`,\n brain_class: brainClassOf(brain),\n trust_epoch: 'post-w107',\n };\n}\n","/**\n * Tool runner for headless mesh agents.\n *\n * Provides a small, sandboxed set of tools that LLM agents can call during\n * task execution. Anthropic tool-use shape — these specs are passed to\n * `messages.stream({ tools: [...] })`, the model returns `tool_use` blocks,\n * the runner executes them via `runTool()` and feeds results back as\n * `tool_result` blocks until the model emits its final text response.\n *\n * Sandbox model:\n * - read_file / list_dir: restricted to ALLOWED_READ_ROOTS (task inputs +\n * read-only views of the cloned repo). No /etc, no /home, no /root/.ssh.\n * - write_file: restricted to ALLOWED_WRITE_ROOTS (just /root/agent-output/).\n * Creates dir if needed, refuses paths that escape via .. or symlinks.\n * - bash: ONLY whitelisted command prefixes (lake build, lean ..., ls, cat,\n * grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter,\n * vitest run --no-coverage). Hard 60s wall timeout, 1MB stdout cap. Refuses\n * anything else (rm, curl, ssh, sudo, eval, etc.).\n * - http_request: HTTPS GET only, 30s timeout, 200KB cap. Private IP ranges\n * (RFC-1918/loopback/link-local) are blocked to prevent SSRF against the\n * host network. Read-only — does not count as a productive tool call.\n *\n * The sandbox is best-effort host isolation — these instances are dedicated\n * to a single mesh-worker identity, so we trade some flexibility for a clear\n * \"what the LLM can do\" contract that audits cleanly.\n */\n\nimport { readFile, writeFile, readdir, mkdir, stat } from 'node:fs/promises';\nimport { resolve, dirname, delimiter, isAbsolute, sep } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport type { ToolSpec, ToolUseBlock, ToolResultBlock } from '@holoscript/llm-provider';\n\n// ---------------------------------------------------------------------------\n// Sandbox roots — keep narrow. Add only when a task needs more.\n//\n// Env-overridable so the SAME runner serves both deployments:\n// - Vast fleet instance: the /root/* defaults below (clone + scp layout).\n// - Local node (laptop / Jetson): point at the local checkout + a local\n// output dir via HOLOSCRIPT_AGENT_READ_ROOTS / _WRITE_ROOTS.\n// Format: OS-path-separator-delimited list (':' on POSIX, ';' on Windows) —\n// e.g. HOLOSCRIPT_AGENT_READ_ROOTS=\"/home/user/HoloScript:/home/user/agent-output\".\n// Unset → fleet defaults (no behavior change on the existing workers).\n// ---------------------------------------------------------------------------\nconst FLEET_READ_ROOTS = [\n '/root/msc-paper-22', // Paper 22 mechanization inputs (scp'd by deploy)\n '/root/holoscript-mesh', // Read-only repo view (clone path on instance)\n '/root/agent-output', // Read back what we wrote\n];\n\nconst FLEET_WRITE_ROOTS = [\n '/root/agent-output', // Single write sink — keeps deliverables in one place\n];\n\nfunction parseRootsEnv(raw: string | undefined, fallback: string[]): string[] {\n if (!raw) return fallback;\n const roots = raw\n .split(delimiter)\n .map((r) => r.trim())\n .filter((r) => r.length > 0 && isAbsolute(r));\n return roots.length > 0 ? roots : fallback;\n}\n\nconst ALLOWED_READ_ROOTS = parseRootsEnv(\n process.env.HOLOSCRIPT_AGENT_READ_ROOTS,\n FLEET_READ_ROOTS,\n);\n\nconst ALLOWED_WRITE_ROOTS = parseRootsEnv(\n process.env.HOLOSCRIPT_AGENT_WRITE_ROOTS,\n FLEET_WRITE_ROOTS,\n);\n\n// Command-prefix whitelist. Prefix-match is intentional — `lake build MSC`\n// matches `lake build`, `pnpm --filter @holoscript/core build` matches\n// `pnpm --filter`, etc. Refuses anything else (no sudo, rm, curl, ssh, eval).\n//\n// Two-tier classification (W.107 tightening 2026-04-26):\n// READ_ONLY — observation-only commands. Pass execution policy, but do\n// NOT count as artifact-producing for the W.107 gate.\n// PRODUCTIVE — commands that build, test, or otherwise produce a real\n// artifact (compile output, test result, etc.). DO count as\n// artifact-producing for the W.107 gate.\n//\n// Pre-tightening, the gate accepted ANY bash call as side-effecting — so\n// `bash echo done` would falsely pass the gate. Now `echo` is read-only and\n// the worker must call something productive (lake build / pnpm --filter\n// build / vitest run / lean compile / etc.) to claim `executed`.\nconst BASH_READ_ONLY_PREFIXES = [\n 'ls ',\n 'ls\\n',\n 'ls$',\n 'cat ',\n 'grep ',\n 'rg ',\n 'find ',\n 'wc ',\n 'head ',\n 'tail ',\n 'git status',\n 'git log',\n 'git diff',\n 'git show',\n 'pwd',\n 'echo ',\n 'lake env',\n];\n\nconst BASH_PRODUCTIVE_PREFIXES = [\n 'lake build',\n 'lake clean',\n 'lean ',\n 'pnpm --filter',\n 'pnpm vitest',\n 'vitest run',\n // Robotics / edge-node (Jetson) productive commands — without these, every\n // ros2/colcon/tegrastats task fails the W.107 artifact gate and is abandoned\n // as no-artifact. (jetson-orin-01 lane.)\n 'ros2 launch',\n 'ros2 topic pub',\n 'ros2 service call',\n 'colcon build',\n 'tegrastats',\n];\n\nconst BASH_WHITELIST = [...BASH_READ_ONLY_PREFIXES, ...BASH_PRODUCTIVE_PREFIXES];\n\n/**\n * Returns true iff `cmd` matches a productive prefix — i.e. would produce a\n * real artifact (compile/test/build output) rather than just observing state.\n * Used by the W.107 artifact-grounding gate in runner.ts.\n */\nexport function isProductiveBashCommand(cmd: string): boolean {\n const trimmed = String(cmd ?? '').trim();\n if (!trimmed) return false;\n return BASH_PRODUCTIVE_PREFIXES.some((prefix) => trimmed.startsWith(prefix.trim()));\n}\n\n/**\n * True iff a single tool_use is a *productive* (artifact-producing) call for the\n * W.107.b artifact-grounding gate:\n * - write_file with non-empty content,\n * - bash with a productive prefix (isProductiveBashCommand),\n * - emit_hardware_receipt (always writes a receipt file).\n * read_file / list_dir and read-only / trivial bash are NOT productive.\n *\n * This is the SINGLE SOURCE OF TRUTH the runner's gate (runner.ts) and the\n * artifact-gate ablation harness both consume — so the measured gate can never\n * drift from the shipped gate (the ablation measures the real thing, not a copy).\n */\nexport function isProductiveToolUse(use: ToolUseBlock): boolean {\n const input = (use.input ?? {}) as Record<string, unknown>;\n switch (use.name) {\n case 'write_file':\n return String(input.content ?? '').length > 0;\n case 'bash':\n return isProductiveBashCommand(String(input.cmd ?? ''));\n case 'emit_hardware_receipt':\n return true;\n case 'str_replace':\n return true;\n case 'vision_analyze':\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Accumulate the productive-call count + the tool names seen across one model\n * turn's tool_use blocks. The runner adds `names` to its toolsCalled set and\n * `productiveCount` to its gate counter.\n */\nexport function summarizeToolProductivity(uses: readonly ToolUseBlock[]): {\n productiveCount: number;\n names: string[];\n} {\n let productiveCount = 0;\n const names: string[] = [];\n for (const u of uses) {\n names.push(u.name);\n if (isProductiveToolUse(u)) productiveCount++;\n }\n return { productiveCount, names };\n}\n\n// ---------------------------------------------------------------------------\n// Tool specs surfaced to the LLM\n// ---------------------------------------------------------------------------\nexport const MESH_TOOLS: ToolSpec[] = [\n {\n name: 'read_file',\n description:\n `Read a file from the agent sandbox. Allowed roots: ${ALLOWED_READ_ROOTS.join(', ')}. ` +\n 'Returns the file content as text. Use this to inspect task inputs and the ' +\n 'read-only repo view.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'list_dir',\n description:\n 'List entries in a directory under the agent sandbox. Same root restrictions ' +\n 'as read_file. Returns a newline-separated list of entries.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'write_file',\n description:\n `Write a file to the deliverable sink (write roots: ${ALLOWED_WRITE_ROOTS.join(', ')}). ` +\n 'Anything you want to emit as task output (a Lean proof, a markdown report, a JSON ' +\n 'dataset, a .holo scene) goes here. Creates parent directories. Will refuse paths ' +\n 'outside the write root(s).',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: `Absolute path under a write root: ${ALLOWED_WRITE_ROOTS.join(', ')}` },\n content: { type: 'string', description: 'File content to write (UTF-8)' },\n },\n required: ['path', 'content'],\n },\n },\n {\n name: 'bash',\n description:\n 'Run a shell command. Whitelisted prefixes only: lake build, lean, ls, cat, ' +\n 'grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter, vitest run, ' +\n 'pwd, echo, ros2 launch/topic/service, colcon build, tegrastats. ' +\n 'Hard 60s wall timeout, 1MB stdout cap. Use for builds, tests, hardware probes. ' +\n 'Refuses rm, curl, ssh, sudo, eval.',\n input_schema: {\n type: 'object',\n properties: {\n cmd: { type: 'string', description: 'Whitelisted shell command' },\n cwd: { type: 'string', description: 'Optional working directory (defaults to /root)' },\n },\n required: ['cmd'],\n },\n },\n {\n name: 'http_request',\n description:\n 'HTTPS GET a public URL and return the response body as text. ' +\n 'HTTPS only — http:// and private IPs (RFC-1918, loopback, link-local) are blocked. ' +\n '200KB cap, 30s timeout. Read-only: does not satisfy the write_file artifact gate.',\n input_schema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'https:// URL to fetch' },\n headers: {\n type: 'object',\n description: 'Optional request headers (e.g. {\"Accept\": \"application/json\"})',\n },\n },\n required: ['url'],\n },\n },\n {\n name: 'emit_hardware_receipt',\n description:\n 'Emit a portable hardware receipt (PortableHardwareReceiptMetadata v1) capturing ' +\n 'device identity, runtime, and measured performance. Writes a JSON receipt to the ' +\n 'agent output dir. Use after running tegrastats or colcon build to record hardware ' +\n 'evidence for the CAEL audit chain. Accepts either pre-parsed measurements or raw ' +\n 'tegrastats output (the tool parses it automatically).',\n input_schema: {\n type: 'object',\n properties: {\n device_kind: {\n type: 'string',\n description: 'Device identifier, e.g. \"jetson-orin-nano-super\", \"raspberry-pi-5\"',\n },\n accelerator: {\n description: 'Accelerator string, e.g. \"NVIDIA CUDA 8.7\", or null for CPU-only',\n },\n runtime_name: { type: 'string', description: 'Inference runtime, e.g. \"Ollama\", \"llama.cpp\"' },\n runtime_version: { type: 'string', description: 'Runtime version, e.g. \"0.30.8\"' },\n host_os: { type: 'string', description: 'OS + firmware, e.g. \"JetPack 6.2.1 / Ubuntu 22.04\"' },\n composition_id: { type: 'string', description: 'Brain composition reference, e.g. \"jetson-orin-brain\"' },\n measurements: {\n type: 'array',\n description: 'Pre-parsed measurements. Each item: {metric: string, value: number, unit: string}',\n items: { type: 'object' },\n },\n tegrastats_output: {\n type: 'string',\n description: 'Raw tegrastats output line(s) — tool auto-parses GPU%, RAM, temp, power',\n },\n },\n required: ['device_kind', 'runtime_name', 'runtime_version', 'host_os'],\n },\n },\n {\n name: 'str_replace',\n description:\n 'Surgical in-place edit of a file: find an exact string and replace it. ' +\n 'The old string must appear exactly once in the file — if it appears zero or more than once ' +\n 'the tool returns an error with the actual count, letting you refine the search string. ' +\n 'Only files under the write root(s) can be edited. ' +\n 'Counts as a productive tool call (equivalent to write_file).',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: `Absolute path under a write root: ${ALLOWED_WRITE_ROOTS.join(', ')}` },\n old: { type: 'string', description: 'Exact string to find (must occur exactly once)' },\n new: { type: 'string', description: 'Replacement string' },\n },\n required: ['path', 'old', 'new'],\n },\n },\n {\n name: 'delegate_task',\n description:\n 'Post a new task to the team board so another agent can claim and execute it. ' +\n 'Use this to spawn sub-work the current agent cannot or should not do itself ' +\n '(e.g. a vision task for jetson-orin-fara, a cloud compute task for the fleet). ' +\n 'The task appears on the shared board and is claimed by the first agent with matching capability tags.',\n input_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Task title (max 200 chars)' },\n description: { type: 'string', description: 'Detailed task description (max 2000 chars)' },\n priority: { type: 'number', description: 'Priority 1-10 (1 = critical, default 5)' },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Capability tags for routing to the right agent, e.g. [\"vision\",\"edge\"]',\n },\n source: { type: 'string', description: 'Where this subtask came from (e.g. parent task id)' },\n },\n required: ['title'],\n },\n },\n {\n name: 'vision_analyze',\n description:\n 'Analyze an image using the local Fara-7B vision model (Ollama on loopback). ' +\n 'Reads the image file at `image_path` (max 512KB — downscale larger images first), ' +\n 'sends it to the vision model via the local Ollama API (env: HOLOSCRIPT_AGENT_VISION_MODEL), ' +\n 'and returns the model\\'s text analysis. ' +\n 'Counts as a productive tool call — use for GUI-grounding, visual QA, image captioning, ' +\n 'or any task that requires perceiving image content. ' +\n 'Only available on surfaces with a local Ollama instance and HOLOSCRIPT_AGENT_LOCAL_LLM_BASE_URL set.',\n input_schema: {\n type: 'object',\n properties: {\n image_path: {\n type: 'string',\n description: 'Absolute path to the image file (png, jpg, webp) — must be under 512KB',\n },\n prompt: {\n type: 'string',\n description: 'Instruction for the vision model (default: \"Describe this image in detail.\")',\n },\n model: {\n type: 'string',\n description: 'Ollama model tag override (default: HOLOSCRIPT_AGENT_VISION_MODEL env var)',\n },\n },\n required: ['image_path'],\n },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Active-tool resolution (F.126 #1 — author behavior as DATA the runtime consumes)\n// ---------------------------------------------------------------------------\n/**\n * Assemble the tool set the model sees from the brain's OWN DECLARATION — the\n * `behavior on_task { llm_call { tools: [...] } }` array — instead of a hardcoded\n * list. This is principle #1 of the native doctrine (F.126): the runtime consumes\n * the brain's authored capability set, so \"add a tool\" becomes \"declare it in the\n * brain,\" not \"edit this TypeScript.\" Fixes the dead-data bug where every brain's\n * declared tools were ignored and local-llm brains were amputated to write_file-only.\n *\n * - Declared names are resolved against the available specs; an unknown name is\n * dropped (the runner logs it) so a typo can't crash the loop.\n * - A brain that declares NO tools falls back to the prior safe default\n * (write_file-only for small local-llm models — the artifact-grounding floor;\n * full menu otherwise) so this is backward-compatible.\n * - W.710 progressive disclosure: a small local model can overflow its num_ctx\n * output budget reasoning over a big menu before it emits a tool call, so a\n * declared set larger than the budget is SLIM-trimmed (write_file kept first)\n * for local-llm brains. Budget via HOLOSCRIPT_AGENT_TOOL_BUDGET (default 6).\n */\nexport function resolveActiveTools(\n brain: { requires: string[]; onTaskActions?: Array<{ verb: string; config?: Record<string, unknown> }> },\n opts: { all?: ToolSpec[]; isLocal?: boolean; budget?: number } = {}\n): { tools: ToolSpec[]; declared: string[]; dropped: string[] } {\n const all = opts.all ?? MESH_TOOLS;\n const isLocal = opts.isLocal ?? brain.requires.includes('local-llm');\n const budget = opts.budget ?? (Number(process.env.HOLOSCRIPT_AGENT_TOOL_BUDGET) || 6);\n\n const declaredRaw = brain.onTaskActions?.find((a) => a.verb === 'llm_call')?.config?.tools;\n const declared = Array.isArray(declaredRaw)\n ? declaredRaw.filter((n): n is string => typeof n === 'string')\n : [];\n\n if (declared.length === 0) {\n // No declaration → prior safe default (backward-compatible).\n const fallback = isLocal ? all.filter((t) => t.name === 'write_file') : all;\n return { tools: fallback, declared: [], dropped: [] };\n }\n\n const dropped = declared.filter((n) => !all.some((t) => t.name === n));\n let resolved = declared\n .map((n) => all.find((t) => t.name === n))\n .filter((t): t is ToolSpec => Boolean(t));\n if (resolved.length === 0) resolved = all.filter((t) => t.name === 'write_file'); // never hand the model an empty toolset\n\n // num_ctx guard for small models: trim a large declared set, keeping write_file (grounding) first.\n if (isLocal && resolved.length > budget) {\n const wf = resolved.filter((t) => t.name === 'write_file');\n const rest = resolved.filter((t) => t.name !== 'write_file');\n resolved = [...wf, ...rest].slice(0, budget);\n }\n return { tools: resolved, declared, dropped };\n}\n\n// ---------------------------------------------------------------------------\n// SSRF guard — block private/loopback/link-local hosts (RFC-1918 + RFC-5735)\n// ---------------------------------------------------------------------------\nconst PRIVATE_IP_RE =\n /^(127\\.|10\\.|192\\.168\\.|172\\.(1[6-9]|2\\d|3[01])\\.|169\\.254\\.|0\\.|::1$|fc[0-9a-f]{2}:|fd[0-9a-f]{2}:)/i;\n\nfunction checkHttpAllowed(rawUrl: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n return `invalid URL: \"${rawUrl}\"`;\n }\n if (parsed.protocol !== 'https:') {\n return `only https:// is allowed, got \"${parsed.protocol}\"`;\n }\n const host = parsed.hostname.toLowerCase();\n if (host === 'localhost' || PRIVATE_IP_RE.test(host)) {\n return `host \"${host}\" is a private/loopback address — blocked to prevent SSRF`;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Path-sandbox helpers\n// ---------------------------------------------------------------------------\nfunction isUnderRoot(absPath: string, root: string): boolean {\n const resolved = resolve(absPath);\n const rootResolved = resolve(root);\n return resolved === rootResolved || resolved.startsWith(rootResolved + sep);\n}\n\nfunction checkReadAllowed(path: string): string | null {\n if (!isAbsolute(path)) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_READ_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `read denied — path \"${path}\" not under allowed roots: ${ALLOWED_READ_ROOTS.join(', ')}`;\n}\n\nfunction checkWriteAllowed(path: string): string | null {\n if (!isAbsolute(path)) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_WRITE_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `write denied — path \"${path}\" not under allowed roots: ${ALLOWED_WRITE_ROOTS.join(', ')}`;\n}\n\nfunction checkBashAllowed(cmd: string): string | null {\n const trimmed = cmd.trim();\n if (trimmed.length === 0) return 'empty command';\n // Reject obvious shell-injection attempts. Whitelist below still applies.\n if (/[;&|`$<>]|>>|\\|\\||&&/.test(trimmed)) {\n return `command contains shell metachars (; & | \\` $ < > >> || &&) — not allowed for safety`;\n }\n for (const prefix of BASH_WHITELIST) {\n if (trimmed.startsWith(prefix.trim())) return null;\n }\n return `command not on whitelist. Allowed prefixes: ${BASH_WHITELIST.join(' / ')}`;\n}\n\n// ---------------------------------------------------------------------------\n// Tool implementations\n// ---------------------------------------------------------------------------\n/** Optional capabilities the caller (runner) can inject into a tool run. */\nexport interface RunToolOptions {\n /**\n * Sign a hardware receipt's canonical body. Injected by index.ts from the seat\n * wallet (ethers EIP-191). Absent → the receipt is content-hashed but unsigned\n * and self-reports `signed:false`, so it can never overclaim.\n */\n signReceipt?: (canonical: string) => Promise<{ alg: string; signer: string; signature: string }>;\n /**\n * Post new tasks to the team board. Injected by runner.ts from mesh.addTasks().\n * Absent → delegate_task returns an error explaining the capability is unavailable.\n */\n addTask?: (tasks: Array<{ title: string; description?: string; priority?: number; source?: string; tags?: string[] }>) => Promise<{ added: number }>;\n}\n\nexport async function runTool(use: ToolUseBlock, opts: RunToolOptions = {}): Promise<ToolResultBlock> {\n try {\n if (use.name === 'read_file') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const text = await readFile(path, 'utf8');\n // Cap at 200KB to avoid context blowups\n const truncated =\n text.length > 200_000\n ? text.slice(0, 200_000) + `\\n…[truncated, full file is ${text.length} bytes]`\n : text;\n return okResult(use.id, truncated);\n }\n\n if (use.name === 'list_dir') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const entries = await readdir(path, { withFileTypes: true });\n const lines = entries.map((e) => `${e.isDirectory() ? 'd' : '-'} ${e.name}`);\n return okResult(use.id, lines.join('\\n'));\n }\n\n if (use.name === 'write_file') {\n const path = use.input.path as string;\n const content = use.input.content as string;\n const denied = checkWriteAllowed(path);\n if (denied) return errResult(use.id, denied);\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n const s = await stat(path);\n return okResult(use.id, `wrote ${s.size} bytes to ${path}`);\n }\n\n if (use.name === 'bash') {\n const cmd = use.input.cmd as string;\n const cwd = (use.input.cwd as string | undefined) ?? '/root';\n const denied = checkBashAllowed(cmd);\n if (denied) return errResult(use.id, denied);\n const result = await runBash(cmd, cwd);\n return result.code === 0\n ? okResult(use.id, result.stdout)\n : errResult(use.id, `exit=${result.code}\\n${result.stderr || result.stdout}`);\n }\n\n if (use.name === 'http_request') {\n const rawUrl = String(use.input.url ?? '');\n const denied = checkHttpAllowed(rawUrl);\n if (denied) return errResult(use.id, denied);\n const userHeaders = (use.input.headers ?? {}) as Record<string, string>;\n const RESPONSE_CAP = 200_000;\n const TIMEOUT_MS = 30_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);\n try {\n const res = await fetch(rawUrl, {\n method: 'GET',\n headers: { 'user-agent': 'holoscript-agent/1.0', ...userHeaders },\n signal: controller.signal,\n });\n clearTimeout(timer);\n const buf = await res.arrayBuffer();\n const text = new TextDecoder('utf-8', { fatal: false }).decode(buf);\n const truncated =\n text.length > RESPONSE_CAP\n ? text.slice(0, RESPONSE_CAP) + `\\n…[truncated, full body is ${text.length} chars]`\n : text;\n if (!res.ok) return errResult(use.id, `HTTP ${res.status} ${res.statusText}\\n${truncated}`);\n return okResult(use.id, truncated);\n } catch (err) {\n clearTimeout(timer);\n const msg = err instanceof Error ? err.message : String(err);\n return errResult(use.id, msg.includes('abort') ? `request timed out after ${TIMEOUT_MS}ms` : msg);\n }\n }\n\n if (use.name === 'emit_hardware_receipt') {\n const deviceKind = String(use.input.device_kind ?? 'unknown-device');\n const accelerator =\n use.input.accelerator === null || use.input.accelerator === 'null'\n ? null\n : String(use.input.accelerator ?? '').trim() || null;\n const runtimeName = String(use.input.runtime_name ?? 'Ollama');\n const runtimeVersion = String(use.input.runtime_version ?? 'unknown');\n const hostOs = String(use.input.host_os ?? 'unknown');\n const compositionId = String(use.input.composition_id ?? 'unknown');\n\n // Collect measurements — from pre-parsed array and/or raw tegrastats output.\n let measurements: Array<{ metric: string; value: number; unit: string; method: string }> = [];\n if (Array.isArray(use.input.measurements)) {\n for (const m of use.input.measurements as Array<Record<string, unknown>>) {\n const metric = String(m.metric ?? '');\n const value = Number(m.value ?? 0);\n const unit = String(m.unit ?? '');\n if (metric && Number.isFinite(value)) {\n measurements.push({ metric, value, unit, method: 'measured' });\n }\n }\n }\n if (typeof use.input.tegrastats_output === 'string' && use.input.tegrastats_output.length > 0) {\n measurements = [...measurements, ...parseTegrastats(use.input.tegrastats_output as string)];\n }\n // Minimum 1 measurement so the schema validator doesn't reject the receipt.\n if (measurements.length === 0) {\n measurements.push({ metric: 'agent-tick', value: 1, unit: 'count', method: 'presence' });\n }\n\n const capturedAt = new Date().toISOString();\n const receipt = {\n schemaVersion: 'holoscript.hardware-receipt-metadata.v1',\n target: {\n id: `${deviceKind}-${Date.now()}`,\n kind: deviceKind,\n architecture: /jetson|orin|nano|agx|xavier/i.test(deviceKind) ? 'arm64' : 'unknown',\n artifactKind: 'measurement-trace',\n },\n device: {\n vendor: /jetson|orin|nvidia/i.test(deviceKind) ? 'nvidia' : 'unknown',\n model: deviceKind,\n accelerator,\n },\n runtime: { name: runtimeName, version: runtimeVersion, hostOS: hostOs },\n compilerVersion: 'holoscript-agent-1.0.0',\n constraints: [],\n measuredResults: measurements,\n replayInputs: [\n { kind: 'composition-ref', uri: `compositions/${compositionId}`, sha256: 'unknown' },\n ],\n provenance: {\n capturedAt,\n sourceCompositionHash: compositionId,\n },\n owner: {\n agent: process.env.HOLOSCRIPT_AGENT_HANDLE ?? 'unknown',\n ...(process.env.HOLOMESH_TEAM_ID ? { team: process.env.HOLOMESH_TEAM_ID } : {}),\n },\n };\n\n // Integrity seal (F.123 — a tamper-evident, not plain-JSON, receipt):\n // a deterministic SHA-256 content hash over the canonical body (keyless\n // content-addressing) plus an OPTIONAL wallet signature when a signer is\n // injected (index.ts wires the seat wallet). `signed` self-reports honestly\n // so an unsigned receipt can never masquerade as signed.\n const canonical = JSON.stringify(receipt);\n const contentHash = createHash('sha256').update(canonical).digest('hex');\n let signature: { alg: string; signer: string; signature: string } | null = null;\n if (opts.signReceipt) {\n try {\n signature = await opts.signReceipt(canonical);\n } catch {\n signature = null; // best-effort: an unsigned receipt is honest, not fatal\n }\n }\n const sealed = {\n ...receipt,\n integrity: { alg: 'sha256', contentHash, signed: Boolean(signature), signature },\n };\n\n // Slug timestamp: \"2026-06-16T07-35-01-000Z\"\n const ts = capturedAt.replace(/[:.]/g, '-');\n const outPath = resolve(ALLOWED_WRITE_ROOTS[0], `hardware-receipt-${ts}.json`);\n const denied = checkWriteAllowed(outPath);\n if (denied) return errResult(use.id, `Cannot write receipt: ${denied}`);\n await mkdir(dirname(outPath), { recursive: true });\n await writeFile(outPath, JSON.stringify(sealed, null, 2), 'utf8');\n return okResult(\n use.id,\n `Hardware receipt written to ${outPath} — ${measurements.length} measurements, ` +\n `contentHash=${contentHash.slice(0, 12)}…, signed=${Boolean(signature)}, accelerator=${accelerator ?? 'none'}`\n );\n }\n\n if (use.name === 'str_replace') {\n const path = use.input.path as string;\n const oldStr = use.input.old as string;\n const newStr = use.input.new as string;\n const denied = checkWriteAllowed(path);\n if (denied) return errResult(use.id, denied);\n const text = await readFile(path, 'utf8');\n // Count occurrences to guarantee exactly-one semantics.\n const count = text.split(oldStr).length - 1;\n if (count === 0) return errResult(use.id, `str_replace: \"old\" string not found in ${path} — 0 occurrences`);\n if (count > 1) return errResult(use.id, `str_replace: \"old\" string is ambiguous in ${path} — ${count} occurrences; add more surrounding context`);\n const updated = text.replace(oldStr, newStr);\n await writeFile(path, updated, 'utf8');\n const s = await stat(path);\n return okResult(use.id, `str_replace: replaced 1 occurrence in ${path} (${s.size} bytes)`);\n }\n\n if (use.name === 'delegate_task') {\n if (!opts.addTask) {\n return errResult(use.id, 'delegate_task: capability not available (no addTask callback injected — board posting requires a mesh connection)');\n }\n const title = String(use.input.title ?? '').trim();\n if (!title) return errResult(use.id, 'delegate_task: title is required');\n const description = use.input.description != null ? String(use.input.description) : undefined;\n const priority = use.input.priority != null ? Number(use.input.priority) : undefined;\n const source = use.input.source != null ? String(use.input.source) : undefined;\n const tags = Array.isArray(use.input.tags) ? (use.input.tags as unknown[]).map(String) : undefined;\n const result = await opts.addTask([{ title, description, priority, source, tags }]);\n return okResult(use.id, `delegate_task: posted \"${title}\" to board — ${result.added} task(s) added`);\n }\n\n if (use.name === 'vision_analyze') {\n const imagePath = String(use.input.image_path ?? '').trim();\n if (!imagePath) return errResult(use.id, 'vision_analyze: image_path is required');\n const denied = checkReadAllowed(imagePath);\n if (denied) return errResult(use.id, `vision_analyze: ${denied}`);\n const prompt = String(use.input.prompt ?? 'Describe this image in detail.');\n // Model: task can override via `model` param; env HOLOSCRIPT_AGENT_VISION_MODEL\n // is the surface default (set to the full Ollama tag on the device).\n const model = String(\n use.input.model ?? process.env.HOLOSCRIPT_AGENT_VISION_MODEL ?? 'fara:7b'\n );\n // Dedicated local-inference tool — /founder ruled 2026-06-18: NOT a bandaid.\n // SSRF guard in http_request is correct and stays; this tool is a different\n // trust boundary (fixed local model endpoint, path-sandboxed input, env-driven\n // URL — no user-controlled URL). D.098 + vision pillar #6.\n const ollamaBase = process.env.HOLOSCRIPT_AGENT_LOCAL_LLM_BASE_URL;\n if (!ollamaBase) {\n return errResult(\n use.id,\n 'vision_analyze: HOLOSCRIPT_AGENT_LOCAL_LLM_BASE_URL is not set — configure it to point to your local Ollama instance'\n );\n }\n const MAX_IMAGE_BYTES = 512_000; // ~512KB — larger images must be downscaled before passing to vision_analyze\n const TIMEOUT_MS = 120_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);\n try {\n const imageBytes = await readFile(imagePath);\n if (imageBytes.length > MAX_IMAGE_BYTES) {\n clearTimeout(timer);\n return errResult(\n use.id,\n `vision_analyze: image is ${Math.round(imageBytes.length / 1024)}KB — exceeds ${MAX_IMAGE_BYTES / 1024}KB limit. ` +\n 'Downscale the image first (e.g. to 256×256 or smaller) then retry vision_analyze.'\n );\n }\n const imageB64 = imageBytes.toString('base64');\n const res = await fetch(`${ollamaBase}/api/generate`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ model, prompt, images: [imageB64], stream: false }),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (!res.ok) {\n const text = await res.text();\n return errResult(use.id, `vision_analyze: Ollama HTTP ${res.status}: ${text.slice(0, 500)}`);\n }\n const json = (await res.json()) as { response?: string; error?: string };\n if (json.error) return errResult(use.id, `vision_analyze: model error — ${json.error}`);\n return okResult(use.id, json.response ?? '');\n } catch (err) {\n clearTimeout(timer);\n const msg = err instanceof Error ? err.message : String(err);\n return errResult(\n use.id,\n msg.includes('abort') ? `vision_analyze: timed out after ${TIMEOUT_MS}ms` : `vision_analyze: ${msg}`\n );\n }\n }\n\n return errResult(use.id, `unknown tool: ${use.name}`);\n } catch (err) {\n return errResult(use.id, err instanceof Error ? err.message : String(err));\n }\n}\n\n/**\n * Parse a single tegrastats output line into structured measurements.\n * Handles the Jetson Orin / Nano / AGX format emitted by `tegrastats --interval 1000`.\n *\n * Example line:\n * 06-16-2026 07:35:01 RAM 2819/7618MB (lfb 73x4MB) SWAP 0/3809MB CPU [37%@1510,off,off]\n * EMC_FREQ 0% GR3D_FREQ 42% cpu@40.2C tj@41.25C VDD_CPU_CV 570mW VDD_SOC 1380mW\n */\nfunction parseTegrastats(raw: string): Array<{ metric: string; value: number; unit: string; method: string }> {\n const results: Array<{ metric: string; value: number; unit: string; method: string }> = [];\n const m = (pattern: RegExp, metric: string, unit: string, transform?: (v: string) => number) => {\n const match = raw.match(pattern);\n if (match?.[1]) {\n const value = transform ? transform(match[1]) : Number(match[1]);\n if (Number.isFinite(value)) results.push({ metric, value, unit, method: 'tegrastats' });\n }\n };\n\n // RAM: \"RAM 2819/7618MB\"\n const ram = raw.match(/RAM\\s+(\\d+)\\/(\\d+)MB/);\n if (ram) {\n const used = Number(ram[1]);\n const total = Number(ram[2]);\n results.push({ metric: 'ram-used', value: used, unit: 'MB', method: 'tegrastats' });\n results.push({ metric: 'ram-total', value: total, unit: 'MB', method: 'tegrastats' });\n if (total > 0)\n results.push({ metric: 'ram-pct', value: Math.round((used / total) * 100), unit: '%', method: 'tegrastats' });\n }\n\n m(/GR3D_FREQ\\s+(\\d+)%/, 'gpu-util', '%');\n m(/EMC_FREQ\\s+(\\d+)%/, 'emc-freq-pct', '%');\n m(/tj@([\\d.]+)C/, 'temp-tj', 'C', parseFloat);\n m(/cpu@([\\d.]+)C/, 'temp-cpu', 'C', parseFloat);\n m(/gpu@([\\d.]+)C/, 'temp-gpu', 'C', parseFloat);\n m(/VDD_SOC\\s+(\\d+)mW/, 'power-soc', 'mW');\n m(/VDD_CPU_CV\\s+(\\d+)mW/, 'power-cpu-cv', 'mW');\n m(/VDD_IN\\s+(\\d+)mW/, 'power-total', 'mW');\n\n // CPU first-core utilisation: \"CPU [37%@1510,...\"\n m(/CPU\\s+\\[(\\d+)%/, 'cpu-util-core0', '%');\n\n return results;\n}\n\ninterface BashResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runBash(cmd: string, cwd: string): Promise<BashResult> {\n // Test short-circuit (task_1778113854009_x6p3): under vitest, return a\n // fast synthetic exit instead of spawning bash. Without this, mocks that\n // emit a \"vitest run\" tool_use cause runner.test.ts to recursively spawn\n // vitest startup per tick (~1.7s each), pushing 3-tick tests over the\n // 5000ms timeout. Production paths (NODE_ENV != 'test', VITEST unset)\n // are unchanged and still spawn the real shell.\n if (process.env.VITEST === 'true' || process.env.NODE_ENV === 'test') {\n return Promise.resolve({\n code: 0,\n stdout: `[mock-bash under vitest] cmd=\"${cmd}\" cwd=\"${cwd}\"`,\n stderr: '',\n });\n }\n return new Promise((resolveProm) => {\n const child = spawn('bash', ['-c', cmd], { cwd, env: process.env });\n let stdout = '';\n let stderr = '';\n let killed = false;\n const STDOUT_CAP = 1_000_000;\n const TIMEOUT_MS = 60_000;\n const killer = setTimeout(() => {\n killed = true;\n child.kill('SIGKILL');\n }, TIMEOUT_MS);\n child.stdout.on('data', (d: Buffer) => {\n if (stdout.length < STDOUT_CAP) stdout += d.toString('utf8');\n });\n child.stderr.on('data', (d: Buffer) => {\n if (stderr.length < STDOUT_CAP) stderr += d.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(killer);\n resolveProm({ code: 1, stdout, stderr: stderr + '\\nspawn-error: ' + err.message });\n });\n child.on('exit', (code) => {\n clearTimeout(killer);\n const finalStdout =\n stdout.length >= STDOUT_CAP\n ? stdout + `\\n…[stdout truncated at ${STDOUT_CAP} bytes]`\n : stdout;\n const note = killed ? `\\n[bash killed after ${TIMEOUT_MS}ms timeout]` : '';\n resolveProm({ code: code ?? 1, stdout: finalStdout + note, stderr });\n });\n });\n}\n\nfunction okResult(id: string, content: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content };\n}\n\nfunction errResult(id: string, message: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content: message, is_error: true };\n}\n","/**\n * On-task cognitive verbs — the edge executor (Phase 2.2).\n *\n * A brain's `behavior on_task { … }` block parses into an ordered sequence of\n * cognitive verbs (brain.ts extractOnTaskActions). The lightweight AgentRunner\n * executes them WITHOUT a @holoscript/core / engine dependency — provider + mesh\n * only — so the edge package keeps its clean publish dep-closure:\n *\n * - `llm_call { prompt }` → append the prompt as a domain directive (was the\n * only wired verb before this; W.736).\n * - `rag_query { query }` → retrieve from TEAM knowledge → inject as context.\n * - `recall { query }` → retrieve from the agent's PRIVATE workspace →\n * filter by query client-side → inject.\n * - `plan { goal|prompt }` → one provider call producing a short plan → inject.\n *\n * Each verb is best-effort: a retrieval/plan failure is logged and skipped, never\n * breaking the tick. The verbs run in authored order and their outputs accumulate\n * onto the system prompt the tool-loop sees. `reflect` is handled separately\n * (post-artifact gate in runner.ts), not here.\n *\n * @module holoscript-agent/cognitive-verbs\n */\nimport type { KnowledgeEntry } from './holomesh-client.js';\nimport type { OnTaskAction } from './types.js';\n\nexport interface CognitiveVerbDeps {\n /** The brain's base system prompt to augment. */\n systemPrompt: string;\n /** Parsed `behavior on_task` verbs, in authored order. */\n onTaskActions: OnTaskAction[];\n /** Task being executed (for `plan` goal fallback + logging). */\n task: { id: string; title: string };\n /** TEAM knowledge retrieval (rag_query, keyword/semantic). */\n queryTeamKnowledge: (query: string, limit: number) => Promise<KnowledgeEntry[]>;\n /**\n * Codebase GraphRAG semantic search (rag_query Phase 2.3, W.753).\n * Optional — when absent OR it returns [] (graph not loaded), rag_query falls\n * back to team-knowledge search. Wires the in-process HoloEmbed index via the\n * bearer-gated mesh route POST /api/holomesh/codebase/search.\n */\n queryCodebase?: (query: string, topK: number) => Promise<Array<{ name: string; file: string; line?: number; type: string; score: number; signature?: string | null }>>;\n /** PRIVATE workspace retrieval (recall). */\n queryPrivateKnowledge: () => Promise<KnowledgeEntry[]>;\n /** One-shot provider planner (plan). Optional — when absent, `plan` is skipped. */\n plan?: (prompt: string) => Promise<string>;\n /**\n * Embed text for SEMANTIC `recall` (the fleet nomic model). Optional — when absent\n * OR it returns null (no fleet/registry reachable), `recall` falls back to the\n * substring filter. Pairs with `similarity`. (W.753: recall should rank via the\n * semantic stack, not keyword-match the private workspace.)\n */\n embed?: (text: string) => Promise<number[] | null>;\n /** Cosine similarity for ranking recalled entries (required alongside `embed`). */\n similarity?: (a: number[], b: number[]) => number;\n /** Structured logger. */\n log: (ev: Record<string, unknown>) => void;\n}\n\nconst DEFAULT_LIMIT = 5;\n/** Cap injected context so the edge model's num_ctx isn't blown (qwen3:4b). */\nconst MAX_ENTRY_CHARS = 320;\nconst MAX_INJECTED_CHARS = 2400;\n/** Cap entries embedded per recall so a large private store can't stall a tick. */\nconst MAX_RECALL_EMBED = 40;\n\nfunction strField(config: Record<string, unknown>, ...keys: string[]): string {\n for (const k of keys) {\n const v = config[k];\n if (typeof v === 'string' && v.trim()) return v.trim();\n }\n return '';\n}\n\nfunction numField(config: Record<string, unknown>, key: string, fallback: number): number {\n const v = config[key];\n return typeof v === 'number' && Number.isFinite(v) ? v : fallback;\n}\n\nfunction formatEntries(entries: KnowledgeEntry[]): string {\n let out = '';\n for (const e of entries) {\n const line = `- ${(e.content ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_ENTRY_CHARS)}`;\n if (out.length + line.length > MAX_INJECTED_CHARS) break;\n out += (out ? '\\n' : '') + line;\n }\n return out;\n}\n\n/**\n * Execute a brain's on_task cognitive verbs and return the augmented system\n * prompt the tool-loop should use. Pure-ish: all I/O is injected via deps.\n */\nexport async function augmentWithOnTaskCognition(deps: CognitiveVerbDeps): Promise<string> {\n let content = deps.systemPrompt;\n if (!deps.onTaskActions || deps.onTaskActions.length === 0) return content;\n\n for (const action of deps.onTaskActions) {\n try {\n switch (action.verb) {\n case 'llm_call': {\n const prompt = strField(action.config, 'prompt');\n if (prompt) {\n content += `\\n\\n[Brain on_task directive]\\n${prompt}`;\n deps.log({ ev: 'on-task-llm-call', taskId: deps.task.id, promptLen: prompt.length });\n }\n break;\n }\n case 'rag_query': {\n const query = strField(action.config, 'query', 'q') || deps.task.title;\n const limit = numField(action.config, 'limit', DEFAULT_LIMIT);\n // Phase 2.3 (W.753): try codebase GraphRAG (in-process HoloEmbed via the mesh bearer\n // route) first — returns ranked symbols (name/file/score). Falls back to team-knowledge\n // search when the graph isn't loaded or the dep isn't wired.\n let mode = 'team-knowledge';\n let injected = '';\n if (deps.queryCodebase) {\n const symbols = await deps.queryCodebase(query, limit);\n if (symbols.length > 0) {\n mode = 'codebase-graphrag';\n const lines = symbols\n .slice(0, limit)\n .map(\n (s) =>\n `- ${s.name} (${s.type}) ${s.file}${s.line != null ? `:${s.line}` : ''}` +\n (s.signature ? ` — ${s.signature.slice(0, 80)}` : '') +\n ` [score:${s.score.toFixed(2)}]`\n )\n .join('\\n');\n injected = `\\n\\n[Codebase search for \"${query}\"]\\n${lines}`;\n }\n }\n if (!injected) {\n // Fallback: team knowledge store (already semantic via HoloEmbed ranking, bb28ecc25).\n const entries = await deps.queryTeamKnowledge(query, limit);\n if (entries.length > 0) {\n injected = `\\n\\n[Retrieved knowledge for \"${query}\"]\\n${formatEntries(entries)}`;\n }\n }\n if (injected) content += injected;\n deps.log({ ev: 'on-task-rag-query', taskId: deps.task.id, query, mode, retrieved: injected ? limit : 0 });\n break;\n }\n case 'recall': {\n const query = strField(action.config, 'query', 'q');\n const limit = numField(action.config, 'limit', DEFAULT_LIMIT);\n const all = await deps.queryPrivateKnowledge();\n let matched: KnowledgeEntry[] | null = null;\n let mode = 'substring';\n // SEMANTIC recall (W.753): rank the private workspace by embedding-cosine\n // when an embed route resolves. Best-effort — any miss (no embed dep, fleet\n // unreachable, null vectors) drops to the substring filter below; never breaks the tick.\n if (deps.embed && deps.similarity && query && all.length > 0) {\n const qv = await deps.embed(query);\n if (qv) {\n const scored: Array<{ e: KnowledgeEntry; score: number }> = [];\n for (const e of all.slice(0, MAX_RECALL_EMBED)) {\n const ev = await deps.embed(e.content ?? '');\n if (ev) scored.push({ e, score: deps.similarity(qv, ev) });\n }\n if (scored.length > 0) {\n scored.sort((a, b) => b.score - a.score);\n matched = scored.slice(0, limit).map((s) => s.e);\n mode = 'semantic';\n }\n }\n }\n if (!matched) {\n const needle = query.toLowerCase();\n matched = (\n needle\n ? all.filter((e) => `${e.id ?? ''} ${e.content ?? ''}`.toLowerCase().includes(needle))\n : all\n ).slice(0, limit);\n }\n if (matched.length > 0) {\n content += `\\n\\n[Recalled memory${query ? ` for \"${query}\"` : ''}]\\n${formatEntries(matched)}`;\n }\n deps.log({ ev: 'on-task-recall', taskId: deps.task.id, query, recalled: matched.length, mode });\n break;\n }\n case 'plan': {\n if (!deps.plan) break;\n const goal = strField(action.config, 'goal', 'prompt', 'of') || deps.task.title;\n const planText = await deps.plan(\n `Produce a short numbered plan (max 6 steps) to accomplish this task. Be concrete and specific to the goal; do not execute it.\\n\\nGoal: ${goal}`\n );\n const trimmed = planText.trim().slice(0, MAX_INJECTED_CHARS);\n if (trimmed) {\n content += `\\n\\n[Plan]\\n${trimmed}`;\n deps.log({ ev: 'on-task-plan', taskId: deps.task.id, planLen: trimmed.length });\n }\n break;\n }\n // `reflect` is handled post-artifact in runner.ts, not here.\n default:\n break;\n }\n } catch (err) {\n deps.log({\n ev: 'on-task-verb-error',\n taskId: deps.task.id,\n verb: action.verb,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return content;\n}\n"],"mappings":";AACA,SAAS,kBAAkB,wBAAwB;;;ACDnD,SAAS,UAAU,YAAY,aAAa;AAC5C,SAAS,eAAe;AA4WjB,SAAS,kBACd,OACA,qBACuB;AACvB,QAAM,SAAS,IAAI,IAAI,oBAAoB,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACtE,QAAM,OAAO,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,SAAS;AACpE,QAAM,SAAS,KACZ,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,UAAU,GAAG,MAAM,EAAE,EAAE,EACrD,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EACzB,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,SAAS,EAAE,IAAI,IAAI,SAAS,EAAE,IAAI,CAAC;AAC1E,SAAO,OAAO,CAAC,GAAG;AACpB;AAEA,SAAS,UAAU,MAAiB,QAA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