Skip to content
المشاريع

Harmeet10000/AgentNexus-LangChain-FastAPI

عرض على GitHub

حول

Langchain FastAPI server

تطوير الويب والتطبيقات

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
+١
خلال 15 يومًا
+١
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

Agent Saul

Tenant-aware, human-in-the-loop legal contract analysis on LangGraph. Saul ingests messy real-world contracts into canonical, versioned chunks, retrieves evidence under server-derived authorization, and produces grounded findings — every claim carried by a verified evidence handle, every terminal state typed, nothing answered from memory.

📚 Documentation: Mintlify site in apps/docs/ — cd apps/docs and run npx mintlify dev locally.

CI Greptile: The War on Bugs

Why this exists

Legal work has a strange cruelty to it: the most expensive human judgment sits behind a wall of repetitive reading, clause sorting, calendar math, template comparison, and anxious second-guessing. The people who need clarity most are usually the least able to buy it continuously — founders signing vendor terms, families reading settlement papers, policyholders facing claim language, small businesses trying not to discover a liability clause after the damage is done.

Agent Saul exists to reduce that information asymmetry. Not by pretending to be a lawyer, and not by turning legal judgment into autocomplete, but by making the repetitive surface area small enough that humans spend their attention on the parts that actually require judgment.

The pain in India is specific: small startups rarely have strong legal teams on call; individuals are intimidated by fine print and legal notices; much of the work is high-volume, low-judgment grunt work; and most contract-AI products carry US/UK assumptions, not Indian statutes, procedures, and enforcement realities. The high-volume surface worth automating: clause tagging, risk flagging (one-sided indemnity, unlimited liability), deadline tracking, template comparison, stamp-duty and jurisdiction sanity checks, "is this clause enforceable in India?"

Time is a symptom. Risk and uncertainty are the disease. The same principle governs how we build this project: agents should remove avoidable strain and the quiet dread of "what if I chose wrong" — lifting invisible weight off people, not adding a new layer of it.

What it does

  • Bulletproof ingestion — bounded uploads (size + extension checked before buffering) → queued Celery pipeline → canonical chunks carrying contract_index, page_no, document_version, pipeline_version. Terminal states are truthful: completed, completed_with_warnings, or failed — never a silent partial.
  • Scoped hybrid retrieval — BM25 + pgvector fusion under allowed_doc_ids and contract_index scoping, with Graphiti as an optional relationship backend and coverage signal.
  • Evidence-handle security — search returns server-issued, TTL-scoped handles; read_evidence_by_id re-authorizes on every call (run, thread, checkpoint, document version). Identity and scope never come from the model.
  • Grounded specialist analysis — risk, compliance and deep-research sub-agents behind a ≤7-tool projection, mandatory grounding gate (handle membership → quoted-text substring check → entailment), typed findings, then human review.
  • Human-in-the-loop by construction — plan approval and report review are LangGraph interrupts; resumes re-resolve authorization because a checkpoint can outlive a role change.
  • An evaluated system — a provenance-gated evaluation corpus (105 cases, 23 categories, dual-annotated, Cohen's κ 0.815) runs in CI with checksum, licensing and adjudication gates.

How Saul reasons

Frontend toolchain

The static console in apps/console/ uses Bun 1.4.4. Install and verify it with the checked-in lockfile before changing frontend dependencies:

cd apps/console
bun install --frozen-lockfile
bun check --threads 4
bun run lint
bun fmt --check
bun run build

The Bun version is pinned in apps/console/.bun-version and apps/console/package.json; CI uses the same version and bun ci. Bun 1.4.4 provides the built-in TypeScript checker and formatter. Its pinned CLI does not provide the newer native lint command, so this project retains ESLint for linting. Python tooling continues to use uv.

CI caches Bun's package cache against apps/console/bun.lock. For an offline or prewarmed install, run bun pm fetch before bun ci; to move the exact cache entries for this lockfile, use bun pm cache pack <archive> and bun pm cache unpack <archive>.

Saul is a stateful, resumable, memory-aware reasoning pipeline: a distributed, resumable, schema-driven cognitive workflow engine with controlled reasoning surfaces, built on three layers:

  1. Memory shaping — filters, trimming, bounded context.
  2. Runtime control — specialist sub-agents, routing, orchestration.
  3. Execution durability — pause, resume, retry, replay.

The mental model underneath:

  • The LLM is a stateless reasoning engine.
  • State is the source of truth (LegalAgentState and its projections).
  • Memory is indexed projections of state — advisory surfaces, never the record.

The deepest design constraint: if your system cannot deterministically replay a run, you do not control your agent. Hence the shape:

Plan -> deterministic execution -> validated output -> persisted state

Not:

LLM -> decide -> act -> hope it works

The orchestration maps one-to-one onto the requirements. The orchestrator plans, then delegates to specialist sub-agents (risk, compliance, deep research) that loop over their tool surfaces until the plan step is done; the orchestrator reviews specialist output, handles failures, and replans when needed. Both plan approval and final report review are LangGraph interrupts — humans sit inside the loop, not on top of it. State lives in LegalAgentState; specialists read and write through controlled surfaces, and every resume re-resolves server-derived authorization before any evidence handle is honored.

LangGraph performance rules

Do not initialize models or compile agents inside graph nodes. That is the fast path to slow requests, memory churn, noisy traces, and production pain.

# Wrong: rebuilds the runtime on every call
def research_node(state):
    model = init_chat_model("<provider:model>")
    agent = create_agent(model, tools)
    return agent.invoke(state)

# Right: compile once, execute many
research_agent = create_agent(
    init_chat_model("<provider:model>"),
    tools=[search_caselaw],
)

def research_node(state):
    return research_agent.invoke(state)

Model initialization can spend 100–500 ms fetching config and metadata; agent construction adds tens of milliseconds more. Ten nodes across ten concurrent requests become hundreds of avoidable constructions per second — and traces stop being comparable because the runtime shape keeps being rebuilt.

The convention in this repo: models, tools, and graphs are compiled once at startup (FastAPI lifespan), held on app.state, and passed into graph.add_node(...) as ready callables. Checkpointers are wired per-workflow where isolation matters, dynamic model selection goes through explicit lookup tables, and heavy resources are never built inside node bodies. The graph behaves like infrastructure, not improvisation.

Architecture

Agent Saul full architecture Deployment topology
Orchestration — LangGraph with HITL interrupts, server-owned authorization, TTL evidence handles, mandatory grounding. Topology — Caddy → FastAPI → role-separated Celery pools → Timescale/Postgres, RabbitMQ, Redis, Neo4j, MongoDB, R2.
Hybrid query pipeline Memory stack
Query path — deterministic scoping → hybrid fusion → optional Graphiti enrichment → answers that disclose their evidence policy. Memory — durable workflow state (checkpointer, handle store) vs advisory memory (Graphiti, cognee), surfaced through a coverage signal.
Search system overview
Documents system — bounded upload → canonical ingestion → versioned persistence → evaluation as a first-class subsystem.

Honest status

What is real today: the ingestion pipeline with truthful terminal states and bounded validation; the evidence-handle service; the Saul orchestration graph with HITL and a grounding gate; the evaluation corpus and its CI gates (64 release-tier cases; 41 await human SME adjudication — the corpus is designated candidate, not gold, until adjudication completes). What is pending: SME adjudication of judgment-dependent labels (typed relationship edges landed with the retired plan's Phase D — the archived plan carries the completion audit), retrieval unification (mount-retrieval-graph) and the portfolio tool layer (see PLAN-agent-tools.md).

Agent Saul also has a default-off AG-UI run API at POST /api/v2/agent-saul/agui/runs, with owner-scoped session and transcript reads at GET /api/v2/agent-saul/sessions and GET /api/v2/agent-saul/sessions/{session_id}/transcript. The same-origin /console client remains behind AGENT_CONSOLE_ENABLED. Locally, FastAPI can serve apps/console/dist when the bundle is present; production Compose serves the independently tagged console image behind Caddy. Its Agent Saul RunProvider uses the AG-UI HttpAgent directly; no Copilot Runtime service is deployed. Each human interrupt terminates one run, and the client resumes by posting a new run for the same threadId. The console is served only when the corresponding feature flag is on. Its SPA document uses a restrictive same-origin CSP and revalidation; hashed assets are cached immutably. The production bundle still needs its build-under-CSP acceptance. The GCP Cloud Run request timeout is 2,100 seconds above the 1,800-second run budget. Other deployment proxies must disable buffering and allow a read timeout longer than the run; Uvicorn trusts forwarded scheme/client headers only from the configured UVICORN_FORWARDED_ALLOW_IPS peers (loopback by default). The Cloud Run Terraform service explicitly sets * because managed ingress is the only path to its container. Caddy deployments must set the setting to the exact Caddy peer address or a tightly scoped proxy subnet; never use * on a host or container deployment. The existing WebSocket interface remains compatible and is deprecated for new clients.

Security model

  • Server-derived authorization. ToolRuntimeContext/AuthorizationContext (user, tenant, role, allowed_doc_ids) is constructed from authenticated claims on every request and WebSocket resume — client-supplied identity is never trusted.
  • Capability-shaped evidence. Handles are short-lived, run- and version-bound, and mechanically invalid outside their provenance context.
  • Untrusted documents. Document text is data, never instructions; injection fixtures are part of the evaluation corpus and CI.
  • Bounded inputs. Upload size and extension are enforced before buffering; per-document cost/latency budgets are part of the hardening track.

Evaluation

The evals/ subsystem is CI-gated, offline and provenance-first:

# validate a gold set (provenance, checksums, adjudication state)
uv run python -m app.ai.evaluation.validate evals/golden/legal_retrieval_v2.jsonl

# run the deterministic experiment harness (console script: legal-eval)
uv run python -m app.ai.evaluation.experiment evals/experiments/legal_retrieval_smoke.json

The v2 corpus (evals/golden/legal_retrieval_v2.jsonl, 105 cases) ships with a per-artifact provenance manifest (source URLs, licences, SHA-256, permission and redistribution status), dual blind annotations, and an adjudication runbook. CI fails on unknown provenance, missing checksums, unadjudicated release-quality cases, multi-contract cases without contract_index, and raw binaries whose terms disallow redistribution.

Quickstart

Prerequisites: Python 3.12, uv, and configured development services. Docker is optional for the local RabbitMQ and PostgreSQL services shown below. With existing development services, use the console development guide to start FastAPI with uv and run Vite. Start the worker for a feature when that workflow needs it.

git clone https://github.com/Harmeet10000/AgentNexus-LangChain-FastAPI.git
cd AgentNexus-LangChain-FastAPI
cp .env.example .env.development        # fill in providers + infra credentials
# Recommended: replace the marked local JWT value with: openssl rand -hex 32

docker compose up -d rabbitmq timescale # local RabbitMQ + PostgreSQL/Timescale
uv sync --extra dev
uv run alembic -c apps/api/alembic.ini upgrade head             # see caveat below

make backend
make celery-ingestion                   # separate terminal — ingest your uploads

Migration caveat: the Alembic chain assumes the provisioned lineage. A brand-new database stops at revisions whose tables predate the chain (documented in apps/api/src/alembic/versions/0012_* and 0014_*). If upgrade head fails past the extensions, you are past what a fresh database can reach — use a provisioned snapshot. Compose does not mount a Postgres entrypoint init script: the referenced scripts/init-db.sql does not exist, and the Alembic revisions are the existing source of truth for extension and schema setup. Postgres entrypoint scripts run only while initializing an empty data directory, so they cannot replace the one-shot migration step for an existing volume.

Tenancy note: new users need a personal tenant before tenant-scoped routes work (tools/operations/migrate_personal_tenants.py backfills; registration-based provisioning is tracked in docs/server-smoke-2026-10-28.md F4).

The app also runs against fully managed infrastructure (Timescale Cloud, Redis Cloud, MongoDB Atlas, Cloudflare R2, Railway RabbitMQ) — set the POSTGRES_*, REDIS_*, MONGODB_*, RABBITMQ_* and S3_* variables in .env.development accordingly.

Common commands

uv run ruff check --fix && uv run ruff format   # lint + format
uv run ty check apps/api/src/                            # types
uv run pytest                                   # unit suite (integration excluded by default)
uv run pytest -m integration                    # integration (needs live services)
make test-e2e                                   # hermetic end-to-end critical journey (no live services)
make perf-gate                                  # measured RRF fusion budget (also in make selfcheck)
make coverage                                   # measured coverage gate (also in make selfcheck)
ast-grep scan apps/api/src/                              # structural rules

# worker role profiles — queue, pool, concurrency and child-recycle are
# owned by the role definition; do not add a second -Q or process-shape flag
.venv/bin/worker --role default --loglevel=info
.venv/bin/worker --role ingestion --loglevel=info
.venv/bin/worker --role crawler --loglevel=info
.venv/bin/beat --loglevel=info

# local entry points, as make targets
make backend            # FastAPI backend (BACKEND_HOST/BACKEND_PORT can override defaults)
make celery              # default worker pool
make celery-ingestion    # ingestion worker pool
make celery-crawler      # crawler worker pool
make celery-beat         # periodic scheduler

End-to-end coverage

tests/e2e/ holds the repeatable critical-journey suite. The current scenario drives signup → email verification → verified login → authenticated profile read → logout through the real FastAPI app (create_app() and its v1 routes, middleware, dependency wiring and AuthService). It is hermetic: MongoDB, Redis, PostgreSQL/tenant provisioning and the email-token edge are replaced by narrow in-memory doubles, so it needs no .env, secrets, or running services and is safe to repeat in CI. The exact command is:

make test-e2e          # uv run pytest tests/e2e/ -q -m e2e --tb=short

The same suite is also collected by make coverage and is run explicitly by the test CI workflow.

Project structure

apps/api/src/app/
├── api/                 # v1/v2 routers, strict response envelopes
├── ai/                  # LLM clients, embeddings, tools registry, evaluation
│   └── evaluation/      # gold-set schema, provenance validator, experiment harness
├── config/              # pydantic settings (.env.development)
├── connections/         # Postgres/Timescale, Redis, Mongo, RabbitMQ, Graphiti
├── extraction/          # Docling parsing, LangExtract (incl. two-pass relationships)
├── features/            # hexagonal slices: api/ application/ domain/ adapters/
│   ├── agent_saul/      # orchestration graph (graph/ at slice root), HITL, WebSocket
│   ├── documents/       # upload, ingestion shim, retrieval, evidence service, tools
│   ├── auth/            # accounts, tenancy, legal roles, tenant migration
│   └── …                # billing (subdomain-layered by design), crawler, health
├── shared/              # cross-feature runtime: jobs, langchain/langgraph layers, rate_limit
├── kernel/              # pure primitives: clock, ids, result, tenancy
├── retrieval/           # Graphiti integration + idempotent graph writer
├── lifecycle/           # lifespan startup policies with typed degradation
└── worker/              # Celery role profiles, task catalog, beat schedule
evals/                   # golden corpus, provenance manifest, annotations, reports
docs/                    # diagrams, runbooks, smoke-test findings
apps/docs/               # Mintlify documentation site

For the system overview and architecture deep dives, see the Architecture documentation.

Documentation

Acknowledgments

Built on LangGraph, Graphiti, LangExtract, cognee, Celery, Timescale and Mintlify. Public corpus documents reproduced under the NHAI / Indian Railways / Supreme Court of India copyright policies and UK Open Government Licence v3 — attribution recorded per artifact in evals/corpus/.


Lynk: Where Legal Documents Meet Compiler Theory

Most legal AI companies do the same thing: throw raw text at an LLM and pray. The results are inconsistent, unexplainable, and impossible to trust in high-stakes contract review.

Lynk takes a different path. It treats legal documents as source code—complete with syntax trees, type checkers, and deterministic linting rules. The result is a system that produces the same output for the same input, every single time.

This plan documents how to make that vision technically real.


The Core Insight: Determinism by Design

The Vale plan for Lynk establishes a crucial architectural principle: ambiguity is a bug, not a feature. The linter rule suite enforces this through four mechanisms:

1. RFC 2119 Capitalization Rules

Legal language has words that carry contractual weight. "MUST" means mandatory. "SHOULD" means recommended. "MAY" means optional.

When engineers write "must" instead of "MUST", they've introduced ambiguity. The linter catches this immediately:

# .vale/styles/SDD/RFC2119Capitalization.yml
extends: existence
message: "RFC 2119 keyword '%s' MUST be UPPERCASE to carry contractual weight."
level: error
raw:
  - '\b(must|should|shall|may|must not|should not|shall not)\b'

Why this matters for agents: When an agent reviews a contract, it doesn't need to guess intent. The capitalization IS the intent. This reduces the cognitive load on downstream reasoning and eliminates an entire class of interpretation errors.

2. The "No Fluff" Rule

Subjective adjectives are kryptonite to automated analysis. "Fast", "scalable", "user-friendly"—these words mean nothing to a machine.

# .vale/styles/SDD/NoUntestableFluff.yml
tokens:
  - fast
  - robust
  - scalable
  - seamless
  - user-friendly
  - performant

Agent quality impact: When the linter rejects untestable language, the human author is forced to replace "fast response time" with "response within 200ms at p99". The agent now has a concrete threshold it can verify. The spec becomes executable.

3. EARS+ Syntax Enforcement

Easy Approach to Requirements Syntax (EARS) is a structured format for writing requirements. Every requirement starts with a specific clause:

  • Ubiquitous: "The [system] MUST..."
  • Event-driven: "When [trigger], the [system] SHALL..."
  • State-driven: "While [state], the [system] SHALL..."
  • Optional: "Where [feature], the [system] MAY..."
  • Unwanted behavior: "If [error], the [system] SHALL..."

The linter enforces this structure:

# .vale/styles/SDD/EARSSyntax.yml
raw:
  - '^\s*[-*]\s+\*\*REQ-[A-Z0-9_-]+\*\*:\s*(?!(When|While|Where|If|The\s+[A-Za-z0-9_-]+)\b).*'

Agent determinism gain: Instead of parsing free-form English prose, the agent receives structured, predictable sentence patterns. This is the difference between parsing a sentence like "Sometimes the system might respond quickly depending on load" and parsing "When load exceeds 80%, the system MUST respond within 500ms." One requires interpretation; the other requires verification.

4. Temporal Boundaries

Event-driven requirements must include numerical bounds:

# .vale/styles/SDD/EARSTemporalBounds.yml
message: "Event requirement ('When'/'If') lacks bounded numerical units."
raw:
  - '^\s*[-*]\s+\*\*REQ-.*?\*\*:\s*(When|If)\b(?!.*\b(\d+.*(?:ms|s|%|TPS|MB))\b).*'

Agent output quality: This forces requirements to be measurable. An agent checking contract compliance doesn't need to debate what "reasonable time" means—it checks against the stated threshold.


The Six-Step Workflow: From Ambiguity to Execution

The Vale plan isn't just about linting. It describes an end-to-end pipeline that transforms human intent into machine-verifiable artifacts.

Step 1: Intake & Bounded Context Classification

Current gap: Raw requests contain implicit assumptions about scope and boundaries. An agent might interpret "add payment processing" as a minor feature or a complete billing system redesign.

The fix: The workflow requires explicit C4 System Context diagrams and Bounded Context Maps before any specification work begins. The agent doesn't proceed to design until it can answer: "What system are we changing, and what systems are we NOT changing?"

Determinism improvement: Forces explicit boundary definition before solutioning begins.

Step 2: Interactive Spec Generation

Current gap: Agents generate specs in ad-hoc formats—sometimes Markdown, sometimes code comments, sometimes loose descriptions.

The fix: The workflow mandates a structured output:

  • Hexagonal Ports (driving/driven interfaces)
  • Data-Driven Schemas (OpenAPI/AsyncAPI/JSON Schema)
  • ROP Execution Paths (success track and failure track)
  • EARS+ Requirements (with unique REQ-IDs)

Agent output quality: Every generated spec follows the same schema. Downstream tools can parse, validate, and transform these specs without human intervention. The spec becomes a first-class artifact in the development pipeline.

Step 3: Automated Linter & Schema Verification

Current gap: Agents can generate syntactically correct but semantically ambiguous specifications. Humans review manually, inconsistently.

The fix: The Vale linter runs as a gate. If the spec contains lowercase "must", untestable adjectives, or malformed EARS syntax, the pipeline halts. The agent receives immediate feedback and must correct the spec before proceeding.

Determinism improvement: Eliminates human inconsistency in spec review. The linter is the reviewer, and its rules are explicit and version-controlled.

Step 4: Hostile Architecture Audit

Current gap: Agents optimize for the happy path. Edge cases, failure modes, and adversarial conditions are afterthoughts.

The fix: An adversarial review agent acts as a hostile QA architect. It systematically checks for:

  • Race conditions
  • Network partitions
  • Cascading failures
  • Missing fallback requirements

The output is an FMEA (Failure Mode and Effects Analysis) matrix that adds requirements for every identified failure state.

Agent output quality: This is where Lynk transcends typical AI-assisted design. Instead of reactive bug-fixing, the system proactively identifies failure modes during specification. The agent's output isn't just a feature spec—it's a resilient system design.

Step 5: Cryptographic Freeze & Artifact Generation

Current gap: Specs drift. An agent might reference version 1.2 of a requirement while implementation targets version 1.3.

The fix: Once validated, the spec is marked FROZEN with a version number. The system generates three enforcement artifacts:

  1. ArchUnit Rules: Static analysis that prevents code from violating hexagonal boundaries
  2. Property-Based Test Stubs: Tests that assert mathematical invariants from the spec
  3. Traceability Matrix: Machine-readable mapping of REQ-IDs to test annotations

Determinism improvement: The frozen spec becomes an immutable contract between design and implementation. Traceability is automatic and auditable.

Step 6: Atomic Task Deconstruction

Current gap: Agents decompose tasks by technical layer—"build database", "build API", "build frontend". This creates integration hell because no single task delivers end-to-end value.

The fix: The workflow decomposes tasks by ROP Railway Steps per Feature Slice:

  • One primary task for the Success Track
  • Separate sub-tasks for each Failure Track divergence

Agent output quality: Each task is independently testable. Developers can implement, verify, and ship failure handling without waiting for the entire system. This is the difference between "build the whole thing and then test it" and "build one verified slice at a time."


The Hidden Architecture: What Makes This Actually Work

The Vale plan documents several "insider" patterns that separate naive implementations from production-grade systems.

The AST Task Breakdown Anti-Pattern

Most engineering leads decompose by layer. The Lynk approach decomposes by ROP Railway Step. Why?

Layer-based decomposition:

Task 1: Build Database Schema
Task 2: Build API Controller
Task 3: Build Frontend
→ Integration happens at the end, if it works at all

ROP Railway decomposition:

Task 1: Success Track Step 1 → Step 2 → Step 3 (end-to-end slice)
Task 2: Failure Track Divergence A (If payment fails, then...)
Task 3: Failure Track Divergence B (If inventory unavailable, then...)
→ Each task delivers independent, testable value

Agent determinism gain: The agent's task breakdown is no longer a creative interpretation. It follows a deterministic algorithm: one task per ROP step, with failure tracks derived from the FMEA matrix.

The Single-Line Hard Wrap Rule

Vale evaluates rules line-by-line. If a multi-line requirement wraps the EARS trigger onto line 2, the linter fails on line 2 even though the requirement is valid.

The fix: Enforce single-line hard wrap for requirement sections. Every - **REQ-XXX**: ... must be a continuous, un-wrapped string.

Agent quality impact: The agent generates requirements that are guaranteed to parse correctly. No false positives, no ambiguous line breaks, no human intervention required to "fix" valid requirements.

The Legal Null Pointer Exception

The most devastating bug in legal contracts: Section 4.1 references "the limitations in Section 9(b)", but Section 9(b) was deleted during negotiation.

The fix: The linter treats section numbers as pointers, not text. Every ReferenceNode must resolve to an existing DeclarationNode. A broken reference is a compilation error, not a warning.

Agent determinism gain: The agent doesn't "suggest" that a reference might be broken. The system fails the spec until the reference is fixed or the pointer is updated. Deterministic verification, not probabilistic suggestion.


Agent Quality Output: Before and After

Before (Typical AI-Generated Spec)

## Payment Processing

The system should process payments quickly and reliably. When the user
submits a payment, the system validates it and processes it securely.
If something goes wrong, show an error message.

The payment flow should be seamless and user-friendly.

Problems:

  • "Should" is lowercase (RFC 2119 violation)
  • "Quickly", "reliably", "securely", "seamless", "user-friendly" are untestable
  • No temporal bounds on "quickly"
  • No specific error conditions
  • No REQ-IDs for traceability
  • Multi-line wrapping will break line-scoped linters

After (Lynk-Compliant Spec)

## Payment Processing

- **REQ-PAY-001**: When a user submits a valid payment request, the system MUST validate the payment within 100ms and process it within 2000ms at p99.
- **REQ-PAY-002**: If the payment gateway returns a timeout error, the system MUST retry with exponential backoff (100ms, 200ms, 400ms) for a maximum of 3 attempts.
- **REQ-PAY-003**: If all retry attempts fail, the system MUST display error code PAY-ERR-001 and log the failure with correlation ID for support traceability.
- **REQ-PAY-004**: Where the payment amount exceeds INR 10,00,000, the system MUST require two-factor authentication before processing.

Improvements:

  • RFC 2119 keywords are capitalized
  • Every temporal claim has a numerical bound (100ms, 2000ms, p99)
  • Error conditions are explicit with specific codes
  • REQ-IDs enable traceability
  • Single-line format guarantees linter compatibility

Agent output quality: The agent can now verify each requirement against implementation. It can generate tests that assert the temporal bounds. It can trace failures back to specific requirements. The spec is executable.


Implementation Roadmap

Phase 1: Linter Integration (Week 1-2)

  1. Install Vale CLI and configure .vale.ini
  2. Create .vale/styles/SDD/ directory with the five core rules
  3. Run vale docs/sdds/ against existing specifications
  4. Fix violations iteratively until the pipeline passes

Success criterion: Existing specs pass the linter with zero errors.

Phase 2: Agent Workflow Enforcement (Week 3-4)

  1. Modify agent prompts to require EARS+ syntax for all requirements
  2. Add post-generation hook that runs Vale before accepting spec output
  3. Implement REQ-ID auto-generation for traceability
  4. Create validation feedback loop: linter errors → agent correction → re-lint

Success criterion: Agent-generated specs pass Vale on first generation 80% of the time.

Phase 3: FMEA Integration (Week 5-6)

  1. Implement adversarial review agent with failure mode catalog
  2. Generate FMEA matrix from spec analysis
  3. Auto-generate failure track requirements from FMEA findings
  4. Validate that every EARS "If" clause has a corresponding test stub

Success criterion: Failure track coverage > 90% of identified failure modes.

Phase 4: Artifact Generation (Week 7-8)

  1. Implement spec freeze mechanism with versioning
  2. Generate ArchUnit rules from hexagonal port definitions
  3. Generate property-based test stubs from temporal bounds
  4. Generate traceability matrix linking REQ-IDs to tests

Success criterion: Every frozen spec produces runnable tests and static analysis rules.


Metrics That Matter

How do you know the plan is working?

Metric Baseline (Typical AI) Target (Lynk)
Spec ambiguity rate ~40% (subjective language) <5% (enforced by linter)
Temporal bound coverage ~15% of requirements >95% of "When/If" requirements
Failure track coverage ~10% (happy path bias) >90% (FMEA-driven)
Traceability (REQ-ID → Test) Manual, incomplete Automatic, complete
Linter pass rate (first generation) N/A >80%

The Deeper Pattern: From Interpretation to Verification

The Vale plan for Lynk represents a fundamental shift in how agents interact with specifications:

Traditional approach: Agent interprets human intent, generates output, human reviews and corrects.

Lynk approach: Agent works within a structured grammar, generates output that is machine-verifiable, linter enforces consistency, human reviews edge cases only.

This is the difference between a spellchecker that highlights misspelled words and a compiler that rejects syntactically invalid programs. The former is advisory; the latter is enforceable.

For the chosen ones: The ultimate determinism hack is to make the agent's output space so constrained that it cannot produce invalid output. The linter doesn't just check the output—it shapes the generation process. When the agent knows that lowercase "must" will fail, it generates uppercase "MUST". When it knows that "fast" will fail, it generates "200ms". The constraint IS the quality mechanism.

The Vale plan for Lynk is not just a linting strategy. It is a complete rethinking of the agent-specification relationship. The spec is no longer a document to be interpreted—it is a program to be executed.


Getting Started

# Install Vale CLI
brew install vale  # macOS
# or: choco install vale / apt install vale

# Configure for your project
mkdir -p .vale/styles/SDD
# Copy the five rule files from the plan

# Run against your specs
vale docs/sdds/

# Run in CI
vale --output=JSON docs/sdds/ > vale-report.json

The first run will hurt. That's the point. Every error is an ambiguity you didn't know you had.


"The linter is the law. Everything else is commentary."


STRIDE Threat Model

"""STRIDE threat model — Agent Saul (legal-corpus document intelligence).

Derived from the STRIDE-per-boundary walk over the shipped data flows, 2026-11-14. Companion to the harden change's red-team suites (Phase 8) and the observability program (Phase 5.9/9.1). Each finding cites its enforcement point and test.

Trust boundaries walked

B1 user → WS/API (auth, session start/resume) B2 API/worker → ingestion pipeline (Docling, extraction LLM, embeddings) B3 Saul graph → tools (evidence seam, knowledge tools) B4 tools → stores (Postgres pgvector/bm25, Neo4j Aura, R2, Redis) B5 model outputs → persisted state (extraction, findings, verdicts) B6 deployment boundary (this machine → cloud free-tier services)

The six categories, mapped

S — Spoofing

  • Forged evidence handles: server-issued, run-scoped, hash-verified at read; the grounding gate rejects forged handles (test_grounding_gate_matrix).
  • Forged party names / injected authority: injection fixtures prove extraction stays source-derived (evals/ingestion, commit c1ca96e).
  • Client-supplied reviewer roles: DTO-stripped; authority re-derived from live membership on every resume (test_resume_authorization.py).
  • Residual: S-1 — the WS session token lifetime vs long pauses (reviewed in Phase 9 rollout; accepted for synthetic-only pilot data).

T — Tampering

  • Metadata-override injection ("SYSTEM NOTE ... OVERWRITE METADATA"): the extraction prompt delimits untrusted content; persisted metadata stays source-derived (test_forged_metadata_cannot_displace_server_side_extraction).
  • Delimiter forgery inside documents: delimiter neutralization (commit 49e752e).
  • Boundary heading forgery: headings restricted to # / ALL-CAPS markers; the length arm that let ordinary clauses re-own boundaries was removed (red-team finding, fixed 2026-11-11 — see notes/phase8-eval-ci-redteam.md).
  • Residual: T-1 — relationship-edge tampering inside Neo4j (the graph store is shared; writes are partition-scoped by group id — accepted for pilot).

R — Repudiation

  • Read audit: append-only DocumentAccessAuditEvent per evidence search/read, non-content fields only (test_structured_events_no_secrets.py).
  • Deletion repudiation: tombstone + audit retention (90 days, APPROVED 2026-11-14) — the tombstone precedes any load.
  • Residual: R-1 — role-change events are not yet emitted (9.1 audit GAP; owned by the auth feature).

I — Information Disclosure

  • Cross-tenant reads: two-tenant isolation suites over all six legal tools + all 13 repository read predicates (query-level); dedup is tenant-scoped (migration 0029).
  • Scope widening: model-supplied scope never reaches the graph (V6 tests); the key-set seatbelt gates every compiled graph's input channels.
  • Grounding disclosure: unsupported/contradicted findings render in review with contract identity (6.7).
  • Residual: I-1 — _legal/ask's graphiti_verified policy discloses graph coverage counts (deliberate, documented — 5.11).

D — Denial of Service

  • Upload size/extension caps before buffering (2.4); per-document extraction budgets (2.5); stage budgets on every graph node (G6) with the standing degradation alert (5.9).
  • Observed non-malicious DoS (both live, 2026-11-11/13):
    • D-1: a transient Timescale LISTEN timeout shut the whole API down — a dependency blip became a full outage. Fix owed: the listener loop must reconnect-and-degrade, not terminate serving.
    • D-2: the OOM killer terminated workers mid-ingestion (Docling's per-call model load ≈ 3.7 GB RSS on the 37 MB document). Fix owed: the singleton- converter follow-up in the parser (named in its docstring) + worker memory bounds are already configured (--max-memory-per-child).
    • D-3: the Gemini free-tier daily embedding quota exhausted mid-burst, failing 12/15 ingestions with no typed quota signal surfaced. FIXED 2026-11-15 — quota-aware guard at the one embedding choke point (app.ai.embeddings._quota_guarded: seconds-scale probes for transient 429s; a 429 that names the daily cap, or one that survives the probes, raises the typed EmbeddingQuotaExhaustedError). The documents twin parks the document in the NON-terminal quota_exhausted status with typed metadata (resumable by the next quota window's idempotent driver — never a dead-letter, never a sleeping worker); the search twin dead-letters immediately with the typed code (SearchIngestQuotaExhaustedError).
  • Residual: D-4 — no rate limit on evidence-handle reads beyond auth (pilot- scale accepted).

E — Elevation of Privilege

  • Model-supplied scope arguments: never read — runtime context only (V6 tests; test_model_state_cannot_widen_the_tenant_boundary).
  • Key-set seatbelt: every compiled graph's input channels are contract-tested (set(initial_state) <= set(State.__annotations__)) — the LangGraph silent-drop class is closed.
  • Operation policy: analyst/reviewer/admin operation sets, orchestrator pre-dispatch checks, reviewer-role checks on every resume (3.6).
  • Residual: E-1 — role-change emission (the 9.1 GAP) would close the elevation-audit loop.

Standing residuals (accepted, with owners)

ID Threat Category Owner / trigger
S-1 WS token lifetime vs long pauses S Phase 9 pilot review
T-1 Shared Neo4j write surface T harden 7.x / staging
R-1 Role-change event emission R auth feature (9.1 audit)
D-1 LISTEN timeout → full API shutdown D root-caused 2026-11-14: systemd-oomd SIGTERM of the cgroup under memory pressure (not a listener bug — the relay's reconnect loop is sound). Mitigated by D-2's memory fix; the relay degrades via its backoff loop
D-2 OOM under Docling model load D FIXED 2026-11-14 — process-wide singleton converter, convert serialised by lock (tests: test_parser_converter_singleton.py); trade-off documented in parse_document
D-3 Embedding quota exhaustion untyped D FIXED 2026-11-15 — typed EmbeddingQuotaExhaustedError at the embedding choke point (probe-then-classify: seconds-scale probes separate a per-minute rate limit from the daily cap); documents park in non-terminal quota_exhausted with typed metadata, search dead-letters typed (SearchIngestQuotaExhaustedError). Measured incident: 2026-11-14, free-tier 1000/day cap, 12/15 ingestions
D-4 No secondary rate limit on handle reads D pilot-scale accepted
E-1 Role-change audit loop closure E auth feature (with R-1)

Method note

This model was produced by the STRIDE-per-boundary walk over the shipped flows, cross-checked against the red-team suites (Phase 8: 88/0 after the boundary regression fix) and the live incidents observed during the measurement runs. It is a living document: update on every new trust boundary or dependency.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…