From e7b9c43c97635c0fd2977673d6679336fd2a7487 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 5 Jul 2026 07:12:22 +0000 Subject: [PATCH 1/8] Document agent-run triage as the evidence-sink phase of 007's Zero Trust roadmap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds docs/agent-run-triage.md: reuses the existing confirmed/static-only/ runtime-only triage pattern (runtime-contract.md) and rule-to-verdict methodology (audit-data-leverage.md) for a new evidence source — 007's structured per-run audit trail — instead of building a separate pipeline. Scopes it explicitly as ingest-and-report only: enforcement stays with 007+Sandboy, disposition stays human, per the same orchestrator-not-analyzer charter already codified for the security profile (P-024 in Own.NET). --- README.md | 1 + docs/agent-run-triage.md | 132 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 docs/agent-run-triage.md diff --git a/README.md b/README.md index 7c4d63b..cd25a5b 100644 --- a/README.md +++ b/README.md @@ -34,5 +34,6 @@ console crash on the Russian-locale Windows target. | boundary + STS runner + artifacts + lift-out home | `OwnAudit/` (this repo) | active | | fix arm — wire mass appliers + safety wrapper + OWN fixer | `OwnAudit/` ([docs/fix-arm.md](docs/fix-arm.md)) | design | | LeakFixMine — mine real leak-fixes, SZZ-prove them, score OwnAudit vs baselines | `leakmine/` ([docs/leakfix-mine.md](docs/leakfix-mine.md)) | active | +| agent-run triage — ingest 007's Zero Trust audit trail as evidence | `OwnAudit/` ([docs/agent-run-triage.md](docs/agent-run-triage.md)) | design | See [PLAN.md](PLAN.md), the [Fix arm design](docs/fix-arm.md), and [LeakFixMine](docs/leakfix-mine.md). diff --git a/docs/agent-run-triage.md b/docs/agent-run-triage.md new file mode 100644 index 0000000..d211e7f --- /dev/null +++ b/docs/agent-run-triage.md @@ -0,0 +1,132 @@ +# Agent-run triage — 007's Zero Trust audit trail as an evidence source + +Status: design note / vision, not implementation (same status as +[`audit-data-leverage.md`](audit-data-leverage.md) and +[`own-net-auditor.md`](own-net-auditor.md)). Trigger to build: once **007** +actually emits structured per-run capability events (its Phase 1 — see +[`007/docs/zero-trust-framework.md`](https://github.com/PhysShell/007/blob/main/docs/zero-trust-framework.md)). +Gated on that repo's data existing, not something to build ahead of it. + +## 0. What this is + +007 is a private harness that drives `claude`/`codex` over Own.NET and OwnAudit +via their CLIs, in a throwaway `git worktree`, gated by `.007/gate.toml`. Its own +ADR (`007/docs/security-layers.md`) is honest that the worktree is not a +sandbox and gate steps are attacker-controlled code execution if the target +repo isn't fully trusted. 007's Zero Trust roadmap closes that gap in phases — +Sandboy isolation, a capability manifest, structured audit events. The last +phase in that roadmap is: **something has to look at the resulting evidence and +decide what's noise vs. a real incident.** That's this repo's job, not 007's — +007 orchestrates and enforces; it isn't built to triage its own findings, same +reason OwnAudit doesn't run its own detectors (see +[`docs/proposals/P-024-security-audit-profile.md`](https://github.com/PhysShell/Own.NET/blob/main/docs/proposals/P-024-security-audit-profile.md) +in Own.NET: "оркестратор, не анализатор" applies here verbatim). + +## 1. Reuse, don't build a new pipeline + +OwnAudit already has the exact shape this needs, built for a different evidence +source: + +- **The confirmed / static-only / runtime-only triage** in + [`runtime-contract.md`](runtime-contract.md) — a static finding plus + independent corroborating evidence (heap retention) becomes `confirmed`; a + finding with no corroboration is a suspect false positive; corroboration with + no matching finding is the analyzer's **blind spot**. The same three buckets + apply directly to policy events: a capability violation that the manifest + intended to catch and did → `confirmed`; a violation rule that never fires → + candidate for retirement; an agent action that *succeeded* but matched no rule + at all → **policy gap** (the blind spot — a candidate for a new rule, exactly + like "runtime-only" means "the static analyzer's blind spot" today). +- **The rule → verdict methodology** in + [`audit-data-leverage.md`](audit-data-leverage.md) — findings are concentrated + (top-N rules dominate volume), so characterizing a handful of rules + characterizes most of the backlog. The same applies to gate/policy rules: a + network-deny rule that fires on every run because a common tool phones home + for a version check is noise to tune, not a real incident every time. + +Nothing here is a new detection engine. It's the same normalize → aggregate → +score → report pipeline, fed a new evidence source. + +## 2. What gets ingested + +From a 007 run record (`runs///`): `meta.json` (run identity — +`run_id`, `agent_id`, `target_repo`, `base_commit`, `policy_id`), `gate/*.log` + +`gate/verdict.json` (per-step pass/fail), and — once Phase 1 lands — capability +manifest violations (attempted network egress under `network = "deny"`, a write +outside the declared scope, an unrecognized `[permissions]` field that failed +closed) and output-filter hits (a secret pattern caught before it reached +`agent.stdout`/`diff.patch`). + +This is **not** source-code SARIF — there's no file/line to point at, the +"finding" is about a process's behavior during a run, not a static code +location. It needs its own thin record shape and its own adapter into the +existing aggregation, parallel to how `zap_to_sarif` / `dotnet_vuln_to_sarif` +adapt non-native tool output in the security profile (P-024 in Own.NET) — not a +new report pipeline, a new adapter feeding the one that exists. + +```jsonc +// illustrative — the shape 007 would emit, the adapter's input +{ + "schema": "o7/audit-event/v1", + "run_id": "…", + "agent_id": "claude", + "target_repo": "Own.NET", + "policy_id": "own-net.cue#", + "events": [ + { + "kind": "policy-violation", + "rule": "network.default", + "action": "connect example.com:443", + "step": "regression", + "outcome": "denied" + } + ] +} +``` + +## 3. Triage buckets + +| Bucket | Meaning | Action | +|---|---|---| +| `policy-violation-confirmed` | an action tripped a capability-manifest rule and was denied | evidence of the boundary working — log, don't page | +| `policy-violation-allowed-then-flagged` | an action matched a rule marked `requires_approval` and proceeded | the actual triage queue — did a human actually approve it, or did it slip through | +| `policy-gap` | an action succeeded, matched no rule at all | the manifest's blind spot — candidate for a new rule, same lens as "runtime-only" in `runtime-contract.md` | +| `suppressed-noise` | a rule fires on nearly every run for a benign reason (e.g. a toolchain's version-check phones home) | tune the rule, don't keep flagging it — same rule→verdict lens as `audit-data-leverage.md` | + +## 4. Non-goals + +- **Not enforcement.** OwnAudit never blocks or allows an agent action — that + authority stays at 007 + Sandboy, at the process boundary, before the action + happens. This repo only ever looks at what already happened. +- **Not disposition.** Per the Zero Trust framework this whole effort traces + back to: agents can automate evidence collection, enrichment, and drafting an + incident note; containment, rerun, and escalation decisions stay a human + call. A `policy-violation-allowed-then-flagged` event becomes a note a person + reads, not an automatic rerun/block. +- **Not a new detector engine.** Same charter as P-024 in Own.NET: no bespoke + heuristics, no own severity model reinvented from scratch — reuse the + cross-tool-agreement scorer and the coverage-map discipline (`NO-TOOL: + skipped` beats a guess) that already exist for static and runtime findings. + +## 5. Cross-repo division of responsibility (this repo's view) + +| Concern | Owner | +|---|---| +| Declares/verifies the capability vocabulary (`owen.policy`, authored in CUE) | Own.NET — `docs/notes/agent-capability-layer.md` | +| Process/syscall isolation boundary | Own.NET — `sandboy/` | +| Enforces policy at runtime, emits the structured audit trail | 007 — `docs/zero-trust-framework.md` | +| Ingests the trail, triages, reports, keeps disposition human | **OwnAudit** — this doc | + +## 6. Where this lands + +Layout, if/when 007 Phase 1 lands and this gets built: + +```text +audit/agent-runs/ # parallel to audit/security/ (Own.NET) + adapters/ # o7_run_to_finding.py + profiles/ # which run stores to poll, retention window +``` + +Consistent with the existing lift-out discipline (`PLAN.md`): the pipeline +logic belongs wherever the rest of `audit/aggregate` lives at build time, and +this repo carries the boundary + validated runs, same as everything else here. From 98f11be6b1995213760bb9c5c55fb2723894fe96 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 5 Jul 2026 07:17:47 +0000 Subject: [PATCH 2/8] Add provenance verification and concrete red-flag examples to agent-run triage Ingest adapter's first move should be verifying 007's run-record hash chain before trusting any of it, same reflex already applied to runtime.json inputs. Names concrete instances of the policy-violation-confirmed bucket so the triage buckets aren't purely abstract, and flags an agent editing its own gate config as always requiring human review, even when the step itself passed. --- docs/agent-run-triage.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/agent-run-triage.md b/docs/agent-run-triage.md index d211e7f..517df5b 100644 --- a/docs/agent-run-triage.md +++ b/docs/agent-run-triage.md @@ -57,6 +57,25 @@ outside the declared scope, an unrecognized `[permissions]` field that failed closed) and output-filter hits (a secret pattern caught before it reached `agent.stdout`/`diff.patch`). +**Before trusting any of it, verify provenance.** 007's records are meant to be +hash-chained (`prev_record_hash`/`record_hash` over the gate manifest, each +step's sandbox policy, the task, the diff, and stdout — see +`007/docs/zero-trust-framework.md` §5). The ingest adapter's first move is +checking that chain, the same reflex `runtime.json`'s consumer already applies +to its own inputs: a broken chain (or a hash that doesn't match the artifact it +claims to describe) is itself the finding — `provenance-broken`, filed +alongside the buckets below, not silently trusted because the JSON parsed. + +Concrete instances of the `policy-violation-confirmed` bucket worth naming, so +"triage" doesn't stay abstract: a step whose policy declares `tcp_connect = []` +shows a denied connect attempt anyway (the boundary caught something — log it, +it's not automatically an incident); a step writes outside its declared `fs_rw` +scope and gets denied; the diff touches `.007/policies/**` without the task +naming a policy change; the diff touches `.007/gate.toml` itself — that last one +is `policy-violation-allowed-then-flagged` even when the gate step technically +passed, because an agent editing its own leash is the one action this pipeline +should never wave through unread. + This is **not** source-code SARIF — there's no file/line to point at, the "finding" is about a process's behavior during a run, not a static code location. It needs its own thin record shape and its own adapter into the From 799d1e8f56ffa5bf40b722ff8b71ef37cefecfea Mon Sep 17 00:00:00 2001 From: PhysShell <45852143+PhysShell@users.noreply.github.com> Date: Sun, 5 Jul 2026 12:43:55 +0500 Subject: [PATCH 3/8] docs: add agentic coding discipline proposal --- docs/agentic-coding-discipline-proposal.md | 1103 ++++++++++++++++++++ 1 file changed, 1103 insertions(+) create mode 100644 docs/agentic-coding-discipline-proposal.md diff --git a/docs/agentic-coding-discipline-proposal.md b/docs/agentic-coding-discipline-proposal.md new file mode 100644 index 0000000..73b3191 --- /dev/null +++ b/docs/agentic-coding-discipline-proposal.md @@ -0,0 +1,1103 @@ +# Agentic Coding Discipline — Proposal + +> Статус: **proposal / design note**, не implementation plan. Зафиксировано как +> отправная точка для дисциплинированного agentic coding поверх Own.NET, +> OwnAudit и 007. Часть тезисов ниже уже реализована и задокументирована в +> репозиториях на момент коммита — см. раздел "Что уже есть". Остальное — +> открытые предложения, ждущие решения о приоритете. + +## Что из этого уже реализовано/задокументировано + +- **007** (`README.md`, `TODO.md`) — цикл `isolate → run → gate → harvest` уже + работает: `o7 run` делает git worktree, гоняет `claude` full-auto, прогоняет + `.007/gate.toml`, собирает `task.md / meta.json / agent.stdout / diff.patch / + gate/*.log` (`src/agent.rs`, `gate.rs`, `worktree.rs`, `record.rs`, + `verdict.rs`). +- **007/docs/security-layers.md** — источник тезисов про "deny-list ≠ sandbox", + "worktree isolation ≠ security boundary", `bash -lc` из target repo как + attacker-controlled code execution поверхность. +- **007/docs/performance.md** + **TODO.md** — тезис "007 subprocess/LLM-bound, + единственный рычаг — bounded `--jobs N` для per-file judge calls" и план + STS-run на 156 FP-suspects. +- **007/judge/** (`README.md`, `prompt.template.md`, `rubric.example.md`, + `fp-verdicts.schema.json`) — `o7 judge` как отдельный read-only режим с + machine-readable verdict уже реализован и верифицирован на oracle + (contract-conforming `fp-verdicts.json`). +- **OwnAudit/docs/fp-judge/verdict-contract.md + rubric.md** — источник истины, + под который подстроена схема `007/judge/fp-verdicts.schema.json`. +- **Own.NET/AGENTS.execution-surfaces.md** — живой пример agent-contract в духе + предложения ниже: ADR-решение (accept/reject), секция "Что НЕ делать" + (negative prompts), acceptance criteria, trigger table "пересмотреть если...". +- **Own.NET/AGENTS.md**, **OwnAudit/AGENTS.md** — repo-level своды правил для + агентов уже существуют. + +## Чего нет и что здесь предлагается как открытая задача + +- Папка `.ai/` в Own.NET (`project-context.md`, `architecture-rules.md`, + `forbidden-changes.md`, `task-template.md`, `review-template.md`, + `domain-glossary.md`, `testing-policy.md`). +- Машиночитаемый `task.o7.toml` / `TaskContract` + `DiffPolicy` gate в 007 — + сейчас есть только `examples/task.example.md` как обычный markdown-таск, без + scope/forbidden-paths/dependency enforcement. +- Команды `o7 plan`, `o7 judge-run`, `o7 replay`, `trust_level` + (trusted-local / semi-trusted / untrusted). +- Каталог analyzer rule id вида `OWNASYNC001` / `OWNLIFE00x` / `OWNWPF00x` / + `OWNDATA00x` для Own.NET. + +--- + +## Исходный текст предложения + +Я бы забрал из NoBootCamp не "vibe coding", а disciplined agentic coding. То есть не "AI, сделай мне модуль", а "AI, вот клетка, вот правила, вот тесты, вот ножницы, шаг влево — review тебя сожрёт". Иначе это не разработка, а генератор PR'ов, которые выглядят уверенно, пока не открываешь diff. + +### 1. Главное правило: AI не должен владеть задачей целиком + +Плохой стиль: + +``` +Сделай модуль анализа async-проблем в Own.NET. +``` + +Это приглашение к катастрофе. Агент начнёт придумывать архитектуру, термины, классы, API, тесты, формат отчёта и, возможно, религию. + +Правильный стиль: + +``` +Сделай только analyzer rule OWN0001: +- найти async void методы, кроме event handlers +- проект: .NET 8 analyzer +- целевые проекты: .NET Framework 4.7.2 legacy codebase +- diagnostic severity: Warning +- code fix пока не нужен +- не менять существующую архитектуру +- добавить unit tests на Roslyn analyzer test framework +``` + +Вот это уже задача. Маленькая, проверяемая, без "AI построит Рим, но на TypeScript". + +### 2. Plan-then-build: сначала план, потом код + +Для тебя это must-have. Особенно если агент работает с legacy WPF, графой расчётов, SQL, DevExpress, старым .NET Framework. Там любое "я просто чуть-чуть поправил" обычно означает "я переломал жизненный цикл окна и теперь форма держится в памяти до тепловой смерти Вселенной". + +Шаблон: + +``` +Сначала НЕ пиши код. + +Дай план изменения: +1. какие файлы надо менять; +2. какие файлы нельзя трогать; +3. какие public API останутся совместимыми; +4. какие риски есть; +5. какие тесты надо добавить; +6. как проверить, что поведение не изменилось. + +После плана остановись. +``` + +Зачем это нужно: ты ловишь бред до того, как он превратился в diff на 900 строк. Если в плане агент пишет "создадим новый ServiceLocator", сразу бьёшь по рукам. Потому что ServiceLocator в legacy-проекте — это не паттерн, это плесень с интерфейсом. + +### 3. Negative prompts: запрещай явно + +AI очень любит "помочь" через скрытые побочные эффекты. Поэтому ему надо не только сказать, что делать, но и что категорически нельзя. + +Для твоих проектов я бы держал постоянный блок: + +``` +Запрещено: +- менять public API без явного указания; +- добавлять NuGet-пакеты без отдельного разрешения; +- использовать static mutable state; +- добавлять service locator; +- глотать исключения через catch { }; +- использовать async void, кроме UI event handlers; +- использовать Task.Run как маскировку синхронного IO; +- менять SQL-семантику без тестов; +- менять threading model WPF; +- трогать .csproj, packages.config, build scripts без отдельного разрешения; +- делать "рефакторинг заодно"; +- переименовывать классы/методы, если задача не про это. +``` + +Это выглядит занудно, но это дешевле, чем потом спрашивать: "а почему checkout документа стал падать только на удалённом SQL Server после 17:30 по четвергам". + +### 4. Для Own.NET это можно оформить как "Agent Contract" + +Я бы сделал в репозитории папку: + +``` +.ai/ + project-context.md + architecture-rules.md + forbidden-changes.md + task-template.md + review-template.md + domain-glossary.md + testing-policy.md +``` + +Примерно так: + +**`.ai/project-context.md`** + +``` +Проект Own.NET — набор инструментов для анализа .NET-кода: +- Roslyn analyzers; +- архитектурные проверки; +- async/threading diagnostics; +- IDisposable/lifetime diagnostics; +- WPF-specific diagnostics; +- legacy .NET Framework compatibility checks. + +Цель: помогать безопасно улучшать legacy .NET/WPF код без массовых рискованных переписываний. +``` + +**`.ai/architecture-rules.md`** + +``` +Правила: +- analyzer rules должны быть маленькими и независимыми; +- каждая rule имеет ID, описание, severity, examples, tests; +- analyzer не должен требовать runtime execution; +- false positives должны быть явно описаны; +- dangerous autofix запрещён без отдельного review; +- diagnostics должны объяснять не только "что плохо", но и "почему". +``` + +**`.ai/forbidden-changes.md`** + +``` +Нельзя: +- делать глобальные refactorings; +- добавлять зависимости без обоснования; +- смешивать analyzer logic и reporting; +- добавлять rule без тестов; +- добавлять code fix без negative tests; +- ломать deterministic output. +``` + +Это превращает "чат с AI" в почти нормальный engineering workflow. Почти. Роботы всё ещё могут уверенно нести чушь, но хотя бы по форме. + +### 5. Self-review: заставлять агента проверять собственный diff + +После генерации кода не надо сразу верить. Это как верить junior'у, который говорит "у меня локально работает". Работает?! Телега с тремя колёсами тоже "работает", пока не надо повернуть. + +Шаблон review: + +``` +Проверь этот diff как злой maintainer. + +Ищи: +- изменение поведения; +- скрытые breaking changes; +- race conditions; +- memory leaks; +- swallowed exceptions; +- async/threading проблемы; +- слишком широкие изменения; +- отсутствие тестов; +- несоответствие задаче. + +Формат ответа: +1. Blocking issues +2. Non-blocking issues +3. Missing tests +4. Safer alternative +``` + +Для Own.NET можно сделать это отдельным режимом: AI Review Pass. + +Например: + +``` +Review rule OWN0003: EventSubscriptionLeakAnalyzer. +Проверь, не даёт ли analyzer false positive на weak event pattern, IDisposable cleanup, composite disposable, и WPF Binding events. +``` + +Вот это уже полезно. Не "похвали мой код", а "найди, где он врёт". + +### 6. Для legacy WPF особенно важны agent-readable invariants + +AI плохо понимает невидимые правила старого проекта. Поэтому их надо записывать явно. + +Например: + +``` +WPF invariants: +- ViewModel не должен напрямую знать о View; +- подписки на events должны освобождаться; +- Dispatcher usage должен быть явным; +- long-running операции не должны блокировать UI thread; +- ObservableCollection изменяется только на UI thread; +- IDisposable ownership должен быть очевиден; +- Presenter/Coordinator не должен превращаться в God Object. +``` + +Или для твоих справочников/TNVED/ставок: + +``` +Data invariants: +- не материализовать весь справочник без необходимости; +- большие деревья загружать лениво; +- MessagePack blobs не декодировать полностью ради одного поля; +- SQL query должен быть parameterized; +- paging обязателен для больших выборок; +- LRU/cache не должен менять доменную семантику. +``` + +Это прям корм для AI-агентов. Без этого они будут "улучшать" код так, что справочник на 20k узлов внезапно грузится весь "для удобства". Удобство, ага. Для пожара. + +### 7. Задачи надо резать на "атомы" + +Не так: + +``` +Сделай модуль AsyncAnalyzer. +``` + +А так: + +``` +Task 1: OWN0001 async void detector +Task 2: OWN0002 .Result/.Wait() detector in UI context +Task 3: OWN0003 fire-and-forget Task without observation +Task 4: OWN0004 ConfigureAwait misuse policy +Task 5: OWN0005 Task.Run around synchronous DB call +Task 6: report formatter +Task 7: suppression mechanism +Task 8: documentation examples +``` + +Каждая задача должна иметь: + +``` +- вход; +- ожидаемый diagnostic; +- false positive cases; +- false negative acceptable cases; +- тесты; +- запреты; +- done criteria. +``` + +Иначе агент сделает функцию, которая делает больше работ, чем single parent on three shifts. IT'S FUCKING BUGGY! + +### 8. Очень полезная штука: "definition of done" для AI + +В конце каждого промпта: + +``` +Definition of Done: +- код компилируется; +- добавлены тесты; +- покрыты positive и negative cases; +- нет изменений вне заявленных файлов; +- public API не изменён; +- нет новых зависимостей; +- diagnostic message понятный; +- есть пример bad/good code; +- описаны known limitations. +``` + +Это не гарантия качества. Это забор. AI всё ещё может перелезть, но хотя бы будет видно, где он испачкал штаны. + +### 9. Для твоего Own.NET я бы начал с таких модулей + +**Async module** + +Самый жирный кандидат. + +``` +OWNASYNC001: async void outside event handlers +OWNASYNC002: blocking wait on Task: .Wait(), .Result, GetAwaiter().GetResult() +OWNASYNC003: fire-and-forget Task without observation/logging +OWNASYNC004: Task.Run used to hide sync IO +OWNASYNC005: async method without CancellationToken in service boundary +OWNASYNC006: ConfigureAwait policy violation +``` + +Особенно интересно для WPF: ловить `.Result`/`.Wait()` в UI-пути. Это прям классика "почему окно умерло, хотя процесс живой". + +**IDisposable / lifetime module** + +``` +OWNLIFE001: IDisposable field not disposed +OWNLIFE002: event subscription not unsubscribed +OWNLIFE003: IDisposable created but not owned +OWNLIFE004: CancellationTokenSource not disposed +OWNLIFE005: Stream/SqlConnection/DbCommand lifetime leak +``` + +Для legacy desktop это золото. Там утечки обычно не "одна большая ошибка", а тысяча мелких "ну оно же работает". + +**SQL/data-access module** + +``` +OWNDATA001: string interpolation in SQL +OWNDATA002: concatenated SQL with user/domain input +OWNDATA003: SELECT * in repository/query object +OWNDATA004: missing transaction boundary +OWNDATA005: provider-specific SQL without abstraction marker +OWNDATA006: temp table incompatibility SQL Server/SQLite +``` + +С учётом твоей боли SQL Server/SQLite — прям вкусно. Можно делать analyzer + test corpus на query builder. + +**WPF module** + +``` +OWNWPF001: ObservableCollection modified outside UI thread +OWNWPF002: event subscription leak in View/ViewModel/Presenter +OWNWPF003: long-running operation in command handler +OWNWPF004: Dispatcher.Invoke instead of BeginInvoke/async path +OWNWPF005: direct View reference from ViewModel +OWNWPF006: Bitmap/Image resource not released +``` + +Вот тут надо аккуратно: WPF-анализ легко даёт false positive. Но даже advisory diagnostics уже полезны. + +### 10. Самый ценный формат промпта для тебя + +Вот шаблон, который можно реально использовать: + +``` +Ты работаешь как senior .NET/Roslyn developer. + +Контекст: +- проект: Own.NET +- цель: analyzer для legacy .NET/WPF проектов +- стиль: маленькие независимые rules +- тесты обязательны + +Задача: +Реализовать rule OWNASYNC001: async void outside event handlers. + +Требования: +- diagnostic для async void методов; +- не репортить event handlers вида void Handler(object sender, EventArgs e); +- не репортить override методов, если сигнатура навязана базовым API; +- diagnostic message должен объяснять риск; +- severity: Warning; +- code fix не делать. + +Ограничения: +- не добавлять NuGet dependencies; +- не менять public API существующих rules; +- не делать unrelated refactoring; +- не менять build scripts. + +Сначала дай план: +- какие файлы создашь/изменишь; +- какие тесты добавишь; +- какие false positives возможны; +- где нужна осторожность. + +После плана остановись. +``` + +А после утверждения плана: + +``` +Реализуй только согласованный план. +После кода дай: +1. список изменённых файлов; +2. краткое объяснение; +3. тестовые сценарии; +4. known limitations. +``` + +Вот это уже не "vibe". Это нормальный рабочий протокол. + +### 11. Для PR-review можно сделать отдельный "злой режим" + +Например: + +``` +Review this PR for Own.NET. + +Be strict. Assume the code is wrong until proven otherwise. + +Check: +- analyzer correctness; +- false positives; +- false negatives; +- Roslyn performance; +- allocations; +- cancellation support; +- concurrency safety; +- deterministic diagnostics; +- tests quality; +- public API compatibility. + +Do not praise. Find risks. +``` + +Это очень подходит под твой стиль "код должен заработать право существовать". И да, тут "не хвали" важно. AI по дефолту ведёт себя как HR на корпоративе: всё "promising", "solid foundation", "nice work". А тебе нужен maintainer, который скажет: "WHERE'S THE ERROR HANDLING?!" + +### 12. Что реально можно протащить в твой процесс + +Я бы внедрял так: + +1. `.ai/` папка с правилами проекта — чтобы каждый агент не начинал с нуля и не изобретал очередной "чистый" ад. +2. Task template — одинаковый формат задач для analyzer/rule/refactor/test. +3. Review template — отдельный промпт для проверки diff'а. +4. Negative constraints — запреты на side effects, новые зависимости, public API changes. +5. Rule skeleton generator — агент генерит каркас analyzer rule, тесты, examples, docs. +6. Golden test corpus — папка с bad/good examples, чтобы AI не спорил с реальностью. +7. Regression checklist — особенно для графы 47, SQL builder, WPF lifecycle, async/threading. + +### 13. Самая важная мысль + +AI полезен не как "разработчик вместо тебя", а как ускоритель конкретных операций: + +- накидать Roslyn analyzer skeleton; +- придумать negative test cases; +- проверить diff на риски; +- объяснить чужой код; +- сгенерить documentation examples; +- составить migration plan; +- найти edge cases; +- сделать boring code. + +Но архитектурные инварианты, границы модулей, совместимость, lifecycle, перформанс и "а не превратится ли это в болото через 3 месяца" — это всё ещё на тебе. Несправедливо, конечно. Но зато без иллюзии, что "vibe" заменяет engineering. Вайб не ловит memory leak. Тесты ловят. Анализаторы ловят. Review ловит. Иногда senior с кофеином ловит. + +Да. Более того, 007 — это как раз место, где такие подходы надо превращать из "хороших советов" в исполняемый протокол. + +Для Own.NET это выглядело как: + +> "AI, напиши analyzer rule, но вот инварианты, тесты, запреты, review." + +А для 007 это должно выглядеть так: + +> "007, запусти агента только внутри заданного контракта, собери diff, прогоняй gates, зафиксируй evidence, потом отдельный judge/reviewer решает, можно ли это вообще считать работой." + +То есть Own.NET — пациент, а 007 — хирургическая операционная. Если операционная не стерильная, пациенту кирдык, даже если врач в белом халате и с Claude Max. + +#### Что уже в 007 идеально подходит + +Судя по README, 007 уже задуман как harness: `o7 run` делает worktree, запускает claude/codex, прогоняет gate steps и складывает canonical record: `task.md`, `meta.json`, `agent.stdout`, `diff.patch`, `gate/*.log`, `verdict.json`. Это прям база для disciplined agentic coding, а не "AI, сделай красиво, я отвернусь". + +То есть NoBootCamp-идею надо не "применить к 007", а закодировать в 007 как режимы работы: + +``` +task contract → isolated run → gates → harvest → judge/review → verdict +``` + +И вот тут начинается мясо. + +--- + +### 1. Для 007 нужен не "prompt template", а Task Contract + +В Own.NET можно было держать `.ai/task-template.md`. + +В 007 лучше сделать машиночитаемый task contract, например: + +```toml +# task.o7.toml + +[target] +repo = "../Own.NET" +base = "main" + +[agent] +provider = "claude" +mode = "full-auto" + +[scope] +allowed_paths = [ + "src/OwnNet.Analyzers/**", + "tests/OwnNet.Analyzers.Tests/**" +] + +forbidden_paths = [ + "*.csproj", + "Directory.Build.props", + ".github/**" +] + +[change_policy] +allow_new_dependencies = false +allow_public_api_changes = false +allow_unrelated_refactoring = false +require_tests = true + +[task] +kind = "roslyn-analyzer" +summary = "Implement OWNASYNC001: async void outside event handlers" + +[done] +commands = [ + "dotnet test", + "dotnet build -warnaserror" +] +``` + +Почему это лучше обычного `task.md`? Потому что обычный markdown — это просьба. А `.toml`/schema — это контракт. Компьютер хотя бы может проверить, что агент не полез в `.csproj`, вместо того чтобы потом человек руками обнаруживал "маленький рефакторинг" на 1800 строк. Технический долг, но с бантиком. + +Что добавить в 007: + +``` +o7 validate-task --task task.o7.toml +o7 run --task task.o7.toml +o7 inspect-run runs/ +o7 judge-run runs/ +``` + +Минимальный MVP: + +``` +task.md # человеческое описание +task.o7.toml # машинный контракт +gate.toml # команды проверки +policy.toml # запреты / scope / allowlist +``` + +### 2. plan-then-build в 007 должен стать отдельной фазой + +Сейчас README описывает один цикл: isolate → run → gate → harvest. + +Но для coding-agent задач я бы разделил: + +``` +o7 plan +o7 run +o7 judge +``` + +То есть агент сначала не имеет права менять код. Он должен сгенерировать план: + +``` +runs/// + plan.md + plan.meta.json + plan.verdict.json +``` + +Потом отдельный gate проверяет план: + +``` +- план не трогает запрещённые файлы; +- план не добавляет зависимости; +- план перечисляет тесты; +- план содержит rollback/check strategy; +- план не предлагает глобальный рефакторинг. +``` + +И только потом: + +``` +o7 run --from-plan runs/.../plan.md +``` + +Это сильно лучше, чем давать агенту full-auto сразу. Потому что full-auto без предварительного плана — это как дать экскаватор человеку, который "примерно понял задачу". Земля, конечно, будет двигаться. Вопрос только, чья. + +### 3. Negative prompts в 007 должны стать policy/gate, а не текстом + +В Own.NET мы могли писать: + +``` +Не меняй public API. +Не добавляй зависимости. +Не трогай build scripts. +``` + +В 007 это надо превратить в проверяемые правила: + +```toml +[diff_policy] +max_changed_files = 8 +max_added_lines = 500 +forbid_paths = [ + "Cargo.toml", + "flake.nix", + ".github/**", + "**/*.sln", + "**/*.csproj" +] + +[dependency_policy] +allow_new_nuget = false +allow_new_npm = false +allow_new_cargo = false + +[api_policy] +require_public_api_report = true +``` + +И gate после diff должен проверять: + +``` +diff.patch против policy.toml +``` + +Если агент полез куда не просили: + +``` +FAIL: touched forbidden file Directory.Build.props +FAIL: added dependency Microsoft.Extensions.DependencyInjection +FAIL: changed public API without approval +``` + +Вот это уже нормальная инженерия. Не "агент, пожалуйста, будь хорошим мальчиком", а "вышел за пределы клетки — run failed". WHERE'S THE ERROR HANDLING?! Вот оно, наконец-то. + +### 4. 007 должен собирать не просто diff, а evidence pack + +README уже говорит, что 007 harvest'ит `meta.json`, `agent.stdout`, `diff.patch`, gate logs и verdict. + +Я бы расширил canonical record: + +``` +runs/// + task.md + task.o7.toml + plan.md + meta.json + + diff.patch + changed-files.json + forbidden-touches.json + + agent/ + stdout.log + stderr.log + tool-calls.json + + gate/ + build.log + test.log + lint.log + policy.log + verdict.json + + judge/ + review.md + verdict.json + risks.json + + replay/ + base_commit.txt + head_commit.txt + commands.sh +``` + +Зачем: 007 должен быть не просто "запустил агента", а черный ящик самолёта после падения. Агент внёс diff? Докажи: + +``` +что он запускался в правильном repo; +от какого base commit; +какие файлы поменял; +какие gates прошли; +какие упали; +что judge сказал; +где логи; +какой prompt был; +чем run воспроизводится. +``` + +Иначе это не automation harness, а "скрипт, который доверяет LLM". А это уже почти религиозная практика. + +### 5. judge в 007 — прямое продолжение self-review + +У тебя уже есть `o7 judge`, и TODO говорит, что он проверен на read-only FP-triage и выдавал contract-conforming `fp-verdicts.json`; дальше запланирован FP-control и реальный STS-run на 156 FP-suspects. + +Это очень важная часть. В терминах NoBootCamp: + +``` +self-correction / review prompt +``` + +В терминах 007: + +``` +judge command + rubric + schema + verdict contract +``` + +То есть не "Claude сам себя проверил, ну значит норм". Нет. Отдельный режим: + +``` +agent делает diff +judge смотрит diff + task + gate logs +judge возвращает machine-readable verdict +``` + +Например: + +```json +{ + "verdict": "fail", + "blocking": [ + { + "kind": "scope_violation", + "file": "Directory.Build.props", + "reason": "Task did not permit build infrastructure changes" + } + ], + "missing_tests": [ + "No negative test for event handler async void exception" + ], + "risk": "high" +} +``` + +Вот это годно. + +### 6. Для 007 особенно важна безопасность, потому что сейчас worktree не sandbox + +Вот тут надо быть неприятно честным, а не гладить 007 по README. Документ `security-layers.md` прямо говорит: `run` использует deny-list, а это не sandbox, потому что command obfuscation может проскочить. Там же указано, что worktree isolation — это cleanup/convention, но не security boundary: процесс всё равно может читать/писать вне worktree через абсолютные или `..` пути и ходить в сеть. + +Ещё хуже: `.007/gate.toml` запускает произвольный `bash -lc ` из target repo. Для недоверенного repo это attacker-controlled code execution. Документ прямо фиксирует, что `current_dir` не ограничивает ни writes, ни reads, ни egress. + +Что это значит для применения NoBootCamp-идей: + +``` +Для доверенных своих реп: +Можно начинать с policy/gates/worktree/evidence. + +Для чужих или полудоверенных реп: +Без container/WASI/egress hardening это рискованно. Агентный harness без +настоящей песочницы — это "изоляция" уровня таблички "не входить" на двери +без замка. +``` + +Практический вывод + +В 007 надо добавить `trust_level`: + +```toml +[target] +trust = "trusted-local" +# trusted-local | semi-trusted | untrusted +``` + +И правила: + +``` +trusted-local: + worktree + gates ok + +semi-trusted: + container required + network off by default + write mount only to worktree + +untrusted: + no agent full-auto + judge/read-only only + no bash gates unless sandboxed +``` + +Это прям должно быть в 007, иначе someday someone will run `o7 run` на "интересном" репозитории, и будет цирк с логами. + +### 7. Верификация в 007 уже ближе к правильной, но её надо встроить в агентный workflow + +`docs/verification.md` говорит, что проект уже использует/планирует несколько уровней: proptest для pure functions, cargo-fuzz для парсеров model stdout / findings.json / gate.toml, Kani для bounded no-panic proofs, плюс строгие lints и cargo deny. + +Это отлично подходит к 007, потому что 007 — glue/orchestration, а самые опасные поверхности там: + +``` +- model output parsing; +- gate.toml parsing; +- findings.json parsing; +- path handling; +- command execution; +- harvest/replay correctness. +``` + +Я бы добавил gate profile: + +```toml +[gate.profiles.fast] +steps = [ + "cargo test", + "cargo clippy --all-targets -- -D warnings" +] + +[gate.profiles.security] +steps = [ + "cargo test", + "cargo deny check", + "cargo +nightly fuzz run extract_json_array -- -max_total_time=60" +] + +[gate.profiles.release] +steps = [ + "nix flake check", + "cargo deny check" +] +``` + +И тогда task может сказать: + +```toml +[required_gates] +profile = "fast" +``` + +А security-sensitive change: + +```toml +[required_gates] +profile = "security" +``` + +Без этого агент может менять parser, а ты потом такой: "ну вроде тесты прошли". Какие тесты? Один happy path и молитва? IT'S FUCKING BUGGY! + +### 8. Перформанс-часть: NoBootCamp тут почти не нужен, но 007 уже знает правильный рычаг + +`docs/performance.md` правильно фиксирует, что 007 subprocess/LLM-bound, а не compute-bound: почти всё время уходит в ожидание claude, git, bash, а Rust glue занимает микросекунды. Единственный реальный рычаг — параллелить независимые per-file judge calls через bounded worker pool. + +И TODO это подтверждает: для STS-run уже указано, что per-file claude calls независимы, sequential = сумма latency, а bounded `--jobs N` даст near-linear speedup без изменения логики pairing. + +То есть для 007 я бы не тратил время на микротюнинг Rust. Никаких "давайте SmallVec", "давайте inline", "давайте cache locality". Это всё косметика на человеке, который опаздывает потому что ждёт поезд. + +Что делать: + +``` +o7 judge --jobs 4 +o7 judge --jobs 8 +``` + +Но обязательно: + +``` +- bounded concurrency; +- retry/backoff; +- per-file error isolation; +- deterministic output ordering; +- rate-limit aware logs. +``` + +### 9. Как бы я разложил NoBootCamp-подход именно по 007 + +**A. `o7 plan`** + +Новый режим: + +``` +o7 plan --repo ../Own.NET --base main --task ./task.md --out ./runs/... +``` + +Выход: + +``` +plan.md +plan.json +plan-verdict.json +``` + +Проверяет: + +``` +- scope; +- forbidden files; +- required tests; +- risk level; +- estimated gates. +``` + +**B. `o7 run`** + +Текущий MVP, но с policy: + +``` +o7 run --task task.o7.toml --gate ../Own.NET/.007/gate.toml +``` + +Обязательно собирает: + +``` +- diff.patch; +- changed files; +- touched forbidden paths; +- dependency changes; +- gate logs. +``` + +**C. `o7 judge-run`** + +Отдельная проверка результата: + +``` +o7 judge-run runs/Own.NET/ +``` + +Judge получает: + +``` +- original task; +- plan; +- diff; +- gate verdict; +- changed files; +- logs; +- policy violations. +``` + +Возвращает: + +``` +PASS | FAIL | NEEDS_HUMAN +``` + +**D. `o7 replay`** + +Суперважно: + +``` +o7 replay runs/Own.NET/ +``` + +Если нельзя воспроизвести, значит evidence pack неполный. А неполный evidence pack — это как тест без assert. Красиво, бесполезно, пахнет обманом. + +### 10. Самая сильная идея: 007 как "CI для AI-агентов" + +Вот как я бы сформулировал роль 007: + +``` +007 is not an AI coding assistant. +007 is a reproducible, gated, auditable execution harness for AI coding assistants. +``` + +По-русски: + +> 007 не должен быть "ещё одним агентом". 007 должен быть судьёй, клеткой, журналом и турникетом для агентов. + +Claude/Codex могут генерировать код. 007 должен отвечать за: + +``` +- изоляцию; +- scope; +- запреты; +- gates; +- diff capture; +- evidence; +- judge; +- воспроизводимость; +- policy failure; +- human handoff. +``` + +И вот это уже реально применимо ко всем твоим штукам: + +``` +Own.NET → агент пишет analyzer/rule/docs/tests +OwnAudit → агент triage'ит findings / FP / отчёты +legacy WPF → агент делает маленькие refactor tasks +STS → judge по findings и false positives +sandboy → будущая sandbox/plugin boundary +``` + +### 11. Что я бы сделал ближайшим шагом в 007 + +Не sandbox. Не Cedar. Не Verus. Не "consensus multi-agent tournament", как бы ни чесались руки построить роботизированный цирк. + +Ближайший полезный шаг: + +``` +Task Contract + Diff Policy Gate +``` + +Минимально: + +``` +src/task_contract.rs +src/diff_policy.rs +schemas/task.o7.schema.json +examples/task.ownnet.analyzer.o7.toml +examples/policy.safe-defaults.toml +``` + +Первый gate: + +``` +- changed files are inside allowed_paths; +- forbidden_paths untouched; +- max files/lines not exceeded; +- dependency manifests unchanged unless allowed; +- task/gate/meta copied into run record. +``` + +Это даст 007 реальную ценность как harness, а не просто runner. + +MVP формата + +```toml +version = 1 + +[target] +repo = "../Own.NET" +base = "main" + +[scope] +allowed_paths = [ + "src/**", + "tests/**" +] +forbidden_paths = [ + ".github/**", + "*.sln", + "*.csproj", + "Directory.Build.props" +] + +[limits] +max_changed_files = 10 +max_added_lines = 700 +max_deleted_lines = 300 + +[policy] +allow_dependencies = false +allow_public_api_changes = false +require_tests = true +``` + +И после run: + +``` +o7 policy-check runs//diff.patch --policy task.o7.toml +``` + +Вердикт: + +```json +{ + "verdict": "FAIL", + "violations": [ + { + "kind": "forbidden_path", + "path": "Directory.Build.props" + } + ] +} +``` + +Вот это прям вкусно. Маленько, полезно, проверяемо. + +--- + +## Итог + +Да, применимо. Но для 007 это не "как писать промпты". + +Для 007 правильная версия такая: + +``` +NoBootCamp principles → executable agent harness protocol +``` + +Грубо: + +``` +prompt discipline → task contract +negative prompts → diff policy +plan-then-build → o7 plan + o7 run +self-review → o7 judge-run +testing checklist → gate profiles +AI output history → evidence pack +security advice → trust levels + sandbox triggers +``` + +Own.NET использует эти идеи внутри задач. + +007 должен использовать эти идеи как инфраструктуру, которая не даёт задачам превратиться в агентный мусорный пожар. From d693735f76f7c9d80f44d7329bb1e8e3a614c7c5 Mon Sep 17 00:00:00 2001 From: PhysShell <45852143+PhysShell@users.noreply.github.com> Date: Mon, 6 Jul 2026 17:11:33 +0500 Subject: [PATCH 4/8] Create architecture-review.md --- docs/architecture-review.md | 397 ++++++++++++++++++++++++++++++++++++ 1 file changed, 397 insertions(+) create mode 100644 docs/architecture-review.md diff --git a/docs/architecture-review.md b/docs/architecture-review.md new file mode 100644 index 0000000..6c1428c --- /dev/null +++ b/docs/architecture-review.md @@ -0,0 +1,397 @@ +Proposal: OwnAudit Architecture Review, Drift Gate & Report Pipeline + +Status + +Draft. + +Target repository + +"PhysShell/OwnAudit" + +Suggested file: + +"docs/architecture-review-and-drift-pipeline.md" + +Summary + +Introduce an OwnAudit-side architecture review pipeline that consumes architecture facts from Own.NET, applies reporting/baseline/drift logic, and emits PR-friendly architecture reports, SARIF, and gate verdicts. + +OwnAudit should not own the extractor or analyzer core. That belongs in Own.NET. OwnAudit owns: + +- consuming "arch-facts.json" and "arch-findings.json"; +- baseline and diff for architecture findings; +- architecture drift snapshots; +- PR markdown reports; +- SARIF export; +- dashboard integration; +- risk scoring; +- report-only high-level review summaries. + +This proposal turns the existing "arch/" work into a product-shaped pipeline. + +Existing groundwork + +OwnAudit already has an architecture roadmap that positions the project as an auditor built from semantic code graph, architecture rules, WPF/runtime probes, baseline/diff, SARIF/GitHub reports, and an AI explanation layer. + +The roadmap explicitly says this is not a greenfield rewrite: OwnAudit already has findings, CLI orchestration, baseline/diff concepts, graph/dashboard artifacts, history, tiers, gates, and local smells; the real gap is cross-cutting architecture rules. + +OwnAudit already contains "arch/drift.py", which compares structure between graph snapshots and reports coupling movement, new dependency edges, and newly introduced cycles before those necessarily become hard rule violations. + +OwnAudit already has "arch/rules.json" with concrete architecture rules: UI reaching SQL/data layer, Domain depending on WPF/presentation framework, cycle detection, god-class thresholds, coupling rules, and drift-sensitive targets such as SQL/WPF/DevExpress. + +The roadmap also documents Phase 3 as an architecture pass over Roslyn-generated "graph.json", with Python-side evaluation producing findings in the same "findings.json" schema for SARIF/diff/dashboard reuse. + +Related open PRs: + +- OwnAudit PR #35: "docs: add agentic coding discipline proposal" + https://github.com/PhysShell/OwnAudit/pull/35 + This PR adds a design note on disciplined agentic coding, task contracts, negative prompts, plan-then-build, diff policy gates, judge-run, and trust levels for Own.NET/OwnAudit/007. + +- 007 PR #15: "docs: add agentic coding discipline proposal" + https://github.com/PhysShell/007/pull/15 + This is relevant because it records the 007-side isolate → run → gate → harvest loop and future task/diff-policy gates that OwnAudit can depend on instead of reinventing agent execution. + +Problem + +OwnAudit has the right pieces, but architecture review is currently split across: + +- rules; +- drift diff; +- baseline/diff; +- graph docs; +- dashboard generation; +- future SARIF/reporting integration. + +The missing product slice is a single command that answers: + +What architectural debt exists? +What changed in this PR? +What is newly blocking? +What is old/baselined? +What is high-risk but report-only? +What should a reviewer look at first? + +Without this, developers still need to read raw JSON or multiple partial reports. That is how useful analysis dies: not because the detector is wrong, but because the output is a filing cabinet thrown down a staircase. + +Proposed command surface + +Add: + +python3 -m arch.review_cli \ + --facts arch-facts.json \ + --findings arch-findings.json \ + --rules arch/rules.json \ + --baseline architecture-baseline.json \ + --drift-baseline arch-snapshot.main.json \ + --out-dir arch/out \ + --gate-level error + +Outputs: + +arch/out/ + architecture-review.md + architecture-findings.sarif + architecture-findings.json + architecture-drift.json + architecture-drift.md + architecture-verdict.json + architecture-summary.json + +Pipeline + +Own.NET arch facts/findings + ↓ +OwnAudit normalization + ↓ +baseline/diff + ↓ +drift snapshot comparison + ↓ +risk scoring + ↓ +SARIF + markdown + dashboard artifacts + ↓ +gate verdict + +Inputs + +"arch-facts.json" + +Produced by Own.NET. + +Contains project/type/component dependency graph. + +"arch-findings.json" + +Produced by Own.NET "Own.Arch". + +Contains deterministic architecture findings with fingerprints. + +"architecture-baseline.json" + +OwnAudit-owned artifact for accepted historical findings. + +Purpose: + +- allow adoption in dirty legacy codebases; +- fail only on new violations; +- force explicit reason when accepting new debt. + +"arch-snapshot.main.json" + +OwnAudit-owned drift snapshot. + +Used to compare current PR structure against main. + +The existing drift design already treats snapshots as compact summaries containing component metrics, dependency surface, and cycles. + +Report model + +The architecture review report should have five sections. + +1. Verdict + +FAIL: 2 new blocking architecture violations. +WARN: 3 medium-risk drift items. +INFO: 1 dependency removed. + +2. New blocking findings + +Only findings that are: + +- deterministic; +- not present in baseline; +- severity at or above gate level. + +Example: + +ARCH001: Presentation depends on Infrastructure directly +Evidence: + Broker.Presentation -> Broker.Infrastructure + source: Broker.Presentation.csproj ProjectReference + +Why this matters: + Presentation can bypass Application policies and reach persistence implementation directly. + +3. Baselined debt + +Existing violations remain visible but do not block. + +Example: + +ARCH-DOMAIN-WPF: 7 existing findings +Baseline reason: + legacy ViewModel formatting leaked into Domain; tracked separately + +4. Drift since main + +Use existing "arch.drift" concepts: + +- new dependency; +- removed dependency; +- new cycle; +- resolved cycle; +- coupling increase; +- instability shift. + +Example: + +High: new dependency Sts.Domain.Orders -> System.Data.SqlClient +Medium: Sts.UI.ViewModels Ce 21 -> 27 (+6, +29%) +Info: removed dependency Sts.Legacy.Import -> DevExpress.Xpf + +5. Recommended reviewer focus + +This section is report-only and may be generated from deterministic evidence. + +Example: + +Reviewer focus: +1. The PR introduces a new Domain -> SQL dependency. +2. The PR increases UI ViewModel outgoing dependencies by 29%. +3. No new cycles were introduced. + +Gate policy + +Default gate behavior: + +error: fail on new deterministic architecture findings +high drift: fail only if configured +medium drift: report-only by default +heuristics: report-only by default +LLM review text: never gates directly + +Example: + +{ + "schema": "own.audit.arch.verdict/v1", + "verdict": "fail", + "blocking": [ + { + "kind": "finding", + "rule": "ARCH001", + "fingerprint": "sha256:..." + } + ], + "nonBlocking": [ + { + "kind": "drift", + "risk": "medium", + "detail": "Sts.UI.ViewModels Ce 21 -> 27" + } + ] +} + +SARIF export + +OwnAudit should convert architecture findings to SARIF with: + +- rule id; +- severity; +- fingerprint; +- source evidence; +- help text; +- baseline status if available. + +Only deterministic findings should become code scanning alerts by default. + +Drift items can be added as SARIF notes later, but they should start as markdown/report artifacts. Drift often describes component-level movement rather than a single source span. + +AI explanation layer + +The AI layer must be downstream of deterministic results. + +Allowed AI tasks: + +- summarize top architecture risks; +- explain why a rule matters; +- group repeated violations by root cause; +- propose refactoring steps; +- produce PR review text; +- suggest candidate 007 tasks. + +Forbidden AI tasks: + +- invent new blocking findings without analyzer evidence; +- change gate verdict; +- update baseline automatically; +- suppress architecture findings without explicit reason; +- treat style inference as deterministic truth. + +Example report + +# Architecture Review + +Verdict: FAIL + +## Blocking new violations + +### ARCH001: Presentation depends on Infrastructure + +Evidence: +- `Broker.Presentation` -> `Broker.Infrastructure` +- source: `Broker.Presentation.csproj` + +Impact: +Presentation can bypass Application and directly depend on persistence implementation. + +Suggested refactor: +Introduce an Application service or port and move the concrete Infrastructure dependency behind it. + +## Drift since main + +- High: new dependency `Sts.Domain.Orders` -> `System.Data.SqlClient` +- Medium: `Sts.UI.ViewModels` efferent coupling `21 -> 27` +- Info: removed dependency `Sts.Legacy.Import` -> `DevExpress.Xpf` + +## Baselined debt + +- 7 existing `ARCH-DOMAIN-WPF` findings remain unchanged. + +Dashboard integration + +Extend existing dashboard artifacts with an Architecture tab: + +Architecture + - verdict + - new blocking findings + - total baselined debt + - drift count by risk + - top risky components by Ce growth + - cycles introduced/resolved + +No new dashboard model should be invented if existing "viz/" history/report artifacts can be reused. + +Integration with 007 + +OwnAudit should emit machine-readable candidate tasks for 007. + +Example: + +{ + "schema": "own.audit.arch.task-candidates/v1", + "tasks": [ + { + "task_id": "ownarch.fix.arch001.presentation-infrastructure", + "finding_rule": "ARCH001", + "finding_fingerprint": "sha256:...", + "recommended_prompt_module": "ownarch.fix-layer-violation", + "risk": "high", + "constraints": { + "max_files_changed": 5, + "require_reaudit": true, + "forbid_baseline_update": true + } + } + ] +} + +007 remains responsible for executing/refactoring. OwnAudit only prepares evidence and gates. + +Acceptance criteria + +MVP is accepted when: + +1. "arch.review_cli" consumes "arch-findings.json", optional baseline, and optional drift snapshot. +2. It emits "architecture-review.md". +3. It emits "architecture-verdict.json". +4. It can fail with exit code "2" on new blocking deterministic architecture findings. +5. It can run in report-only mode. +6. It integrates with existing baseline/diff conventions. +7. It reuses existing "arch/drift.py" output instead of duplicating drift logic. +8. It emits SARIF for deterministic architecture findings. +9. Tests cover: + - clean architecture report; + - new blocking finding; + - baselined finding; + - new high-risk drift; + - report-only medium drift; + - no baseline file; + - malformed facts/findings input. + +Risks + +Risk: architecture review becomes generic lint soup + +Mitigation: only include findings with architectural evidence. Complexity, dead code, coverage, and formatting belong elsewhere. + +Risk: drift becomes noisy + +Mitigation: drift gates are opt-in and thresholded. Default is report-only except for high-risk sensitive-target dependencies. + +Risk: AI summary overclaims + +Mitigation: every AI-generated claim must cite a deterministic finding, drift item, or metric. No evidence, no claim. + +First implementation slice + +Implement: + +arch/review_cli.py +arch/report.py +architecture-review.md renderer +architecture-verdict.json +SARIF export for deterministic arch findings +tests + +Do not implement LLM review in the first slice. First make the boring pipeline work. Then let the parrot narrate the evidence. \ No newline at end of file From 28f47f2027232964175553d5b2b9d2d8eaf4ee2d Mon Sep 17 00:00:00 2001 From: PhysShell <45852143+PhysShell@users.noreply.github.com> Date: Mon, 6 Jul 2026 18:02:33 +0500 Subject: [PATCH 5/8] Create sketch-based-evidense.md --- docs/sketch-based-evidense.md | 280 ++++++++++++++++++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 docs/sketch-based-evidense.md diff --git a/docs/sketch-based-evidense.md b/docs/sketch-based-evidense.md new file mode 100644 index 0000000..6ff7a2e --- /dev/null +++ b/docs/sketch-based-evidense.md @@ -0,0 +1,280 @@ +Proposal: Sketch-Based Evidence Layer for Architecture and Code Audit + +Target repository + +"PhysShell/OwnAudit" + +Suggested file: + +"docs/proposals/P-029-sketch-based-evidence-layer.md" + +Summary + +OwnAudit should add a sketch-based evidence layer for compactly summarizing audit findings across repositories, pull requests, builds, and analyzer outputs. + +The goal is to make OwnAudit better at answering questions such as: + +- which files are repeatedly risky; +- which rules fire most often; +- which warnings are noise; +- which modules have unstable ownership; +- which tests are slow or flaky; +- which PRs have unusually large blast radius; +- which findings are duplicates under different wording; +- which architecture drift signals are increasing over time. + +This proposal complements the existing direction where OwnAudit acts as an evidence orchestrator and audit/report/gate layer. Own.NET can produce facts. 007 can produce agent execution evidence. OwnAudit should aggregate, rank, compare, and explain. + +Problem + +Architecture audits often drown in raw findings: + +312 warnings +48 changed files +9 analyzer categories +17 test failures +5 architecture rules +2 flaky checks +1 very tired developer + +Raw counts are not enough. They do not explain trend, severity, repetition, blast radius, or whether the same issue keeps coming back wearing a fake mustache. + +OwnAudit needs compact evidence models that can survive repeated runs and answer: + +- what changed since the last audit; +- what is newly risky; +- what is chronically risky; +- what is statistically abnormal; +- what should block a gate; +- what should merely be reported; +- what should be suppressed as known noise. + +Proposed solution + +Introduce a normalized evidence layer: + +"OwnAudit.Evidence.Sketches" + +It should support the following families of summaries. + +1. Heavy hitters for repeated risk + +Use Top-K / Space-Saving style summaries for: + +- files most often changed; +- files most often involved in failed checks; +- rules most often triggered; +- symbols most often touched by refactors; +- modules most often violating architecture boundaries; +- tests most often flaky; +- dependencies most often involved in policy violations. + +Example output: + +{ + "schema": "ownaudit.heavy_hitters.v1", + "kind": "rule_findings_by_file", + "top": [ + { + "key": "src/Foo/Bar.cs", + "estimatedCount": 31, + "lastSeenRunId": "2026-07-06T12-00-00Z" + } + ] +} + +2. Latency sketches for CI and analyzer timing + +Use t-digest/DDSketch-like summaries for: + +- analyzer execution time; +- build step duration; +- test duration; +- PR audit duration; +- report generation duration. + +This lets OwnAudit report: + +Analyzer OWN014: + p50: 180 ms + p95: 2.1 s + p99: 5.8 s + +This matters because “the analyzer is fast on average” is how slow tools sneak into CI and start eating morale. + +3. Bitmap indexes for audit slicing + +Use bitmap or roaring-style indexes to represent sets of internal ids: + +- files affected by rule X; +- files changed in PR Y; +- files owned by module Z; +- files violating architecture boundary B; +- tests covering changed files; +- findings suppressed by policy; +- findings promoted to gate failures. + +Then OwnAudit can compute: + +GateFailures = + ChangedFiles + AND ArchitectureViolations + AND NOT SuppressedFindings + +This gives OwnAudit a compact internal query model for reports and gates. + +4. SimHash / MinHash for finding duplicates and near-duplicates + +Use fingerprints for: + +- similar analyzer findings; +- repeated review comments; +- similar stack traces; +- near-duplicate architecture drift explanations; +- repeated agent mistakes from 007; +- copy-pasted code smells. + +The output should group related findings: + +{ + "schema": "ownaudit.similar_findings.v1", + "groupId": "simhash:8f31...", + "items": [ + "OWN014 in FileA.cs", + "OWN014 in FileB.cs" + ], + "reason": "similar diagnostic message and nearby code structure" +} + +5. Optional HLL for unique cardinality trends + +Use HLL/HLL++ style sketches only where exact distinct counting is too expensive or noisy: + +- unique files touched over time; +- unique rules triggered; +- unique symbols affected; +- unique contributors touching risky modules; +- unique dependency packages observed. + +For most small repositories, exact sets are enough. HLL should not be added just to look sophisticated. That would be technical debt wearing a lab coat. + +Architecture + +OwnAudit should treat sketches as evidence, not as final truth. + +Suggested flow: + +raw inputs + -> parsers + -> normalized facts + -> sketch aggregators + -> audit evidence + -> policy/gate + -> report + +Inputs may include: + +- Own.NET analyzer facts; +- build logs; +- test results; +- Git diff metadata; +- architecture rules; +- 007 action plans and effect ledgers; +- previous OwnAudit reports. + +Outputs should be stable JSON artifacts: + +artifacts/ownaudit/evidence/ + heavy-hitters.json + latency-sketches.json + bitmap-indexes.json + similarity-groups.json + trend-summary.json + +Policy integration + +Sketch evidence should support policies such as: + +rules: + - id: audit.hotspot.file_changed_too_often + when: + heavy_hitter: + kind: changed_files + min_estimated_count: 10 + severity: warning + + - id: audit.pr.large_architecture_blast_radius + when: + bitmap_intersection: + left: changed_files + right: architecture_sensitive_files + min_count: 5 + severity: error + +The goal is not to make OwnAudit mystical. The goal is to make repeated patterns visible and enforceable. + +MVP + +The MVP should include: + +1. stable evidence schema; +2. Top-K heavy hitters for: + - files by findings; + - rules by frequency; + - tests by failure count. +3. simple latency summaries for audit/build/analyzer duration; +4. bitmap index abstraction for file ids and finding ids; +5. report section: + - “Repeated hotspots”; + - “New anomalies”; + - “Chronic findings”; + - “Large blast-radius changes”. + +Phase 2 + +Add: + +- SimHash grouping for similar findings; +- trend comparison across audit runs; +- JSON schema validation; +- gate policy integration; +- ingestion of 007 run evidence; +- ingestion of Own.NET runtime diagnostic exports. + +Non-goals + +OwnAudit should not: + +- become a time-series database; +- store every raw event forever; +- replace Prometheus/Grafana; +- pretend approximate summaries are exact facts; +- block PRs only because a probabilistic estimate twitched; +- require Redis/Valkey to run local audit. + +Approximate evidence can raise suspicion. Exact evidence should convict. Tiny difference, huge legal and engineering consequences. + +Acceptance criteria + +This proposal is successful when: + +- OwnAudit can identify repeated file/rule/test hotspots; +- reports show p95/p99 durations, not only averages; +- PR reports can describe blast radius using set intersections; +- similar findings can be grouped instead of repeated as spam; +- gate rules can consume sketch-derived evidence with clear thresholds; +- exported artifacts are stable enough for 007 and Own.NET integration; +- the system remains usable without external infrastructure. + +Expected benefit + +OwnAudit becomes less of a static report printer and more of an evidence engine: + +- better prioritization; +- clearer architecture drift signals; +- fewer duplicate findings; +- more useful PR gates; +- better historical comparison; +- stronger bridge between Own.NET facts and 007 execution evidence. + +The important part: OwnAudit should not merely say “there are problems”. That is useless; everyone knows there are problems. OwnAudit should say which problems are recurring, growing, risky, and worth fixing now. \ No newline at end of file From 12761432487d80ee816b3359859a978a1581acec Mon Sep 17 00:00:00 2001 From: PhysShell Date: Wed, 8 Jul 2026 11:49:19 +0000 Subject: [PATCH 6/8] docs: normalize imported proposals; fix sketch-based-evidence filename - rename docs/sketch-based-evidense.md -> docs/sketch-based-evidence.md (typo) - replace chat-paste preambles (Target repository / Suggested file) in architecture-review.md and sketch-based-evidence.md with standard headers - index the three new design docs in README's 'where things live' table --- README.md | 3 +++ docs/architecture-review.md | 16 +++------------- ...ased-evidense.md => sketch-based-evidence.md} | 14 +++++--------- 3 files changed, 11 insertions(+), 22 deletions(-) rename docs/{sketch-based-evidense.md => sketch-based-evidence.md} (96%) diff --git a/README.md b/README.md index cd25a5b..3bb4994 100644 --- a/README.md +++ b/README.md @@ -35,5 +35,8 @@ console crash on the Russian-locale Windows target. | fix arm — wire mass appliers + safety wrapper + OWN fixer | `OwnAudit/` ([docs/fix-arm.md](docs/fix-arm.md)) | design | | LeakFixMine — mine real leak-fixes, SZZ-prove them, score OwnAudit vs baselines | `leakmine/` ([docs/leakfix-mine.md](docs/leakfix-mine.md)) | active | | agent-run triage — ingest 007's Zero Trust audit trail as evidence | `OwnAudit/` ([docs/agent-run-triage.md](docs/agent-run-triage.md)) | design | +| architecture review — drift gate & report pipeline over Own.Arch facts | `OwnAudit/` ([docs/architecture-review.md](docs/architecture-review.md)) | design | +| sketch-based evidence layer — compact cross-run finding summaries | `OwnAudit/` ([docs/sketch-based-evidence.md](docs/sketch-based-evidence.md)) | design | +| agentic coding discipline — task contracts, diff gates, judge-run | `OwnAudit/` ([docs/agentic-coding-discipline-proposal.md](docs/agentic-coding-discipline-proposal.md)) | design | See [PLAN.md](PLAN.md), the [Fix arm design](docs/fix-arm.md), and [LeakFixMine](docs/leakfix-mine.md). diff --git a/docs/architecture-review.md b/docs/architecture-review.md index 6c1428c..5a86588 100644 --- a/docs/architecture-review.md +++ b/docs/architecture-review.md @@ -1,18 +1,8 @@ -Proposal: OwnAudit Architecture Review, Drift Gate & Report Pipeline +# OwnAudit architecture review, drift gate & report pipeline -Status +- **Status:** draft. Imported from a design discussion and normalized. -Draft. - -Target repository - -"PhysShell/OwnAudit" - -Suggested file: - -"docs/architecture-review-and-drift-pipeline.md" - -Summary +## Summary Introduce an OwnAudit-side architecture review pipeline that consumes architecture facts from Own.NET, applies reporting/baseline/drift logic, and emits PR-friendly architecture reports, SARIF, and gate verdicts. diff --git a/docs/sketch-based-evidense.md b/docs/sketch-based-evidence.md similarity index 96% rename from docs/sketch-based-evidense.md rename to docs/sketch-based-evidence.md index 6ff7a2e..fa8d135 100644 --- a/docs/sketch-based-evidense.md +++ b/docs/sketch-based-evidence.md @@ -1,14 +1,10 @@ -Proposal: Sketch-Based Evidence Layer for Architecture and Code Audit +# Sketch-based evidence layer for architecture and code audit -Target repository +- **Status:** draft. Imported from a design discussion and normalized; the + pasted original suggested an Own.NET-style `P-NNN` path, but OwnAudit keeps + flat topic docs under `docs/`. -"PhysShell/OwnAudit" - -Suggested file: - -"docs/proposals/P-029-sketch-based-evidence-layer.md" - -Summary +## Summary OwnAudit should add a sketch-based evidence layer for compactly summarizing audit findings across repositories, pull requests, builds, and analyzer outputs. From 8b2a795d2b5c573846db6856075b262593a79534 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Wed, 8 Jul 2026 14:50:37 +0000 Subject: [PATCH 7/8] docs: replace agentic-coding-discipline copy with pointer to canonical Own.NET doc --- docs/agentic-coding-discipline-proposal.md | 1116 +------------------- 1 file changed, 13 insertions(+), 1103 deletions(-) diff --git a/docs/agentic-coding-discipline-proposal.md b/docs/agentic-coding-discipline-proposal.md index 73b3191..6c59f45 100644 --- a/docs/agentic-coding-discipline-proposal.md +++ b/docs/agentic-coding-discipline-proposal.md @@ -1,1103 +1,13 @@ -# Agentic Coding Discipline — Proposal - -> Статус: **proposal / design note**, не implementation plan. Зафиксировано как -> отправная точка для дисциплинированного agentic coding поверх Own.NET, -> OwnAudit и 007. Часть тезисов ниже уже реализована и задокументирована в -> репозиториях на момент коммита — см. раздел "Что уже есть". Остальное — -> открытые предложения, ждущие решения о приоритете. - -## Что из этого уже реализовано/задокументировано - -- **007** (`README.md`, `TODO.md`) — цикл `isolate → run → gate → harvest` уже - работает: `o7 run` делает git worktree, гоняет `claude` full-auto, прогоняет - `.007/gate.toml`, собирает `task.md / meta.json / agent.stdout / diff.patch / - gate/*.log` (`src/agent.rs`, `gate.rs`, `worktree.rs`, `record.rs`, - `verdict.rs`). -- **007/docs/security-layers.md** — источник тезисов про "deny-list ≠ sandbox", - "worktree isolation ≠ security boundary", `bash -lc` из target repo как - attacker-controlled code execution поверхность. -- **007/docs/performance.md** + **TODO.md** — тезис "007 subprocess/LLM-bound, - единственный рычаг — bounded `--jobs N` для per-file judge calls" и план - STS-run на 156 FP-suspects. -- **007/judge/** (`README.md`, `prompt.template.md`, `rubric.example.md`, - `fp-verdicts.schema.json`) — `o7 judge` как отдельный read-only режим с - machine-readable verdict уже реализован и верифицирован на oracle - (contract-conforming `fp-verdicts.json`). -- **OwnAudit/docs/fp-judge/verdict-contract.md + rubric.md** — источник истины, - под который подстроена схема `007/judge/fp-verdicts.schema.json`. -- **Own.NET/AGENTS.execution-surfaces.md** — живой пример agent-contract в духе - предложения ниже: ADR-решение (accept/reject), секция "Что НЕ делать" - (negative prompts), acceptance criteria, trigger table "пересмотреть если...". -- **Own.NET/AGENTS.md**, **OwnAudit/AGENTS.md** — repo-level своды правил для - агентов уже существуют. - -## Чего нет и что здесь предлагается как открытая задача - -- Папка `.ai/` в Own.NET (`project-context.md`, `architecture-rules.md`, - `forbidden-changes.md`, `task-template.md`, `review-template.md`, - `domain-glossary.md`, `testing-policy.md`). -- Машиночитаемый `task.o7.toml` / `TaskContract` + `DiffPolicy` gate в 007 — - сейчас есть только `examples/task.example.md` как обычный markdown-таск, без - scope/forbidden-paths/dependency enforcement. -- Команды `o7 plan`, `o7 judge-run`, `o7 replay`, `trust_level` - (trusted-local / semi-trusted / untrusted). -- Каталог analyzer rule id вида `OWNASYNC001` / `OWNLIFE00x` / `OWNWPF00x` / - `OWNDATA00x` для Own.NET. - ---- - -## Исходный текст предложения - -Я бы забрал из NoBootCamp не "vibe coding", а disciplined agentic coding. То есть не "AI, сделай мне модуль", а "AI, вот клетка, вот правила, вот тесты, вот ножницы, шаг влево — review тебя сожрёт". Иначе это не разработка, а генератор PR'ов, которые выглядят уверенно, пока не открываешь diff. - -### 1. Главное правило: AI не должен владеть задачей целиком - -Плохой стиль: - -``` -Сделай модуль анализа async-проблем в Own.NET. -``` - -Это приглашение к катастрофе. Агент начнёт придумывать архитектуру, термины, классы, API, тесты, формат отчёта и, возможно, религию. - -Правильный стиль: - -``` -Сделай только analyzer rule OWN0001: -- найти async void методы, кроме event handlers -- проект: .NET 8 analyzer -- целевые проекты: .NET Framework 4.7.2 legacy codebase -- diagnostic severity: Warning -- code fix пока не нужен -- не менять существующую архитектуру -- добавить unit tests на Roslyn analyzer test framework -``` - -Вот это уже задача. Маленькая, проверяемая, без "AI построит Рим, но на TypeScript". - -### 2. Plan-then-build: сначала план, потом код - -Для тебя это must-have. Особенно если агент работает с legacy WPF, графой расчётов, SQL, DevExpress, старым .NET Framework. Там любое "я просто чуть-чуть поправил" обычно означает "я переломал жизненный цикл окна и теперь форма держится в памяти до тепловой смерти Вселенной". - -Шаблон: - -``` -Сначала НЕ пиши код. - -Дай план изменения: -1. какие файлы надо менять; -2. какие файлы нельзя трогать; -3. какие public API останутся совместимыми; -4. какие риски есть; -5. какие тесты надо добавить; -6. как проверить, что поведение не изменилось. - -После плана остановись. -``` - -Зачем это нужно: ты ловишь бред до того, как он превратился в diff на 900 строк. Если в плане агент пишет "создадим новый ServiceLocator", сразу бьёшь по рукам. Потому что ServiceLocator в legacy-проекте — это не паттерн, это плесень с интерфейсом. - -### 3. Negative prompts: запрещай явно - -AI очень любит "помочь" через скрытые побочные эффекты. Поэтому ему надо не только сказать, что делать, но и что категорически нельзя. - -Для твоих проектов я бы держал постоянный блок: - -``` -Запрещено: -- менять public API без явного указания; -- добавлять NuGet-пакеты без отдельного разрешения; -- использовать static mutable state; -- добавлять service locator; -- глотать исключения через catch { }; -- использовать async void, кроме UI event handlers; -- использовать Task.Run как маскировку синхронного IO; -- менять SQL-семантику без тестов; -- менять threading model WPF; -- трогать .csproj, packages.config, build scripts без отдельного разрешения; -- делать "рефакторинг заодно"; -- переименовывать классы/методы, если задача не про это. -``` - -Это выглядит занудно, но это дешевле, чем потом спрашивать: "а почему checkout документа стал падать только на удалённом SQL Server после 17:30 по четвергам". - -### 4. Для Own.NET это можно оформить как "Agent Contract" - -Я бы сделал в репозитории папку: - -``` -.ai/ - project-context.md - architecture-rules.md - forbidden-changes.md - task-template.md - review-template.md - domain-glossary.md - testing-policy.md -``` - -Примерно так: - -**`.ai/project-context.md`** - -``` -Проект Own.NET — набор инструментов для анализа .NET-кода: -- Roslyn analyzers; -- архитектурные проверки; -- async/threading diagnostics; -- IDisposable/lifetime diagnostics; -- WPF-specific diagnostics; -- legacy .NET Framework compatibility checks. - -Цель: помогать безопасно улучшать legacy .NET/WPF код без массовых рискованных переписываний. -``` - -**`.ai/architecture-rules.md`** - -``` -Правила: -- analyzer rules должны быть маленькими и независимыми; -- каждая rule имеет ID, описание, severity, examples, tests; -- analyzer не должен требовать runtime execution; -- false positives должны быть явно описаны; -- dangerous autofix запрещён без отдельного review; -- diagnostics должны объяснять не только "что плохо", но и "почему". -``` - -**`.ai/forbidden-changes.md`** - -``` -Нельзя: -- делать глобальные refactorings; -- добавлять зависимости без обоснования; -- смешивать analyzer logic и reporting; -- добавлять rule без тестов; -- добавлять code fix без negative tests; -- ломать deterministic output. -``` - -Это превращает "чат с AI" в почти нормальный engineering workflow. Почти. Роботы всё ещё могут уверенно нести чушь, но хотя бы по форме. - -### 5. Self-review: заставлять агента проверять собственный diff - -После генерации кода не надо сразу верить. Это как верить junior'у, который говорит "у меня локально работает". Работает?! Телега с тремя колёсами тоже "работает", пока не надо повернуть. - -Шаблон review: - -``` -Проверь этот diff как злой maintainer. - -Ищи: -- изменение поведения; -- скрытые breaking changes; -- race conditions; -- memory leaks; -- swallowed exceptions; -- async/threading проблемы; -- слишком широкие изменения; -- отсутствие тестов; -- несоответствие задаче. - -Формат ответа: -1. Blocking issues -2. Non-blocking issues -3. Missing tests -4. Safer alternative -``` - -Для Own.NET можно сделать это отдельным режимом: AI Review Pass. - -Например: - -``` -Review rule OWN0003: EventSubscriptionLeakAnalyzer. -Проверь, не даёт ли analyzer false positive на weak event pattern, IDisposable cleanup, composite disposable, и WPF Binding events. -``` - -Вот это уже полезно. Не "похвали мой код", а "найди, где он врёт". - -### 6. Для legacy WPF особенно важны agent-readable invariants - -AI плохо понимает невидимые правила старого проекта. Поэтому их надо записывать явно. - -Например: - -``` -WPF invariants: -- ViewModel не должен напрямую знать о View; -- подписки на events должны освобождаться; -- Dispatcher usage должен быть явным; -- long-running операции не должны блокировать UI thread; -- ObservableCollection изменяется только на UI thread; -- IDisposable ownership должен быть очевиден; -- Presenter/Coordinator не должен превращаться в God Object. -``` - -Или для твоих справочников/TNVED/ставок: - -``` -Data invariants: -- не материализовать весь справочник без необходимости; -- большие деревья загружать лениво; -- MessagePack blobs не декодировать полностью ради одного поля; -- SQL query должен быть parameterized; -- paging обязателен для больших выборок; -- LRU/cache не должен менять доменную семантику. -``` - -Это прям корм для AI-агентов. Без этого они будут "улучшать" код так, что справочник на 20k узлов внезапно грузится весь "для удобства". Удобство, ага. Для пожара. - -### 7. Задачи надо резать на "атомы" - -Не так: - -``` -Сделай модуль AsyncAnalyzer. -``` - -А так: - -``` -Task 1: OWN0001 async void detector -Task 2: OWN0002 .Result/.Wait() detector in UI context -Task 3: OWN0003 fire-and-forget Task without observation -Task 4: OWN0004 ConfigureAwait misuse policy -Task 5: OWN0005 Task.Run around synchronous DB call -Task 6: report formatter -Task 7: suppression mechanism -Task 8: documentation examples -``` - -Каждая задача должна иметь: - -``` -- вход; -- ожидаемый diagnostic; -- false positive cases; -- false negative acceptable cases; -- тесты; -- запреты; -- done criteria. -``` - -Иначе агент сделает функцию, которая делает больше работ, чем single parent on three shifts. IT'S FUCKING BUGGY! - -### 8. Очень полезная штука: "definition of done" для AI - -В конце каждого промпта: - -``` -Definition of Done: -- код компилируется; -- добавлены тесты; -- покрыты positive и negative cases; -- нет изменений вне заявленных файлов; -- public API не изменён; -- нет новых зависимостей; -- diagnostic message понятный; -- есть пример bad/good code; -- описаны known limitations. -``` - -Это не гарантия качества. Это забор. AI всё ещё может перелезть, но хотя бы будет видно, где он испачкал штаны. - -### 9. Для твоего Own.NET я бы начал с таких модулей - -**Async module** - -Самый жирный кандидат. - -``` -OWNASYNC001: async void outside event handlers -OWNASYNC002: blocking wait on Task: .Wait(), .Result, GetAwaiter().GetResult() -OWNASYNC003: fire-and-forget Task without observation/logging -OWNASYNC004: Task.Run used to hide sync IO -OWNASYNC005: async method without CancellationToken in service boundary -OWNASYNC006: ConfigureAwait policy violation -``` - -Особенно интересно для WPF: ловить `.Result`/`.Wait()` в UI-пути. Это прям классика "почему окно умерло, хотя процесс живой". - -**IDisposable / lifetime module** - -``` -OWNLIFE001: IDisposable field not disposed -OWNLIFE002: event subscription not unsubscribed -OWNLIFE003: IDisposable created but not owned -OWNLIFE004: CancellationTokenSource not disposed -OWNLIFE005: Stream/SqlConnection/DbCommand lifetime leak -``` - -Для legacy desktop это золото. Там утечки обычно не "одна большая ошибка", а тысяча мелких "ну оно же работает". - -**SQL/data-access module** - -``` -OWNDATA001: string interpolation in SQL -OWNDATA002: concatenated SQL with user/domain input -OWNDATA003: SELECT * in repository/query object -OWNDATA004: missing transaction boundary -OWNDATA005: provider-specific SQL without abstraction marker -OWNDATA006: temp table incompatibility SQL Server/SQLite -``` - -С учётом твоей боли SQL Server/SQLite — прям вкусно. Можно делать analyzer + test corpus на query builder. - -**WPF module** - -``` -OWNWPF001: ObservableCollection modified outside UI thread -OWNWPF002: event subscription leak in View/ViewModel/Presenter -OWNWPF003: long-running operation in command handler -OWNWPF004: Dispatcher.Invoke instead of BeginInvoke/async path -OWNWPF005: direct View reference from ViewModel -OWNWPF006: Bitmap/Image resource not released -``` - -Вот тут надо аккуратно: WPF-анализ легко даёт false positive. Но даже advisory diagnostics уже полезны. - -### 10. Самый ценный формат промпта для тебя - -Вот шаблон, который можно реально использовать: - -``` -Ты работаешь как senior .NET/Roslyn developer. - -Контекст: -- проект: Own.NET -- цель: analyzer для legacy .NET/WPF проектов -- стиль: маленькие независимые rules -- тесты обязательны - -Задача: -Реализовать rule OWNASYNC001: async void outside event handlers. - -Требования: -- diagnostic для async void методов; -- не репортить event handlers вида void Handler(object sender, EventArgs e); -- не репортить override методов, если сигнатура навязана базовым API; -- diagnostic message должен объяснять риск; -- severity: Warning; -- code fix не делать. - -Ограничения: -- не добавлять NuGet dependencies; -- не менять public API существующих rules; -- не делать unrelated refactoring; -- не менять build scripts. - -Сначала дай план: -- какие файлы создашь/изменишь; -- какие тесты добавишь; -- какие false positives возможны; -- где нужна осторожность. - -После плана остановись. -``` - -А после утверждения плана: - -``` -Реализуй только согласованный план. -После кода дай: -1. список изменённых файлов; -2. краткое объяснение; -3. тестовые сценарии; -4. known limitations. -``` - -Вот это уже не "vibe". Это нормальный рабочий протокол. - -### 11. Для PR-review можно сделать отдельный "злой режим" - -Например: - -``` -Review this PR for Own.NET. - -Be strict. Assume the code is wrong until proven otherwise. - -Check: -- analyzer correctness; -- false positives; -- false negatives; -- Roslyn performance; -- allocations; -- cancellation support; -- concurrency safety; -- deterministic diagnostics; -- tests quality; -- public API compatibility. - -Do not praise. Find risks. -``` - -Это очень подходит под твой стиль "код должен заработать право существовать". И да, тут "не хвали" важно. AI по дефолту ведёт себя как HR на корпоративе: всё "promising", "solid foundation", "nice work". А тебе нужен maintainer, который скажет: "WHERE'S THE ERROR HANDLING?!" - -### 12. Что реально можно протащить в твой процесс - -Я бы внедрял так: - -1. `.ai/` папка с правилами проекта — чтобы каждый агент не начинал с нуля и не изобретал очередной "чистый" ад. -2. Task template — одинаковый формат задач для analyzer/rule/refactor/test. -3. Review template — отдельный промпт для проверки diff'а. -4. Negative constraints — запреты на side effects, новые зависимости, public API changes. -5. Rule skeleton generator — агент генерит каркас analyzer rule, тесты, examples, docs. -6. Golden test corpus — папка с bad/good examples, чтобы AI не спорил с реальностью. -7. Regression checklist — особенно для графы 47, SQL builder, WPF lifecycle, async/threading. - -### 13. Самая важная мысль - -AI полезен не как "разработчик вместо тебя", а как ускоритель конкретных операций: - -- накидать Roslyn analyzer skeleton; -- придумать negative test cases; -- проверить diff на риски; -- объяснить чужой код; -- сгенерить documentation examples; -- составить migration plan; -- найти edge cases; -- сделать boring code. - -Но архитектурные инварианты, границы модулей, совместимость, lifecycle, перформанс и "а не превратится ли это в болото через 3 месяца" — это всё ещё на тебе. Несправедливо, конечно. Но зато без иллюзии, что "vibe" заменяет engineering. Вайб не ловит memory leak. Тесты ловят. Анализаторы ловят. Review ловит. Иногда senior с кофеином ловит. - -Да. Более того, 007 — это как раз место, где такие подходы надо превращать из "хороших советов" в исполняемый протокол. - -Для Own.NET это выглядело как: - -> "AI, напиши analyzer rule, но вот инварианты, тесты, запреты, review." - -А для 007 это должно выглядеть так: - -> "007, запусти агента только внутри заданного контракта, собери diff, прогоняй gates, зафиксируй evidence, потом отдельный judge/reviewer решает, можно ли это вообще считать работой." - -То есть Own.NET — пациент, а 007 — хирургическая операционная. Если операционная не стерильная, пациенту кирдык, даже если врач в белом халате и с Claude Max. - -#### Что уже в 007 идеально подходит - -Судя по README, 007 уже задуман как harness: `o7 run` делает worktree, запускает claude/codex, прогоняет gate steps и складывает canonical record: `task.md`, `meta.json`, `agent.stdout`, `diff.patch`, `gate/*.log`, `verdict.json`. Это прям база для disciplined agentic coding, а не "AI, сделай красиво, я отвернусь". - -То есть NoBootCamp-идею надо не "применить к 007", а закодировать в 007 как режимы работы: - -``` -task contract → isolated run → gates → harvest → judge/review → verdict -``` - -И вот тут начинается мясо. - ---- - -### 1. Для 007 нужен не "prompt template", а Task Contract - -В Own.NET можно было держать `.ai/task-template.md`. - -В 007 лучше сделать машиночитаемый task contract, например: - -```toml -# task.o7.toml - -[target] -repo = "../Own.NET" -base = "main" - -[agent] -provider = "claude" -mode = "full-auto" - -[scope] -allowed_paths = [ - "src/OwnNet.Analyzers/**", - "tests/OwnNet.Analyzers.Tests/**" -] - -forbidden_paths = [ - "*.csproj", - "Directory.Build.props", - ".github/**" -] - -[change_policy] -allow_new_dependencies = false -allow_public_api_changes = false -allow_unrelated_refactoring = false -require_tests = true - -[task] -kind = "roslyn-analyzer" -summary = "Implement OWNASYNC001: async void outside event handlers" - -[done] -commands = [ - "dotnet test", - "dotnet build -warnaserror" -] -``` - -Почему это лучше обычного `task.md`? Потому что обычный markdown — это просьба. А `.toml`/schema — это контракт. Компьютер хотя бы может проверить, что агент не полез в `.csproj`, вместо того чтобы потом человек руками обнаруживал "маленький рефакторинг" на 1800 строк. Технический долг, но с бантиком. - -Что добавить в 007: - -``` -o7 validate-task --task task.o7.toml -o7 run --task task.o7.toml -o7 inspect-run runs/ -o7 judge-run runs/ -``` - -Минимальный MVP: - -``` -task.md # человеческое описание -task.o7.toml # машинный контракт -gate.toml # команды проверки -policy.toml # запреты / scope / allowlist -``` - -### 2. plan-then-build в 007 должен стать отдельной фазой - -Сейчас README описывает один цикл: isolate → run → gate → harvest. - -Но для coding-agent задач я бы разделил: - -``` -o7 plan -o7 run -o7 judge -``` - -То есть агент сначала не имеет права менять код. Он должен сгенерировать план: - -``` -runs/// - plan.md - plan.meta.json - plan.verdict.json -``` - -Потом отдельный gate проверяет план: - -``` -- план не трогает запрещённые файлы; -- план не добавляет зависимости; -- план перечисляет тесты; -- план содержит rollback/check strategy; -- план не предлагает глобальный рефакторинг. -``` - -И только потом: - -``` -o7 run --from-plan runs/.../plan.md -``` - -Это сильно лучше, чем давать агенту full-auto сразу. Потому что full-auto без предварительного плана — это как дать экскаватор человеку, который "примерно понял задачу". Земля, конечно, будет двигаться. Вопрос только, чья. - -### 3. Negative prompts в 007 должны стать policy/gate, а не текстом - -В Own.NET мы могли писать: - -``` -Не меняй public API. -Не добавляй зависимости. -Не трогай build scripts. -``` - -В 007 это надо превратить в проверяемые правила: - -```toml -[diff_policy] -max_changed_files = 8 -max_added_lines = 500 -forbid_paths = [ - "Cargo.toml", - "flake.nix", - ".github/**", - "**/*.sln", - "**/*.csproj" -] - -[dependency_policy] -allow_new_nuget = false -allow_new_npm = false -allow_new_cargo = false - -[api_policy] -require_public_api_report = true -``` - -И gate после diff должен проверять: - -``` -diff.patch против policy.toml -``` - -Если агент полез куда не просили: - -``` -FAIL: touched forbidden file Directory.Build.props -FAIL: added dependency Microsoft.Extensions.DependencyInjection -FAIL: changed public API without approval -``` - -Вот это уже нормальная инженерия. Не "агент, пожалуйста, будь хорошим мальчиком", а "вышел за пределы клетки — run failed". WHERE'S THE ERROR HANDLING?! Вот оно, наконец-то. - -### 4. 007 должен собирать не просто diff, а evidence pack - -README уже говорит, что 007 harvest'ит `meta.json`, `agent.stdout`, `diff.patch`, gate logs и verdict. - -Я бы расширил canonical record: - -``` -runs/// - task.md - task.o7.toml - plan.md - meta.json - - diff.patch - changed-files.json - forbidden-touches.json - - agent/ - stdout.log - stderr.log - tool-calls.json - - gate/ - build.log - test.log - lint.log - policy.log - verdict.json - - judge/ - review.md - verdict.json - risks.json - - replay/ - base_commit.txt - head_commit.txt - commands.sh -``` - -Зачем: 007 должен быть не просто "запустил агента", а черный ящик самолёта после падения. Агент внёс diff? Докажи: - -``` -что он запускался в правильном repo; -от какого base commit; -какие файлы поменял; -какие gates прошли; -какие упали; -что judge сказал; -где логи; -какой prompt был; -чем run воспроизводится. -``` - -Иначе это не automation harness, а "скрипт, который доверяет LLM". А это уже почти религиозная практика. - -### 5. judge в 007 — прямое продолжение self-review - -У тебя уже есть `o7 judge`, и TODO говорит, что он проверен на read-only FP-triage и выдавал contract-conforming `fp-verdicts.json`; дальше запланирован FP-control и реальный STS-run на 156 FP-suspects. - -Это очень важная часть. В терминах NoBootCamp: - -``` -self-correction / review prompt -``` - -В терминах 007: - -``` -judge command + rubric + schema + verdict contract -``` - -То есть не "Claude сам себя проверил, ну значит норм". Нет. Отдельный режим: - -``` -agent делает diff -judge смотрит diff + task + gate logs -judge возвращает machine-readable verdict -``` - -Например: - -```json -{ - "verdict": "fail", - "blocking": [ - { - "kind": "scope_violation", - "file": "Directory.Build.props", - "reason": "Task did not permit build infrastructure changes" - } - ], - "missing_tests": [ - "No negative test for event handler async void exception" - ], - "risk": "high" -} -``` - -Вот это годно. - -### 6. Для 007 особенно важна безопасность, потому что сейчас worktree не sandbox - -Вот тут надо быть неприятно честным, а не гладить 007 по README. Документ `security-layers.md` прямо говорит: `run` использует deny-list, а это не sandbox, потому что command obfuscation может проскочить. Там же указано, что worktree isolation — это cleanup/convention, но не security boundary: процесс всё равно может читать/писать вне worktree через абсолютные или `..` пути и ходить в сеть. - -Ещё хуже: `.007/gate.toml` запускает произвольный `bash -lc ` из target repo. Для недоверенного repo это attacker-controlled code execution. Документ прямо фиксирует, что `current_dir` не ограничивает ни writes, ни reads, ни egress. - -Что это значит для применения NoBootCamp-идей: - -``` -Для доверенных своих реп: -Можно начинать с policy/gates/worktree/evidence. - -Для чужих или полудоверенных реп: -Без container/WASI/egress hardening это рискованно. Агентный harness без -настоящей песочницы — это "изоляция" уровня таблички "не входить" на двери -без замка. -``` - -Практический вывод - -В 007 надо добавить `trust_level`: - -```toml -[target] -trust = "trusted-local" -# trusted-local | semi-trusted | untrusted -``` - -И правила: - -``` -trusted-local: - worktree + gates ok - -semi-trusted: - container required - network off by default - write mount only to worktree - -untrusted: - no agent full-auto - judge/read-only only - no bash gates unless sandboxed -``` - -Это прям должно быть в 007, иначе someday someone will run `o7 run` на "интересном" репозитории, и будет цирк с логами. - -### 7. Верификация в 007 уже ближе к правильной, но её надо встроить в агентный workflow - -`docs/verification.md` говорит, что проект уже использует/планирует несколько уровней: proptest для pure functions, cargo-fuzz для парсеров model stdout / findings.json / gate.toml, Kani для bounded no-panic proofs, плюс строгие lints и cargo deny. - -Это отлично подходит к 007, потому что 007 — glue/orchestration, а самые опасные поверхности там: - -``` -- model output parsing; -- gate.toml parsing; -- findings.json parsing; -- path handling; -- command execution; -- harvest/replay correctness. -``` - -Я бы добавил gate profile: - -```toml -[gate.profiles.fast] -steps = [ - "cargo test", - "cargo clippy --all-targets -- -D warnings" -] - -[gate.profiles.security] -steps = [ - "cargo test", - "cargo deny check", - "cargo +nightly fuzz run extract_json_array -- -max_total_time=60" -] - -[gate.profiles.release] -steps = [ - "nix flake check", - "cargo deny check" -] -``` - -И тогда task может сказать: - -```toml -[required_gates] -profile = "fast" -``` - -А security-sensitive change: - -```toml -[required_gates] -profile = "security" -``` - -Без этого агент может менять parser, а ты потом такой: "ну вроде тесты прошли". Какие тесты? Один happy path и молитва? IT'S FUCKING BUGGY! - -### 8. Перформанс-часть: NoBootCamp тут почти не нужен, но 007 уже знает правильный рычаг - -`docs/performance.md` правильно фиксирует, что 007 subprocess/LLM-bound, а не compute-bound: почти всё время уходит в ожидание claude, git, bash, а Rust glue занимает микросекунды. Единственный реальный рычаг — параллелить независимые per-file judge calls через bounded worker pool. - -И TODO это подтверждает: для STS-run уже указано, что per-file claude calls независимы, sequential = сумма latency, а bounded `--jobs N` даст near-linear speedup без изменения логики pairing. - -То есть для 007 я бы не тратил время на микротюнинг Rust. Никаких "давайте SmallVec", "давайте inline", "давайте cache locality". Это всё косметика на человеке, который опаздывает потому что ждёт поезд. - -Что делать: - -``` -o7 judge --jobs 4 -o7 judge --jobs 8 -``` - -Но обязательно: - -``` -- bounded concurrency; -- retry/backoff; -- per-file error isolation; -- deterministic output ordering; -- rate-limit aware logs. -``` - -### 9. Как бы я разложил NoBootCamp-подход именно по 007 - -**A. `o7 plan`** - -Новый режим: - -``` -o7 plan --repo ../Own.NET --base main --task ./task.md --out ./runs/... -``` - -Выход: - -``` -plan.md -plan.json -plan-verdict.json -``` - -Проверяет: - -``` -- scope; -- forbidden files; -- required tests; -- risk level; -- estimated gates. -``` - -**B. `o7 run`** - -Текущий MVP, но с policy: - -``` -o7 run --task task.o7.toml --gate ../Own.NET/.007/gate.toml -``` - -Обязательно собирает: - -``` -- diff.patch; -- changed files; -- touched forbidden paths; -- dependency changes; -- gate logs. -``` - -**C. `o7 judge-run`** - -Отдельная проверка результата: - -``` -o7 judge-run runs/Own.NET/ -``` - -Judge получает: - -``` -- original task; -- plan; -- diff; -- gate verdict; -- changed files; -- logs; -- policy violations. -``` - -Возвращает: - -``` -PASS | FAIL | NEEDS_HUMAN -``` - -**D. `o7 replay`** - -Суперважно: - -``` -o7 replay runs/Own.NET/ -``` - -Если нельзя воспроизвести, значит evidence pack неполный. А неполный evidence pack — это как тест без assert. Красиво, бесполезно, пахнет обманом. - -### 10. Самая сильная идея: 007 как "CI для AI-агентов" - -Вот как я бы сформулировал роль 007: - -``` -007 is not an AI coding assistant. -007 is a reproducible, gated, auditable execution harness for AI coding assistants. -``` - -По-русски: - -> 007 не должен быть "ещё одним агентом". 007 должен быть судьёй, клеткой, журналом и турникетом для агентов. - -Claude/Codex могут генерировать код. 007 должен отвечать за: - -``` -- изоляцию; -- scope; -- запреты; -- gates; -- diff capture; -- evidence; -- judge; -- воспроизводимость; -- policy failure; -- human handoff. -``` - -И вот это уже реально применимо ко всем твоим штукам: - -``` -Own.NET → агент пишет analyzer/rule/docs/tests -OwnAudit → агент triage'ит findings / FP / отчёты -legacy WPF → агент делает маленькие refactor tasks -STS → judge по findings и false positives -sandboy → будущая sandbox/plugin boundary -``` - -### 11. Что я бы сделал ближайшим шагом в 007 - -Не sandbox. Не Cedar. Не Verus. Не "consensus multi-agent tournament", как бы ни чесались руки построить роботизированный цирк. - -Ближайший полезный шаг: - -``` -Task Contract + Diff Policy Gate -``` - -Минимально: - -``` -src/task_contract.rs -src/diff_policy.rs -schemas/task.o7.schema.json -examples/task.ownnet.analyzer.o7.toml -examples/policy.safe-defaults.toml -``` - -Первый gate: - -``` -- changed files are inside allowed_paths; -- forbidden_paths untouched; -- max files/lines not exceeded; -- dependency manifests unchanged unless allowed; -- task/gate/meta copied into run record. -``` - -Это даст 007 реальную ценность как harness, а не просто runner. - -MVP формата - -```toml -version = 1 - -[target] -repo = "../Own.NET" -base = "main" - -[scope] -allowed_paths = [ - "src/**", - "tests/**" -] -forbidden_paths = [ - ".github/**", - "*.sln", - "*.csproj", - "Directory.Build.props" -] - -[limits] -max_changed_files = 10 -max_added_lines = 700 -max_deleted_lines = 300 - -[policy] -allow_dependencies = false -allow_public_api_changes = false -require_tests = true -``` - -И после run: - -``` -o7 policy-check runs//diff.patch --policy task.o7.toml -``` - -Вердикт: - -```json -{ - "verdict": "FAIL", - "violations": [ - { - "kind": "forbidden_path", - "path": "Directory.Build.props" - } - ] -} -``` - -Вот это прям вкусно. Маленько, полезно, проверяемо. - ---- - -## Итог - -Да, применимо. Но для 007 это не "как писать промпты". - -Для 007 правильная версия такая: - -``` -NoBootCamp principles → executable agent harness protocol -``` - -Грубо: - -``` -prompt discipline → task contract -negative prompts → diff policy -plan-then-build → o7 plan + o7 run -self-review → o7 judge-run -testing checklist → gate profiles -AI output history → evidence pack -security advice → trust levels + sandbox triggers -``` - -Own.NET использует эти идеи внутри задач. - -007 должен использовать эти идеи как инфраструктуру, которая не даёт задачам превратиться в агентный мусорный пожар. +# Agentic Coding Discipline — Proposal (pointer) + +> Статус: **pointer**. Канонический текст этого предложения (task contracts, +> negative prompts, plan-then-build, diff policy gates, judge-run, trust levels +> — для Own.NET/OwnAudit/007) живёт в публичном репо Own.NET: +> `Own.NET/docs/agentic-coding-discipline-proposal.md` +> (https://github.com/PhysShell/Own.NET/blob/main/docs/agentic-coding-discipline-proposal.md). +> +> Раньше идентичная копия лежала в каждом из трёх репозиториев; копии +> неизбежно расходятся, поэтому здесь оставлен только указатель. + +Что из этого предложения уже опирается на OwnAudit: `docs/fp-judge/verdict-contract.md` +и `docs/fp-judge/rubric.md` — источник истины, под который подстроена judge-схема 007. From 63c621b24e02bb708b57fc5196c2b525c7ecebba Mon Sep 17 00:00:00 2001 From: PhysShell Date: Wed, 8 Jul 2026 16:27:08 +0000 Subject: [PATCH 8/8] docs: apply validation corrections to imported design docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - agent-run-triage: scope the Phase-1 qualifier over the meta.json identity fields (RunMeta today has no agent_id/policy_id — src/record.rs); replace live blob URLs with plain cross-repo paths; qualify the audit/security/ layout as proposed-in-P-024, not built - architecture-review: fence the example report (its raw '# Architecture Review' rendered as a mid-document H1), promote pasted section titles to headings, fence all CLI/JSON/tree examples, replace live-PR references with in-repo links, artifact names as subheadings with a pointer to Own.NET P-032 (Own.Arch) - sketch-based-evidence: promote section titles to headings, fence all examples, add Related links to the sibling sketch docs (007 sketch-aware-evidence, Own.NET P-033), scope SimHash grouping vs 007's per-run fingerprints --- docs/agent-run-triage.md | 11 +++-- docs/architecture-review.md | 78 +++++++++++++++++++++++------------ docs/sketch-based-evidence.md | 56 +++++++++++++++++-------- 3 files changed, 96 insertions(+), 49 deletions(-) diff --git a/docs/agent-run-triage.md b/docs/agent-run-triage.md index 517df5b..826a495 100644 --- a/docs/agent-run-triage.md +++ b/docs/agent-run-triage.md @@ -4,7 +4,7 @@ Status: design note / vision, not implementation (same status as [`audit-data-leverage.md`](audit-data-leverage.md) and [`own-net-auditor.md`](own-net-auditor.md)). Trigger to build: once **007** actually emits structured per-run capability events (its Phase 1 — see -[`007/docs/zero-trust-framework.md`](https://github.com/PhysShell/007/blob/main/docs/zero-trust-framework.md)). +`007/docs/zero-trust-framework.md`). Gated on that repo's data existing, not something to build ahead of it. ## 0. What this is @@ -19,7 +19,7 @@ phase in that roadmap is: **something has to look at the resulting evidence and decide what's noise vs. a real incident.** That's this repo's job, not 007's — 007 orchestrates and enforces; it isn't built to triage its own findings, same reason OwnAudit doesn't run its own detectors (see -[`docs/proposals/P-024-security-audit-profile.md`](https://github.com/PhysShell/Own.NET/blob/main/docs/proposals/P-024-security-audit-profile.md) +`Own.NET docs/proposals/P-024-security-audit-profile.md` in Own.NET: "оркестратор, не анализатор" applies here verbatim). ## 1. Reuse, don't build a new pipeline @@ -50,7 +50,9 @@ score → report pipeline, fed a new evidence source. ## 2. What gets ingested From a 007 run record (`runs///`): `meta.json` (run identity — -`run_id`, `agent_id`, `target_repo`, `base_commit`, `policy_id`), `gate/*.log` + +today `run_id`, `target`, `repo`, `base_commit`, `engine`; the full +`run_id`/`agent_id`/`target_repo`/`base_commit`/`policy_id` identity is itself +a Phase 1 item), `gate/*.log` + `gate/verdict.json` (per-step pass/fail), and — once Phase 1 lands — capability manifest violations (attempted network egress under `network = "deny"`, a write outside the declared scope, an unrecognized `[permissions]` field that failed @@ -141,7 +143,8 @@ new report pipeline, a new adapter feeding the one that exists. Layout, if/when 007 Phase 1 lands and this gets built: ```text -audit/agent-runs/ # parallel to audit/security/ (Own.NET) +audit/agent-runs/ # parallel to the audit/security/ layout proposed + # in Own.NET P-024 (not yet built) adapters/ # o7_run_to_finding.py profiles/ # which run stores to poll, retention window ``` diff --git a/docs/architecture-review.md b/docs/architecture-review.md index 5a86588..f8f368a 100644 --- a/docs/architecture-review.md +++ b/docs/architecture-review.md @@ -8,7 +8,7 @@ Introduce an OwnAudit-side architecture review pipeline that consumes architectu OwnAudit should not own the extractor or analyzer core. That belongs in Own.NET. OwnAudit owns: -- consuming "arch-facts.json" and "arch-findings.json"; +- consuming `arch-facts.json` and `arch-findings.json`; - baseline and diff for architecture findings; - architecture drift snapshots; - PR markdown reports; @@ -19,7 +19,7 @@ OwnAudit should not own the extractor or analyzer core. That belongs in Own.NET. This proposal turns the existing "arch/" work into a product-shaped pipeline. -Existing groundwork +## Existing groundwork OwnAudit already has an architecture roadmap that positions the project as an auditor built from semantic code graph, architecture rules, WPF/runtime probes, baseline/diff, SARIF/GitHub reports, and an AI explanation layer. @@ -31,17 +31,15 @@ OwnAudit already has "arch/rules.json" with concrete architecture rules: UI reac The roadmap also documents Phase 3 as an architecture pass over Roslyn-generated "graph.json", with Python-side evaluation producing findings in the same "findings.json" schema for SARIF/diff/dashboard reuse. -Related open PRs: +Related docs: -- OwnAudit PR #35: "docs: add agentic coding discipline proposal" - https://github.com/PhysShell/OwnAudit/pull/35 - This PR adds a design note on disciplined agentic coding, task contracts, negative prompts, plan-then-build, diff policy gates, judge-run, and trust levels for Own.NET/OwnAudit/007. +- [agentic-coding-discipline-proposal.md](agentic-coding-discipline-proposal.md) + This doc adds a design note on disciplined agentic coding, task contracts, negative prompts, plan-then-build, diff policy gates, judge-run, and trust levels for Own.NET/OwnAudit/007. -- 007 PR #15: "docs: add agentic coding discipline proposal" - https://github.com/PhysShell/007/pull/15 +- 007 `docs/agentic-coding-discipline-proposal.md` This is relevant because it records the 007-side isolate → run → gate → harvest loop and future task/diff-policy gates that OwnAudit can depend on instead of reinventing agent execution. -Problem +## Problem OwnAudit has the right pieces, but architecture review is currently split across: @@ -63,10 +61,11 @@ What should a reviewer look at first? Without this, developers still need to read raw JSON or multiple partial reports. That is how useful analysis dies: not because the detector is wrong, but because the output is a filing cabinet thrown down a staircase. -Proposed command surface +## Proposed command surface Add: +```bash python3 -m arch.review_cli \ --facts arch-facts.json \ --findings arch-findings.json \ @@ -75,9 +74,11 @@ python3 -m arch.review_cli \ --drift-baseline arch-snapshot.main.json \ --out-dir arch/out \ --gate-level error +``` Outputs: +```text arch/out/ architecture-review.md architecture-findings.sarif @@ -86,9 +87,11 @@ arch/out/ architecture-drift.md architecture-verdict.json architecture-summary.json +``` -Pipeline +## Pipeline +```text Own.NET arch facts/findings ↓ OwnAudit normalization @@ -102,22 +105,23 @@ risk scoring SARIF + markdown + dashboard artifacts ↓ gate verdict +``` -Inputs +## Inputs -"arch-facts.json" +### `arch-facts.json` Produced by Own.NET. Contains project/type/component dependency graph. -"arch-findings.json" +### `arch-findings.json` -Produced by Own.NET "Own.Arch". +Produced by Own.NET `Own.Arch` (see `Own.NET docs/proposals/P-032-own-arch-facts.md`). Contains deterministic architecture findings with fingerprints. -"architecture-baseline.json" +### `architecture-baseline.json` OwnAudit-owned artifact for accepted historical findings. @@ -127,7 +131,7 @@ Purpose: - fail only on new violations; - force explicit reason when accepting new debt. -"arch-snapshot.main.json" +### `arch-snapshot.main.json` OwnAudit-owned drift snapshot. @@ -135,15 +139,17 @@ Used to compare current PR structure against main. The existing drift design already treats snapshots as compact summaries containing component metrics, dependency surface, and cycles. -Report model +## Report model The architecture review report should have five sections. 1. Verdict +```text FAIL: 2 new blocking architecture violations. WARN: 3 medium-risk drift items. INFO: 1 dependency removed. +``` 2. New blocking findings @@ -155,6 +161,7 @@ Only findings that are: Example: +```text ARCH001: Presentation depends on Infrastructure directly Evidence: Broker.Presentation -> Broker.Infrastructure @@ -162,6 +169,7 @@ Evidence: Why this matters: Presentation can bypass Application policies and reach persistence implementation directly. +``` 3. Baselined debt @@ -169,9 +177,11 @@ Existing violations remain visible but do not block. Example: +```text ARCH-DOMAIN-WPF: 7 existing findings Baseline reason: legacy ViewModel formatting leaked into Domain; tracked separately +``` 4. Drift since main @@ -186,9 +196,11 @@ Use existing "arch.drift" concepts: Example: +```text High: new dependency Sts.Domain.Orders -> System.Data.SqlClient Medium: Sts.UI.ViewModels Ce 21 -> 27 (+6, +29%) Info: removed dependency Sts.Legacy.Import -> DevExpress.Xpf +``` 5. Recommended reviewer focus @@ -196,12 +208,14 @@ This section is report-only and may be generated from deterministic evidence. Example: +```text Reviewer focus: 1. The PR introduces a new Domain -> SQL dependency. 2. The PR increases UI ViewModel outgoing dependencies by 29%. 3. No new cycles were introduced. +``` -Gate policy +## Gate policy Default gate behavior: @@ -213,6 +227,7 @@ LLM review text: never gates directly Example: +```json { "schema": "own.audit.arch.verdict/v1", "verdict": "fail", @@ -231,8 +246,9 @@ Example: } ] } +``` -SARIF export +## SARIF export OwnAudit should convert architecture findings to SARIF with: @@ -247,7 +263,7 @@ Only deterministic findings should become code scanning alerts by default. Drift items can be added as SARIF notes later, but they should start as markdown/report artifacts. Drift often describes component-level movement rather than a single source span. -AI explanation layer +## AI explanation layer The AI layer must be downstream of deterministic results. @@ -268,8 +284,9 @@ Forbidden AI tasks: - suppress architecture findings without explicit reason; - treat style inference as deterministic truth. -Example report +## Example report +```markdown # Architecture Review Verdict: FAIL @@ -297,11 +314,13 @@ Introduce an Application service or port and move the concrete Infrastructure de ## Baselined debt - 7 existing `ARCH-DOMAIN-WPF` findings remain unchanged. +``` -Dashboard integration +## Dashboard integration Extend existing dashboard artifacts with an Architecture tab: +```text Architecture - verdict - new blocking findings @@ -309,15 +328,17 @@ Architecture - drift count by risk - top risky components by Ce growth - cycles introduced/resolved +``` No new dashboard model should be invented if existing "viz/" history/report artifacts can be reused. -Integration with 007 +## Integration with 007 OwnAudit should emit machine-readable candidate tasks for 007. Example: +```json { "schema": "own.audit.arch.task-candidates/v1", "tasks": [ @@ -335,10 +356,11 @@ Example: } ] } +``` 007 remains responsible for executing/refactoring. OwnAudit only prepares evidence and gates. -Acceptance criteria +## Acceptance criteria MVP is accepted when: @@ -359,7 +381,7 @@ MVP is accepted when: - no baseline file; - malformed facts/findings input. -Risks +## Risks Risk: architecture review becomes generic lint soup @@ -373,15 +395,17 @@ Risk: AI summary overclaims Mitigation: every AI-generated claim must cite a deterministic finding, drift item, or metric. No evidence, no claim. -First implementation slice +## First implementation slice Implement: +```text arch/review_cli.py arch/report.py architecture-review.md renderer architecture-verdict.json SARIF export for deterministic arch findings tests +``` Do not implement LLM review in the first slice. First make the boring pipeline work. Then let the parrot narrate the evidence. \ No newline at end of file diff --git a/docs/sketch-based-evidence.md b/docs/sketch-based-evidence.md index fa8d135..2fee52d 100644 --- a/docs/sketch-based-evidence.md +++ b/docs/sketch-based-evidence.md @@ -3,6 +3,11 @@ - **Status:** draft. Imported from a design discussion and normalized; the pasted original suggested an Own.NET-style `P-NNN` path, but OwnAudit keeps flat topic docs under `docs/`. +- **Related:** `007 docs/sketch-aware-evidence.md` (the 007-side per-run + execution evidence this layer ingests) and + `Own.NET docs/proposals/P-033-probabilistic-data-structures.md` (the + in-process instrumentation whose `own.sketches.v1` exports this layer + anticipates). ## Summary @@ -21,10 +26,11 @@ The goal is to make OwnAudit better at answering questions such as: This proposal complements the existing direction where OwnAudit acts as an evidence orchestrator and audit/report/gate layer. Own.NET can produce facts. 007 can produce agent execution evidence. OwnAudit should aggregate, rank, compare, and explain. -Problem +## Problem Architecture audits often drown in raw findings: +```text 312 warnings 48 changed files 9 analyzer categories @@ -32,6 +38,7 @@ Architecture audits often drown in raw findings: 5 architecture rules 2 flaky checks 1 very tired developer +``` Raw counts are not enough. They do not explain trend, severity, repetition, blast radius, or whether the same issue keeps coming back wearing a fake mustache. @@ -45,15 +52,13 @@ OwnAudit needs compact evidence models that can survive repeated runs and answer - what should merely be reported; - what should be suppressed as known noise. -Proposed solution +## Proposed solution -Introduce a normalized evidence layer: - -"OwnAudit.Evidence.Sketches" +Introduce a normalized evidence layer, `OwnAudit.Evidence.Sketches`. It should support the following families of summaries. -1. Heavy hitters for repeated risk +### 1. Heavy hitters for repeated risk Use Top-K / Space-Saving style summaries for: @@ -67,6 +72,7 @@ Use Top-K / Space-Saving style summaries for: Example output: +```json { "schema": "ownaudit.heavy_hitters.v1", "kind": "rule_findings_by_file", @@ -78,8 +84,9 @@ Example output: } ] } +``` -2. Latency sketches for CI and analyzer timing +### 2. Latency sketches for CI and analyzer timing Use t-digest/DDSketch-like summaries for: @@ -91,14 +98,16 @@ Use t-digest/DDSketch-like summaries for: This lets OwnAudit report: +```text Analyzer OWN014: p50: 180 ms p95: 2.1 s p99: 5.8 s +``` This matters because “the analyzer is fast on average” is how slow tools sneak into CI and start eating morale. -3. Bitmap indexes for audit slicing +### 3. Bitmap indexes for audit slicing Use bitmap or roaring-style indexes to represent sets of internal ids: @@ -112,14 +121,16 @@ Use bitmap or roaring-style indexes to represent sets of internal ids: Then OwnAudit can compute: +```text GateFailures = ChangedFiles AND ArchitectureViolations AND NOT SuppressedFindings +``` This gives OwnAudit a compact internal query model for reports and gates. -4. SimHash / MinHash for finding duplicates and near-duplicates +### 4. SimHash / MinHash for finding duplicates and near-duplicates Use fingerprints for: @@ -127,11 +138,13 @@ Use fingerprints for: - repeated review comments; - similar stack traces; - near-duplicate architecture drift explanations; -- repeated agent mistakes from 007; +- repeated agent mistakes from 007 (the per-run fingerprints arrive via the + export defined in `007 docs/sketch-aware-evidence.md`); - copy-pasted code smells. The output should group related findings: +```json { "schema": "ownaudit.similar_findings.v1", "groupId": "simhash:8f31...", @@ -141,8 +154,9 @@ The output should group related findings: ], "reason": "similar diagnostic message and nearby code structure" } +``` -5. Optional HLL for unique cardinality trends +### 5. Optional HLL for unique cardinality trends Use HLL/HLL++ style sketches only where exact distinct counting is too expensive or noisy: @@ -154,12 +168,13 @@ Use HLL/HLL++ style sketches only where exact distinct counting is too expensive For most small repositories, exact sets are enough. HLL should not be added just to look sophisticated. That would be technical debt wearing a lab coat. -Architecture +## Architecture OwnAudit should treat sketches as evidence, not as final truth. Suggested flow: +```text raw inputs -> parsers -> normalized facts @@ -167,6 +182,7 @@ raw inputs -> audit evidence -> policy/gate -> report +``` Inputs may include: @@ -180,17 +196,20 @@ Inputs may include: Outputs should be stable JSON artifacts: +```text artifacts/ownaudit/evidence/ heavy-hitters.json latency-sketches.json bitmap-indexes.json similarity-groups.json trend-summary.json +``` -Policy integration +## Policy integration Sketch evidence should support policies such as: +```yaml rules: - id: audit.hotspot.file_changed_too_often when: @@ -206,10 +225,11 @@ rules: right: architecture_sensitive_files min_count: 5 severity: error +``` The goal is not to make OwnAudit mystical. The goal is to make repeated patterns visible and enforceable. -MVP +## MVP The MVP should include: @@ -226,7 +246,7 @@ The MVP should include: - “Chronic findings”; - “Large blast-radius changes”. -Phase 2 +## Phase 2 Add: @@ -237,7 +257,7 @@ Add: - ingestion of 007 run evidence; - ingestion of Own.NET runtime diagnostic exports. -Non-goals +## Non-goals OwnAudit should not: @@ -250,7 +270,7 @@ OwnAudit should not: Approximate evidence can raise suspicion. Exact evidence should convict. Tiny difference, huge legal and engineering consequences. -Acceptance criteria +## Acceptance criteria This proposal is successful when: @@ -262,7 +282,7 @@ This proposal is successful when: - exported artifacts are stable enough for 007 and Own.NET integration; - the system remains usable without external infrastructure. -Expected benefit +## Expected benefit OwnAudit becomes less of a static report printer and more of an evidence engine: