Freshware · Interactive Workbook
MDX Source Edition Residual Systems & Verified Compilation Learning Center & Videos
Part II & IV · Specification & Extraction · Chapter 03

Specifying and Extracting Constraints with session-spec-verify and pi-durable

Splitting ground truth between code diffs and session transcripts, enforcing Three-Tier Mutation Hygiene, and isolating invariant conflicts via zero-copy SQLite forks.

Reading time: 11 min Interactive: Lab 02 · Constraint Extractor & Conflict Fork Source: src/content/chapters/03-extract-and-specify.mdx

How do constraints move out of messy human conversations into durable, machine-enforced boundaries without rotting into stale documentation?

The architecture of session-spec-verify rests on a clean epistemological split:

Code / Git Diffs           --->  Ground truth for WHAT the system does
Conversation Transcripts   --->  Ground truth for WHY it looks that way

Code alone never tells you why an accounting check rounds to the half-even cent, why a rush-invoice shortcut was explicitly rejected last month, or which odd-looking fallback exists because a supplier’s legacy endpoint drops zero-value lines. Conversely, chat logs alone drift away from shipped reality the moment someone edits a parser.

Extracting specifications means binding both inputs into a compact, cold-rebuild-sufficient docs/ structure:

  • docs/standards/*.md: Protected external invariants shared across repositories.
  • docs/specs/<layer>/*.md: Conceptual Bounded Context packs with ## Intent, ## Invariants, ## Acceptance Criteria, and ## Verification.
  • docs/decisions.jsonl: Append-only rationale log recording choices, accepted risks, open questions, and override authority (person vs coding_agent vs review_agent).
  • docs/runs/<timestamp>/: Immutable evidence logs (verdicts.jsonl + summary.md) produced by passive audits and isolated sandbox drills.

Three-Tier Mutation Hygiene (Macro Boundaries)

In classical Scheme macros, hygiene prevents an expanding macro from accidentally overwriting bindings owned by its caller. Freshware applies the exact same rule to self-updating software by stratifying every constraint into three mutation tiers:

TierWhat Lives HereWho Can Edit ItCompiler Sandbox Permission
Tier 0 · Hard Invariantsdocs/standards/*.md, penny-balance checks, deduplication keys, signed credit rules, frozen Golden Pinsperson-authored decision only (decisions.jsonl override)Mounted Read-Only (write and edit hard-blocked)
Tier 1 · Mutable PoliciesPlain-English operator playbooks, category mappings, deposit splits, site overridesAuthorized operator or Phase 1 compiler after Gate 1 & Gate 2 passRead/Write candidate bundle (ownedRepoRoot)
Tier 2 · World-State AdaptersExtraction prompts/regexes, vendor PDF column maps, upstream REST DTO adaptersAutonomous Phase 1 self-healing inside Tier 0 + Tier 1 boundsRead/Write inside ACL module boundary only

Step Inside the Loop: Interactive Extractor & Conflict Sandbox

Before examining the TypeScript implementation running in our @earendil-works/pi-durable test suite, step through the full lifecycle interactively below: from alignment grilling, to SQLite constraint recovery, to a compatible Tier 1 promotion, and finally to a Tier 0 invariant collision that halts promotion and spawns a zero-copy conflict fork.

Interactive Lab 02 · Develop -> Specify -> Extract -> Conflict Fork

Step Through Transcript Extraction, Gate Checks, and Invariant Escalation

Step 1 · Alignment Turn
Session Conversation & Probe Input
User: "Let's grill the billing intake boundaries before writing runtime code. What terms and Tier 0 laws cannot shift autonomously?" Assistant: TERM[Canonical Bill]: Normalized invoice entity keyed by (vendorId, invoiceNumber) before ledger sync. TERM[Golden Pin]: Frozen historical invoice expectation that every candidate compilation must satisfy. INVARIANT[no-duplicate-posting]: Never create a second payable bill when the (vendorId, invoiceNumber) key already exists. INVARIANT[signed-credit-notes]: Credit memos preserve negative line totals across extraction and export.
Extracted SQLite State & Verification Gates
docs/specs/accounting-core.md (Extracted via GenerationTask.afterRun): - [tier0_invariant] no-duplicate-posting - [tier0_invariant] signed-credit-notes Ubiquitous Language (CONTEXT.md): - Canonical Bill - Golden Pin Gate Status: BASELINE LOCKED (v1)

How It Works in @earendil-works/pi-durable

Instead of bolting fragile cron scripts or ad-hoc JSON files onto an agent loop, @earendil-works/pi-durable provides transactional SQLite persistence (openNodeSqliteStorage), extension lifecycle hooks (GenerationTask, ToolTask), typed document families (defineDocFamily), and zero-copy conversation forks (conv.fork).

Our executable harness in src/experiments/pi-durable/harness.ts proves three concrete mechanisms:

1. Post-Turn Durable Extraction (GenerationTask.afterRun)

Every committed alignment turn automatically fires a durable background probe task (freshware.extract-probe). It reads the committed user/assistant entries, distills TERM[...], INVARIANT[...], POLICY[...], ADAPTER[...], and DECISION[...] records, and commits them transactionally into ExtractedConstraintsDoc:

export const ExtractedConstraintsDoc = defineDocFamily<ExtractedState, null>({
  kind: "freshware.constraints",
  version: 1,
  family: true,
  scope: "conversation",
  history: "latest",
  fork: "initial",
  initial: () => ({ constraints: [], decisions: [], glossary: {} }),
  checkpointWhen: () => true,
});

Notice the critical concurrency rule inside pi-durable: all extraction inference executes before opening runtime.commit(async (tx) => ...), ensuring zero single-writer lock deadlocks while persisting state atomically across process restarts.

2. Mechanical Oracle Isolation (ToolTask.beforeTool)

When Phase 1 spins up a compiler Habitat to synthesize candidate rules, we pass ownedRepoRoot pointing at the isolated candidate/ directory and mountedReadOnlyRoots pointing at golden-oracles/ and standards/. A ToolTask pre-hook intercepts every file tool call before execution:

if (call.name === "write" || call.name === "edit") {
  const hitReadOnly = readOnlyRoots.find((roRoot) => isWithinRoot(resolved, roRoot));
  if (hitReadOnly) {
    return {
      block: "Mounted oracle/standard path is read-only; Tier 0 invariants cannot be mutated by the compiler.",
    };
  }
}

In our live Scenario 2 test (c1:OK,c2:OK,c3:ERR,c4:ERR), reading the oracle succeeds, writing the candidate rulebook succeeds, and both attempted writes to the oracle fixture and Tier 0 standard are rejected cleanly before touching disk.

3. Conflict-to-Thread Escalation (conv.fork)

What happens when a customer request or operator edit genuinely collides with a Tier 0 invariant? An autonomous compiler must never pick Option B silently. Instead, it halts promotion on the root conversation, creates a zero-copy SQLite fork at the baseline entry (await habitat.fork(baseline.answerEntryId)), records an outcome: "open" conflict record presenting both options, and leaves the active production baseline untouched until a human ratifies either narrowing the rule (Option A) or overriding the invariant with explicit "person" authority (Option B).