[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AW485S7N9W5SS5YWJDJK7F":3,"skill-same:01M7AW485S7N9W5SS5YWJDJK7F":64},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":6,"ownerDescription":28,"updatedAt":29,"install":30,"resources":43},"01M7AW485S7N9W5SS5YWJDJK7F","ts-agent-harness-constructor",null,"SpectreDeath\u002FBrain-Harness","SpectreDeath","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F207463416?v=4","01M7AVGR1D4X8ADT47APKGVH2Z","JL","01M7AVGR2HSGD23BA5DBTJJTVN",0,"MIT","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ts-agent-harness-constructor\ndescription: Construct, validate, and harden zero-dependency AI agent runtime harnesses in TypeScript\u002FNode.js: provider-agnostic loop, contract registry, workspace jail, atomic batch budgets, context windowing, and seeded failure testing. Do not use for harness selection, framework wrappers, or prompt-only scripts.\nversion: 1.0.0\ncategory: agent_orchestration\ntags:\n  - typescript\n  - agent_harness\n  - runtime_loop\n  - workspace_confinement\n  - tool_validation\n  - context_windowing\n  - failure_testing\nprovides:\n  - typescript_agent_harness_construction\n  - tool_contract_registry\n  - workspace_confinement_pattern\n  - agent_failure_testing\nrequires: []\n---\n\n# TypeScript Agent Harness Constructor (`ts-agent-harness-constructor`)\n\n## Scope & Architectural Seam\n\nThis skill provides an authoritative, zero-dependency engineering standard for constructing, validating, and hardening autonomous AI agent runtime harnesses in TypeScript and Node.js. It focuses on the core runtime mechanics: the ReAct agent loop, tool contract validation, filesystem sandboxing, command execution hardening, atomic batch budgeting, sliding context windowing, non-invasive telemetry, and seeded failure testing.\n\n> [!IMPORTANT]\n> **Cross-Reference Seam**: For harness architecture selection, 5-part comparative evaluation, and sandboxing governance, invoke upstream [agent-harness-architect](..\u002Fagent-harness-architect\u002FSKILL.md). Use `ts-agent-harness-constructor` strictly for **implementation, construction, and hardening** from first principles.\n\n---\n\n## Interactive Visual Brief\n\n> Note: the interactive visual brief for this workflow was rendered to a local temp file at generation time and is not shipped with the skill, so the original link (which pointed at a `file:\u002F\u002F\u002F` temp path) has been removed. The brief covered animated ReAct turn transitions, symlink walk diagrams, atomic batch budget timelines, and context window sliding group animations.\n\n---\n\n## The 6-Stage Operational Progression (\"Shu\" Stage)\n\nHarness construction follows a strict 6-stage linear progression where each stage introduces a distinct architectural boundary and failure mode isolation:\n\n```\n[1. Loop & Model Abstraction] ➔ [2. Contract Registry & Validation] ➔ [3. Workspace Containment & Presets]\n               ➔ [4. Execution Limits & Cancellation] ➔ [5. Atomic Context Windowing] ➔ [6. Telemetry, Evals & Adapters]\n```\n\n### Stage 1: Provider-Agnostic Loop & Model Abstraction\n\nThe core agent loop coordinates conversation state, dispatches model generations, routes tool calls, and handles cancellation.\n\n1. **Harness Entrypoint**: Implement `runAgent({ prompt, model, tools, signal, maxSteps })` as the single public entrypoint returning an immutable execution summary:\n   ```typescript\n   export interface RunResult {\n     status: 'completed' | 'step_limit' | 'tool_limit' | 'aborted' | 'model_error';\n     answer?: string;\n     messages: Message[];\n     steps: number;\n     usage: UsageTotals;\n   }\n   ```\n2. **Model Provider Interface**: Decouple the LLM provider behind a minimal contract:\n   ```typescript\n   export interface Model {\n     generate(params: {\n       messages: Message[];\n       tools?: ToolDefinition[];\n       signal?: AbortSignal;\n     }): Promise\u003CModelResponse>;\n   }\n   ```\n3. **Scripted Test Harness**: Construct `scriptedModel(responses[])` to advance through predetermined responses in unit tests. It must throw `'Scripted model exhausted'` if the loop requests unexpected turns, ensuring complete test determinism without live API calls.\n4. **Completion Gate**: Basic loop unit tests pass with `scriptedModel` covering: single-turn answers, tool invocation and result feedback, unknown tool handling, step limit termination, and `AbortSignal` cancellation.\n\n### Stage 2: Contract Registry & Runtime Argument Validation\n\nLLM model outputs are inherently untrusted. Never pass unvalidated arguments to tool implementations.\n\n1. **ToolRegistry Contract**: Implement `ToolRegistry` enforcing tool name regex `^[a-zA-Z][a-zA-Z0-9_-]*$` and duplicate registration rejection.\n2. **Pre-Dispatch Schema Validation**: Validate arguments against the tool's JSON Schema before dispatching to `execute()`:\n   - Support JSON Schema subset: `type`, `properties`, `required`, `additionalProperties: false`, `items`, `enum`.\n   - Report exact failure paths (e.g., `$.flags[0]` or `$.path: required`).\n3. **Strict Error Bifurcation**:\n   - **Tool Failure (Recoverable)**: Unknown tool name, schema validation failure, or exception thrown inside `tool.execute()` ➔ synthesize a `role: 'tool'` message with `isError: true`. The model observes the error and can self-repair on the next turn.\n   - **Model Failure (Terminal)**: `model.generate()` throws (network crash, authentication failure, quota exhaustion) ➔ terminate immediately with `status: 'model_error'`. Never inject synthetic model recovery into the conversation for infrastructure failures.\n4. **Completion Gate**: Malformed model-generated arguments never reach `tool.execute()`; model network crashes yield `model_error`; dedicated test cases verify both paths are strictly non-interchangeable.\n\n### Stage 3: Workspace Containment & Hardened Command Presets\n\nAgents must not read or modify files outside their designated project sandbox or execute arbitrary shell commands.\n\n1. **Workspace Root Canonicalization**: Resolve root path using `await realpath(root)` to prevent base directory symlink deception.\n2. **Path Confinement & Ancestor Walk**:\n   - Enforce lexical containment via `path.resolve(root, input)` and `path.relative(root, resolved)`. Reject absolute paths and `..` escape attempts.\n   - Perform a component-by-component `lstat()` walk on **every ancestor directory** up to root. Reject the operation if any parent directory is a symbolic link.\n   - Use `O_NOFOLLOW` flag when opening files to prevent symlink race conditions (TOCTOU).\n3. **Hardened Command Execution Presets**:\n   - Disallow raw shell command strings (`exec(\"rm -rf \" + input)`).\n   - Require developers to declare explicit presets:\n     ```typescript\n     export interface CommandPreset {\n       name: string;\n       executable: string;\n       args: string[];\n       timeoutMs: number;\n     }\n     ```\n   - The model selects presets by `name` only; it cannot supply executables, add arguments, or invoke shell pipelines.\n   - Spawn child processes with `shell: false`, enforce timeout termination (`child.kill('SIGTERM')`), and cap both `stdout` and `stderr` buffers to 64 KB to prevent memory exhaustion.\n4. **Completion Gate**: Traversal attempts (`..\u002F..\u002Fetc\u002Fpasswd`), symlinked ancestor escapes, and unlisted command names return recoverable tool errors; `shell: false` is verified by test; buffer overflow caps are asserted.\n\n### Stage 4: Execution Limits & Cancellation Propagation\n\nAgent runs must have bounded operational budgets and respond immediately to external cancellation.\n\n1. **Decoupled Budget Limits**:\n   - `maxSteps`: Maximum model conversation turns (default: 25).\n   - `maxToolCalls`: Cumulative individual tool invocations across the entire run (default: 75), including failed or rejected calls.\n2. **Atomic Batch Budget Verification**:\n   - When a model emits multiple tool calls in a single turn, calculate:\n     `remaining = maxToolCalls - cumulativeCalls`\n   - If `calls.length > remaining`, **reject the entire batch atomically before mutating the conversation transcript**.\n   - Terminate the run immediately with `status: 'tool_limit'`. Do NOT append the assistant message or execute a partial prefix of the batch. This prevents orphaned, unanswered tool calls in the transcript.\n3. **AbortSignal Propagation**:\n   - Thread `signal` through `model.generate({ signal })`, `tool.execute(args, signal)`, and `child_process.spawn({ signal })`.\n   - Check `signal.aborted` at loop entry and immediately following every awaited asynchronous operation.\n4. **Completion Gate**: Seeded PRNG property tests (`seed: 0x12345678`, 150 iterations varying `limit ∈ [0, 8]` and `batch ∈ [0, 12]`) verify that admitted batches execute all calls, rejected batches execute zero calls, and rejected batches leave no orphaned tool calls in the transcript.\n\n### Stage 5: Atomic Context Windowing\n\nAs conversations grow, histories must be pruned to fit model context limits without breaking conversation integrity.\n\n1. **Context Slicing Function**: Implement `selectContext(messages, maxChars)` with strict `RangeError` guards on non-positive character budgets.\n2. **Indivisible Turn Groups**:\n   - Never split an assistant tool-call turn from its corresponding tool result messages.\n   - Group messages into atomic units: `[UserPrompt]`, `[AssistantTurn + ToolResults...]`, `[AssistantFinalAnswer]`.\n   - Sliding windowing accumulates whole groups walking backward from the most recent turn.\n3. **Transcript Integrity Invariants**:\n   - Detect and throw on: orphaned tool results (tool message without preceding assistant call), duplicate tool-call IDs within a turn, or incomplete batches (tool result IDs mismatching assistant calls).\n   - The initial user prompt must always be preserved.\n   - If the initial prompt plus the most recent required group exceeds `maxChars`, terminate with `context_limit`.\n4. **Completion Gate**: Tests verify batch indivisibility is preserved under aggressive character constraints, orphan tool results are detected and rejected, tool outputs are truncated before windowing, and coherent message transcripts are emitted regardless of conversation length.\n\n### Stage 6: Non-Invasive Telemetry, Evals & Provider Adapter Pattern\n\nOperational visibility and model connectivity must not invade or destabilize core loop mechanics.\n\n1. **Boundary Event Stream**:\n   - Emit typed lifecycle events via optional `onEvent` callback: `model_start`, `model_end` (with `durationMs`), `tool_start`, `tool_end` (with `durationMs`), `model_error`, `run_end`.\n   - Each event carries monotonic `sequence`, unique `runId`, and ISO `timestamp`.\n2. **Observer Isolation Invariant**:\n   - Wrap all `onEvent?.(event)` dispatches in isolated `try...catch` blocks.\n   - Route listener exceptions to optional `onObserverError`; suppress errors if no handler exists.\n   - **Critical Rule**: An exception in a metrics logger, console formatter, or telemetry client must NEVER fail or alter the outcome of an agent run.\n3. **Accurate Token & Cost Telemetry**:\n   - Accumulate `usage.inputTokens`, `usage.outputTokens`, and `usage.modelCallsWithUsage`.\n   - Distinguish `modelCallsWithUsage === 0` (cost unknown \u002F provider omitted tokens) from `inputTokens === 0` (zero-cost run).\n   - Validate usage values: reject negative numbers or non-integers with `RangeError`.\n4. **Provider Adapter Coaching Note**:\n   - Real LLM providers connect strictly via the `Model` interface: `generate({ messages, tools, signal }) → Promise\u003CModelResponse>`.\n   - Adapters must:\n     1. Translate between provider message formats (OpenAI, Anthropic, Gemini) and the harness `Message` type.\n     2. Preserve tool-call IDs across requests.\n     3. Forward `AbortSignal` to HTTP clients or SDK calls.\n     4. Normalize provider HTTP \u002F API errors into thrown exceptions that the harness catches as `model_error`.\n   - **Seam Rule**: Adding or modifying provider adapters requires zero modifications to the core agent loop, tool registry, workspace sandbox, budget manager, or context windowing components.\n5. **Completion Gate**: 150 seeded batch property tests and 60 tool exception recovery runs pass deterministically; observer failure tests verify harmless isolation; provider adapter coaching rubric is verified.\n\n---\n\n## Bundled Tooling & CLI Seams\n\nThis skill includes an executable domain engine and headless Click CLI seam under `scripts\u002F`:\n\n```bash\n# 1. Audit a codebase against the 9 binary diagnostic seam gates\npython scripts\u002Fts_harness_constructor.py audit --target-dir \u003Cpath> [--json]\n\n# 2. Run 150-run seeded PRNG batch property simulation (Rule 12\u002F43)\npython scripts\u002Fts_harness_constructor.py simulate --seed 0x12345678 --runs 150 [--json]\n\n# 3. Scaffold complete zero-dependency TypeScript harness boilerplate\npython scripts\u002Fts_harness_constructor.py scaffold --output-dir \u003Cpath> [--json]\n```\n\nKey slotted domain models in [`scripts\u002Fts_harness_engine.py`](scripts\u002Fts_harness_engine.py):\n- `HarnessBudgetConfig` — Mathematical budgets and operational thresholds.\n- `ToolContractDefinition` — Schema validation and error bifurcation.\n- `WorkspaceSandboxPolicy` — Ancestor `lstat()` walk and lexical confinement.\n- `AtomicBudgetEvaluator` — Pre-transcript batch budget verification.\n- `ContextWindowManager` — Atomic turn group sliding allocation.\n- `PRNGBatchSimulator` — Deterministic property testing with zero orphaned calls.\n\n---\n\n## Mandatory Checkpoint\n\nBefore finalizing harness implementation or deploying to production, execute this mandatory checkpoint gate:\n\n> [!CAUTION]\n> **Harness Confinement & Budget Verification Checkpoint**:\n> - [ ] Assert that `Workspace.open()` performs an ancestor `lstat()` walk and rejects symlinked parent paths.\n> - [ ] Assert that command presets execute with `shell: false` and strict timeout kill handlers.\n> - [ ] Assert that tool batches exceeding remaining `maxToolCalls` are rejected atomically without writing to the transcript.\n> - [ ] Assert that `onEvent` telemetry dispatches are isolated so observer crashes cannot alter run status.\n\n---\n\n## Diagnostic Coaching Rubrics — Binary Pass\u002FFail Gates\n\n| Seam | Diagnostic Question | **PASS** | **FAIL** |\n|---|---|---|---|\n| **Tool Validation** | Does argument validation happen before `tool.execute()`? | Schema validation runs; invalid input returns `role:'tool'` error; `execute()` never called. | Arguments passed directly to implementation; type errors crash at runtime. |\n| **Error Bifurcation** | Are tool runtime errors segregated from model provider failures? | Tool exceptions ➔ recoverable feedback message. Model provider crash ➔ `status:'model_error'` termination. | Conflating provider downtime with recoverable tool errors. |\n| **Filesystem Sandboxing** | Are symlinks verified across all intermediate directory components? | Iterative `lstat` walk on every ancestor; lexical escape check; `O_NOFOLLOW` on file open. | Only final path target checked; symlinked parent directory allows escape. |\n| **Command Hardening** | Can the model supply an executable path, extra args, or shell syntax? | Named preset selection only; hardcoded executable; `shell: false`; timeout; buffer cap. | Raw shell string interpolation or `child_process.exec()` with model-supplied input. |\n| **Atomic Batch Budget** | Is the tool budget checked before mutating conversation history? | Budget verified before assistant message appended; rejected batches: 0 calls executed, 0 transcript traces. | Assistant message with tool calls appended, then budget exceeded mid-batch ➔ orphaned calls in transcript. |\n| **Context Group Integrity** | Does context sliding preserve indivisible tool-call\u002Fresult pairs? | All tool results for an assistant turn kept with or removed with their parent turn. | Sliding window drops tool results while retaining the assistant tool-call message. |\n| **Observer Isolation** | Can a telemetry listener exception corrupt the agent outcome? | All `onEvent` invocations wrapped in isolated `try...catch`; listener errors suppressed. | Observer throws ➔ successful tool run recorded as failure. |\n| **Deterministic Evals** | Are boundary conditions tested without live API calls or token cost? | `scriptedModel` + 150 seeded PRNG scenarios + 60 exception recovery loops. | Only happy-path tested or live LLM endpoints used in boundary tests. |\n| **Provider Seam Isolation** | Does adding a real LLM provider require changing any harness component? | `Model` interface is the sole seam; adapter translates format, preserves call IDs, forwards signal. | Harness loop modified per provider; registry or context changes needed per model. |\n\n---\n\n## Anti-Patterns\n\n- **Tool Trust Vulnerability** — Passing raw model arguments directly to tool implementations without schema validation. Harness must validate against declared schema; invalid arguments return an error message without calling execute().\n- **Unbounded Shell Injection** — Permitting the model to synthesize raw shell strings or select arbitrary executables. Harness must restrict execution to developer-defined presets with shell: false and fixed argument arrays.\n- **Workspace Sandbox Bypass** — Checking only the final file path for traversal or symlink violations, while ignoring parent directory components. Harness must walk every ancestor with lstat and use O_NOFOLLOW at the file open boundary.\n- **Premature Transcript Mutation** — Appending an assistant tool-call message before verifying that the entire batch fits within the remaining tool budget. Harness must check budget atomically before transcript mutation; rejected batches must leave zero traces.\n- **Coupled Telemetry Failure** — Allowing exceptions in observer or logging callbacks to fail an otherwise successful agent run. All onEvent dispatches must be wrapped in isolated try...catch whose failures are independently suppressed.\n- **Silent Cost Opacity** — Treating absent or null token usage fields from the model provider as zero tokens consumed. Harness must accumulate modelCallsWithUsage separately and surface unknown cost explicitly rather than presenting a misleading 0 total.\n","# TypeScript Agent Harness Constructor (`ts-agent-harness-constructor`)\n\n## Scope & Architectural Seam\n\nThis skill provides an authoritative, zero-dependency engineering standard for constructing, validating, and hardening autonomous AI agent runtime harnesses in TypeScript and Node.js. It focuses on the core runtime mechanics: the ReAct agent loop, tool contract validation, filesystem sandboxing, command execution hardening, atomic batch budgeting, sliding context windowing, non-invasive telemetry, and seeded failure testing.\n\n> [!IMPORTANT]\n> **Cross-Reference Seam**: For harness architecture selection, 5-part comparative evaluation, and sandboxing governance, invoke upstream [agent-harness-architect](..\u002Fagent-harness-architect\u002FSKILL.md). Use `ts-agent-harness-constructor` strictly for **implementation, construction, and hardening** from first principles.\n\n---\n\n## Interactive Visual Brief\n\n> Note: the interactive visual brief for this workflow was rendered to a local temp file at generation time and is not shipped with the skill, so the original link (which pointed at a `file:\u002F\u002F\u002F` temp path) has been removed. The brief covered animated ReAct turn transitions, symlink walk diagrams, atomic batch budget timelines, and context window sliding group animations.\n\n---\n\n## The 6-Stage Operational Progression (\"Shu\" Stage)\n\nHarness construction follows a strict 6-stage linear progression where each stage introduces a distinct architectural boundary and failure mode isolation:\n\n```\n[1. Loop & Model Abstraction] ➔ [2. Contract Registry & Validation] ➔ [3. Workspace Containment & Presets]\n               ➔ [4. Execution Limits & Cancellation] ➔ [5. Atomic Context Windowing] ➔ [6. Telemetry, Evals & Adapters]\n```\n\n### Stage 1: Provider-Agnostic Loop & Model Abstraction\n\nThe core agent loop coordinates conversation state, dispatches model generations, routes tool calls, and handles cancellation.\n\n1. **Harness Entrypoint**: Implement `runAgent({ prompt, model, tools, signal, maxSteps })` as the single public entrypoint returning an immutable execution summary:\n   ```typescript\n   export interface RunResult {\n     status: 'completed' | 'step_limit' | 'tool_limit' | 'aborted' | 'model_error';\n     answer?: string;\n     messages: Message[];\n     steps: number;\n     usage: UsageTotals;\n   }\n   ```\n2. **Model Provider Interface**: Decouple the LLM provider behind a minimal contract:\n   ```typescript\n   export interface Model {\n     generate(params: {\n       messages: Message[];\n       tools?: ToolDefinition[];\n       signal?: AbortSignal;\n     }): Promise\u003CModelResponse>;\n   }\n   ```\n3. **Scripted Test Harness**: Construct `scriptedModel(responses[])` to advance through predetermined responses in unit tests. It must throw `'Scripted model exhausted'` if the loop requests unexpected turns, ensuring complete test determinism without live API calls.\n4. **Completion Gate**: Basic loop unit tests pass with `scriptedModel` covering: single-turn answers, tool invocation and result feedback, unknown tool handling, step limit termination, and `AbortSignal` cancellation.\n\n### Stage 2: Contract Registry & Runtime Argument Validation\n\nLLM model outputs are inherently untrusted. Never pass unvalidated arguments to tool implementations.\n\n1. **ToolRegistry Contract**: Implement `ToolRegistry` enforcing tool name regex `^[a-zA-Z][a-zA-Z0-9_-]*$` and duplicate registration rejection.\n2. **Pre-Dispatch Schema Validation**: Validate arguments against the tool's JSON Schema before dispatching to `execute()`:\n   - Support JSON Schema subset: `type`, `properties`, `required`, `additionalProperties: false`, `items`, `enum`.\n   - Report exact failure paths (e.g., `$.flags[0]` or `$.path: required`).\n3. **Strict Error Bifurcation**:\n   - **Tool Failure (Recoverable)**: Unknown tool name, schema validation failure, or exception thrown inside `tool.execute()` ➔ synthesize a `role: 'tool'` message with `isError: true`. The model observes the error and can self-repair on the next turn.\n   - **Model Failure (Terminal)**: `model.generate()` throws (network crash, authentication failure, quota exhaustion) ➔ terminate immediately with `status: 'model_error'`. Never inject synthetic model recovery into the conversation for infrastructure failures.\n4. **Completion Gate**: Malformed model-generated arguments never reach `tool.execute()`; model network crashes yield `model_error`; dedicated test cases verify both paths are strictly non-interchangeable.\n\n### Stage 3: Workspace Containment & Hardened Command Presets\n\nAgents must not read or modify files outside their designated project sandbox or execute arbitrary shell commands.\n\n1. **Workspace Root Canonicalization**: Resolve root path using `await realpath(root)` to prevent base directory symlink deception.\n2. **Path Confinement & Ancestor Walk**:\n   - Enforce lexical containment via `path.resolve(root, input)` and `path.relative(root, resolved)`. Reject absolute paths and `..` escape attempts.\n   - Perform a component-by-component `lstat()` walk on **every ancestor directory** up to root. Reject the operation if any parent directory is a symbolic link.\n   - Use `O_NOFOLLOW` flag when opening files to prevent symlink race conditions (TOCTOU).\n3. **Hardened Command Execution Presets**:\n   - Disallow raw shell command strings (`exec(\"rm -rf \" + input)`).\n   - Require developers to declare explicit presets:\n     ```typescript\n     export interface CommandPreset {\n       name: string;\n       executable: string;\n       args: string[];\n       timeoutMs: number;\n     }\n     ```\n   - The model selects presets by `name` only; it cannot supply executables, add arguments, or invoke shell pipelines.\n   - Spawn child processes with `shell: false`, enforce timeout termination (`child.kill('SIGTERM')`), and cap both `stdout` and `stderr` buffers to 64 KB to prevent memory exhaustion.\n4. **Completion Gate**: Traversal attempts (`..\u002F..\u002Fetc\u002Fpasswd`), symlinked ancestor escapes, and unlisted command names return recoverable tool errors; `shell: false` is verified by test; buffer overflow caps are asserted.\n\n### Stage 4: Execution Limits & Cancellation Propagation\n\nAgent runs must have bounded operational budgets and respond immediately to external cancellation.\n\n1. **Decoupled Budget Limits**:\n   - `maxSteps`: Maximum model conversation turns (default: 25).\n   - `maxToolCalls`: Cumulative individual tool invocations across the entire run (default: 75), including failed or rejected calls.\n2. **Atomic Batch Budget Verification**:\n   - When a model emits multiple tool calls in a single turn, calculate:\n     `remaining = maxToolCalls - cumulativeCalls`\n   - If `calls.length > remaining`, **reject the entire batch atomically before mutating the conversation transcript**.\n   - Terminate the run immediately with `status: 'tool_limit'`. Do NOT append the assistant message or execute a partial prefix of the batch. This prevents orphaned, unanswered tool calls in the transcript.\n3. **AbortSignal Propagation**:\n   - Thread `signal` through `model.generate({ signal })`, `tool.execute(args, signal)`, and `child_process.spawn({ signal })`.\n   - Check `signal.aborted` at loop entry and immediately following every awaited asynchronous operation.\n4. **Completion Gate**: Seeded PRNG property tests (`seed: 0x12345678`, 150 iterations varying `limit ∈ [0, 8]` and `batch ∈ [0, 12]`) verify that admitted batches execute all calls, rejected batches execute zero calls, and rejected batches leave no orphaned tool calls in the transcript.\n\n### Stage 5: Atomic Context Windowing\n\nAs conversations grow, histories must be pruned to fit model context limits without breaking conversation integrity.\n\n1. **Context Slicing Function**: Implement `selectContext(messages, maxChars)` with strict `RangeError` guards on non-positive character budgets.\n2. **Indivisible Turn Groups**:\n   - Never split an assistant tool-call turn from its corresponding tool result messages.\n   - Group messages into atomic units: `[UserPrompt]`, `[AssistantTurn + ToolResults...]`, `[AssistantFinalAnswer]`.\n   - Sliding windowing accumulates whole groups walking backward from the most recent turn.\n3. **Transcript Integrity Invariants**:\n   - Detect and throw on: orphaned tool results (tool message without preceding assistant call), duplicate tool-call IDs within a turn, or incomplete batches (tool result IDs mismatching assistant calls).\n   - The initial user prompt must always be preserved.\n   - If the initial prompt plus the most recent required group exceeds `maxChars`, terminate with `context_limit`.\n4. **Completion Gate**: Tests verify batch indivisibility is preserved under aggressive character constraints, orphan tool results are detected and rejected, tool outputs are truncated before windowing, and coherent message transcripts are emitted regardless of conversation length.\n\n### Stage 6: Non-Invasive Telemetry, Evals & Provider Adapter Pattern\n\nOperational visibility and model connectivity must not invade or destabilize core loop mechanics.\n\n1. **Boundary Event Stream**:\n   - Emit typed lifecycle events via optional `onEvent` callback: `model_start`, `model_end` (with `durationMs`), `tool_start`, `tool_end` (with `durationMs`), `model_error`, `run_end`.\n   - Each event carries monotonic `sequence`, unique `runId`, and ISO `timestamp`.\n2. **Observer Isolation Invariant**:\n   - Wrap all `onEvent?.(event)` dispatches in isolated `try...catch` blocks.\n   - Route listener exceptions to optional `onObserverError`; suppress errors if no handler exists.\n   - **Critical Rule**: An exception in a metrics logger, console formatter, or telemetry client must NEVER fail or alter the outcome of an agent run.\n3. **Accurate Token & Cost Telemetry**:\n   - Accumulate `usage.inputTokens`, `usage.outputTokens`, and `usage.modelCallsWithUsage`.\n   - Distinguish `modelCallsWithUsage === 0` (cost unknown \u002F provider omitted tokens) from `inputTokens === 0` (zero-cost run).\n   - Validate usage values: reject negative numbers or non-integers with `RangeError`.\n4. **Provider Adapter Coaching Note**:\n   - Real LLM providers connect strictly via the `Model` interface: `generate({ messages, tools, signal }) → Promise\u003CModelResponse>`.\n   - Adapters must:\n     1. Translate between provider message formats (OpenAI, Anthropic, Gemini) and the harness `Message` type.\n     2. Preserve tool-call IDs across requests.\n     3. Forward `AbortSignal` to HTTP clients or SDK calls.\n     4. Normalize provider HTTP \u002F API errors into thrown exceptions that the harness catches as `model_error`.\n   - **Seam Rule**: Adding or modifying provider adapters requires zero modifications to the core agent loop, tool registry, workspace sandbox, budget manager, or context windowing components.\n5. **Completion Gate**: 150 seeded batch property tests and 60 tool exception recovery runs pass deterministically; observer failure tests verify harmless isolation; provider adapter coaching rubric is verified.\n\n---\n\n## Bundled Tooling & CLI Seams\n\nThis skill includes an executable domain engine and headless Click CLI seam under `scripts\u002F`:\n\n```bash\n# 1. Audit a codebase against the 9 binary diagnostic seam gates\npython scripts\u002Fts_harness_constructor.py audit --target-dir \u003Cpath> [--json]\n\n# 2. Run 150-run seeded PRNG batch property simulation (Rule 12\u002F43)\npython scripts\u002Fts_harness_constructor.py simulate --seed 0x12345678 --runs 150 [--json]\n\n# 3. Scaffold complete zero-dependency TypeScript harness boilerplate\npython scripts\u002Fts_harness_constructor.py scaffold --output-dir \u003Cpath> [--json]\n```\n\nKey slotted domain models in [`scripts\u002Fts_harness_engine.py`](scripts\u002Fts_harness_engine.py):\n- `HarnessBudgetConfig` — Mathematical budgets and operational thresholds.\n- `ToolContractDefinition` — Schema validation and error bifurcation.\n- `WorkspaceSandboxPolicy` — Ancestor `lstat()` walk and lexical confinement.\n- `AtomicBudgetEvaluator` — Pre-transcript batch budget verification.\n- `ContextWindowManager` — Atomic turn group sliding allocation.\n- `PRNGBatchSimulator` — Deterministic property testing with zero orphaned calls.\n\n---\n\n## Mandatory Checkpoint\n\nBefore finalizing harness implementation or deploying to production, execute this mandatory checkpoint gate:\n\n> [!CAUTION]\n> **Harness Confinement & Budget Verification Checkpoint**:\n> - [ ] Assert that `Workspace.open()` performs an ancestor `lstat()` walk and rejects symlinked parent paths.\n> - [ ] Assert that command presets execute with `shell: false` and strict timeout kill handlers.\n> - [ ] Assert that tool batches exceeding remaining `maxToolCalls` are rejected atomically without writing to the transcript.\n> - [ ] Assert that `onEvent` telemetry dispatches are isolated so observer crashes cannot alter run status.\n\n---\n\n## Diagnostic Coaching Rubrics — Binary Pass\u002FFail Gates\n\n| Seam | Diagnostic Question | **PASS** | **FAIL** |\n|---|---|---|---|\n| **Tool Validation** | Does argument validation happen before `tool.execute()`? | Schema validation runs; invalid input returns `role:'tool'` error; `execute()` never called. | Arguments passed directly to implementation; type errors crash at runtime. |\n| **Error Bifurcation** | Are tool runtime errors segregated from model provider failures? | Tool exceptions ➔ recoverable feedback message. Model provider crash ➔ `status:'model_error'` termination. | Conflating provider downtime with recoverable tool errors. |\n| **Filesystem Sandboxing** | Are symlinks verified across all intermediate directory components? | Iterative `lstat` walk on every ancestor; lexical escape check; `O_NOFOLLOW` on file open. | Only final path target checked; symlinked parent directory allows escape. |\n| **Command Hardening** | Can the model supply an executable path, extra args, or shell syntax? | Named preset selection only; hardcoded executable; `shell: false`; timeout; buffer cap. | Raw shell string interpolation or `child_process.exec()` with model-supplied input. |\n| **Atomic Batch Budget** | Is the tool budget checked before mutating conversation history? | Budget verified before assistant message appended; rejected batches: 0 calls executed, 0 transcript traces. | Assistant message with tool calls appended, then budget exceeded mid-batch ➔ orphaned calls in transcript. |\n| **Context Group Integrity** | Does context sliding preserve indivisible tool-call\u002Fresult pairs? | All tool results for an assistant turn kept with or removed with their parent turn. | Sliding window drops tool results while retaining the assistant tool-call message. |\n| **Observer Isolation** | Can a telemetry listener exception corrupt the agent outcome? | All `onEvent` invocations wrapped in isolated `try...catch`; listener errors suppressed. | Observer throws ➔ successful tool run recorded as failure. |\n| **Deterministic Evals** | Are boundary conditions tested without live API calls or token cost? | `scriptedModel` + 150 seeded PRNG scenarios + 60 exception recovery loops. | Only happy-path tested or live LLM endpoints used in boundary tests. |\n| **Provider Seam Isolation** | Does adding a real LLM provider require changing any harness component? | `Model` interface is the sole seam; adapter translates format, preserves call IDs, forwards signal. | Harness loop modified per provider; registry or context changes needed per model. |\n\n---\n\n## Anti-Patterns\n\n- **Tool Trust Vulnerability** — Passing raw model arguments directly to tool implementations without schema validation. Harness must validate against declared schema; invalid arguments return an error message without calling execute().\n- **Unbounded Shell Injection** — Permitting the model to synthesize raw shell strings or select arbitrary executables. Harness must restrict execution to developer-defined presets with shell: false and fixed argument arrays.\n- **Workspace Sandbox Bypass** — Checking only the final file path for traversal or symlink violations, while ignoring parent directory components. Harness must walk every ancestor with lstat and use O_NOFOLLOW at the file open boundary.\n- **Premature Transcript Mutation** — Appending an assistant tool-call message before verifying that the entire batch fits within the remaining tool budget. Harness must check budget atomically before transcript mutation; rejected batches must leave zero traces.\n- **Coupled Telemetry Failure** — Allowing exceptions in observer or logging callbacks to fail an otherwise successful agent run. All onEvent dispatches must be wrapped in isolated try...catch whose failures are independently suppressed.\n- **Silent Cost Opacity** — Treating absent or null token usage fields from the model provider as zero tokens consumed. Harness must accumulate modelCallsWithUsage separately and surface unknown cost explicitly rather than presenting a misleading 0 total.\n",{},"main","eff3b00e36d1d233ad4a4389605c82fbfa0326d3",".agents\u002Fskills\u002Fts-agent-harness-constructor","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness","https:\u002F\u002Fgithub.com\u002FSpectreDeath","I'm here to manage stress so I wouldn't expect earth shattering break throughs I'm just an enthusiast that likes making stuff. ","2026-11-15 05:32:58",{"source":7,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add SpectreDeath\u002FBrain-Harness --skill ts-agent-harness-constructor",{"tool":36,"command":37},"bunx","bunx skills add SpectreDeath\u002FBrain-Harness --skill ts-agent-harness-constructor",{"tool":39,"command":40},"pnpm","pnpm dlx skills add SpectreDeath\u002FBrain-Harness --skill ts-agent-harness-constructor","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002FSKILL.md",true,[44,50,54,60],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"CARD.md","REFERENCE","参考文档",6371,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002FCARD.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"config.default.yaml",914,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002Fconfig.default.yaml",{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"scripts\u002Fts_harness_constructor.py","SCRIPT","脚本",7229,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002Fscripts\u002Fts_harness_constructor.py",{"path":61,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":62,"sourceHtmlUrl":63},"scripts\u002Fts_harness_engine.py",27495,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fts-agent-harness-constructor\u002Fscripts\u002Fts_harness_engine.py",[65,72,79,86,93,100],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":18},"01M7E0W6FR68J2N9CXCZTAQJFX","ui-behavior-primitive-architect","Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA\u002FSSR\u002FRTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fui-behavior-primitive-architect\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M7E0VZ7JQNW34G271DENFGYP","trustgraph-ontology-governor","Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftrustgraph-ontology-governor\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7E0VQ6Z7R45Q8QAZ4MT39EK","shim-harness-governor","Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fshim-harness-governor\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":18},"01M7E0VC18NMP1QBSRJ3TPQ7MB","graphiti-zep-memory-governor","Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash\u002FLSH entity dedup, RRF\u002FMMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgraphiti-zep-memory-governor\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":18},"01M7E0V12ABE1RW3ZRCST8VH5Z","agora-mcp-workbench-architect","Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway\u002Fdispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fagora-mcp-workbench-architect\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":18},"01M7BFYG6QT3484VC57TZ19V7P","skill-eval-assurance-runner","Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fskill-eval-assurance-runner\u002FSKILL.md",[],[]]