#source
170 files tagged source.
Dispatch Scanner
import { Agent } from "@earendil-works/pi-agent-core"; import { getModel } from "@earendil-works/pi-ai"; import { Type }…
Dispatch Scanner V2
import { Agent } from "@earendil-works/pi-agent-core"; import { getModel } from "@earendil-works/pi-ai"; import { Type }…
Dispatch Scanner V3
import { Agent } from "@earendil-works/pi-agent-core"; import { getModel } from "@earendil-works/pi-ai"; import { Type }…
Analyze Batches
import { Agent } from "@earendil-works/pi-agent-core"; import { getModel } from "@earendil-works/pi-ai"; import { Type }…
Live Run
/** * Live-wire smoke run: real opencode-go model through the full 5-loop harness. * * set -a && source /home/mikes…
Pretooluse Gate Guard
#!/usr/bin/env python3 """pretooluse_gate_guard.py — Claude Code PreToolUse hook enforcing N15. Blocks Edit/Write/Multi…
Register Pretooluse
#!/usr/bin/env python3 """register_pretooluse.py — safely register the gate guard in .claude/settings.json. Discipline …
Pre Commit Gate Guard
#!/usr/bin/env python3 """pre_commit_gate_guard.py — git pre-commit enforcement of N15 (layer 3). Rules: 1. Any stage…
Gate Integrity
/** * gate-integrity.ts — Layer 1 runtime enforcement (A13 / N15 / N16). * * Verifies a spec's pinned gate reference …
Spec Lint Gates
#!/usr/bin/env python3 """spec_lint_gates.py — lint dispatch specs for gate governance (N16 + fidelity). Checks, per sp…
Gate Manifest
#!/usr/bin/env python3 """gate_manifest.py — single hashing authority for the gate governance system. Every component (…
Cut Gate Version
#!/usr/bin/env python3 """cut_gate_version.py — the ONLY sanctioned way a gate pack changes (N15/N17). Creates gates/v<…
Index
export * from "./types/index.ts"; export * from "./monitors/index.ts"; export * from "./storage/index.ts"; export * from…
Util
/** Deterministic shared helpers — no LLM reasoning, no randomness beyond ids. */ let idCounter = 0; export function n…
Index
/** * Enforcement artifact types — the bridge from pi-cybernetic Loop-5 lessons to * loom-builder gate enforcement art…
Exporter
/** * exporter.ts — emits enforcement artifacts to a file-based queue. * * Callable from MetaEngine.consolidateLesson…
Config
/** Harness configuration — one section per loop. */ import type { ToolExecutionMode } from "@earendil-works/pi-agent-c…
Messages
/** * ADR-003 — inter-loop communication as custom AgentMessage types via * declaration merging. Carried in the transc…
Goal State
/** Loop 1 — goal homeostasis types (P3). */ export type GoalItemStatus = "pending" | "active" | "complete" | "failed";…
Index
export * from "./goal-state.ts"; export * from "./metrics.ts"; export * from "./tool-registry.ts"; export * from "./memo…
Tool Registry
/** Loop 2 — variety + reversibility registries (P2, P4). */ export type Reversibility = "read" | "recoverable" | "dest…
Metrics
/** Cross-loop metric, escalation, and meta-learning types. */ export type LoopId = "strategic" | "management" | "execu…
Memory
/** Loop 4 — three-level memory hierarchy types (P6). */ export interface InteractionTrace { id: string; kind: "too…
Index
export * from "./cybernetic-harness.ts"; export * from "./desideratum-gate.ts"; export * from "./ladders.ts";
Ladders
/** * Model escalation ladders — P2 variety expansion. * A ladder is an ordered list of rungs with strictly increasing…
Desideratum Gate
/** * ADR-004 — D1→D2→D3 enforced at runtime. Failed prerequisites put dependent * modules into degraded passthrough m…
Cybernetic Harness
/** * ADR-001 — Concentric Wrapper. One pi-agent Agent instance, four regulatory * layers attached through its hook su…
Semantic Store
/** Semantic memory — compressed summaries + entity-relation tuples, with promotion. */ import type { CompressedSummary…
Procedural Store
/** Procedural memory — verified skills + working memory (active hypotheses). */ import type { ActiveHypothesis, Eviden…
Index
export * from "./episodic-store.ts"; export * from "./semantic-store.ts"; export * from "./procedural-store.ts"; export …
Episodic Store
/** Episodic memory — raw traces with deterministic term-overlap retrieval. */ import type { InteractionTrace } from ".…
Performance Log
/** Loop 5 raw data — structured event log for pattern analysis. */ export interface ToolExecutionRecord { toolName: …
Meta
/** * Loop 5 — MetaEngine. Second-order regulator (P5): watches the regulators, * extracts failure patterns, revises c…
Consolidation
/** * Offline consolidation: Hippocampus -> Neocortex. * * This engine is intentionally not called from transformCont…
Index
export * from "./management.ts"; export * from "./strategic.ts"; export * from "./memory.ts"; export * from "./gear-shif…
Strategic
/** * Loop 1 — StrategicEngine. Homeostatic regulator over Ω_goal (P3, P5). * * pi-agent-core 0.79 exposes `shouldSto…
Gear Shifter
/** * Loop 4 — GearShifter. Deterministic memory router (ADR-005..009). * Preserves the MemoryEngine hook surface whil…
Management
/** * Loop 2 — ManagementEngine. Variety allocator + feedback enforcer (P1, P2, P4). * Attaches via beforeToolCall (di…
Memory
/** * Loop 4 — MemoryEngine. Channel-capacity manager (P6). * Attaches via transformContext (entropy gate) and convert…
Loop Detector
/** P5 — action-sequence loop detection over a sliding window. */ import type { Escalation } from "../types/index.ts"; …
Index
export * from "./loop-detector.ts"; export * from "./confidence-calibrator.ts"; export * from "./drift-detector.ts"; exp…
Confidence Calibrator
/** P5 — Brier-score confidence calibration over (stated confidence, outcome) pairs. */ import type { Escalation } from…
Entropy Monitor
/** P6 — channel capacity tracking: context utilization, query/source entropy. */ import { estimateTokens, extractText,…
Drift Detector
/** P3 — semantic drift between execution trajectory and original spec. */ import type { Escalation } from "../types/in…
Index
console.log("Hello via Bun!");
Pre Commit Gate Guard
#!/usr/bin/env python3 """pre_commit_gate_guard.py — git pre-commit enforcement of N15 (layer 3). Rules: 1. Any stage…
Spec Lint Gates
#!/usr/bin/env python3 """spec_lint_gates.py — lint dispatch specs for gate governance (N16 + fidelity). Checks, per sp…
Gate Manifest
#!/usr/bin/env python3 """gate_manifest.py — single hashing authority for the gate governance system. Every component (…
Cut Gate Version
#!/usr/bin/env python3 """cut_gate_version.py — the ONLY sanctioned way a gate pack changes (N15/N17). Creates gates/v<…
Pretooluse Gate Guard
#!/usr/bin/env python3 """pretooluse_gate_guard.py — Claude Code PreToolUse hook enforcing N15. Blocks Edit/Write/Multi…
Types
/** Contract types for loom-builder dispatches. */ export interface ModelRef { provider: string; id: string; } exp…
Gate Packs
import { existsSync, readFileSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; import type { V…
Gate Integrity
/** * gate-integrity.ts — Layer 1 runtime enforcement (A13 / N15 / N16). * * Verifies a spec's pinned gate reference …
Gate Analyzer
/** * gate-analyzer — preflight gate complexity review. * * Runs on EVERY dispatch after spec lint, before the execut…
Pi Executable
import { existsSync } from "node:fs"; export interface PiExecutableCheck { ok: boolean; path: string; reason: str…
Model Router
import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { DispatchSpec, Mod…
Spec Lint
/** * Spec-schema lint — validates DispatchSpec at preflight before dispatch. * * Checks: * - Unknown top-level keys…
Preflight Cli
/** * Pre-flight CLI: estimate tokens for a spec and exit non-zero if too large. * Usage: bun run src/preflight-cli.ts…
Preflight
import { readFileSync } from "node:fs"; import { globSync } from "glob"; import { resolve, relative } from "node:path"; …
Outcome
import type { DispatchOutcome } from "./types.js"; export type DispatchStatus = DispatchOutcome["status"]; export func…
Run
/** * loom-builder — homeostatic dispatch harness. * Runs one DispatchSpec: agent loop (pi-coding-agent SDK) under har…
Exit Matrix
/** * Exit-code retry matrix — maps process outcomes to verdicts. * * Bug fixed: executor exit -1 previously could re…
Import Lesson
/** * import-lesson.ts — reads enforcement artifacts from pi-cybernetic's file-based * queue and applies them to loom-…
Dispatch Archive
/** * dispatch-archive — THE single source of truth for the Dispatch Artifact Contract. * * Contract (see /home/mikes…
Gate Escalation
/** * gate-escalation — consecutive-failure tracking and diagnostic interrogation. * * When the same validation gate …
Gates
import { createHash } from "node:crypto"; import { GateHaltError, type HaltReason, type ValidationCmd } from "./types.js…
Purpose
import type { DispatchSpec } from "./types.js"; export const PURPOSE_HEADER = "## PURPOSE (INVARIANT — restated verbati…
Trace
import { appendFileSync, mkdirSync } from "node:fs"; import { dirname } from "node:path"; import type { TraceEvent } fro…
Index
console.log("Hello via Bun!");
Pre Commit Gate Guard
#!/usr/bin/env python3 """pre_commit_gate_guard.py — git pre-commit enforcement of N15 (layer 3). Rules: 1. Any stage…
Spec Lint Gates
#!/usr/bin/env python3 """spec_lint_gates.py — lint dispatch specs for gate governance (N16 + fidelity). Checks, per sp…
Gate Manifest
#!/usr/bin/env python3 """gate_manifest.py — single hashing authority for the gate governance system. Every component (…
Cut Gate Version
#!/usr/bin/env python3 """cut_gate_version.py — the ONLY sanctioned way a gate pack changes (N15/N17). Creates gates/v<…
Pretooluse Gate Guard
#!/usr/bin/env python3 """pretooluse_gate_guard.py — Claude Code PreToolUse hook enforcing N15. Blocks Edit/Write/Multi…
Types
/** Contract types for loom-builder dispatches. */ export interface ModelRef { provider: string; id: string; } exp…
Gate Packs
import { existsSync, readFileSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; import type { V…
Gate Integrity
/** * gate-integrity.ts — Layer 1 runtime enforcement (A13 / N15 / N16). * * Verifies a spec's pinned gate reference …
Gate Analyzer
/** * gate-analyzer — preflight gate complexity review. * * Runs on EVERY dispatch after spec lint, before the execut…
Pi Executable
import { existsSync } from "node:fs"; export interface PiExecutableCheck { ok: boolean; path: string; reason: str…
Model Router
import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { DispatchSpec, Mod…
Spec Lint
/** * Spec-schema lint — validates DispatchSpec at preflight before dispatch. * * Checks: * - Unknown top-level keys…
Preflight Cli
/** * Pre-flight CLI: estimate tokens for a spec and exit non-zero if too large. * Usage: bun run src/preflight-cli.ts…
Preflight
import { readFileSync } from "node:fs"; import { globSync } from "glob"; import { resolve, relative } from "node:path"; …
Outcome
import type { DispatchOutcome } from "./types.js"; export type DispatchStatus = DispatchOutcome["status"]; export func…
Run
/** * loom-builder — homeostatic dispatch harness. * Runs one DispatchSpec: agent loop (pi-coding-agent SDK) under har…
Exit Matrix
/** * Exit-code retry matrix — maps process outcomes to verdicts. * * Bug fixed: executor exit -1 previously could re…
Import Lesson
/** * import-lesson.ts — reads enforcement artifacts from pi-cybernetic's file-based * queue and applies them to loom-…
Dispatch Archive
/** * dispatch-archive — THE single source of truth for the Dispatch Artifact Contract. * * Contract (see /home/mikes…
Gate Escalation
/** * gate-escalation — consecutive-failure tracking and diagnostic interrogation. * * When the same validation gate …
Gates
import { createHash } from "node:crypto"; import { GateHaltError, type HaltReason, type ValidationCmd } from "./types.js…
Purpose
import type { DispatchSpec } from "./types.js"; export const PURPOSE_HEADER = "## PURPOSE (INVARIANT — restated verbati…
Trace
import { appendFileSync, mkdirSync } from "node:fs"; import { dirname } from "node:path"; import type { TraceEvent } fro…
0001 Scrape Store
-- 0001_scrape_store.sql — B6 D1 persistence layer for codemode-gateway. -- Creates the single `scrape_pages` table back…
Scrape And Store
async () => { const md = await browser.markdown({ url: "https://example.com" }); const summary = await ai.generate({…
Index
import { DynamicWorkerExecutor } from "@cloudflare/codemode"; import type { Env, ErrorResponse, ExecuteRequest, …
Parse
/** * Parse-don't-validate helpers for tool argument parsing. * * Each helper throws a plain `Error` with a `"<tool>:…
Registry
import { DynamicWorkerExecutor, type ResolvedProvider } from "@cloudflare/codemode"; import type { Env, ToolDef, T…
Client
import type { CfEnvelope, CfError, Env } from "../types"; import { CloudflareApiError } from "../types"; /** * Host-si…
Tools
import type { CfEnvelope, CfError, D1Database, Env, KvNamespace } from "../types"; import { CloudflareApiError } from ".…
Snippet
/** * Snippet store types. A snippet is a saved, named sandbox script — the * gateway's "procedural memory". Stored as…
Index
/** * Barrel export for gateway-local types. */ export type { Env } from "./env"; export type { ExecuteRequest, Ex…
Env
/** * Worker environment bindings for codemode-gateway. * * `LOADER` is the `worker_loaders` binding used by `Dynamic…
Cf
/** * Cloudflare REST API client types and the typed error surfaced to sandbox * code when the API returns `success:fa…
Execute
/** * HTTP request/response contracts for `POST /execute`. * * These are the gateway's own wire types and are intenti…
Registry
import type { Env } from "./env"; /** * Tool registry types. The registry (`src/registry.ts`) is the single source * …
Store
import { normalizeCode } from "@cloudflare/codemode"; import type { Env, Snippet, SnippetSummary } from "../types"; /**…
Browser
import type { Env } from "../types"; /** * Browser namespace tools — powered by Browser Rendering quick actions. * *…
Artifacts
import type { Env } from "../types"; /** * Artifacts namespace tools — R2 bucket for binary artifacts. * * Provides …
Scrape
import type { Env } from "../types"; /** * `scrape` namespace tools — convenience persistence over the bound D1 * dat…
Db
import type { Env } from "../types"; /** * `db` namespace tools — generic SQL over the bound D1 database `env.DB`. * …
Util
/** * Implementations for the `util` namespace: `util.echo(x)`, `util.now()`, * `util.rand()`. Contains only trivial, …
Ai
import type { Env } from "../types"; /** * AI namespace tools — powered by Workers AI binding. * * Uses `env.AI.run(…
Drizzle.Config
import type { Config } from "drizzle-kit"; /** * Drizzle is the typed query layer over D1 (src/db/schema.ts). * Migra…
0001 Init
-- LOOM 0001_init — 7 core tables + FTS5 + append-only enforcement. -- Identical on local workerd (--local) and edge D1 …
Parity Check
#!/usr/bin/env bun /** * Parity Check — byte-stable decision log for LOOM monitor decision path. * * Replays a script…
Approve Skills
#!/usr/bin/env bun /** * Approval CLI for skill proposals. * * This is OPERATOR TOOLING — a bun script, NOT workerd c…
Index
import { drizzle } from "drizzle-orm/d1"; import { dispatches, traceEvents } from "./db/schema"; import { checkContract,…
Loop Detector
/** * H3.2 — Loop Detector: actionHash(tool, args) via src/lib/ids.ts; * ring buffer W=10; ≥3 identical in window → HA…
Preflight
/** * H3.7 — Preflight: before any recoverable|destructive action, scan a provided * list of staged file contents for …
Budget Governor
/** * H3.6 — Budget Governor: hard caps B_tokens / B_calls / B_wallclock_ms from * the envelope. Breach → graceful sus…
Conf Monitor
/** * H3.5 — Confidence Monitor: every assistant turn must include conf ∈ [0,1] * (schema-enforced; extract from a tra…
Reinjector
/** * H3.4 — Reinjector: normalize observations. Truncate to per-tool obs_cap_tokens * from the envelope; store full t…
Reversibility Gate
/** * H3.3 — Reversibility Gate: every tool call checked against the envelope * allowlist. Each allowlist entry has re…
Model Client
/** * H3.0 — Fetch-based Anthropic Messages API client. * workerd-compatible: plain fetch, NO node SDK, no node:* impo…
Ack Gate
/** * H3.1 — Ack Gate: wrap every tool result with obs_hash; enforce that the * NEXT assistant turn begins with `<ack …
Harness
/** * H3 — Harness: runStage(envelope, modelCaller, deps): Promise<StageResult> * composing all monitors around the to…
Index
/** * Loop 5 — Synthesis batch glue. * * Thin scheduled() handler that wires injectables from the worker's Env * int…
Entropy Monitors
/** * H5.4 — Entropy Monitors. * * Queries entropy H(q) (dispatch outcome entropy) and H(s) (source/variety_class * …
Registry Updater
/** * H5.3 — Registry Updater. * * Recomputes mode_registry success_n / fail_n / avg_cost_tokens per * (mode, variet…
Dataset Emitter
/** * H5.6 — Dataset Emitter. * * Exports (failure_pattern, root_cause_signature, successful_intervention) * tuples …
Report
/** * Synthesis Report Assembler. * * Orchestrates all Loop 5 monitors (H5.1–H5.6) into a single SynthesisReport: * …
Revision Governor
/** * H5.5 — Revision Governor. * * Hard caps on skill proposals per window (tunable, default 5). * Tunable-paramete…
Skill Proposer
/** * H5.2 — Skill Proposer. * * Detects recurring successful sub-sequences across ≥ N distinct goals * (tunable, de…
Failure Clusterer
/** * H5.1 — Failure Clusterer. * * Groups trace failures by (tool, normalized error signature, variety_class). * Er…
Index
/** * Loop 2 dispatcher — thin worker-side barrel + concrete wire-ups. * * All logic lives in src/dispatcher/core/ (p…
Registry Seed
/** * Seed data for the mode_registry D1 table. * * Three modes covering the spec's default model set, with typed see…
Mode Registry
/** * H2.1 — D1-backed mode registry. * * selectMode(variety_class) picks the mode with highest success rate for that…
Types
/** * Injectable interfaces for the Loop 2 dispatcher core. * * Every dependency is an interface so tests inject fake…
Envelope Compiler
/** * H2.2 + H2.3 — Envelope Compiler. * * compile(stage, mode, opts): DispatchEnvelope * - Tool allowlist: only the…
Probe Planner
/** * H2.5 — Probe Planner. * * For stages with variety_class === "api_integration" AND no management-scope * behavi…
Dlq Escalator
/** * H2.4 — DLQ Escalator. * * Converts a dead letter into a Loop 1 escalation: * - builds typed escalation payload…
Index
/** * Loop 4 — Memory Service: thin worker shell. * * Factory: pick VectorizeIndex when env.SEMANTIC binding present,…
Pointer Hierarchy
/** * H4.4 — Pointer Hierarchy. * * topic → summary → episodic_ref (R2 key). * * memoryExpand(record_id): resolve e…
Promotion Engine
/** * H4.2 — Promotion Engine. * * episodic → semantic: when a pattern recurs across ≥ m_promote distinct traces. * …
Scope Wall
/** * H4.3 — Scope Wall. * * All reads/writes carry a required scope. Default read path filters to the * caller's sc…
Semantic Index
/** * H4.6 — SemanticIndex: search abstraction with two implementations. * * VectorizeIndex — wraps Cloudflare Vecto…
Compactor
/** * H4.5 — Compactor: summarize raw working context into semantic MemoryRecords. * * compactStage(goal_id, stage_id…
Context Assembler
/** * H4.1 — Context Assembler. * * assembleContext({scope, goal_id, query, token_budget}): * 1. Query SemanticIndex…
Index
/** Barrel — import all LOOM types from "@/types" or relative "../types". */ export * from "./contracts"; export * from …
Env
import type { DispatchEnvelope } from "./contracts"; /** Worker bindings — must match wrangler.jsonc exactly. */ export…
Contracts
/** * TypeScript mirrors of the 5 LOOM contracts (src/contracts/*.schema.json). * The JSON Schemas are the source of t…
Errors
/** Typed error hierarchy — never throw bare Error, never swallow. */ export abstract class LoomError extends Error { …
Synthesis
/** * Loop 5 synthesis types — report shapes, interfaces, contract-style types. * * All Loop 5 outputs are typed here…
Execution
/** * Execution harness types — Loop 3: model client, monitors, stage result. * All new execution types go here; barre…
Memory
/** * Memory service types — Loop 4. * * Injectables: BlobStore, SemanticIndex, Clock, TokenCounter. * D1DatabaseLik…
Schema
import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core"; /** * 7-table D1 schema — mirrors LOOM-SP…
Retry
import { RetryExhaustedError } from "../types/errors"; /** * Exponential backoff with FULL jitter (HC-6): delay = rand…
Ids
/** * Identity + hashing primitives shared by every loop. * Web Crypto only — identical behavior on workerd and Bun (H…
Logger
/** * Structured logger. The single sanctioned sink for log output — * bare console.log in logic paths is a lint-level…
Hmac
/** * HMAC utilities shared by Loop 1 (token-mint) and Loop 3 (reversibility-gate). * WebCrypto only — workerd-compati…
Validate
import { Ajv, type ValidateFunction } from "ajv"; import addFormats from "ajv-formats"; import { ContractViolationError …
Do
import { drizzle } from "drizzle-orm/d1"; import { goals } from "../db/schema"; import { parseContract } from "../lib/va…
Types
/** * Injectable interfaces for LOOM Loop 1 orchestration core. * Every dependency is an interface so tests can inject…
Predicates
/** * H1.1 — Predicate evaluators for the six machine-evaluable predicate kinds. * * Each takes a Predicate spec + an…
Escalation Ledger
/** * H1.4 — Escalation ledger for per-stage fail_streak persistence and * escalation records. Append-only records are…
Index
/** * Barrel — all core orchestration classes and types. */ export { type PredicateEvaluation, evaluatePredicate, eva…
Drift Sentinel
/** * H1.6 — Drift Sentinel: embed last N stage summaries, compare cosine distance * against the original_spec embeddi…
Checkpoint
/** * H1.1 + H1.4 — The alarm-tick sequence: assemble current GoalState, * evaluate active stage done-criteria predica…
Decomposer
/** * H1.3 — Decompose a goal spec into a sequence of StageSpec[] via a single * model call. Each StageSpec is validat…
Token Mint
/** * H1.5 — HMAC single-use, stage-scoped, TTL'd approval tokens for destructive * actions. WebCrypto only. * * Tok…