Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
6742bb1
draft(userspec): create user-spec for snark-policy-certificates
mnemonik-dev Jun 29, 2026
495bcb4
draft(userspec): create user-spec for universal-memory-system
mnemonik-dev Jul 26, 2026
2462a80
chore(userspec): validation round 1 — error handling, RUMBA baseline,…
mnemonik-dev Jul 26, 2026
3aee6a1
chore(userspec): approve user-spec for universal-memory-system
mnemonik-dev Jul 27, 2026
e940373
chore(userspec): add zero-admin-rights constraint for local mode
mnemonik-dev Jul 27, 2026
130dc32
draft(techspec): create tech-spec for universal-memory-system
mnemonik-dev Jul 27, 2026
6e5eeab
chore(techspec): validation round 1 — security decisions, mirages, co…
mnemonik-dev Jul 27, 2026
7ff4634
chore(techspec): resolve DEV-1 — BM25 default + optional Ollama setup…
mnemonik-dev Jul 27, 2026
9358298
chore(techspec): approve tech-spec for universal-memory-system
mnemonik-dev Jul 27, 2026
b43f7a6
draft(tasks): create 14 tasks from tech-spec for universal-memory-system
mnemonik-dev Jul 27, 2026
6d3fd3f
chore(tasks): validation round 1 — reality fixes (ThinkResult, http-t…
mnemonik-dev Jul 27, 2026
b755bfb
chore: review reports for task 1
mnemonik-dev Jul 27, 2026
605208e
docs: decisions.md entry for task 1
mnemonik-dev Jul 27, 2026
f4af23b
chore: complete wave 1 task 1 — update status and decisions
mnemonik-dev Jul 27, 2026
1672904
docs: decisions.md entry for task 2
mnemonik-dev Jul 27, 2026
f2a0da2
chore: complete wave 1 — T1+T2 done, start wave 2 T3
mnemonik-dev Jul 27, 2026
4d46726
chore: review reports for task 3
mnemonik-dev Jul 27, 2026
d61e8ef
chore(task-3): update decisions.md with Task 3 findings
mnemonik-dev Jul 27, 2026
295434b
chore: complete wave 2 T3, start wave 3 T4+T5+T6
mnemonik-dev Jul 27, 2026
9bcdc77
chore: review reports for task 4
mnemonik-dev Jul 27, 2026
c8ca04c
chore: decisions.md updated for task 4
mnemonik-dev Jul 27, 2026
32df094
chore: T4 done — memory_delete + 160 tests
mnemonik-dev Jul 27, 2026
d115b5a
chore: review reports for task 5
mnemonik-dev Jul 27, 2026
134a617
chore: review reports for task 6
mnemonik-dev Jul 27, 2026
591d06d
chore(decisions): task 5 — CloudAdapter + verify synthesize
mnemonik-dev Jul 27, 2026
2d9f3c3
chore: T5 done — CloudAdapter + 164 tests
mnemonik-dev Jul 27, 2026
f1d01e6
chore: task 6 decisions.md entry
mnemonik-dev Jul 27, 2026
55c226a
chore: T6 done (Mnemonik idempotency), start T7 (Docker+nginx)
mnemonik-dev Jul 27, 2026
d5926f8
chore: review reports for task 7
mnemonik-dev Jul 27, 2026
67e2ab0
chore(task-7): update decisions.md with Task 7 infra decisions
mnemonik-dev Jul 27, 2026
72356f7
chore: T7 done, start Wave 6 T8+T9
mnemonik-dev Jul 27, 2026
e767950
chore: review reports for task 9
mnemonik-dev Jul 27, 2026
c435ffa
chore(decisions): task 9 complete — RUMBA eval + client config docs
mnemonik-dev Jul 27, 2026
f6e80c8
chore: T9 done — RUMBA eval + client configs
mnemonik-dev Jul 27, 2026
4875a8a
chore: Wave 6 done (315 tests), start Wave 7 Audit T10+T11+T12
mnemonik-dev Jul 27, 2026
d4b3546
chore: T10 code audit done — 2 critical found
mnemonik-dev Jul 27, 2026
f41dcb6
chore: T12 test audit done — 315 tests, all criteria met
mnemonik-dev Jul 27, 2026
36b5058
chore: T11 security audit done — 0 critical, 3 medium found
mnemonik-dev Jul 27, 2026
9b8e74b
chore: audit fixes done (369 tests), start Wave 8 T13 QA
mnemonik-dev Jul 27, 2026
321f586
chore: T13 QA done — 32/38 pass, 1 blocking (memory_sign id vs content)
mnemonik-dev Jul 27, 2026
03197eb
chore: QA fixes done (376 tests), start T14 Deploy
mnemonik-dev Jul 27, 2026
31761ec
chore: T14 done — feature complete, all waves finished
mnemonik-dev Jul 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions work/snark-policy-certificates/logs/userspec/interview.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
metadata:
feature_name: snark-policy-certificates
work_type: feature
size: M
status: completed
started: "2026-06-29"
last_updated: "2026-06-29"
current_question_num: 0

phase1_feature_overview:
feature_name:
value: "snark-policy-certificates"
score: 100
status: done

work_type:
value: "feature"
score: 100
status: done

what_we_build:
value: |
End-to-end pipeline: policy predicate → SNARK proof → verifiable certificate.
Phase 1 (this spec): circom + snarkjs circuit for one concrete payment policy
(spend ≤ budget ∧ recipient ∈ allowlist ∧ tool_args satisfy schema).
New package packages/policy-certs/ in the monorepo.
Optional integration hook in withPaywall() middleware.
score: 90
gaps: []
status: done

why:
value: |
AI agents in the trustless economy need to prove compliance with declared policies
without the verifier re-executing their computation or trusting the operator.
SNARK certificates let a verifier check compliance in sublinear time — no re-execution,
no trusted intermediary. Direct application to Universal Paywall: middleware can verify
a proof that the agent's payment satisfies the policy rather than just verifying the tx.
score: 90
gaps: []
status: done

target_users:
value: |
- AI agents (provers): generate proof that their action satisfies a declared policy
- Developers (verifiers): verify agent compliance without trusting the agent
- Universal Paywall middleware: optional policy-proof extension to withPaywall()
score: 88
gaps: []
status: done

key_scenarios:
value: |
Happy path: agent executes action → generates (action, pub_inputs, proof) →
verifier calls verify(action, proof, vk) → bool true → access granted.
Non-compliant action: proof generation fails (witness doesn't satisfy constraints) →
agent cannot produce a valid certificate → verifier rejects.
Replay attack: pub_inputs includes action_hash = blake3(action_manifest) →
proof is bound to specific action, cannot be reused.
ZK variant: private witness (full tx context) hidden in proof;
verifier confirms compliance without seeing the witness.
score: 90
gaps: []
status: done

out_of_scope:
value: |
- zkVM general path (RISC Zero / SP1) — Phase 2, separate spec
- ZK private witness variant — Phase 3, separate spec
- On-chain proof verification (Solidity verifier contract) — post-MVP
- Arbitrary policy compilation (only the one concrete 3-clause policy in Phase 1)
- Production integration into withPaywall() — PoC hook only
score: 90
gaps: []
status: done

phase2_user_experience:
api_design:
value: |
packages/policy-certs/src/
prover.ts — generateCertificate(action, witness) → Certificate
verifier.ts — verifyCertificate(action, cert, vk) → boolean
Certificate type: { policyId, actionHash, pubInputs, vk, proof }
Policy: PaymentPolicy = { maxSpend: number, allowlist: string[], schemaFields: string[] }
score: 90
gaps: []
status: done

developer_config:
value: |
withPaywall(handler, { price, developerId, policyProof: true })
If policyProof: true — middleware also expects X-Policy-Proof header with base64(certificate).
Verifying key (vk) shipped with the package as a static asset.
score: 85
gaps: []
status: done

error_handling:
value: |
Invalid proof → HTTP 402 { error: "policy_violation", reason: "invalid_proof" }
Proof for wrong action (hash mismatch) → 402 { reason: "action_hash_mismatch" }
Missing proof when policyProof: true → 402 { reason: "proof_required" }
score: 88
gaps: []
status: done

phase3_integration:
proving_stack:
value: |
circom 2.x + snarkjs (Groth16). No new tooling beyond existing npm ecosystem.
Circuit: circuits/payment_policy_v1.circom
Gadgets: range check (spend ≤ budget), Merkle inclusion (recipient ∈ allowlist),
field equality constraints (schema check).
Trusted setup: Powers of Tau ceremony (existing ptau files from hermez/snarkjs).
score: 90
gaps: []
status: done

deploy_approach:
value: |
No on-chain deployment needed for Phase 1.
npm package: @universal-paywall/policy-certs
Verifying key shipped as static JSON asset in the package.
Tests run locally (no external RPC needed).
score: 90
gaps: []
status: done

manual_user_actions:
value: |
Developer: install @universal-paywall/policy-certs, use pre-shipped vk.
Agent (prover): have the witness (spend amount, recipient, args) ready before calling generateCertificate().
No on-chain registration or USDC balance needed for policy-certs package itself.
score: 90
gaps: []
status: done

mnemonik_tieIn:
value: |
pub_inputs.action_hash = blake3(action_manifest)
Proof is anchored to a specific action via its blake3 hash.
Cannot be replayed on a different action.
score: 88
gaps: []
status: done

conversation_history: []

notes:
- "Phase 1 only: circom + snarkjs, one concrete 3-clause policy"
- "Based on arxiv:2606.23768 — polynomial semantics: equality=(t-t')², AND=sum, OR=product"
- "Certificate format: { policyId, actionHash, pubInputs, vk, proof }"
- "Phase 2 (zkVM) and Phase 3 (ZK private witness) are separate future specs"
- "Optional middleware hook: withPaywall({ policyProof: true })"
177 changes: 177 additions & 0 deletions work/snark-policy-certificates/user-spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
---
feature: snark-policy-certificates
status: approved
created: 2026-06-29
---

# SNARK Policy Certificates для AI-агентов

## Что делаем

Реализуем end-to-end pipeline: декларативная политика → SNARK-доказательство → верифицируемый сертификат. Агент прикладывает к своему действию криптографическое доказательство того, что оно соответствует объявленной политике — без повторного выполнения и без доверия оператору.

**Scope Phase 1 (этот спек):** новый пакет `packages/policy-certs/` + опциональный хук в `withPaywall()`.

**Конкретная политика (Phase 1):**
```
spend ≤ budget_B ∧ recipient ∈ allowlist ∧ tool_args satisfy schema_S
```

**Стек:** circom 2.x + snarkjs (Groth16). Никакой новой инфраструктуры — только npm.

**Три компонента:**

1. **`circuits/payment_policy_v1.circom`** — арифметическая схема, кодирующая политику через полиномиальные ограничения (по методу из arxiv:2606.23768):
- `spend ≤ B` → range check гаджет
- `recipient ∈ allowlist` → Merkle inclusion proof
- `schema check` → field equality constraints

2. **`packages/policy-certs/`** — TypeScript npm-пакет:
- `generateCertificate(action, witness) → Certificate` — prover
- `verifyCertificate(action, cert, vk) → boolean` — verifier
- Verifying key (`vk`) поставляется статическим ассетом в пакете

3. **Хук в middleware** — опциональное расширение `withPaywall({ policyProof: true })`: middleware дополнительно требует заголовок `X-Policy-Proof` и верифицирует сертификат наряду с x402 платежом.

## Зачем

AI-агенты в trustless-экономике должны доказывать соответствие политике без того, чтобы верификатор повторно выполнял вычисление или доверял оператору. SNARK-сертификат проверяется за сублинейное время — независимо от стоимости исходного вычисления.

Прямое применение в Universal Paywall: разработчик получает **портативное, машинопроверяемое доказательство** того, что агент действительно соблюдал политику платежа — а не просто прошёл проверку транзакции.

## Пользователи

- **AI-агент (prover):** генерирует `Certificate` перед запросом; прикладывает к `X-Policy-Proof` заголовку
- **Разработчик (verifier):** вызывает `verifyCertificate()` или включает `policyProof: true` в `withPaywall()`
- **Universal Paywall middleware:** опциональная верификация сертификата поверх x402

## Флоу

### Happy path (агент с сертификатом)

```
1. Агент → формирует witness:
{ spend: 10000, recipient: "0xABC...", args: { model: "gpt-4" } }

2. Агент → generateCertificate(action, witness)
→ Circuit: проверяет spend ≤ budget, recipient в Merkle дереве, args валидны
→ Certificate {
policyId: "payment_policy_v1",
actionHash: blake3(action_manifest), // привязка к конкретному действию
pubInputs: { merkleRoot, schemaHash, maxSpend },
vk: "...",
proof: "0x..."
}

3. Агент → POST /api/resource
X-Payment: base64(x402_payment)
X-Policy-Proof: base64(certificate)

4. Middleware → verifyCertificate(action, cert, vk) → true
Middleware → верифицирует x402 транзакцию
→ HTTP 200 + ресурс

5. Агент → нарушает политику (spend > budget)
→ generateCertificate() не может найти валидный witness
→ Certificate не создаётся → запрос не отправляется
```

### Верификация без повторного выполнения

```
verifier:
1. Проверяет actionHash == blake3(action) — proof привязан к этому действию
2. Проверяет proof по vk и pubInputs — sublinear time, ~constant
3. Не знает witness (spend, recipient, args) — только то, что они удовлетворяют схеме
```

### Middleware хук

```typescript
withPaywall(handler, {
price: '0.01',
developerId: '0xDev...',
policyProof: true // включает требование X-Policy-Proof заголовка
})
```

## Типы и API

```typescript
// packages/policy-certs/src/types.ts
interface Certificate {
policyId: string;
actionHash: string; // blake3(action_manifest)
pubInputs: {
merkleRoot: string; // root allowlist дерева
schemaHash: string; // hash объявленной схемы
maxSpend: number; // верхняя граница spend
};
proof: string; // Groth16 proof (base64)
}

interface PaymentPolicy {
maxSpend: number;
allowlist: string[]; // hex адреса
schemaFields: string[]; // обязательные поля args
}

// prover
function generateCertificate(
action: AgentAction,
witness: PolicyWitness,
policy: PaymentPolicy
): Promise<Certificate>

// verifier
function verifyCertificate(
action: AgentAction,
cert: Certificate,
vk?: object // опционально; по умолчанию — bundled vk
): Promise<boolean>
```

## Критерии приёмки

### Circuit & proving

- [ ] `circuits/payment_policy_v1.circom` компилируется без ошибок (`circom --r1cs --wasm`)
- [ ] Trusted setup завершён: `ptau` файл + `zkey` файл сгенерированы и закоммичены в репо
- [ ] `generateCertificate()` возвращает валидный `Certificate` для корректного witness (spend ≤ budget, recipient в allowlist, args содержат schemaFields)
- [ ] `generateCertificate()` бросает исключение для некорректного witness (невозможно построить witness → нет доказательства)

### Верификатор

- [ ] `verifyCertificate(action, cert)` возвращает `true` для всех корректных сертификатов
- [ ] `verifyCertificate()` возвращает `false` при spend > budget (crafted non-compliant proof)
- [ ] `verifyCertificate()` возвращает `false` при recipient не из allowlist
- [ ] `verifyCertificate()` возвращает `false` при нарушении schema (отсутствует обязательное поле)
- [ ] `verifyCertificate()` возвращает `false` при `actionHash` mismatch (proof из другого действия)
- [ ] Время верификации ≤ 100ms и ~constant (не зависит от размера witness или allowlist)

### Привязка к действию (anti-replay)

- [ ] `cert.actionHash = blake3(action_manifest)` — вычисляется детерминированно
- [ ] Подстановка другого действия при той же proof → `false` (hash не совпадает)

### Middleware интеграция

- [ ] `withPaywall(handler, { policyProof: true })` при отсутствии `X-Policy-Proof` → HTTP 402 `{ reason: "proof_required" }`
- [ ] Невалидная proof → HTTP 402 `{ error: "policy_violation", reason: "invalid_proof" }`
- [ ] Hash mismatch → HTTP 402 `{ reason: "action_hash_mismatch" }`
- [ ] Валидная proof + валидная x402 → HTTP 200

### Пакет

- [ ] `@universal-paywall/policy-certs` публикуется на npm
- [ ] Bundled `vk` поставляется в пакете; кастомный `vk` принимается опционально
- [ ] README: инструкция "запустить prover → получить сертификат → верифицировать"

## Что не входит

- **zkVM general path** (RISC Zero / SP1) — Phase 2, отдельный спек
- **ZK private witness variant** — Phase 3, отдельный спек
- **On-chain верификатор** (Solidity contract для proof verification) — post-MVP
- **Произвольная компиляция политик** — только конкретная 3-clause payment policy
- **Продакшн интеграция в middleware** — PoC хук, не production-ready
- **Поддержка других proof систем** (PLONK, STARKs) — только Groth16 в Phase 1
Loading