Commit 0c2ca1a4
0c2ca1a42c36Merged
Scott Nixon <[email protected]> Β· 5 months ago Β· 1 file Β· +1 added
Description
Merge branch 'worktree-agent-ab2504b30c8316f02' into feat/attractor-5b8
Details
- Commit
- 0c2ca1a42c36
- Parent
- ef65aba49bb7
- Merge parent
- 2f2c356328f5
docs/specs/SPEC_PAS_INIT.mdaddedView file
1+
# SPEC-005: Automated Project Initialization and Declarative Quality Loops (`pas init`)2+
3+
**Revision:** 2 (2026-06-03 β closes P1-1 through P1-4 per review)4+
**Status:** Approved for implementation5+
6+
---7+
8+
## 1. Overview & Objective9+
10+
To maximize "Vibe Coding" velocity within Pascal's Discrete Attractor (PAS), we must eliminate manual scaffolding configuration. This specification details the implementation of the `pas init` subcommandβa smart, engine-aware bootstrapping system that automatically detects a codebase's toolchain (Rust, Python, TypeScript), configures local quality gates, and generates a structured `pas.toml` manifest file.11+
12+
Furthermore, this document specifies how the `pas` core engine natively consumes `pas.toml` during execution to handle recursive, agentic self-correction loops when quality checks fail.13+
14+
---15+
16+
## 2. The `pas init` Subcommand Architecture17+
18+
When a user or autonomous workspace builder executes `pas init`, the CLI triggers a **three-phase** initialization process combining high-speed deterministic static scanning with a lightweight agentic evaluation step and an interactive confirmation phase.19+
20+
```21+
[pas init] ββ> Phase 1: Static Heuristics ββ> Phase 2: Agentic Enrichment ββ> Phase 3: TUI Confirmation ββ> [pas.toml Generated]22+
```23+
24+
### CLI Flags25+
26+
| Flag | Description |27+
| :--- | :--- |28+
| `--force` | Overwrite an existing `pas.toml` without prompting. Also bypasses the "no git repo" refusal in non-interactive mode. |29+
| `--non-interactive` / `--yes` | Skip Phase 3 TUI; write manifest directly. Implied when stdout is not a TTY. |30+
| `--no-enrich` | Skip Phase 2 LLM enrichment even when multiple toolchains are detected. |31+
| `--dry-run` | Print the planned `pas.toml` to stdout without writing to disk. |32+
33+
**Existing `pas.toml` handling:**34+
35+
- Interactive mode: prompt to confirm overwrite. Default is **N** (do not overwrite).36+
- Non-interactive mode (no TTY or `--non-interactive`): refuse to overwrite without `--force`.37+
- `--force` always overrides both the "existing manifest" and "no git repo" refusals.38+
39+
**Non-interactive / autonomous mode:**40+
41+
| Env var | Effect |42+
| :--- | :--- |43+
| `PAS_NON_INTERACTIVE=1` | Behaves as `--non-interactive` even when a TTY is detected. |44+
| `PAS_AGENT=1` | Implies `PAS_NON_INTERACTIVE=1` + `PAS_TRUST_THIS=1`. Single flag for orchestrators and subagents. |45+
46+
### Phase 1: Static Signature Heuristics47+
48+
The CLI natively performs rapid pattern matching on the current working directory to identify the dominant programming languages and tooling stacks:49+
50+
| Signature File | Detected Toolchain | Default Quality Target Framework |51+
| :--- | :--- | :--- |52+
| `Cargo.toml` | Rust | `cargo fmt`, `cargo clippy`, `cargo test` |53+
| `pyproject.toml`, `poetry.lock`, `requirements.txt` | Python | `ruff format`, `ruff check`, `mypy`, `pytest` |54+
| `package.json`, `tsconfig.json` | TypeScript / Node | `prettier`, `eslint`, `tsc --noEmit`, `vitest`/`jest` |55+
56+
### Phase 2: Lightweight Agentic Enrichment57+
58+
Phase 2 is triggered when **any** of the following conditions are true:59+
60+
| Condition | Trigger |61+
| :--- | :--- |62+
| β₯2 distinct toolchains detected in Phase 1 | Polyglot resolution needed |63+
| Detected language has no recognized config file | Ambiguous project structure |64+
| Phase 1 produces no detection results | Unknown ecosystem |65+
66+
If `--no-enrich` is set, Phase 2 is skipped and `pas init` emits a multi-language stub manifest with all detected stage blocks and a `# TODO: review and consolidate` comment header.67+
68+
**Payload:** The agent is supplied with a **positive allowlist** of filenames only. Files not matching the allowlist are excluded from the LLM payload regardless of their presence on disk.69+
70+
Allowed filenames (exact match or glob):71+
`Cargo.toml`, `package.json`, `pyproject.toml`, `tsconfig*.json`, `requirements*.txt`, `setup.py`, `setup.cfg`, `pnpm-lock.yaml`, `yarn.lock`, `poetry.lock`, `.gitignore`, `README.md`, `Makefile`72+
73+
Files matching `.env*`, `*.key`, `*.pem`, `secrets/*`, `.git/`, `node_modules/`, `target/`, `__pycache__/` are **never** sent, even if they match an allowlist pattern. The allowlist fails closed β new ecosystem files require an explicit allowlist update.74+
75+
**Objective:** Determine the precise build commands, lint boundaries, and execution contexts that static scanning might misinterpret.76+
77+
**Fallback:** If the LLM errors or times out, Phase 2 falls back silently to the unenriched multi-stage stub from Phase 1. Phase 2 is a hint, not authoritative.78+
79+
### Phase 3: Interactive TUI Confirmation80+
81+
Before generating the manifest, the CLI outputs a clean user interface (via `dialoguer`) displaying the discovered configurations, giving the user an immediate opportunity to modify hooks before writing to disk.82+
83+
**TUI library:** `dialoguer` (version 0.12+). `ratatui` is explicitly deferred to a future `pas dashboard` feature.84+
85+
Phase 3 is skipped when:86+
- stdout is not a TTY87+
- `--non-interactive` / `--yes` is passed88+
- `PAS_NON_INTERACTIVE=1` is set89+
90+
---91+
92+
## 3. Complete `pas.toml` Manifest Schema Specification93+
94+
The `pas.toml` file resides at the root of the project codebase. The `pas` engine parses this file at runtime using a strongly-typed Rust parser (`toml` crate, version 1.x).95+
96+
```toml97+
[project]98+
name = "pascals-discrete-attractor"99+
version = "0.1.0"100+
primary_language = "rust" # Options: rust | python | typescript | custom101+
102+
[toolchain]103+
# Allows the local agent to understand compilation constraints104+
min_version = "1.75.0"105+
package_manager = "cargo"106+
107+
[quality]108+
# Required: explicit ordered list of stages to execute109+
stages = ["format", "lint", "typecheck", "test"]110+
111+
[quality.hooks.format]112+
cmd = "cargo fmt --check"113+
allow_failure = false114+
115+
[quality.hooks.lint]116+
cmd = "cargo clippy --all-targets -- -D warnings"117+
allow_failure = false118+
119+
[quality.hooks.typecheck]120+
cmd = "cargo check"121+
allow_failure = false122+
123+
[quality.hooks.test]124+
cmd = "cargo test -- --nocapture"125+
allow_failure = false126+
127+
[quality.telemetry]128+
# Dictates how error logs are parsed and summarized before injection into the LLM prompt129+
parse_ansi_escape_codes = true130+
truncate_logs_after_bytes = 4096131+
132+
[agent.loop_control]133+
# Hard stops to protect API spend and prevent infinite loops134+
max_fix_iterations = 3135+
```136+
137+
**Schema notes:**138+
139+
- `[quality] stages` is **required** and defines execution order. The engine runs stages in the order listed, not in TOML key order.140+
- Each stage in `stages` must have a corresponding `[quality.hooks.<stage>]` sub-table.141+
- Stage names in `stages` must be unique.142+
- `cmd` strings must be non-empty and β€4 KB.143+
- The `toml` crate (1.x) is used for the read path; `toml_edit` (0.22+) is used for the `pas init` write path to preserve comments and key ordering on re-runs.144+
- `allow_failure = true` semantics: a non-zero exit code emits a `WARN`-level log entry but the engine proceeds to the next stage. The node final status is `pass` if all `allow_failure = false` stages succeed.145+
- `backoff_factor` is not a supported field in v1. A hardcoded 1-second sleep is applied between retry iterations.146+
147+
**Reserved future fields (do not implement in v1):**148+
149+
- `[quality.hooks.<stage>].depends_on` β per-stage dependency ordering150+
- `[quality.hooks.<stage>].cwd` β per-stage working directory override151+
- `[quality.hooks.<stage>].env` β per-stage environment variable map152+
- `[quality.hooks.<stage>].timeout_secs` β per-stage timeout override153+
154+
### Alternative Reference Definitions (Python & TypeScript)155+
156+
#### Python Template157+
158+
```toml159+
[quality]160+
stages = ["format", "lint", "typecheck", "test"]161+
162+
[quality.hooks.format]163+
cmd = "ruff format --check ."164+
allow_failure = false165+
166+
[quality.hooks.lint]167+
cmd = "ruff check ."168+
allow_failure = false169+
170+
[quality.hooks.typecheck]171+
cmd = "mypy ."172+
allow_failure = false173+
174+
[quality.hooks.test]175+
cmd = "pytest -v"176+
allow_failure = false177+
```178+
179+
#### TypeScript Template180+
181+
```toml182+
[quality]183+
stages = ["format", "lint", "typecheck", "test"]184+
185+
[quality.hooks.format]186+
cmd = "npx prettier --check ."187+
allow_failure = true188+
189+
[quality.hooks.lint]190+
cmd = "npm run lint"191+
allow_failure = false192+
193+
[quality.hooks.typecheck]194+
cmd = "npx tsc --noEmit"195+
allow_failure = false196+
197+
[quality.hooks.test]198+
cmd = "npx vitest run"199+
allow_failure = false200+
```201+
202+
---203+
204+
## 4. Core Rust Engine Runtime Integration205+
206+
### 4.1 Graphviz `.dot` Integration207+
208+
To activate the declarative checks within a PAS workflow, developers or autonomous generation loops use the `quality` handler. The handler name is lowercase without a namespace prefix, matching the existing convention (`codergen`, `wait_human`, `parallel`).209+
210+
```dot211+
digraph G {212+
// Define the agent generation node213+
generate_code [handler="codergen", prompt="Implement the user schema parser"];214+
215+
// Define the automated validation node powered by pas.toml216+
validate_code [handler="quality"];217+
218+
// Routing Cascade Logic219+
generate_code -> validate_code;220+
validate_code -> compile_success [label="pass"];221+
validate_code -> generate_code [label="fail"];222+
}223+
```224+
225+
### 4.2.0 Manifest Resolution226+
227+
Before executing any stage, the engine resolves `pas.toml` by walking upward from `--workdir` (canonicalized at entry; symlinks are not followed during ascent). The walk is bounded to **16 ascents**. It stops at the first `.git` directory or workspace root marker (`Cargo.toml` with `[workspace]`, `pyproject.toml`, or `package.json`). The **first `pas.toml` found wins**.228+
229+
**Resolution outcomes:**230+
231+
| Outcome | Condition | Engine behavior |232+
| :--- | :--- | :--- |233+
| `Found(path, blake3_hash)` | `pas.toml` exists and parses cleanly | Cache on `RunContext`; proceed to trust check |234+
| `NotFound { searched: Vec<PathBuf> }` | No `pas.toml` in the walk range | Handler returns `Fail` with `system_guidance = "No pas.toml found at <searched paths>. Run 'pas init' to generate one."` |235+
| `Malformed { path, diagnostic }` | `pas.toml` exists but fails TOML parse | Handler returns `Fail` with `last_error_log = "<toml parse diagnostic>"`. No silent fallback to defaults. |236+
| `Invalid { path, missing_fields }` | Parses as TOML but fails schema validation | Same as `Malformed` |237+
238+
**No silent fallback to defaults.** Silent fallbacks have hidden a category of bugs already fixed elsewhere.239+
240+
**Startup warning (preflight):** When `pas run` loads a pipeline, it scans for `handler="quality"` nodes. If any are present and no `pas.toml` can be resolved at `--workdir`, it emits a single structured warning at startup:241+
242+
```243+
WARN: pipeline uses the 'quality' handler but no pas.toml was found at <workdir>. Run 'pas init' to generate one. The quality node will fail when reached.244+
```245+
246+
The pipeline still starts (dry-runs and partial executions work), but the quality node will fail when reached. The warning **does not fire** when no node uses the `quality` handler.247+
248+
**Resolution is performed exactly once per `pas run` invocation** (in the preflight layer, before any node executes). The result is stored on `RunContext.quality_manifest`. The handler reads from the cache; it does not re-resolve.249+
250+
### 4.2 Runtime Order of Operations251+
252+
When the execution engine hits a node bound to `handler="quality"`, it uses the pre-resolved manifest from `RunContext` and executes stages asynchronously:253+
254+
1. **Load Config:** Reads the pre-resolved `pas.toml` from `RunContext.quality_manifest`. If resolution produced an error variant, returns `Fail` immediately with structured `system_guidance`.255+
2. **Trust Check:** Verifies the manifest is trusted (see Β§6). In non-TTY contexts with no trust entry, aborts with exit code 2.256+
3. **Sequential Loop:** Iterates through stages in the order defined by `[quality] stages`.257+
4. **Process Execution:** Executes the mapped `cmd` string via `tokio::process::Command` (not `std::process::Command` β the tokio runtime must not be blocked during long test runs). Each stage runs in its own process group to enable orphan-free cancellation.258+
5. **Exit Evaluation:**259+
- If a command exits with code `0`, it proceeds to the next stage.260+
- If a command exits with a non-zero code and `allow_failure = false`, execution breaks immediately. The engine marks the node status as `fail`.261+
- If a command exits with a non-zero code and `allow_failure = true`, a `WARN`-level log entry is emitted and execution continues.262+
263+
---264+
265+
## 5. Telemetry Feedback and Agent Self-Correction266+
267+
When a quality hook encounters a failure, raw CLI dump text can confuse an LLM agent or cause model distraction. The `quality` handler processes the telemetry payload systematically before feeding it into the edge routing state.268+
269+
### 5.1 Telemetry Context Schema270+
271+
When a failure occurs, the engine populates the internal node outcome state with the following payload structure. `last_error_log` is JSON-string-encoded: newlines, tabs, and quotes are escaped per RFC 8259. The field is bounded by `truncate_logs_after_bytes` from `[quality.telemetry]`; this bound is a hard contract guarantee on the output schema that downstream consumers can rely on.272+
273+
```json274+
{275+
"status": "fail",276+
"failed_stage": "typecheck",277+
"execution_metadata": {278+
"command_attempted": "cargo clippy --all-targets -- -D warnings",279+
"exit_code": 101,280+
"working_directory": "/workspace/pascals-discrete-attractor"281+
},282+
"context_updates": {283+
"last_error_log": "error[E0308]: mismatched types\n --> src/main.rs:42:18\n |\n42 | let x: String = 100;\n | ------ ^^^ expected struct `String`, found integer\n | |\n | expected due to this",284+
"system_guidance": "The code you generated failed compilation during the 'typecheck' phase. Read the exact error trace above carefully and refactor the source code to fix the type definitions.",285+
"failure_footprint": "a3f9c2b14e8d7012"286+
}287+
}288+
```289+
290+
**`failure_footprint`** is a 16-character hex string: the first 16 bytes of a BLAKE3 hash computed over `failed_stage + "|" + first_2KB(last_error_log)` (after ANSI escape code stripping). It is used by loop control (Β§5.2) to detect identical error states across iterations.291+
292+
**Output truncation strategy:** Per-command output is captured into a bounded ring buffer. Truncation uses a head-and-tail strategy: the first 25% of bytes are preserved, followed by `... [<N> bytes truncated] ...`, followed by the last 75% of bytes. This preserves both setup context and the actual failure line. The total size is bounded by `truncate_logs_after_bytes`.293+
294+
### 5.2 Mitigation of Agentic Infinite Loops295+
296+
If the `codergen` node repeatedly loops back to `quality` with the same error footprint, the engine intervenes using the parameters defined in `[agent.loop_control]`:297+
298+
1. **Iteration Tracking:** Increment the internal loop counter keyed on the `quality` node ID. The counter resets when control enters the `quality` node from a different upstream node (i.e., the counter is bound to the `quality` node, not the upstream `codergen` node). The counter and last `failure_footprint` are persisted to the checkpoint so resume preserves them β a resumed pipeline does not reset to zero.299+
2. **Prompt Modification:** On iteration 2 and higher, the engine prepends a structured retry warning to the downstream node's context:300+
301+
```xml302+
<retry-warning iteration="2" prev-footprint="a3f9c2b14e8d7012">303+
This is your second attempt to fix the failed quality stage 'typecheck'. The previous attempt produced an identical error footprint. Try a structurally different approach.304+
</retry-warning>305+
```306+
307+
3. **Hard Ceiling:** Once `max_fix_iterations` is exhausted, the CLI aborts execution cleanly with exit code 1 and a final log entry naming the unhealing stage. A hardcoded 1-second sleep is applied before the second and subsequent iterations.308+
309+
---310+
311+
## 6. Trust Model312+
313+
### 6.1 Motivation and Threat Model314+
315+
`pas.toml` is intended to be checked into version control. The implied flow `git clone <repo> && pas run <pipeline>` means an attacker-controlled `pas.toml` can execute arbitrary shell commands via the `cmd` fields. This is not theoretical for a CLI whose purpose is to run AI-generated and template-generated code.316+
317+
**Threats addressed by this model:**318+
319+
- **Clone scenario:** `pas.toml` author β `pas` runner. A cloned repository with a malicious `pas.toml` should not silently run its commands.320+
- **Supply-chain modification:** `pas.toml` modified by a checked-in pre-commit hook after the user last reviewed it.321+
322+
**Not addressed in v1 (documented explicitly to prevent future ambiguity):**323+
324+
- `pas.toml` symlinked to `/dev/random` or `/proc/*` β resource exhaustion via symlink. Mitigated partially by the canonicalized walk-up (see Β§4.2.0), but not fully defended.325+
- Cross-process trust invalidation mid-run β a `pas trust --remove` in a separate terminal does not affect an in-flight pipeline.326+
327+
### 6.2 Trust File328+
329+
Trust state is stored at `$XDG_CONFIG_HOME/pas/trusted.json` (fallback: `~/.config/pas/trusted.json`). The file has permissions `0600` on Unix. Writes use `tempfile::NamedTempFile` + atomic `persist()` rename to prevent corruption from concurrent invocations.330+
331+
```json332+
{333+
"trusted": [334+
{335+
"path": "/absolute/path/to/repo",336+
"blake3": "<blake3 hash of pas.toml at time of trust grant>",337+
"trusted_at": "2026-05-29T14:00:00Z",338+
"source": "pas init"339+
}340+
]341+
}342+
```343+
344+
Trust is keyed on `(absolute_path, blake3(pas.toml))`. Editing `pas.toml` changes its hash, which invalidates the trust entry. The next `pas run` will re-prompt (interactive) or abort with exit code 2 (non-interactive).345+
346+
### 6.3 Trust Prompt Behavior347+
348+
On first `pas run` in a directory whose `pas.toml` hash is not in `trusted.json`:349+
350+
- **Interactive TTY:** Display the resolved `pas.toml` path and hash. Prompt the user to trust. On confirmation, write the trust entry and proceed. This is the same pattern as `direnv allow` and VS Code Workspace Trust.351+
- **Non-TTY / `PAS_NON_INTERACTIVE=1`:** Abort with exit code 2 and message: `"Untrusted manifest at <path>. Run 'pas trust --add <path>' or pass --trust to authorize, or run 'pas init' to generate a trusted manifest."`352+
- **`--trust` flag:** One-shot trust for this run only; does not write to `trusted.json`.353+
- **`PAS_TRUST_THIS=1`:** Same as `--trust` for CI contexts.354+
- **`PAS_AGENT=1`:** Implies `PAS_TRUST_THIS=1` (see Β§2 CLI Flags).355+
356+
### 6.4 Auto-Trust on `pas init`357+
358+
`pas init` writes the trust entry as its final step, keyed on the manifest it just wrote. A user who ran `pas init` does not see a trust prompt on the first `pas run`. The trust entry records `"source": "pas init"`.359+
360+
### 6.5 `pas trust` Subcommand361+
362+
Trust management is a first-class CLI subcommand for symmetric human/agent access:363+
364+
| Command | Description |365+
| :--- | :--- |366+
| `pas trust --add <path>` | Add trust entry for the `pas.toml` at `<path>` (uses current blake3 hash) |367+
| `pas trust --remove <path>` | Remove trust entry for `<path>` |368+
| `pas trust --list` | List all trusted paths and their hashes |369+
370+
**Exit codes for `pas trust`:**371+
372+
| Code | Condition |373+
| :--- | :--- |374+
| 0 | Success |375+
| 2 | `TrustError::Untrusted` β entry not present or hash mismatch (recoverable) |376+
| 3 | `TrustError::CorruptedStore` β trust file malformed or unreadable (manual intervention required) |377+
378+
### 6.6 Prior Art379+
380+
This trust model is directly analogous to `direnv allow` (per-directory shell trust) and `mise trust` (per-config-file tool trust). Both use a file-hash-keyed allowlist. The `PAS_TRUST_THIS` env var parallels `MISE_TRUSTED_CONFIG_PATHS`.381+
382+
---383+
384+
## Appendix: Summary of Changes from Revision 1385+
386+
| Change | Review finding | Section affected |387+
| :--- | :--- | :--- |388+
| Added Β§4.2.0 Manifest Resolution (walk-up, `NotFound`/`Malformed`/`Invalid` variants, startup warning) | P1-1 | Β§4.2.0 |389+
| Added Β§6 Trust Model (XDG trust file, direnv-style prompt, auto-trust on init, `pas trust` subcommand) | P1-2 | Β§6 |390+
| Fixed malformed telemetry JSON (`\n`-escaped newlines, added `failure_footprint` field) | P1-3 | Β§5.1 |391+
| Restructured schema: `stages` array + `[quality.hooks.<stage>]` sub-tables | P1-4 | Β§3 |392+
| Renamed `serde_toml` β `toml` (correct crate name, 1.x) | P2-1 | Β§3 |393+
| Renamed "two-phase" β "three-phase"; added `--yes`/`--non-interactive`/`--no-enrich`/`--force`/`--dry-run` flags | P2-2 | Β§2 |394+
| Clarified `allow_failure = true` semantics | P2-3 | Β§3 |395+
| Specified Phase 2 trigger conditions as a decision table | P3-3 | Β§2 |396+
| Added filename allowlist for LLM payload; renamed `--no-agent` β `--no-enrich` | P3-3 | Β§2 |397+
| Renamed handler `pas::quality` β `quality` (matches existing convention) | P2-6 | Β§4.1 |398+
| Replaced "quality runner thread" framing with `tokio::process::Command` | P2-6 | Β§4.2 |399+
| Defined `failure_footprint` (BLAKE3, closes loop-control ambiguity) | P2-5 | Β§5.1, Β§5.2 |400+
| Clarified loop counter binding to `quality` node ID; checkpoint persistence | P2-5 | Β§5.2 |401+
| Removed `backoff_factor` field (hardcoded 1-second sleep in v1) | P2-5 | Β§3, Β§5.2 |