@holoscript/holoscript-agent 2.0.2 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/holoscript-agent.cjs +0 -0
- package/dist/brain.js +49 -1
- package/dist/brain.js.map +1 -1
- package/dist/holomesh-client.d.ts +21 -1
- package/dist/holomesh-client.js +31 -0
- package/dist/holomesh-client.js.map +1 -1
- package/dist/identity.js +2 -2
- package/dist/identity.js.map +1 -1
- package/dist/index.js +301 -24
- package/dist/index.js.map +1 -1
- package/dist/runner.js +119 -1
- package/dist/runner.js.map +1 -1
- package/dist/supervisor.js +199 -2
- package/dist/supervisor.js.map +1 -1
- package/dist/types.d.ts +16 -1
- package/package.json +11 -11
- package/LICENSE +0 -21
package/dist/runner.js
CHANGED
|
@@ -430,6 +430,109 @@ function errResult(id, message) {
|
|
|
430
430
|
return { type: "tool_result", tool_use_id: id, content: message, is_error: true };
|
|
431
431
|
}
|
|
432
432
|
|
|
433
|
+
// src/cognitive-verbs.ts
|
|
434
|
+
var DEFAULT_LIMIT = 5;
|
|
435
|
+
var MAX_ENTRY_CHARS = 320;
|
|
436
|
+
var MAX_INJECTED_CHARS = 2400;
|
|
437
|
+
function strField(config, ...keys) {
|
|
438
|
+
for (const k of keys) {
|
|
439
|
+
const v = config[k];
|
|
440
|
+
if (typeof v === "string" && v.trim()) return v.trim();
|
|
441
|
+
}
|
|
442
|
+
return "";
|
|
443
|
+
}
|
|
444
|
+
function numField(config, key, fallback) {
|
|
445
|
+
const v = config[key];
|
|
446
|
+
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
|
447
|
+
}
|
|
448
|
+
function formatEntries(entries) {
|
|
449
|
+
let out = "";
|
|
450
|
+
for (const e of entries) {
|
|
451
|
+
const line = `- ${(e.content ?? "").replace(/\s+/g, " ").trim().slice(0, MAX_ENTRY_CHARS)}`;
|
|
452
|
+
if (out.length + line.length > MAX_INJECTED_CHARS) break;
|
|
453
|
+
out += (out ? "\n" : "") + line;
|
|
454
|
+
}
|
|
455
|
+
return out;
|
|
456
|
+
}
|
|
457
|
+
async function augmentWithOnTaskCognition(deps) {
|
|
458
|
+
let content = deps.systemPrompt;
|
|
459
|
+
if (!deps.onTaskActions || deps.onTaskActions.length === 0) return content;
|
|
460
|
+
for (const action of deps.onTaskActions) {
|
|
461
|
+
try {
|
|
462
|
+
switch (action.verb) {
|
|
463
|
+
case "llm_call": {
|
|
464
|
+
const prompt = strField(action.config, "prompt");
|
|
465
|
+
if (prompt) {
|
|
466
|
+
content += `
|
|
467
|
+
|
|
468
|
+
[Brain on_task directive]
|
|
469
|
+
${prompt}`;
|
|
470
|
+
deps.log({ ev: "on-task-llm-call", taskId: deps.task.id, promptLen: prompt.length });
|
|
471
|
+
}
|
|
472
|
+
break;
|
|
473
|
+
}
|
|
474
|
+
case "rag_query": {
|
|
475
|
+
const query = strField(action.config, "query", "q") || deps.task.title;
|
|
476
|
+
const limit = numField(action.config, "limit", DEFAULT_LIMIT);
|
|
477
|
+
const entries = await deps.queryTeamKnowledge(query, limit);
|
|
478
|
+
if (entries.length > 0) {
|
|
479
|
+
content += `
|
|
480
|
+
|
|
481
|
+
[Retrieved knowledge for "${query}"]
|
|
482
|
+
${formatEntries(entries)}`;
|
|
483
|
+
}
|
|
484
|
+
deps.log({ ev: "on-task-rag-query", taskId: deps.task.id, query, retrieved: entries.length });
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case "recall": {
|
|
488
|
+
const query = strField(action.config, "query", "q");
|
|
489
|
+
const limit = numField(action.config, "limit", DEFAULT_LIMIT);
|
|
490
|
+
const all = await deps.queryPrivateKnowledge();
|
|
491
|
+
const needle = query.toLowerCase();
|
|
492
|
+
const matched = (needle ? all.filter((e) => `${e.id ?? ""} ${e.content ?? ""}`.toLowerCase().includes(needle)) : all).slice(0, limit);
|
|
493
|
+
if (matched.length > 0) {
|
|
494
|
+
content += `
|
|
495
|
+
|
|
496
|
+
[Recalled memory${query ? ` for "${query}"` : ""}]
|
|
497
|
+
${formatEntries(matched)}`;
|
|
498
|
+
}
|
|
499
|
+
deps.log({ ev: "on-task-recall", taskId: deps.task.id, query, recalled: matched.length });
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
case "plan": {
|
|
503
|
+
if (!deps.plan) break;
|
|
504
|
+
const goal = strField(action.config, "goal", "prompt", "of") || deps.task.title;
|
|
505
|
+
const planText = await deps.plan(
|
|
506
|
+
`Produce a short numbered plan (max 6 steps) to accomplish this task. Be concrete and specific to the goal; do not execute it.
|
|
507
|
+
|
|
508
|
+
Goal: ${goal}`
|
|
509
|
+
);
|
|
510
|
+
const trimmed = planText.trim().slice(0, MAX_INJECTED_CHARS);
|
|
511
|
+
if (trimmed) {
|
|
512
|
+
content += `
|
|
513
|
+
|
|
514
|
+
[Plan]
|
|
515
|
+
${trimmed}`;
|
|
516
|
+
deps.log({ ev: "on-task-plan", taskId: deps.task.id, planLen: trimmed.length });
|
|
517
|
+
}
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
// `reflect` is handled post-artifact in runner.ts, not here.
|
|
521
|
+
default:
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
} catch (err) {
|
|
525
|
+
deps.log({
|
|
526
|
+
ev: "on-task-verb-error",
|
|
527
|
+
taskId: deps.task.id,
|
|
528
|
+
verb: action.verb,
|
|
529
|
+
message: err instanceof Error ? err.message : String(err)
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return content;
|
|
534
|
+
}
|
|
535
|
+
|
|
433
536
|
// src/runner.ts
|
|
434
537
|
var RUNTIME_VERSION = "1.0.0";
|
|
435
538
|
var AgentRunner = class {
|
|
@@ -512,8 +615,23 @@ var AgentRunner = class {
|
|
|
512
615
|
log({ ev: "claim", taskId: target.id, title: target.title });
|
|
513
616
|
await mesh.claim(target.id);
|
|
514
617
|
const start = Date.now();
|
|
618
|
+
const systemContent = await augmentWithOnTaskCognition({
|
|
619
|
+
systemPrompt: brain.systemPrompt,
|
|
620
|
+
onTaskActions: brain.onTaskActions ?? [],
|
|
621
|
+
task: { id: target.id, title: target.title },
|
|
622
|
+
queryTeamKnowledge: (q, limit) => mesh.queryTeamKnowledge(q, limit),
|
|
623
|
+
queryPrivateKnowledge: () => mesh.queryPrivateKnowledge(),
|
|
624
|
+
plan: async (prompt) => {
|
|
625
|
+
const resp = await provider.complete(
|
|
626
|
+
{ messages: [{ role: "user", content: prompt }], maxTokens: 512, temperature: 0.3 },
|
|
627
|
+
identity.llmModel
|
|
628
|
+
);
|
|
629
|
+
return resp.content;
|
|
630
|
+
},
|
|
631
|
+
log
|
|
632
|
+
});
|
|
515
633
|
const messages = [
|
|
516
|
-
{ role: "system", content:
|
|
634
|
+
{ role: "system", content: systemContent },
|
|
517
635
|
{ role: "user", content: buildTaskPrompt(target) }
|
|
518
636
|
];
|
|
519
637
|
let aggUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
|
package/dist/runner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/holomesh-client.ts","../src/cael-builder.ts","../src/tools.ts","../src/runner.ts"],"sourcesContent":["import 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\nexport interface TeamMessage {\n id: string;\n fromAgentId: string;\n fromAgentName: string;\n content: string;\n messageType: 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\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 }\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 }): 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 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 *\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 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// 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: '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\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// ---------------------------------------------------------------------------\nexport async function runTool(use: ToolUseBlock): 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 === '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 // 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(receipt, null, 2), 'utf8');\n return okResult(\n use.id,\n `Hardware receipt written to ${outPath} — ${measurements.length} measurements, accelerator=${accelerator ?? 'none'}`\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","import type { ILLMProvider, LLMMessage, TokenUsage } 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 { MESH_TOOLS, runTool, isProductiveBashCommand } from './tools.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\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 const messages: LLMMessage[] = [\n { role: 'system', content: brain.systemPrompt },\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 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 // Local-LLM brains (qwen3:4b on Jetson) generate 3000+ thinking tokens\n // reasoning over a 5-tool menu — overflowing num_ctx output budget before\n // a tool call can be emitted. Limit to write_file only for local-llm brains:\n // it satisfies the artifact-grounding gate and keeps thinking under ~400 tokens.\n const activeTools = brain.requires.includes('local-llm')\n ? MESH_TOOLS.filter((t) => t.name === 'write_file')\n : MESH_TOOLS;\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 // Track tool names for the artifact-grounding gate.\n for (const u of resp.toolUses) {\n toolsCalled.add(u.name);\n // Productive-call accounting (W.107.b tighter gate).\n if (u.name === 'write_file') {\n const content = String((u.input as Record<string, unknown>)?.content ?? '');\n if (content.length > 0) productiveCallCount++;\n } else if (u.name === 'bash') {\n const cmd = String((u.input as Record<string, unknown>)?.cmd ?? '');\n if (isProductiveBashCommand(cmd)) productiveCallCount++;\n } else if (u.name === 'emit_hardware_receipt') {\n // Hardware receipt emission always produces a file artifact.\n productiveCallCount++;\n }\n }\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(resp.toolUses.map((u) => runTool(u)));\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 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 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, mesh, logger } = this.opts;\n const log = logger ?? (() => undefined);\n try {\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });\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 });\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"],"mappings":";AAqOO,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,C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AAW,SAAS,QAAQ,SAAS,SAAS,QAAQ,CAAC;AAC9E,UAAI,EAAE,IAAI,kCAAkC,CAAC;AAAA,IAC/C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,kBAAkB,KAAuB;AAC/C,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,WAAO,QAAQ,KAAK,GAAG,KAAK,gBAAgB,KAAK,GAAG;AAAA,EACtD;AACF;AAEA,SAAS,gBAAgB,MAAyB;AAChD,SAAO;AAAA,IACL,0BAA0B,KAAK,EAAE;AAAA,IACjC,UAAU,KAAK,KAAK;AAAA,IACpB,aAAa,KAAK,QAAQ;AAAA,IAC1B,UAAU,KAAK,QAAQ,CAAC,GAAG,KAAK,IAAI,CAAC;AAAA,IACrC;AAAA,IACA;AAAA,IACA,KAAK,eAAe;AAAA,IACpB;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAC7C;AAEA,SAAS,OAAO,MAAsB;AACpC,SAAO,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,OAAO,GAAG;AACtD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/holomesh-client.ts","../src/cael-builder.ts","../src/tools.ts","../src/cognitive-verbs.ts","../src/runner.ts"],"sourcesContent":["import 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\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\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 }\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 }): 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 // ── 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 try {\n const data = await this.req<{ entries?: KnowledgeEntry[] }>('GET', `/knowledge/private`);\n return data.entries ?? [];\n } catch {\n return [];\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 *\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 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// 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: '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\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// ---------------------------------------------------------------------------\nexport async function runTool(use: ToolUseBlock): 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 === '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 // 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(receipt, null, 2), 'utf8');\n return okResult(\n use.id,\n `Hardware receipt written to ${outPath} — ${measurements.length} measurements, accelerator=${accelerator ?? 'none'}`\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). */\n queryTeamKnowledge: (query: string, limit: number) => Promise<KnowledgeEntry[]>;\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 /** 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\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 const entries = await deps.queryTeamKnowledge(query, limit);\n if (entries.length > 0) {\n content += `\\n\\n[Retrieved knowledge for \"${query}\"]\\n${formatEntries(entries)}`;\n }\n deps.log({ ev: 'on-task-rag-query', taskId: deps.task.id, query, retrieved: entries.length });\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 const needle = query.toLowerCase();\n const matched = (\n needle\n ? all.filter((e) => `${e.id ?? ''} ${e.content ?? ''}`.toLowerCase().includes(needle))\n : all\n ).slice(0, limit);\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 });\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","import type { ILLMProvider, LLMMessage, TokenUsage } 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 { MESH_TOOLS, runTool, isProductiveBashCommand } 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\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 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 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 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 // Local-LLM brains (qwen3:4b on Jetson) generate 3000+ thinking tokens\n // reasoning over a 5-tool menu — overflowing num_ctx output budget before\n // a tool call can be emitted. Limit to write_file only for local-llm brains:\n // it satisfies the artifact-grounding gate and keeps thinking under ~400 tokens.\n const activeTools = brain.requires.includes('local-llm')\n ? MESH_TOOLS.filter((t) => t.name === 'write_file')\n : MESH_TOOLS;\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 // Track tool names for the artifact-grounding gate.\n for (const u of resp.toolUses) {\n toolsCalled.add(u.name);\n // Productive-call accounting (W.107.b tighter gate).\n if (u.name === 'write_file') {\n const content = String((u.input as Record<string, unknown>)?.content ?? '');\n if (content.length > 0) productiveCallCount++;\n } else if (u.name === 'bash') {\n const cmd = String((u.input as Record<string, unknown>)?.cmd ?? '');\n if (isProductiveBashCommand(cmd)) productiveCallCount++;\n } else if (u.name === 'emit_hardware_receipt') {\n // Hardware receipt emission always produces a file artifact.\n productiveCallCount++;\n }\n }\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(resp.toolUses.map((u) => runTool(u)));\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 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 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, mesh, logger } = this.opts;\n const log = logger ?? (() => undefined);\n try {\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });\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 });\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"],"mappings":";AAgRO,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;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