Rules & Standards

Development standards, testing protocols, lessons learned.

Overview

Rules & Standards Overview

Development standards, testing protocols, and lessons learned.

Owner: John Last Verified: 2026-02-17

Contents

To be populated from ~/system/rules/

Development Standards

Development Standards

Workflow — PARALLEL TESTER

Testing — ZAKON (CEO directive 2026-02-13)

→ FULL STANDARD: ~/system/rules/testing.md

5 obaveznih nivoa za SVAKI projekat:

  1. Unit — svaka funkcija izolovano (80% coverage min)
  2. Integration — API + DB (svaki endpoint HTTP testiran)
  3. E2E — Playwright full user flows
  4. Regression — test za svaki fixani bug
  5. Performance — latency, load, concurrent

5 iteracija prije shippinga. Nema izuzetaka. Pipeline NE NAPREDUJE iz Testing faze bez svih 5 nivoa.

Automated Testing Tools

Test Protocol — OBAVEZNO

Prije nego kažeš "testirano":

  1. Pokreni npm test za code promjene
  2. Koristi Playwright MCP za vizuelne/UI promjene
  3. Pokreni smoke-test.js za infrastrukturne promjene
  4. Provjeri coverage (80%+ lines)
  5. Ako nema test → napiši ga PRVI, pa onda implementiraj

Spec Indexing Rule

After creating any spec, analysis, or research document, OBAVEZNO post to HiveMind:

node ~/system/agents/hivemind/hivemind.js post <agent> analysis "Created: <path> — <summary>"

This ensures all knowledge is discoverable.

Approval Gates — OBAVEZNO

Research → Spec → APPROVAL → Build. Nema preskakanja.

Faza Ko radi Ko odobrava
Research John/agenti Auto (slobodno)
Spec/Proposal draft John/agenti Auto (slobodno)
BUILD John/agenti CEO (Alem) MORA odobriti spec

Code Standards

Git

Testing Standards

Last Verified: 2026-02-17 | Owner: John

Testing Standard — GLOBAL (All Projects)

Authority: CEO directive (2026-02-13). Non-negotiable. Scope: Every project under ~/projects/, ~/ALAI/products/, and all client work.


ZAKON: No Ship Without Full Test Coverage

Nijedan projekat se NE DEPLOYA bez svih 5 nivoa testiranja. Svaki nivo mora proći MINIMUM 5 iteracija prije shipping-a.

Iteracija = full test run → fix failures → re-run. Prvih 5 iteracija otkrivaju 95% bugova.


5 Obaveznih Nivoa Testiranja

Nivo 1 — Unit Tests

Šta: Svaka funkcija, helper, utility, validator testiran izolovano. Coverage: Minimum 80% line coverage. Alati: Vitest (JS/TS), pytest (Python), Jest (ako već u projektu). Pravilo: Svaki novi fajl u src/lib/, src/utils/, src/helpers/ MORA imati odgovarajući test fajl.

src/lib/auth.ts      → tests/unit/auth.test.ts
src/lib/utils.ts     → tests/unit/utils.test.ts
src/lib/middleware.ts → tests/unit/middleware.test.ts

Nivo 2 — Integration Tests

Šta: Moduli u kombinaciji — DB + API, Auth + Session, Payment + Rate. Scope: Svaki API endpoint testiran sa stvarnim DB-om (in-memory SQLite / test DB). Pravilo: Svaki API route MORA imati integration test koji:

src/app/api/auth/register/route.ts → tests/integration/auth-register.test.ts
src/app/api/auth/login/route.ts    → tests/integration/auth-login.test.ts
src/app/api/transactions/*/route.ts → tests/integration/transactions.test.ts

Nivo 3 — E2E Tests (End-to-End)

Šta: Cijeli user flow od UI do DB i nazad. Alati: Playwright (primary), Cypress (alternativa). Scope: Svaki user-facing flow MORA imati e2e test:

Pravilo: E2E testovi se pokreću protiv running dev server.

tests/e2e/registration.spec.ts
tests/e2e/login.spec.ts
tests/e2e/remittance.spec.ts
tests/e2e/navigation.spec.ts

Nivo 4 — Regression Tests

Šta: Testovi za SVAKI bug koji je pronađen i fixan. Pravilo: Kad se fix napravi, PRVO se napiše test koji reproducira bug, PA ONDA fix. Format: Test name mora sadržavati bug referencu.

it("BUG-001: rateLimit must be awaited to prevent bypass", async () => { ... });
it("BUG-002: validation errors must show specific details, not generic message", async () => { ... });

Direktorij: tests/regression/

Nivo 5 — Performance Tests (Ytelsestest)

Šta: Baseline performance za kritične operacije. Alati: k6, Artillery, ili custom Vitest benchmarks. Scope:

tests/performance/api-latency.test.ts
tests/performance/concurrent-sessions.test.ts
tests/performance/page-load.test.ts

Test Execution Protocol

Prije svakog deploya/shippinga:

Iteracija 1: npm test                    → fix failures → commit
Iteracija 2: npm test                    → fix failures → commit
Iteracija 3: npm test                    → fix failures → commit
Iteracija 4: npm test                    → fix new edge cases → commit
Iteracija 5: npm test (FINAL)            → ALL GREEN → ready to ship

Svaka iteracija MORA biti logirana:

npm test 2>&1 | tee tests/logs/iteration-N.log

Test Coverage Report

Svaki projekat MORA generisati coverage report:

npx vitest run --coverage

Minimum pragovi:


Pipeline Gate — Testing Phase

Pipeline-controller.js Testing phase gate check:

  1. npm test prolazi (exit code 0)
  2. ✅ Postoje test fajlovi za svih 5 nivoa
  3. ✅ Coverage >= 80%
  4. ✅ Minimum 5 iteracija logirane
  5. ✅ Zero KNOWN failures (sve što je nađeno je fixano)

Bez svih 5 — pipeline NE NAPREDUJE iz Testing faze.


Mandatory: Input Rejection Tests (Stupid User Category)

ZAKON: Svaki form input MORA imati testove koji provjeravaju da loš input bude ODBIJEN — ne samo da app "ne crashuje".

Problem koji je ovo pravilo izazvao: CEO je ručno ukucao "12345" u name polje i prošlo je. 765 linija chaos testova je provjeravalo "no crash" ali NIJEDAN test nije provjerio da forma ODBIJA loš input. 3-4 iteracije e2e testiranja — niko nije primijetio.

Dva tipa test assertions (OBA obavezna):

  1. Resilience assertion: "App se ne ruši" → expect(pageAlive).toBe(1) — OVO NIJE DOVOLJNO
  2. Rejection assertion: "App ODBIJA input" → expect(errorVisible).toBe(true) — OVO JE OBAVEZNO

Obavezni "stupid user" test inputi za SVAKO polje:

Polje tipa Test input Očekivano
Ime/prezime "12345" (samo brojevi) ODBIJENO — greška vidljiva
Ime/prezime "!@#$%" (samo specijalni znakovi) ODBIJENO — greška vidljiva
Ime/prezime " " (samo razmaci) ODBIJENO — greška vidljiva
Email "notanemail" (bez @) ODBIJENO — greška vidljiva
Email "12345" (brojevi) ODBIJENO — greška vidljiva
Telefon "abcdef" (slova umjesto brojeva) ODBIJENO — greška vidljiva
Lozinka "12345678" (samo brojevi, bez slova) ODBIJENO — greška vidljiva
Datum "9999-99-99" (nemoguć datum) ODBIJENO — greška vidljiva
Iznos "-100" (negativan) ODBIJENO — greška vidljiva
Iznos "abc" (tekst) ODBIJENO — greška vidljiva
Bilo koje "" (prazno) ODBIJENO — greška vidljiva

Pravilo za e2e chaos testove:

// ❌ NEDOVOLJNO — samo provjera da ne crashuje
const pageAlive = await page.locator("body").count();
expect(pageAlive).toBe(1);

// ✅ OBAVEZNO — provjera da je input ODBIJEN
const errorVisible = await page.locator('[class*="text-"][class*="EF4444"], [role="alert"]')
  .isVisible({ timeout: 3000 }).catch(() => false);
expect(errorVisible).toBe(true);
// I provjera da NIJE prošao na sljedeći korak
const nextStepVisible = await page.locator("text=next step indicator")
  .isVisible({ timeout: 1000 }).catch(() => false);
expect(nextStepVisible).toBe(false);

Princip:

Ako imaš CHAOS_STRINGS definisane u testu — svaki string MORA biti testiran na SVAKOM polju. Inače, zašto postoji?


Project Test Structure (Template)

Svaki projekat MORA imati ovu strukturu:

tests/
├── unit/              ← Izolovani function testovi
├── integration/       ← API + DB testovi
├── e2e/               ← Full user flow testovi (Playwright)
├── regression/        ← Bug reproduction testovi
├── performance/       ← Latency, load, concurrent testovi
├── logs/              ← Iteration logs (iteration-1.log ... iteration-5.log)
└── coverage/          ← Coverage reports

Enforcement

Nivoi enforcement-a:

  1. Pipeline gate — pipeline-controller.js blokira advance bez test evidence
  2. Pre-deploy hook — blokira deploy ako npm test ne prolazi
  3. Code review — reviewer MORA verificirati test coverage za svaki PR
  4. MC task — testing task ne može biti DONE bez svih 5 nivoa

Consequences:


CEO Quote (2026-02-13):

"Hocu da imamo testove za sve, svaki projekt. Ako nesto nije testirano — bicu pravo ljut. Unit test, integration test, e2e test, regression test, performance test. Ne ship app ako nije testirano sve i to 5 iteracija."

Ovo je zakon. Nema izuzetaka. Nema kompromisa.

Agent Anti-Hallucination Rules

Last Verified: 2026-02-17 | Owner: John

Agent Anti-Hallucination Rules

Source: FjordConsulting simulation test (2026-02-06) Findings: 75/100 accuracy — 25% hallucinated details


Rule 0: VERIFY BEFORE CLAIMING (NAJVAŽNIJE PRAVILO)

NIKAD ne tvrdi da nešto postoji ili ne postoji bez da PROVJERIS.

Prije nego kažeš "fajl ne postoji" → pokreni ls ili cat. Prije nego kažeš "tool ne radi" → pokreni ga. Prije nego kažeš "nema komunikacije" → provjeri kanal.

# ISPRAVNO: provjeri pa tvrdi
ls ~/path/to/file.txt          # postoji? → ONDA reci "postoji"
cat ~/path/to/config.json      # čitljiv? → ONDA reci šta piše

# POGREŠNO: tvrdi bez provjere
"Taj fajl ne postoji"          # ← KAKO ZNAŠ? Jesi li pokrenuo ls?
"Sistem nije konfigurisan"     # ← KAKO ZNAŠ? Jesi li provjerio?

Primjer greške (2026-02-06): Edita tvrdila da 5 fajlova "ne postoji nigdje u Dropboxu" — ls na istoj mašini je pokazao da SVI postoje. Nije provjerila filesystem prije nego je donijela zaključak.

Pravilo: Ako nisi pokrenuo komandu koja DOKAZUJE tvoju tvrdnju — ne tvrdi.


Rule 1: TBD > Hallucination

If you don't know a specific value, write TODO: or TBD instead of inventing it.

NEVER invent:

ALWAYS mark uncertainty:

// TODO: verify — this API may not exist in iOS 17
// TBD: Norwegian developer hourly rate (estimate 800-1500 NOK/h, needs verification)
// PLACEHOLDER: replace with real bcrypt hash before deployment

Rule 2: Cross-File Consistency

Before writing code that references another file, READ that file first.

Mandatory checks:

Anti-pattern (caught in test):

// websocket.ts writes status='online'
// BUT schema.sql only allows: 'active', 'away', 'offline', 'deactivated'
// Result: runtime crash

Rule 3: No Phantom Dependencies

Every dependency in package.json / Package.swift MUST be:

  1. Actually imported in at least one source file
  2. Actually used (not just imported)

If you add a dependency for future use, comment it:

// "ioredis": "^5.4.2"  // Phase 2: session caching — NOT YET IMPLEMENTED

Rule 4: Health Checks Must Be Real

Never hardcode health check responses. Always verify:

// BAD (caught in test):
return { database: 'up', redis: 'up' }; // lies

// GOOD:
const dbOk = await pool.query('SELECT 1').then(() => true).catch(() => false);
return { database: dbOk ? 'up' : 'down' };

Rule 5: Spec-Implementation Parity

If you write a specification (API spec, design doc), track implementation status:

## Endpoints

| Endpoint | Status |
|----------|--------|
| POST /auth/login | IMPLEMENTED |
| POST /auth/register | IMPLEMENTED |
| GET /groups | NOT YET IMPLEMENTED |
| POST /push/register | PHASE 2 |

Never present unimplemented features as done.


Rule 6: Budget and Timeline Reality Checks

When estimating costs or timelines:


Rule 7: Placeholder Code Must Scream

Mock implementations must be OBVIOUSLY fake:

// BAD (caught in test): looks like real encryption but is base64
func encrypt(_ data: Data) -> Data {
    return data.base64EncodedData() // This is NOT encryption
}

// GOOD: impossible to miss
func encrypt(_ data: Data) -> Data {
    fatalError("PLACEHOLDER: Real encryption not yet implemented. Integrate libsignal-client-swift before shipping.")
}

Rule 9: Config/Schema Changes Require Docs (dodano 2026-02-12)

ROOT CAUSE: John mijenjao hooks format u settings.json bez čitanja docs. Haiku validator potvrdio pogrešan format.

PRAVILA:

  1. NIKAD mijenjaj config format (hooks, settings, schema) bez čitanja oficijelne dokumentacije
  2. WebFetch/WebSearch OBAVEZAN za: hooks format, API schema, config migration, breaking changes
  3. Validator agent NIJE rubber stamp — mora imati docs URL ili spec file kao input
  4. Anti-pattern: "Provjeri da sam dobro uradio" bez davanja izvora istine agentu

Primjer greške (2026-02-12):

// POGREŠNO (John napisao):
"matcher": {}        // objekt — Claude Code expects string

// ISPRAVNO (iz docs):
"matcher": "*"       // regex string — matcha sve toolove
"matcher": "Bash"    // regex string — matcha samo Bash

Workflow za config promjene:

1. WebFetch oficijelnu docs stranicu
2. Pročitaj schema/format
3. Tek onda mijenjaj fajl
4. Validator dobije docs URL kao input za nezavisnu provjeru

Hallucination Examples from Test

What agent wrote Reality Root cause
"Sesame Algorithm" Does not exist Invented name for concept
contentSecureLevel iOS 17 API Does not exist Invented API
bcrypt hash $2b$12$vJ4... Invalid hash Generated random string
150 NOK/h developer rate Norway is 800-1500 NOK/h No market context
Redis "up" in health check Redis never connected Hardcoded response
status = 'online' DB enum has no 'online' Didn't read schema
ReportCo AS "WON client" Demo data, firma ne postoji Test data bez is_test flag
FitLife AS "50K deal" Demo data, firma ne postoji Lead→WON bez ugovora
FjordConsulting "200K proposal" Kontakt ne postoji u contacts.db Phantom pipeline entry
Revenue plan 774K Q1 Realno 544K (230K phantom) Auto-generated bez review

Rule 8: Demo/Test Data Protection (dodano 2026-02-11)

ROOT CAUSE: John kreirao demo podatke (FitLife, ReportCo) 2026-02-04 za AIOS testing. Bez oznake. Propagirali kroz leads→contacts→invoices→revenue plan kao REALNI klijenti 7 dana.

PRAVILA:

  1. NIKAD kreiraj test/demo podatke u production bazama bez jasne oznake
  2. Flag marking: Svaki test zapis MORA imati polje is_test=true ili ekvivalent
  3. Name prefix: Test firme MORAJU imati prefix TEST: ili DEMO: u imenu
  4. Email: Test kontakti koriste @test.local domenu, NIKAD realne domene
  5. Human gate: Lead koji ide u WON stage MORA imati:
    • Potpisan ugovor, ILI
    • Eksplicitna potvrda od Alema
  6. Revenue plan: NIKAD auto-generate i publish — uvijek draft + human review
  7. Invoice kreacija: Zahtijeva referencu na potpisan ugovor ili Alem approval
  8. Contacts baza: Novi kontakt MORA imati verificiran email i dokumentovan source
  9. Cross-check: Prije uključivanja firme u revenue plan, verificiraj da postoji u contacts.db SA realnom komunikacijom

Ako kreiraš test data za demo:

# ISPRAVNO:
node contacts.js add "TEST: DemoFirma" "test@test.local" --notes "DEMO DATA for testing only"

# POGREŠNO:
node contacts.js add "ReportCo AS" "cfo@reportco.no"  # izgleda realno, propagira

Lessons Learned

Lessons Learned — Accumulated Knowledge


2026-04-04: P0 Endpoint Hallucination — LightRAG /upload vs /documents/text

Problem: Builder agent hallucinated /upload endpoint for LightRAG when correct endpoint is /documents/text. Error passed through entire system without detection — code written, deployed, and failed in production demo.

Root Cause Analysis:

  1. Agent assumed endpoint name based on "sounds right" pattern matching
  2. No endpoint verification hook in place
  3. qa-19 quality gate lacked endpoint testing
  4. Tool-registry.db was inactive — no nightly endpoint audit

Impact: Demo-blocking bug in LumisCare, revealed systemic vulnerability to API hallucinations.

Solution (3-Part):

  1. P1: Anti-Hallucination Hook — hallucination-detector.py now has KNOWN_API_ENDPOINTS dict + check_phantom_endpoints()

    • Blocks Write/Edit with known invalid endpoints
    • Examples: /upload → use /documents/text
  2. P2: Nightly Audit Daemon — tool-sync-audit.js scans all tools for stale endpoints

    • Tests each HTTP endpoint via HEAD (timeout 3s)
    • Logs to health-events.db
    • Alerts Slack if stale endpoints found
    • LaunchAgent: com.john.tool-sync-audit (03:00 daily)
  3. P3: Quality Gate Check — qa-19.js now includes Check #20: Endpoint Verification

    • Parses GOTCHA for HTTP endpoints
    • Tests each before task completion
    • Blocks mc.js done if endpoints fail

Pravilo (Rule 10 — agent-anti-hallucination.md):

Before using any HTTP endpoint:
1. curl -s http://localhost:PORT/health
2. Check OpenAPI spec: curl -s http://localhost:PORT/openapi.json
3. Verify in KNOWN_API_ENDPOINTS (hallucination-detector.py)
NEVER assume endpoint exists because it "sounds right"

Prevention for future:

Lekcija: API hallucinations are deterministic errors — agent + endpoint name that sounds right = confident wrong code. Solution is three-layer: hook prevention + nightly audit + quality gate. Builder agent can't self-verify, so verification must be external + automated.


2026-02-12: NIKAD BUILD od self-generated spec-a bez CEO approval

Problem: John je na DROP projektu sam napravio UI/UX spec (competitor analysis, 3 dizajn opcije), pa odmah krenuo graditi full app — 97 fajlova, 24K LOC. Bez ijednog Alemovog odobrenja na spec. Rezultat: kod zaglavljen na wrong git branch, prazan drop-app/ dir, wasted tokens, Alem ne zna šta je napravljeno.

Root Cause: Nedostajao approval gate između faze Research/Spec i faze Build. John je tretirao self-generated spec kao odobren spec.

Pravilo (ZAKON):

  1. Research → OK, radi slobodno
  2. Spec/Proposal draft → OK, radi slobodno
  3. BUILD → STOP. Explicit CEO odobrenje na spec PRIJE prvog LOC.
  4. Ako CEO nije pregledao spec, spec NE POSTOJI kao basis za build.
  5. Self-generated spec ≠ Approved spec. NIKAD.

Recovery: fontelepay/ auto-backup branch merged to master. Kod recovered.

Fix nivo: Rule (ovaj fajl) + HiveMind (#76) + MEMORY.md. Idealan fix bi bio hook koji blokira build bez approved spec — ali approval gate je human decision, teško za hook.

Lekcija: AI može napraviti spec, ali samo čovjek može ODOBRITI spec. Bez odobrenja, build je gubitak resursa.


2026-02-08: Next Steps MORAJU postati MC taskovi

Problem: Session log imao "Next Steps" ali nikad nisam kreirao MC taskove za njih. Rezultat: 2 akcije (Edita MC onboarding + Mini SSH update) izgubljene jer niko ne čita session log automatski.

Root Cause: Session-save workflow zapisuje next steps u markdown ali nema korak koji ih pretvara u MC taskove.

Fix: PRAVILO — prije kraja sesije, svaki "Next Step" iz session state-a MORA postati mc.js add task. Session state je za kontekst, MC je za akciju. Ako nije u MC-u, ne postoji.

Lekcija: Passive documentation (markdown) ≠ active tracking (MC). Ako nešto treba biti urađeno, mora biti task.


2026-02-04: Task Management + Problem Solving Enforcement

Problem: Skip-ovao sam task tracking i problem solving proces, delegirao agenta bez proper requirements gathering, agent riješio pogrešan problem.

Root Cause Analysis:

  1. Nisam dodao task u tasks.db
  2. Nisam pratio problem-solving.md proces (koraci 1-6)
  3. Spawn-ovao agenta sa PRVIM rješenjem (email infrastructure umjesto client communication system)
  4. Agent radio PLAN fazu solo - trebalo John + client
  5. Nisam završio Next Steps iz SESSION-STATE

Impact: Alem dobio pogrešno rješenje, izgubljeno vrijeme, "veći problem" kreiran

Solution Implemented:

  1. ✅ Kreiran ~/system/tools/start-task.sh - mandatory validation script
  2. ✅ Update MEMORY.md sa CORE PROTOCOL sekcijom
  3. ✅ Dokumentovano u lessons-learned.md (ovdje)
  4. ✅ boot.sh reminder dodan

Validation:

Prevention:

Key Mantras:


2026-02-12: Sub-agent Validator Hallucination — "PASS" na pogrešan format

Problem: John mijenjao Claude Code hooks format u .claude/settings.json. Napisao matcher: {} (objekt) umjesto matcher: "*" (regex string). Pozvao haiku sub-agenta kao "testera" — agent rekao PASS. Alem pokrenuo Claude, dobio isti error.

Root Cause (2 nivoa):

  1. John nije pročitao dokumentaciju prije izmjene config formata. Pretpostavio format iz error poruke.
  2. Sub-agent validirao John-ov output umjesto da nezavisno provjeri spec. Haiku agent nema znanje o novom hooks formatu — hallucinate-ovao da je ispravan.

Impact: Alem dobio error 2x, izgubljeno povjerenje u "tester" agente.

Fix:

  1. Pravilo: NIKAD mijenjaj config/schema format bez čitanja oficijelne dokumentacije (WebFetch/WebSearch)
  2. Pravilo: Validator/tester sub-agent MORA imati instrukciju da NEZAVISNO provjeri source of truth (docs URL, spec file), NE da validira caller-ov rad
  3. Anti-pattern: "Provjeri da sam dobro uradio" ≠ testiranje. Testiranje = nezavisna verifikacija protiv spec-a.

Key Mantras:


2026-02-16: UI promjene bez prethodne provjere dizajn referenci (Drop #979)

Problem: Landing page imao "Virtuelt kort" feature koji je kontradiktoran Drop PSD2 pass-through modelu (no cards, no wallet). Kad sam to fixovao u "Kontooversikt", napravio sam promjenu BEZ prethodne provjere Make exporta. Alem morao eksplicitno reći: "Jeli li validirao imas vizuelno u MAKE pa tako treba da je i UI."

Root Cause: Dva propusta:

  1. Niko nije validirao original — "Virtuelt kort" je ušao u kod bez provjere protiv Make dizajna koji NEMA Cards screen
  2. Fix bez referenci — Ja sam fixovao sadržaj iz glave umjesto da prvo pročitam Make export i repliciram TAČNO šta je tamo

Impact: Srećom output je bio tačan (Make JESTE imao BankAccounts, ne Cards), ali proces je bio pogrešan. Da je Make imao nešto drugačije, ja bih opet deployao pogrešno.

Fix:

  1. Drop CLAUDE.md — Dodan "UI Source of Truth" sekcija sa Make export putanjom i pravilom "BEFORE any UI change, read Make component"
  2. visual-verification.md — Dodan korak 0: "REFERENCA PRIJE KODA" — zabranjeno mijenjati UI pa tek onda provjeriti dizajn
  3. HiveMind — Logirano za budući kontekst

Lekcija: Redoslijed je uvijek: dizajn → kod → verifikacija. Nikad: kod → (možda) verifikacija.


2026-02-16: UVIJEK koristi official brand template za firmine dokumente

Problem: Kreirao PDF za SpareBank 1 pitch i poslao Alemu. Prvo poslao markdown umjesto PDF-a. Onda napravio PDF sa pogrešnim bojama (#0B6E35 Drop green umjesto #00E5A0 ALAI green), pogrešnim cover dizajnom (light umjesto dark navy), bez korištenja official template-a. Alem: "Gdje si nasao ovaj template u ALAI? TO nije pravi."

Root Cause: Nema pravilo koje forsira provjeru brand guidelines i template-a PRIJE kreiranja bilo kakvog firmino-brendiranog dokumenta. John je improvizirao dizajn umjesto da pročita brand-guidelines.md i pogleda template slike.

Pravilo (ZAKON):

  1. SVAKI dokument sa ALAI branding mora PRVO pročitati ~/ALAI/brand/brand-guidelines.md
  2. SVAKI dokument mora koristiti official boje: Primary Green #00E5A0, Dark Navy #0F172A
  3. SVAKI PDF mora vizualno odgovarati template-ima iz ~/ALAI/brand/templates/ (presentation.png za prezentacije, letter.png za pisma, invoice.png za fakture)
  4. NIKAD ne improvizuj brand — ako ne znaš kako izgleda, PROČITAJ template prije nego počneš
  5. GOTCHA C (Context) sekcija za branded dokumente MORA sadržavati "brand-guidelines.md read" i navesti tačne boje

Brand Quick Reference:

Fix nivo: Rule (ovaj fajl) + HiveMind + MEMORY.md

Lekcija: Branded dokument bez brand guidelines = amaterski. Uvijek čitaj guidelines PRIJE dizajna, nikad poslije.


2026-02-16: Agent .md hooks: sekcija OVERRIDUJE globalne hookove

Problem: Builder agent za task #1039 napisao kod bez GOTCHA checkliste. Validator potvrdio: /tmp/gotcha-task-1039.md — NOT FOUND. gotcha-enforcer.py nikad nije blokirao jer se nikad nije pokrenuo.

Root Cause: Agent .md fajlovi (builder.md, frontend-builder.md, backend-builder.md, design-builder.md) imali hooks: sekciju u YAML frontmatteru. Kad agent definira hooks — to ZAMIJENI globalne hookove iz settings.json, NE merge-uje ih. Rezultat: SVE PreToolUse enforcement hookove (gotcha-enforcer, plan-enforcer, security-guard, hallucination-detector, pii-scanner) su zaobiđeni.

Impact: 4 agenta radila bez ikakvog enforcement-a. Ironično, design-validator (jedini hook u agent .md) je VEĆ bio registrovan globalno u settings.json — lokalne kopije su bile duplikati koji su samo blokirali ostale hookove.

Fix:

  1. Uklonjene hooks: sekcije iz sva 4 agenta (builder, frontend-builder, backend-builder, design-builder)
  2. Svi agenti sada nasljeđuju SVE globalne hookove iz settings.json
  3. design-validator ostaje u globalnom PostToolUse (settings.json linija 142-147)
  4. Backup: ~/system/backups/setup-changelog/20260216-184634/

Pravilo (ZAKON):

Fix nivo: Deterministic (uklanjanje hooks: iz agent .md) + Rule (ovaj fajl) + HiveMind (#7191) + CHANGELOG


Vercel Deployment

Resend Email

Telegram Bot Auth

General

Background Agents & Security Hooks

Testing


2026-02-04: Problem-Solving Enforcement System

Problem: John preskakao CORE PROTOCOL - išao direktno na implementaciju bez analize.

Root cause: Validation flag bio statičan, nikad se nije resetovao.

Rješenje implementirano:

  1. boot.sh briše /tmp/claude-task-validated na početku sesije
  2. security-guard.py traži problem-solving dokumentaciju u /tmp/claude-problem-solving.md
  3. Dokumentacija mora imati 5 sekcija: PROBLEM, RESEARCH, OPCIJE, EVALUACIJA, ODLUKA
  4. Bootstrap exception: Write dozvoljeno SAMO na problem-solving fajl
  5. Kad dokumentacija kompletna → auto-validacija → flag kreiran

Workflow:

Fajlovi izmijenjeni:

Lekcija: Enforcement mora biti automatski i neizbježan. Ako se može preskočiti, bit će preskočen.


2026-02-04: Hooks Can Only Approve/Block, NOT Modify

Problem: Agent-protocol-enforcer.py vraćao updatedInput misleći da će Claude Code koristiti modificirani prompt. Agenti su i dalje pitali tehnicka pitanja.

Root Cause: updatedInput nije podržan u Claude Code hooks API. Hooks mogu samo:

Hooks su GATE kontrola, ne transformacija.

Fix:

  1. Hook sada BLOKIRA Task bez CORE PROTOCOL markera
  2. John mora eksplicitno dodati protokol u svaki agent prompt
  3. Built-in tipovi (Explore, Plan, Bash) su izuzeti - imaju svoje instrukcije

Fajl: ~/.claude/hooks/agent-protocol-enforcer.py

Lekcija: Ne pretpostavljaj da feature postoji. Testiraj da hook STVARNO radi kako misliš.


2026-02-04: DocuSeal — Paid Only

Problem: Koristili DocuSeal za digitalni potpis NDA/ugovora sa Wizard NUF-om. Nije radilo.

Root Cause: DocuSeal nema free plan - zahtijeva plaćenu pretplatu za production use.

Impact: Wizard NUF onboarding ostao bez potpisanih dokumenata. Pipeline testiran ali faza 3 (NDA) i 5 (Contract) nisu kompletne.

Next: Task #52 - naći alternativu za digitalni potpis koja ima free tier ili je self-hosted.

Lekcija: Prije integracije sa SaaS alatom, provjeri pricing i limits. "Free trial" ≠ "Free tier".


2026-02-17: Preskočen /hop-build pipeline — output ne valja (Drop #1309)

Problem: Task #1309 (Drop mobile production build) — John je preskočio /hop-build pipeline. Umjesto toga: ručno spawnao 3 builder agenta paralelno, napisao surface-level GOTCHA checklist samo da prođe hook, nije koristio validator agente. Rezultat: Alem dobio APK koji "ne valja". ZAKON #0 prekršen OPET.

Root Cause (iz analize):

  1. Nema enforcement za /hop-build — gotcha-enforcer provjerava GOTCHA checklist ali NE provjerava da li je hop-build PROCES korišten
  2. Skill invocation je dobrovoljna — nema hook koji detektuje "trebao si koristiti /hop-build ali nisi"
  3. Builder spawn bez process state — orchestrator-delegation-enforcer dozvoljava direktan builder spawn, ne razlikuje "via hop-build" od "ručno"
  4. MEDIUM priority nema plan enforcer — plan-enforcer.py zahtijeva plan JSON samo za HIGH priority

Impact: 3 builder agenta radila bez proper plana, bez validatora, bez verifikacijske faze. Output deployovan na Expo bez validacije. Alem eksplicitno rekao: "ovo sto si mi dao ne valja" i "kreni ispočetka".

Fix (tiered):

  1. Hook (WARNING): gotcha-enforcer.py CHECK 5 — warn kad MEDIUM+ task nema /tmp/hop-build-started-{id} marker
  2. Skill update: /hop-build Phase 1 sad kreira marker fajl
  3. ZAKON #5: "Svaki implementation task MORA koristiti /hop-build" (MEMORY.md)
  4. Lessons-learned: Ovaj zapis

Zašto WARNING a ne BLOCK: Novo pravilo — treba validacijski period. Ako se pokaže da false positive rate je nizak, escalirat će se na exit 2 (BLOCK).

Lekcija: GOTCHA checklist je "razmisli prije kodiranja". /hop-build je "slijedi PROCES kodiranja". Jedno bez drugog = half-assed. Task #1309 dokazuje: razmišljanje bez procesa → shortcuti → broken output.


2026-02-04: Agenti moraju znati za sistem

Problem: Agenti kad zapnu pitaju umjesto da koriste problem-solving proces.

Root Cause: Agentima nisam davao informaciju O sistemu — samo task. Ne znaju da /tmp/claude-problem-solving.md postoji.

Fix: Kreiran ~/system/agents/BOOTSTRAP.md — svaki agent prompt počinje sa "Pročitaj BOOTSTRAP.md".

Lekcija: Agent bez konteksta o sistemu će raditi ad-hoc. Mora znati KAKO rješavamo probleme, ne samo ŠTA treba uraditi.

Lesson Learned: PI Orchestrator Task Routing Failures

Date: 2026-03-11 Context: World-Class Gap Analysis — 13 parallel tasks Impact: 4+ hours delay, 3 rounds of manual re-dispatching

Root Causes Found

1. delegate_task → Event Bus drops tasks silently

2. Owner mismatch: delegate_task assigns to "pi-orchestrator" but orchestrator queries --owner john

3. mc.js start puts tasks in "in_progress" — orchestrator only picks up "open"

4. Classifier sends research tasks to human-queue (complexity=5)

5. Classifier sends tasks to qwen3:8b which fails on complex analysis

Correct Workflow (Until Fixed)

  1. Create tasks directly with mc.js add "title" --priority H --owner john
  2. Do NOT use mc.js start — let orchestrator pick them up
  3. Do NOT rely on delegate_task for batch dispatching — verify MC task creation
  4. After delegate_task, always check mc.js list --owner john --status open to confirm

Systemic Fix Required


CI/CD & Production Monitoring (2026-03-12)

Incident: getdrop.no served drop-app instead of landing page for 7 days. No one noticed except CEO.

Root Cause

Lessons

  1. Every production URL must have a smoke test — not just health check, but CONTENT verification (expected title, expected response body)
  2. Domain ownership must be explicit and audited — document which service owns which domain. Alert on any change.
  3. Deploy pipelines must verify the DESTINATION, not just the build — ZAKON #10 says "verify on destination" but we only verify locally
  4. CI must GATE deploy — deploy should require CI pass. Currently deploy is independent of CI.
  5. Infrastructure changes (DNS, custom domains, TF apply) must go through PR review — never ad-hoc CLI commands
  6. One fix for ALL products, not per-product — every fix must be systemic, applied to Drop AND Tok AND Bilko AND Lobby AND Plock AND BasicFakta

Required Actions (systemic, all products)


2026-04-08: Testing Failure — Agents Write Tests That Cannot Fail (Drop)

Analysis by: Petter Graff + James Whittaker framework Context: 10+ consecutive CEO test failures. CEO found bugs in 5 minutes that 1232 E2E tests missed. Full analysis: ~/system/rules/lessons-learned-testing-2026-04-08.md

Root Cause

Test agents design tests to PASS, not to FIND BUGS. This is a design philosophy failure, not a quantity failure.

Measured failures in Drop E2E suite:

The 5 Behavioral Differences (CEO vs Agent)

  1. CEO tests EXPECTATIONS. Agents test ASSERTIONS.
  2. CEO tests JOURNEYS. Agents test COMPONENTS.
  3. CEO tests WHAT EXISTS. Agents test WHAT THEY BUILT.
  4. CEO tests CURRENT STATE (full regression). Agents test WHAT CHANGED.
  5. CEO STOPS on ambiguity. Agents SKIP on ambiguity.

Anti-Patterns (BANNED in all E2E tests)

Required Patterns

Whittaker's 7 Tours (run after every deploy)

  1. Guidebook Tour — follow the primary user path by clicking, not goto
  2. Money Tour — verify every number on every screen (fee, rate, total, recipient)
  3. Landmark Tour — navigate ONLY via visible UI elements
  4. Intellectual Tour — test hardest features with complex inputs
  5. FedEx Tour — follow data creation to completion and verify it matches
  6. Garbage Collector Tour — visit ALL pages, including least-used ones
  7. Bad Neighborhood Tour — re-test every previous CEO-found bug scenario

Solution Implemented

Lekcija: 1232 tests that skip on failure are worse than 10 tests that actually fail when things break. The required shift: tests must be designed to FIND bugs, not to PASS.


2026-06-12 — Generalizable process fixes (SnowIT-SEO OAuth session) — apply to ALL projects/clients

Memo: ~/.claude/projects/-Users-makinja/memory/feedback_generalizable_corrections_2026-06-12.md.

Tool-First Protocol

Tool-First Protocol

OBAVEZNO za SVE agente. Prije nego tražiš na internetu ili pišeš novo — provjeri šta već imamo.


Redoslijed (UVIJEK ovim redom)

1. NAŠI ALATI (~/system/tools/)

# Provjeri manifest — postoji li tool za ovo?
cat ~/system/tools/manifest.md

Ako tool postoji → KORISTI GA. Ne piši novi.

2. NAŠI SKILLOVI (~/.claude/commands/)

/plan-with-team    — plan sa builder/validator timom
/build-plan        — izvrši odobren plan
/code-review       — sistematski code review
/debugging         — sistematsko debugiranje
/security-audit    — security pregled

Ako skill pokriva tvoj zadatak → KORISTI GA.

3. NAŠA BAZA ZNANJA

# HiveMind — jesmo li ovo već radili?
node ~/system/agents/hivemind/hivemind.js query "<keyword>"

# Prošle sesije — je li neko već rješavao ovo?
bash ~/system/tools/session-search.sh keyword "<keyword>"

# Kontekst dokumentacija
ls ~/system/context/docs/

# Pravila
ls ~/system/rules/

# Specifikacije
ls ~/system/specs/

4. INTERNET (tek ako 1-3 ne daju odgovor)

Ako ništa od gore ne pokriva tvoj problem — ONDA pretražuj internet. Ali OBAVEZNO dokumentiraj šta si naučio (vidi Korak 5).

5. AŽURIRAJ BAZU (nakon svakog značajnog saznanja)

# Novo saznanje → HiveMind
node ~/system/agents/hivemind/hivemind.js post <agent> knowledge "<šta si naučio>"

# Nova greška → HiveMind
node ~/system/agents/hivemind/hivemind.js post <agent> bugfix "<bug + fix + prevencija>"

# Novi pattern → HiveMind
node ~/system/agents/hivemind/hivemind.js post <agent> pattern "<pattern + kad koristiti>"

# Ako je toliko važno da treba u rules/ → predloži update

Primjeri

LOŠE (preskaču naše alate):

❌ "Let me search the web for how to send email in Node.js"
   → IMAMO email.js! Provjeri manifest.

❌ "I'll write a function to track tasks"
   → IMAMO mc.js! Provjeri manifest.

❌ "Let me create a new database utility"
   → IMAMO hivemind.js, invoice-generator.js, etc! Provjeri manifest.

DOBRO (koriste naše alate):

✅ "Let me check manifest.md... We have email.js, using that."
✅ "Checking HiveMind for past solutions... Found: [result]"
✅ "No existing tool for this. Searching web... Found solution. Logging to HiveMind."

Za Buildere i Validatore

Builder — prije implementacije:

  1. cat ~/system/tools/manifest.md — postoji li tool?
  2. node ~/system/agents/hivemind/hivemind.js query "<task-keyword>" — imamo li iskustvo?
  3. Ako ne → implementiraj, ali na kraju postaj saznanje na HiveMind

Validator — provjeri da je builder slijedio protokol:


Zašto

  1. Izbjegavamo duplikate — ne pišemo tool koji već postoji
  2. Kumulativno znanje — svako saznanje se sprema, sljedeći agent ga koristi
  3. Manja cijena — web search košta tokene. Lokalni lookup je besplatan.
  4. Manja greška — naši alati su testirani. Novi kod = novi bugovi.
  5. Brže — lokalni file read < web search < pisanje novog koda

Security Rules

Last Verified: 2026-02-17 | Owner: John

Security Policies

ZABRANJENO — Forbidden Access

NIKAD ne pristupaj:

Enforced deterministically by ~/.claude/hooks/security-guard.py.

Credential Storage

Internal Credentials

Client Credentials (NEW - 2026-02-06)

One-Time Sharing:

Long-Term Storage:

Process: See ~/system/tools/credentials-handoff.md

NEVER:

Prompt Injection Protection

Path Validation

node ~/system/tools/security.js check <path>

Run BEFORE any file/browser action.

NEVER DELETE

Network Security

Task Management Rules

Last Verified: 2026-02-17 | Owner: John


Task Execution Discipline (2026-02-10) — ENFORCER

Pravilo: Svaka akcija prolazi kroz lifecycle

Kad radiš na bilo čemu (mail, deploy, fix, dokument), OBAVEZAN ciklus:

1. OPEN    → Nađi ili kreiraj task (task.sh)
2. START   → task.sh start <id> — sad si accountable
3. DO      → Odradi posao
4. CHECK   → Provjeri rezultat (mail poslan? file kreiran? API radi?)
5. TEST    → Testiraj ako je primjenjivo (smoke test, verify)
6. ASK     → Ako treba user interakcija — pitaj PRIJE zatvaranja
7. FIX     → Popravi ako nešto ne valja
8. TEST    → Ponovo testiraj nakon fix-a
9. CLOSE   → task.sh done <id> "Output: ..., Next: ..." — SAMO ako je OK
10. FOLLOW → Otvori follow-up taskove ako treba

Automatski trigger:

Anti-pattern (ZABRANJENO):

Napomena:

Ovaj enforcer se primjenjuje na SVE akcije — ne samo development. Mail, dokumenti, client communication, setup — SVE ima task lifecycle.


Task System Integration (2026-02-04)

Dva sistema, dvije svrhe:

1. Claude TaskCreate/TaskUpdate (session-scoped)

2. task.sh (persistent, tasks.db)

Workflow:

Početak rada na tasku:
1. task.sh start <id>           # Persistent tracking
2. TaskCreate + TaskUpdate      # Session tracking

Završetak:
1. TaskUpdate status=completed  # Session
2. task.sh done <id>            # Persistent

Pravilo:


WIP Limit (2026-02-09)

Pravilo: Max 3 aktivna taska po agentu

John: max 3 in_progress taska (development fokus) Alem: max 3 in_progress taska (personal/business tasks)

Zašto:

Kako:

  1. Prije task.sh start <id> — provjeri koliko imaš aktivnih: task.sh list | grep "in_progress" | grep "<owner>" | wc -l
  2. Ako >= 3 — PRVO završi ili pauziraj jedan
  3. Ne otvaraj novi task dok ne zatvoriš stari

Hijerarhija prioriteta:

  1. HIGH taskovi UVIJEK prvi
  2. MEDIUM samo ako nema HIGH
  3. LOW samo ako nema ništa drugo

Task Hygiene (sedmično):

Visual Verification Rules

Last Verified: 2026-02-17 | Owner: John

Rule: Visual Verification — Razlike prvo, sličnosti nikad

Kad se primjenjuje

Svaki put kad agent mijenja UI kod ili poredi vizualni output sa referencom.

Pravilo

0. REFERENCA PRIJE KODA

Prije bilo kakve UI promjene — PRVO pročitaj source of truth dizajn:

Zabranjeno: Mijenjati UI kod pa TEK ONDA provjeriti dizajn. Redoslijed je: dizajn → kod → verifikacija.

1. RAZLIKE PRVO

Kad poredim dva vizualna elementa, PRVI korak je nabrojati sve razlike. Ne sličnosti.

Pitanje NIJE: "Šta se poklapa?" Pitanje JESTE: "Šta se NE poklapa?"

2. EKSPLICITNA LISTA

Svaka razlika mora biti zapisana sa:

3. NULA RAZLIKA = SUMNJA

Ako ne mogu naći nijednu razliku — ne gledam dovoljno pažljivo. Minimum provjera:

4. NIKAD "POKLAPA SE" BEZ LISTE RAZLIKA

Zabranjena rečenica: "Poklapa se sa dizajnom." Dozvoljena rečenica: "Uporedio sam X elemenata. Našao Y razlika: [lista]. Ostalo se poklapa."

5. AKO JE UI/DESIGN TASK

Obavezno u evidence:

Zašto

Task #850/#853: Agent tri puta proglasio login "gotov" i "poklapa se". Font bio pogrešan, tagline stil pogrešan, ikone drugačije. Nijedan mehanički check (build, JSON, file existence) ovo ne hvata. Samo pažljivo GLEDANJE hvata vizualne razlike.

HiveMind Convention

Last Verified: 2026-02-17 | Owner: John

HiveMind Convention

Odobreno: Alem, 2026-02-06 Updated: 2026-02-12 (Edita archived)


Arhitektura

SHARED BUS (svi agenti čitaju/pišu)
  ~/system/agents/hivemind/hivemind.db

CROSS-SESSION TASKS (Alem vidi)
  ~/system/databases/mission-control.db

PER-CLIENT DATA (izolirano po projektu)
  ~/projects/<klijent>/client.db

Hijerarhija

Alem → John (direktno)

HiveMind Type Konvencija

agent type Značenje
john task John loguje task
john response John odgovara
john update John javlja status
john discovery John pronašao korisnu informaciju
builder task-update Builder javlja napredak na tasku
validator validation Validator javlja rezultat provjere
* alert Hitno — treba pažnja odmah
* learning Naučeno nešto novo
* error Nešto puklo

Historijski tipovi (Edita, archived): task-update, question, response ostaju u bazi za referencu.

Komande

# John loguje task
node ~/system/agents/hivemind/hivemind.js post john task \
  "Opis taska" '{"client":"ime","priority":"high"}'

# John javlja update
node ~/system/agents/hivemind/hivemind.js post john update \
  "Task XY: zavrseno" '{"client":"ime","status":"done"}'

# Builder javlja napredak
node ~/system/agents/hivemind/hivemind.js post builder task-update \
  "Implementation progress" '{"task_id":"123","status":"in_progress"}'

# Validator javlja rezultat
node ~/system/agents/hivemind/hivemind.js post validator validation \
  "Validation passed" '{"task_id":"123","result":"pass"}'

# Čitaj sve
node ~/system/agents/hivemind/hivemind.js read 10

# Čitaj samo od jednog agenta
node ~/system/agents/hivemind/hivemind.js read john 10

# Pretraži
node ~/system/agents/hivemind/hivemind.js query "fitlife"

Per-Client DB Pattern

Svaki klijentski projekat ima svoju bazu:

~/projects/<klijent>/
├── CLAUDE.md          ← Pravila za taj projekat
├── client.db          ← Klijent-specifični podaci (SQLite)
└── src/               ← Kod

Pravilo: Klijentski podaci NIKAD u HiveMind. HiveMind je samo za komunikaciju i koordinaciju između agenata.

Data Field (JSON)

Svaki post može imati data JSON polje za strukturirane podatke:

{
  "client": "fitlife",
  "priority": "high|medium|low",
  "status": "pending|in_progress|done|blocked",
  "deadline": "2026-02-07",
  "blocked": true,
  "files": ["src/index.html"],
  "ref_task_id": 73
}

Primjer Workflow

1. John: post john task "Implement landing page for FitLife" {client:fitlife, priority:high, mc_task_id:123}
2. Builder: post builder task-update "FitLife: started" {client:fitlife, status:in_progress, mc_task_id:123}
3. Builder: post builder task-update "FitLife: done" {client:fitlife, status:done, mc_task_id:123}
4. Validator: post validator validation "FitLife: PASS - all criteria met" {client:fitlife, result:pass, mc_task_id:123}
5. John: post john update "FitLife: deployed to production" {client:fitlife, mc_task_id:123}

ACK Protocol

Kad primiš novu instrukciju, javi ACK:

node hivemind.js post <agent> response "ACK: <kratki opis>"

Communication Rules

Last Verified: 2026-02-17 | Owner: John

Communication Protocols

Channels (active)

Deprecated (UGAŠENO 2026-02-11)

Mattermost Setup

MM Commands

Command Usage
Send node ~/system/tools/mm.js send <team> <channel> "msg"
Read node ~/system/tools/mm.js read <team> <channel> [limit]
Unread node ~/system/tools/mm.js unread <team>
Gate node ~/system/tools/mm.js gate <team> "question"
Status node ~/system/tools/mm.js status

Daily Rhythm

Vrijeme Sta
08:00 John salje jutarnji brief na MM basic/ai-ops
Non-stop Daemon prati: tasks (30min John autowork)
Kad treba John javlja ako treba Alemova odluka (MM gate)
19:00 Vecernji summary na MM

Language Matching Rules

All client-facing communication MUST match the detected language:

Language detection: Automatic via intake-analyzer.js detectLanguage()

Internal communication: Always English (team, HiveMind, Slack, MM)

Implementation:

Odluke

Tip Ko odlucuje
Operativno (<5K EUR) John — radi, loguje
Stratesko (>5K EUR, partneri, pivoti) Alem
Hitno John eskalira na MM basic/town-square

Core Protocol

Last Verified: 2026-02-17 | Owner: John

CORE PROTOCOL — Agent Self-Sufficiency Rule

Status: ACTIVE (enforced by ~/.claude/hooks/agent-protocol-enforcer.py) Created: 2026-02-17 Origin: Alem directive — agents must never ask users technical questions


Rule

Every agent spawned via Task tool MUST behave as a self-sufficient expert:

  1. NIKAD NE PITAJ korisnika tehnicka pitanja — Ti si ekspert, ne on.
  2. Ako zapneš → istraži sam (čitaj fajlove, dokumentaciju, HiveMind)
  3. Ako ne možeš riješiti → vrati parcijalni rezultat sa objašnjenjem
  4. NIKAD ne pitaj "kako da implementiram X"

Enforcement

Hook agent-protocol-enforcer.py blokira Task tool pozive koji ne sadrže:

Required Prompt Template

Svaki Task prompt MORA početi sa:

## CORE PROTOCOL

NIKAD NE PITAJ korisnika tehnicka pitanja. Ti si ekspert, ne on.
- Ako zapneš → istraži sam (čitaj fajlove, dokumentaciju)
- Ako ne možeš riješiti → vrati parcijalni rezultat sa objašnjenjem
- NIKAD ne pitaj "kako da implementiram X"

## GOTCHA BOOT
PRVI KORAK — prije BILO ČEGA, pročitaj:
1. ~/system/rules/tool-first-protocol.md
2. ~/system/rules/agent-anti-hallucination.md
3. ~/system/tools/manifest.md
Tek NAKON čitanja nastavi sa taskovima.

MC task #XXX

Exempt Agent Types

Rationale

Alem je CEO, ne developer. Kad agent pita "kako da implementiram X?" — to je prebaćeno na čovjeka koji nije tu da rješava tehničke probleme. Agent mora biti ekspert ili priznati ograničenje sa parcijalnim rezultatom.

Agent Teams Rules

Last Verified: 2026-02-17 | Owner: John

Agent Teams — Pravila korištenja (2026-02-12)

CEO approved. Ova pravila su obavezna za John-a i sve agente.


1. TIER SISTEM — Routing po kompleksnosti

Svaki task ima tier koji određuje način izvršavanja:

Tier Token budget Kad Kako
T1 Solo ~200K Bug fix, config, single file edit, quick research John direktno, nema agenata
T2 Subagent ~440K Focused build, parallel research, file search 1-3 subagenta (sonnet/haiku)
T3 Team ~800K+ Multi-layer feature, audit, QA swarm, cross-domain Agent team sa lead + teammates

Pravilo: MC task MORA imati tier oznaku (T1/T2/T3) prije starta. Default: T1 Solo. Eskalacija na T2/T3 samo kad task zahtijeva.


2. PLAN-FIRST GATE — Obavezno za T2 i T3

T1: Task → GOTCHA → Build (direktno)
T2: Task → GOTCHA → Plan (~10K) → Build (~400K)
T3: Task → GOTCHA → Plan (~10K) → CEO approve → Build (~800K+)

T3 UVIJEK zahtijeva CEO approval prije builda. Plan je jeftin (~10K tokena). Rework je skup (~500K+). Bolje 10 minuta planiranja nego 1 sat ponovnog rada.


3. DELEGATE MODE — Lead ne implementira

Kad John koristi T3 Agent Team:

Zašto: Lead kontekst je skup (opus). Implementacija troši kontekst bez potrebe. Lead koji implementira = skuplji agent koji radi isti posao.


4. FILE OWNERSHIP — Nema konflikata

Svaki agent task MORA definisati koje fajlove smije dirati:

## Task za Agent X
Files (WRITE): src/api/auth.js, src/api/auth.test.js
Files (READ): src/config.js, src/db.js

Pravilo: Dva agenta NIKAD ne pišu u isti fajl. Ako dva taska trebaju isti fajl — sekvencijalno, ne paralelno.


5. TASK GRANULARNOST — 5-6 units per agent

Svaki agent dobija 5-6 self-contained task units:

Anti-pattern: "Napravi cijeli backend" (preveliko) Dobro: "Napravi auth API: register, login, logout, me endpoint. Fajlovi: src/api/auth.js + test."


6. MODEL BUDGET — Strogo

Uloga Model Razlog
Lead (John) opus Orkestracija, planning, CEO interakcija
Builder agent sonnet Implementacija — dobar balans kvalitet/cijena
Validator agent sonnet Verifikacija — treba razumjeti kod
Research/search haiku Trivijalno — ne treba duboko razumijevanje

NIKAD opus za agente. NIKAD haiku za build.


7. CONTEXT U SPAWN PROMPTU

Agenti NE nasljeđuju lead-ov conversation history. Zato:

Loše: "Fixaj bug u API-ju" Dobro: "Fix auth token expiry bug u src/api/auth.js:45. Token se ne refresha nakon 1h. Acceptance: test src/api/auth.test.js prolazi, token refresh radi na 59min."


8. GRACEFUL SHUTDOWN

Svaki team MORA završiti čisto:

  1. Lead šalje shutdown_request svakom agentu
  2. Agent odgovara shutdown_response
  3. Lead poziva TeamDelete

Nikad ne ostavljaj zombie agente.


9. DECISION TREE — Kad šta koristiti

Pitanje: Trebaju li agenti međusobno komunicirati?
├── NE → Subagenti (T2) — jeftinije, dovoljno
└── DA → Agent Team (T3) — skuplje, ali potrebno

Pitanje: Može li se uraditi u jednom fajlu / jednom koraku?
├── DA → Solo (T1) — ne troši na agente
└── NE → T2 ili T3

Pitanje: Treba li CEO approval?
├── DA (build od spec-a, >800K tokena, deploy) → T3 + Plan-First
└── NE (research, fix, maintenance) → T1 ili T2

10. MJERENJE USPJEHA

Svaki T3 team session MORA logirati:

Log u HiveMind: hivemind.js post john metrics "T3 team: X agents, Y tokens, Z min, PASS/FAIL"

Ovo gradi dataset za optimizaciju budućih team sessija.


Primjeri iz prakse

SENTINEL audit (T3): 5 agenata, ~540K tokena, 6.8/10 score — PASS alai.no update (T1): Solo, ~30K tokena, 8 edita — PASS SLA loop fix (T1): Solo, ~20K tokena, 4 fajla — PASS Shell injection fix (T1): Solo, ~25K tokena, 4 fajla — PASS

Lekcija: Većina posla je T1. Timovi samo za kompleksno.

Anti-Hallucination Rules

Agent Anti-Hallucination Rules

Source: FjordConsulting simulation test (2026-02-06) Findings: 75/100 accuracy — 25% hallucinated details


Rule 0: VERIFY BEFORE CLAIMING (NAJVAŽNIJE PRAVILO)

NIKAD ne tvrdi da nešto postoji ili ne postoji bez da PROVJERIS.

Prije nego kažeš "fajl ne postoji" → pokreni ls ili cat. Prije nego kažeš "tool ne radi" → pokreni ga. Prije nego kažeš "nema komunikacije" → provjeri kanal.

# ISPRAVNO: provjeri pa tvrdi
ls ~/path/to/file.txt          # postoji? → ONDA reci "postoji"
cat ~/path/to/config.json      # čitljiv? → ONDA reci šta piše

# POGREŠNO: tvrdi bez provjere
"Taj fajl ne postoji"          # ← KAKO ZNAŠ? Jesi li pokrenuo ls?
"Sistem nije konfigurisan"     # ← KAKO ZNAŠ? Jesi li provjerio?

Primjer greške (2026-02-06): Edita tvrdila da 5 fajlova "ne postoji nigdje u Dropboxu" — ls na istoj mašini je pokazao da SVI postoje. Nije provjerila filesystem prije nego je donijela zaključak.

Pravilo: Ako nisi pokrenuo komandu koja DOKAZUJE tvoju tvrdnju — ne tvrdi.


Rule 1: TBD > Hallucination

If you don't know a specific value, write TODO: or TBD instead of inventing it.

NEVER invent:

ALWAYS mark uncertainty:

// TODO: verify — this API may not exist in iOS 17
// TBD: Norwegian developer hourly rate (estimate 800-1500 NOK/h, needs verification)
// PLACEHOLDER: replace with real bcrypt hash before deployment

Rule 2: Cross-File Consistency

Before writing code that references another file, READ that file first.

Mandatory checks:

Anti-pattern (caught in test):

// websocket.ts writes status='online'
// BUT schema.sql only allows: 'active', 'away', 'offline', 'deactivated'
// Result: runtime crash

Rule 3: No Phantom Dependencies

Every dependency in package.json / Package.swift MUST be:

  1. Actually imported in at least one source file
  2. Actually used (not just imported)

If you add a dependency for future use, comment it:

// "ioredis": "^5.4.2"  // Phase 2: session caching — NOT YET IMPLEMENTED

Rule 4: Health Checks Must Be Real

Never hardcode health check responses. Always verify:

// BAD (caught in test):
return { database: 'up', redis: 'up' }; // lies

// GOOD:
const dbOk = await pool.query('SELECT 1').then(() => true).catch(() => false);
return { database: dbOk ? 'up' : 'down' };

Rule 5: Spec-Implementation Parity

If you write a specification (API spec, design doc), track implementation status:

## Endpoints

| Endpoint | Status |
|----------|--------|
| POST /auth/login | IMPLEMENTED |
| POST /auth/register | IMPLEMENTED |
| GET /groups | NOT YET IMPLEMENTED |
| POST /push/register | PHASE 2 |

Never present unimplemented features as done.


Rule 6: Budget and Timeline Reality Checks

When estimating costs or timelines:


Rule 7: Placeholder Code Must Scream

Mock implementations must be OBVIOUSLY fake:

// BAD (caught in test): looks like real encryption but is base64
func encrypt(_ data: Data) -> Data {
    return data.base64EncodedData() // This is NOT encryption
}

// GOOD: impossible to miss
func encrypt(_ data: Data) -> Data {
    fatalError("PLACEHOLDER: Real encryption not yet implemented. Integrate libsignal-client-swift before shipping.")
}

Rule 9: Config/Schema Changes Require Docs (dodano 2026-02-12)

ROOT CAUSE: John mijenjao hooks format u settings.json bez čitanja docs. Haiku validator potvrdio pogrešan format.

PRAVILA:

  1. NIKAD mijenjaj config format (hooks, settings, schema) bez čitanja oficijelne dokumentacije
  2. WebFetch/WebSearch OBAVEZAN za: hooks format, API schema, config migration, breaking changes
  3. Validator agent NIJE rubber stamp — mora imati docs URL ili spec file kao input
  4. Anti-pattern: "Provjeri da sam dobro uradio" bez davanja izvora istine agentu

Primjer greške (2026-02-12):

// POGREŠNO (John napisao):
"matcher": {}        // objekt — Claude Code expects string

// ISPRAVNO (iz docs):
"matcher": "*"       // regex string — matcha sve toolove
"matcher": "Bash"    // regex string — matcha samo Bash

Workflow za config promjene:

1. WebFetch oficijelnu docs stranicu
2. Pročitaj schema/format
3. Tek onda mijenjaj fajl
4. Validator dobije docs URL kao input za nezavisnu provjeru

Rule 10: API Endpoint Verification (dodano 2026-04-04)

ROOT CAUSE: Builder agent hallucinated /upload endpoint for LightRAG when correct endpoint is /documents/text. Error passed through system without detection.

PRAVILA:

  1. NIKAD pretpostavi da HTTP endpoint postoji bez verifikacije
  2. Prije pisanja kod-a sa HTTP pozivom — provjeri /health ili OpenAPI spec
  3. Hallucination-detector hook blokira poznate pogrešne endpoint-e
  4. KNOWN_API_ENDPOINTS u ~/.claude/hooks/hallucination-detector.py je source of truth

Poznati pogrešni endpoint-i (BLOCKED):

❌ /upload               → ✓ /documents/text (LightRAG)
❌ /ingest              → ✓ /documents/texts (LightRAG)
❌ /add                 → ✓ /documents/text (LightRAG)

Workflow za novi endpoint:

# 1. Provjeri existence
curl -s http://localhost:9621/health  # Ako 404 → endpoint nije to
curl -s http://localhost:9621/openapi.json | grep "endpoint-path"

# 2. Ako postoji — dodaj u KNOWN_API_ENDPOINTS
# 3. Ako NE postoji — STOP, pitaj arhitektora

# 4. Tek onda koristi u kodu:
httpRequest('GET', 'http://localhost:9621/documents/text', null)

Hook blokada:

hallucination-detector.py check_phantom_endpoints()
└─ Skenira sve httpRequest/fetch/axios pozive
└─ Ako slijedi poznati invalid endpoint → EXIT(2) sa porukom

Hallucination Examples from Test

What agent wrote Reality Root cause
"Sesame Algorithm" Does not exist Invented name for concept
contentSecureLevel iOS 17 API Does not exist Invented API
bcrypt hash $2b$12$vJ4... Invalid hash Generated random string
150 NOK/h developer rate Norway is 800-1500 NOK/h No market context
Redis "up" in health check Redis never connected Hardcoded response
status = 'online' DB enum has no 'online' Didn't read schema
ReportCo AS "WON client" Demo data, firma ne postoji Test data bez is_test flag
FitLife AS "50K deal" Demo data, firma ne postoji Lead→WON bez ugovora
FjordConsulting "200K proposal" Kontakt ne postoji u contacts.db Phantom pipeline entry
Revenue plan 774K Q1 Realno 544K (230K phantom) Auto-generated bez review

Rule 8: Demo/Test Data Protection (dodano 2026-02-11)

ROOT CAUSE: John kreirao demo podatke (FitLife, ReportCo) 2026-02-04 za AIOS testing. Bez oznake. Propagirali kroz leads→contacts→invoices→revenue plan kao REALNI klijenti 7 dana.

PRAVILA:

  1. NIKAD kreiraj test/demo podatke u production bazama bez jasne oznake
  2. Flag marking: Svaki test zapis MORA imati polje is_test=true ili ekvivalent
  3. Name prefix: Test firme MORAJU imati prefix TEST: ili DEMO: u imenu
  4. Email: Test kontakti koriste @test.local domenu, NIKAD realne domene
  5. Human gate: Lead koji ide u WON stage MORA imati:
    • Potpisan ugovor, ILI
    • Eksplicitna potvrda od Alema
  6. Revenue plan: NIKAD auto-generate i publish — uvijek draft + human review
  7. Invoice kreacija: Zahtijeva referencu na potpisan ugovor ili Alem approval
  8. Contacts baza: Novi kontakt MORA imati verificiran email i dokumentovan source
  9. Cross-check: Prije uključivanja firme u revenue plan, verificiraj da postoji u contacts.db SA realnom komunikacijom

Ako kreiraš test data za demo:

# ISPRAVNO:
node contacts.js add "TEST: DemoFirma" "test@test.local" --notes "DEMO DATA for testing only"

# POGREŠNO:
node contacts.js add "ReportCo AS" "cfo@reportco.no"  # izgleda realno, propagira

Task Management


Task Execution Discipline (2026-02-10) — ENFORCER

Pravilo: Svaka akcija prolazi kroz lifecycle

Kad radiš na bilo čemu (mail, deploy, fix, dokument), OBAVEZAN ciklus:

1. OPEN    → Nađi ili kreiraj task (task.sh)
2. START   → task.sh start <id> — sad si accountable
3. DO      → Odradi posao
4. CHECK   → Provjeri rezultat (mail poslan? file kreiran? API radi?)
5. TEST    → Testiraj ako je primjenjivo (smoke test, verify)
6. ASK     → Ako treba user interakcija — pitaj PRIJE zatvaranja
7. FIX     → Popravi ako nešto ne valja
8. TEST    → Ponovo testiraj nakon fix-a
9. CLOSE   → task.sh done <id> "Output: ..., Next: ..." — SAMO ako je OK
10. FOLLOW → Otvori follow-up taskove ako treba

Automatski trigger:

Anti-pattern (ZABRANJENO):

Napomena:

Ovaj enforcer se primjenjuje na SVE akcije — ne samo development. Mail, dokumenti, client communication, setup — SVE ima task lifecycle.


Task System Integration (2026-02-04)

Dva sistema, dvije svrhe:

1. Claude TaskCreate/TaskUpdate (session-scoped)

2. task.sh (persistent, tasks.db)

Workflow:

Početak rada na tasku:
1. task.sh start <id>           # Persistent tracking
2. TaskCreate + TaskUpdate      # Session tracking

Završetak:
1. TaskUpdate status=completed  # Session
2. task.sh done <id>            # Persistent

Pravilo:


WIP Limit (2026-02-09)

Pravilo: Max 3 aktivna taska po agentu

John: max 3 in_progress taska (development fokus) Alem: max 3 in_progress taska (personal/business tasks)

Zašto:

Kako:

  1. Prije task.sh start <id> — provjeri koliko imaš aktivnih: task.sh list | grep "in_progress" | grep "<owner>" | wc -l
  2. Ako >= 3 — PRVO završi ili pauziraj jedan
  3. Ne otvaraj novi task dok ne zatvoriš stari

Hijerarhija prioriteta:

  1. HIGH taskovi UVIJEK prvi
  2. MEDIUM samo ako nema HIGH
  3. LOW samo ako nema ništa drugo

Task Hygiene (sedmično):

Communication Standards

Communication Protocols

Channels (active)

Deprecated (UGAŠENO 2026-02-11)

Mattermost Setup

MM Commands

Command Usage
Send node ~/system/tools/mm.js send <team> <channel> "msg"
Read node ~/system/tools/mm.js read <team> <channel> [limit]
Unread node ~/system/tools/mm.js unread <team>
Gate node ~/system/tools/mm.js gate <team> "question"
Status node ~/system/tools/mm.js status

Daily Rhythm

Vrijeme Sta
08:00 John salje jutarnji brief na MM basic/ai-ops
Non-stop Daemon prati: tasks (30min John autowork)
Kad treba John javlja ako treba Alemova odluka (MM gate)
19:00 Vecernji summary na MM

Language Matching Rules

All client-facing communication MUST match the detected language:

Language detection: Automatic via intake-analyzer.js detectLanguage()

Internal communication: Always English (team, HiveMind, Slack, MM)

Implementation:

Odluke

Tip Ko odlucuje
Operativno (<5K EUR) John — radi, loguje
Stratesko (>5K EUR, partneri, pivoti) Alem
Hitno John eskalira na MM basic/town-square

Security Standards

Security Policies

ZABRANJENO — Forbidden Access

NIKAD ne pristupaj:

Enforced deterministically by ~/.claude/hooks/security-guard.py.

Credential Storage

Internal Credentials

Client Credentials (NEW - 2026-02-06)

One-Time Sharing:

Long-Term Storage:

Process: See ~/system/tools/credentials-handoff.md

NEVER:

Prompt Injection Protection

Path Validation

node ~/system/tools/security.js check <path>

Run BEFORE any file/browser action.

NEVER DELETE

Network Security

Guardrails

Guardrails — What to NEVER Do

ZABRANJENO — Proactive Actions

ZABRANJENO — Security

ZABRANJENO — Development

PRAVILO — Context Check

NIKAD ne reci "ne znam" ili "nemamo X" prije nego provjeriš:

  1. node ~/system/agents/hivemind/hivemind.js query "search" — PRVO lokalne baze
  2. node ~/system/agents/hivemind/hivemind.js agents — svi agenti
  3. MEMORY.md, daily logs
  4. SSH chat unread (bash ~/system/tools/ssh-chat.sh unread)

Ako odgovor nije 100% siguran iz trenutnog konteksta, PROŠIRI pretragu na sve izvore PRIJE odgovora.

PRAVILO — Planning discipline (ZAKON PLAN)

PRAVILO — Decisions

Problem Solving

Problem Solving — GLOBAL CORE DIRECTIVE

Ovo pravilo važi za SVE — development, dizajn, debugging, komunikaciju, sistem, odluke.

Princip

NIKAD ne skači na prvo rješenje.

Proces

Kad naiđeš na bilo koji problem:

  1. Definiraj problem jasno — šta tačno ne radi i zašto
  2. Istraži prvo — WebSearch, GitHub, dokumentacija. Internet je pun rješenja. Ne izmišljaj od nule kad neko već riješio isti problem
  3. Napravi 2-3 rješenja — sagledaj problem sa više strana
  4. Procijeni svako — tradeoffs, slabosti, prednosti
  5. Kombinuj najbolje — uzmi tuđe best practices, prilagodi našem sistemu
  6. Tek onda implementiraj

Mantras

Completeness Protocol (ZAKON #11)

ZAKON #11 — Completeness Protocol

NIKAD "evo cijela slika" bez POTPUNE slike.

Date: 2026-02-24 Origin: Alem repeatedly had to say "nemaš cijelu sliku" 3+ times before John gathered all data. Root cause: 67 hooks enforce code/deploy/sync verification but ZERO enforce information completeness in CEO briefings.


Rule

Before ANY briefing, status update, or email summary to CEO:

  1. Check ALL sources — not just the first one that returns results
  2. NEVER present partial data as complete — "evo šta imam do sad" ≠ "evo cijela slika"
  3. Explicitly state known unknowns — what you COULD NOT check and why
  4. Read previous session context — when CEO asks about past topics, FIRST read session logs

Briefing Completeness Checklist

Before answering ANY CEO question about status, emails, people, or follow-ups:

# Source Command Required?
1 Email — john mail-native.js unread --account john + sent --account john YES
2 Email — info mail-native.js unread --account info + sent --account info YES
3 Email — alem mail-native.js unread --account alem + sent --account alem YES
4 Email — alai mail-native.js unread --account alai + sent --account alai YES
5 Email — dev mail-native.js unread --account dev + sent --account dev YES
6 MC tasks — Alem's mc.js list --owner alem --status open YES
7 MC tasks — Blocked mc.js list --status blocked YES
8 Session logs session-search.sh topic <topic> or keyword <keyword> When topic-specific
9 HiveMind hivemind.js query "<topic>" or semantic-query "<topic>" When topic-specific
10 Email briefing ~/system/logs/email-briefing-latest.md YES

Shortcut: node ~/system/tools/ceo-briefing.js --full runs ALL of the above.


"Known Unknowns" Protocol

EVERY briefing MUST end with a "Known Unknowns" section:

## Known Unknowns
- [source I couldn't check] — [why]
- [information gap] — [what would resolve it]

If all sources were checked: ## Known Unknowns: None — all sources checked.


Session Context Rule

When CEO asks about something from a previous session:

  1. FIRST run session-search.sh topic "<topic>" or keyword "<keyword>"
  2. READ the relevant session file(s)
  3. THEN check current state (emails, MC tasks)
  4. Present: What we discussed → What changed since → Current state

CEO Briefing Output Format

Use the structured format from ceo-briefing.js:

# CEO Briefing — {date} {time}

## DECISIONS NEEDED (your call required)
## ACTION REQUIRED (only you can do this)
## WAITING FOR (sent, no response yet)
## COMPLETED SINCE LAST SESSION
## OPEN THREADS (context from previous sessions)
## KNOWN UNKNOWNS

Anti-Patterns (NEVER do these)

  1. "Provjerio sam email" → Which account? ALL accounts? Inbox AND sent?
  2. "Nema ništa novo" → Checked where? When? All 5 accounts?
  3. "Evo cijela slika" → Did you check sessions, HiveMind, MC tasks, ALL emails?
  4. Answering from memory → ALWAYS verify with tools. Memory is unreliable across sessions.
  5. Checking 1-2 accounts → ALL 5 accounts (john, info, alem, alai, dev) or explicit statement about what was skipped
  6. "Čeka odgovor X sati" → Did you verify the THREAD? Subject changes ("Re: ... — new topic") prove replies exist. Inbox DB status can be stale. ALWAYS check thread chain before reporting email as unanswered. (Added 2026-03-01, ZAKON #10 violation)

Enforcement


Ljestvica (ZAKON #1)

This is a RULE + TOOL + HOOK fix (3 layers):

No Agent Persona as Public Author

Pravilo — Agent persona NIKAD nije public author credit

Date: 2026-04-19 Scope: sve ALAI agente (Vizu, CodeCraft, FlowForge, Datavera, Proveo, Securion, Lexicon, Finverge, Proxima, Skybound, AgentForge, Helixsupport, Skillforge)

Pravilo

Ni jedan tekst koji ide van ALAI sistema (web stranice, klijentske ponude, email-ovi, PDF-ovi, socijalni mediji, slide deckovi) ne smije imenovati Claude agent personu kao autora ili izvor.

Šta je agent persona?

Claude agent persone su interne routing oznake za dispatching:

Svi su imena stvarnih ekspertnih osoba u javnom svijetu, korištena kao interne routing oznake. ALAI ih nema zaposlene, nema license za njihova imena, ne predstavlja ih kao svoj tim.

Šta je dozvoljeno kao author credit

Zašto

  1. Pravno: korištenje stvarnog imena javne osobe za sadržaj koji on nije napisao može biti klevetnička ili impersonacijska tužba
  2. Etički: krivotvorenje izvora
  3. Brand integritet: ALAI je AI-native agencija — naš diferencijator je sistemski rad, ne lažne individualne rep tags
  4. Klijenti nisu idioti: ako LinkedIn provjera pokaže da "Petter Graff" nije u ALAI-u, gubimo povjerenje u sekundi

Kako primijeniti

Kod pisanja bilo kojeg public materijala:

  1. Ako vidiš prompt koji traži "write as Petter Graff" / "brad frost thinks" / itd — pretvori u interno korištenje, ne u krajnji tekst
  2. Finalni copy koristi "ALAI" kao subject
  3. Interni memo smije spomenuti personu (npr. ovaj dokument), public ne smije
  4. Code comments, commit messages, docs specifikacije — interno OK

Kod ReportBack-ova agenata:

Incident koji je pokrenuo pravilo

2026-04-19: alai.no/ucenje je imalo 22 pojavljivanja "Petter Graff" kao author credit u footer-ima i pullquotes. CEO Alem je uočio i tražio uklanjanje. Vizu agent je uradio replace na "ALAI, 2026". Commit 6c19257 na alai-web repou.

Povezani dokumenti

Verifikacija pre-merge

Prije push-a bilo kojeg public fajla, agenti trebaju pokrenuti:

# Grep za poznate agent personas
grep -iE "petter graff|brad frost|lea verou|kelsey hightower|chip huyen|parisa tabriz|angie jones|martin kleppmann|bruce momjian|markos zachariadis|paul hudson|lee robinson|hadi hariri|georgi gerganov" <file>

Ako vrati match u public materijalu (ne u internal docs, ne u specialist-mapping.json) → STOP, revizija potrebna.

DNS & Domain Inventory Verification Protocol

DNS & Domain Inventory Verification Protocol

Rule ID: DNS-VERIFY-001
Effective Date: 2026-04-20
Owner: FlowForge (DevOps)
Applies To: All agents adding domains to hosting platforms or inventory docs


Rule Statement

Every domain added to hosting platforms or ALAI inventory MUST pass DNS + RDAP registry verification BEFORE deployment or documentation.

This rule prevents typos, phantom domains, and inventory errors from propagating through systems.


When This Rule Applies

BEFORE any of these actions:

  1. Adding domain to hosting platform (Vercel, Cloudflare Pages, GCP, Azure)
  2. Updating alai-hosting-inventory.md with new domain
  3. Creating DNS records (A, CNAME, NS)
  4. Documenting client domains in BookStack
  5. Writing domain into specs, blueprints, or task descriptions

Triggers:


Verification Steps

1. DNS Resolution Check

Command:

dig +short {DOMAIN} A

Expected output:

2. RDAP Registry Check (PRIMARY VALIDATION)

Purpose: Verify domain is actually registered in TLD registry (catches typos)

Command:

curl -sS "https://rdap.nic.{TLD}/domain/{DOMAIN}" | jq -r '.handle // .ldhName // "NOT_FOUND"'

TLD-specific RDAP servers:

TLDRDAP Base URL
.nohttps://rdap.norid.no/domain/
.comhttps://rdap.verisign.com/com/v1/domain/
.iohttps://rdap.nic.io/domain/
.prohttps://rdap.nic.pro/domain/
.ba(no public RDAP, use WHOIS)
.rs(no public RDAP, use WHOIS)

Expected output:

3. WHOIS Fallback (for TLDs without RDAP)

Command:

whois {DOMAIN} | grep -i "domain name\|status\|registrar"

4. Registrar Identification

Command (via RDAP):

curl -sS "https://rdap.nic.{TLD}/domain/{DOMAIN}" | jq -r '.entities[] | select(.roles[] == "registrar") | .vcardArray[1][] | select(.[0] == "fn") | .[3]'

Purpose: Replace generic "Third Party" with actual registrar name

5. Expiry Date Check

Command (via RDAP):

curl -sS "https://rdap.nic.{TLD}/domain/{DOMAIN}" | jq -r '.events[] | select(.eventAction == "expiration") | .eventDate'

Failure Actions

If domain fails RDAP check (404 error):

DO NOT:

INSTEAD:

  1. Verify spelling with client/team
  2. Check if domain is registered
  3. Flag as TYPO_OR_MISSING status
  4. Update requester

Inventory Standards

Required fields for every domain entry:

DomainRegistrarNS ProviderHostingRepoStackExpiryStatus
example.comNamecheapCloudflareCF Pages~/pathNext.js2027-01-15✅ LIVE

Field validation:


Incident: kenyhot.pro Typo (2026-04-20)

What happened:

Why this rule prevents it:

Prevention checklist:


Exceptions

This rule does NOT apply to:

  1. Internal-only domains (localhost, *.local, *.internal)
  2. Development subdomains on verified parent domain
  3. IP-based access (e.g., Azure VM via IP)

Partial verification for:


Compliance

Enforcement:

Audit frequency:


References:


Created by: ALAI, 2026
Last synced: 2026-04-20
Source: /Users/makinja/system/rules/dns-inventory-verification.md

CF-Proxied Automation APIs — Whitelist BIC (INFRA-CF-001)

Rule: CF-Proxied Automation APIs — Whitelist BIC

ID: INFRA-CF-001
Priority: MEDIUM
Created: 2026-04-20
Related incident: LightRAG 46h outage (MC #8487 followup)

Rule

Svaki CF-proxied hostname koji servisira headless HTTP klijente (LightRAG, email-agent, pi-orchestrator, automation daemone, containerized services) MORA imati Cloudflare Configuration Rule koja disable-uje Browser Integrity Check (BIC).

Why

BIC filtrira requestove na osnovu User-Agent-a i fingerprint-a. Python urllib / requests / httpx default UA triggeruje block (HTTP 403, error code 1010) čak i ako je IP u Access bypass listi. BIC layer se evaluira PRIJE Access policies.

Ovo se ne vidi odmah jer:

How to apply

Za svaki novi CF-proxied automation endpoint:

  1. Identifikuj hostname (npr. ollama.basicconsulting.no)
  2. Kreiraj Configuration Rule kroz CF API:
    # Get zone ID first
    export CF_ZONE_ID="<your-zone-id>"
    export CF_API_TOKEN="<your-cloudflare-api-token>"
    
    # Create rule
    curl -X PUT "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/rulesets/phases/http_config_settings/entrypoint" \
      -H "Authorization: Bearer ${CF_API_TOKEN}" \
      -H "Content-Type: application/json" \
      --data '{
        "rules": [{
          "action": "set_config",
          "action_parameters": {"bic": false},
          "expression": "(http.host eq \"HOSTNAME\")",
          "description": "Disable BIC for HOSTNAME (automation clients)",
          "enabled": true
        }]
      }'
    
  3. Verifikuj: test query sa Python default UA — mora vratiti 200

Hostnames koji trebaju ovu zaštitu (live list)

Evidence

Gotchas

Technical Details

Problem:
LightRAG ingestion daemon (Python container) could not reach ollama.basicconsulting.no — all requests returned HTTP 403 with Cloudflare error code 1010 (Browser Integrity Check block). This was not visible in initial testing because:

Root cause:
Cloudflare Access IP bypass policies evaluate AFTER Browser Integrity Check. Even with correct Access service token headers, BIC rejected the request based on User-Agent string before the Access policy could allow it.

Solution:
Configuration Rule that disables BIC for the specific hostname. Expression: (http.host eq "ollama.basicconsulting.no"). This allows automation clients through while preserving other Cloudflare security layers (WAF, DDoS, Access).

Time to incident:
46 hours from LightRAG Azure migration (2026-04-18) to detection (2026-04-20 21:00). Initial hypothesis: Neo4j memory pressure, NSG IP rotation, Azure network issue. All false. Real cause: CF security layer blocking automation client UA.

Fix time:
11 minutes from root cause identification to deployment + verification.


Generated by: ALAI, 2026

ZAKON FEASIBILITY — Pre-Execution Constraint Consistency Check

ZAKON FEASIBILITY: Pre-Execution Constraint Consistency Check

Status: ENFORCED Created: 2026-04-26 Trigger: Every task before execution (John + every specialist agent) Origin: 2026-04-26 incident — "odbroji do 10 ali počni od 11" — agent attempted to satisfy mutually exclusive constraints by stretching interpretation instead of recognizing the contradiction.

The Rule

Before executing ANY task, the agent MUST verify that all stated constraints are mutually satisfiable. If they are not — STOP. Do NOT attempt the task. Return to the user with:

  1. The specific constraints that conflict (named explicitly, A vs B)
  2. Why they cannot both hold (one-sentence proof)
  3. A clarifying question offering 2 disambiguated interpretations

What Counts as a Contradiction

What is NOT a Contradiction (do not over-trigger)

The Mechanical Check (4 questions, in order)

  1. Constraint inventory: list every explicit constraint as "A1, A2, ... An"
  2. Pairwise conflict: for each (Ai, Aj), is there a state where both hold? If no → flagged
  3. Range/numeric sanity: if numbers are involved, evaluate the proposed range (start, end, direction). Does a valid sequence exist?
  4. Resource/authority sanity: does the action require a permission/resource excluded by another constraint?

If ANY pair fails → STOP, report contradiction, do not improvise an interpretation.

Output Format When Contradiction Detected

CONTRADICTION DETECTED — task halted before execution.

Constraints in conflict:
  • A: <verbatim quote from request>
  • B: <verbatim quote from request>

Why incompatible: <one sentence, no hedging>

Clarification needed. Did you mean:
  (1) <interpretation 1, e.g., drop constraint A>
  (2) <interpretation 2, e.g., drop constraint B>

Anti-Patterns Banned by This ZAKON

Enforcement

Reporting Violation

If an agent executes a contradictory task without flagging:

  1. Document in feedback_contradictory_task_detection.md with the verbatim prompt
  2. Add to GOTCHA framework as recurrence-prevention test case
  3. Update this ZAKON if a new contradiction class was missed

Discovering a contradiction is a SUCCESS, not a failure. It saves wasted execution and surfaces a real ambiguity in the user's intent. Never paper over it.

Skill: prompt-forge — Pre-flight team for H/BLOCKER tasks

Skill: prompt-forge — Pre-flight team for H/BLOCKER tasks

Skill path: ~/.claude/skills/prompt-forge/

Description

Pre-flight team meta-design for H/BLOCKER MC tasks. Spawns 5 specialist agents (petter-graff + devils-advocate + anthropic-chief-architect + openai-chief-architect + chip-huyen) in parallel. Synthesizer (petter-graff in 2nd role) combines into unified prompt with preserved <disagreements> XML field.

Output: ~/system/prompts/forged/<mc_id>.md

Trigger: /prompt-forge <mc_id>

When to Use

Run prompt-forge when ALL of the following apply:

Skip prompt-forge (go directly to /mehanik) when ANY of:

Workflow

  1. Preconditions: Verify MC task exists, status is open/in_progress, scope gate passes
  2. Parallel dispatch: Spawn all 5 panelists simultaneously (Sonnet × 4, Opus × 1)
  3. Synthesis: Petter Graff in synthesis role combines outputs into unified prompt
  4. Output format: 8 sections including mandatory <disagreements> block
  5. Next step: Feed forged prompt into /mehanik

Cost and Scope Gates

Output Format (8 sections)

The forged prompt at ~/system/prompts/forged/<mc_id>.md contains:

  1. OBJECTIVE — Single paragraph: what and why
  2. CONTEXT FILES — Explicit list with absolute paths
  3. DELIVERABLES — Numbered artifacts with acceptance signals
  4. CONSTRAINTS — Hard limits (what NOT to do)
  5. SUCCESS CRITERIA — Machine-verifiable checklist
  6. AGENT ROUTING — Which specialist handles this
  7. <disagreements> — Raw panelist conflicts, unsmoothed
  8. FOOTER — Synthesis flag, cost estimate, next step

v0.1 Deferred (post-Akershus 2026-05-04)

References


Author: ALAI, 2026

Last updated: 2026-04-28

Skill: task-postflight — Post-dispatch validation + learning loop

Skill: task-postflight — Post-dispatch validation + learning loop

Skill path: ~/.claude/skills/task-postflight/

Description

Closes the loop on H/BLOCKER MC tasks after specialist dispatch. Runs Proveo (Angie Jones) validation against MC acceptance criteria, detects anomalies, invokes /learning-opportunity if anomaly found (root cause + memory entry), and writes mc.js ready submission with evidence path.

Trigger: /task-postflight <mc_id>

Use AFTER: Specialist dispatch completes for any task that went through /prompt-forge or any H/BLOCKER task.

Workflow

  1. Preconditions: Verify MC task exists, status is in_progress, evidence dir exists (or flag MISSING)
  2. Proveo dispatch: Spawn Angie Jones (Proveo) to validate against acceptance criteria
  3. Anomaly detection: Parse Proveo report, classify failure type and severity
  4. Learning-opportunity: Invoke learning loop on PARTIAL/FAIL verdicts (skip if PASS or known issue)
  5. Memory entry: Write feedback file if learning-opportunity returns memory path
  6. MC ready: Submit mc.js ready with evidence summary (or BLOCK on FULL_FAILURE)
  7. Audit trail: Append JSON line to ~/system/postflight-log.jsonl

Proveo Integration

Angie Jones (Proveo) validates against MC acceptance criteria. Expected output:

Report written to: /tmp/postflight-<mc_id>/proveo-report.md

Anomaly Classification

Verdict Anomaly Class Action
PASS (all criteria) ANOMALY:NONE Skip to mc.js ready
PASS (some SKIP) ANOMALY:PARTIAL_COVERAGE Learning-opportunity (LOW severity)
PARTIAL ANOMALY:PARTIAL_FAILURE Learning-opportunity (MEDIUM severity)
FAIL ANOMALY:FULL_FAILURE Learning-opportunity (HIGH severity) + BLOCK mc.js ready
Proveo timeout/error SYNTHESIS:DEGRADED Inline fallback check + escalate to John

Learning-Opportunity Loop

Invoked when anomaly class is not NONE. Receives:

Expected output:

Skip learning-opportunity if:

Cost and Limits

Failure Modes

Condition Action
Proveo unavailable SYNTHESIS:DEGRADED — inline fallback, flag in mc.js notes, escalate
Proveo timeout Same as unavailable
learning-opportunity fails Log LEARNING:FAILED, skip memory entry, continue with warning
MEMORY.md write fails Log error, skip index update, include content inline in mc.js notes
ANOMALY:FULL_FAILURE Block mc.js ready, write failure-summary.md, report re-dispatch required

Audit Trail

Every invocation appends one JSON line to ~/system/postflight-log.jsonl:

{"mc_id":9959,"timestamp":"2026-04-28T12:12:00Z","proveo_verdict":"PASS","anomaly_class":"NONE","learning_invoked":false,"ready_status":"submitted","cost_estimate":"$0.15"}

Log is lightweight observability — does NOT replace evidence files.

v0.1 Deferred (post-Akershus 2026-05-04)

References


Author: ALAI, 2026

Last updated: 2026-04-28

ZAKON #25 — Pre/Post-flight Mandatory (H/BLOCKER)

ZAKON #25 — Pre/Post-flight Mandatory (H/BLOCKER)

Source: ~/system/rules/john-operating-system.md line 77

Instituted: 2026-04-28 (MC #9941 panel approved 4/5 + DA timing dissent preserved)

The Rule

WHEN task priority = H AND (BLOCKER label OR multi-component OR effort ≥ M)

THEN workflow MUST be:

  1. /prompt-forge <mc_id> — 5-panel pre-flight, unified prompt
  2. /mehanik "task" <path> <mc_id> — gate clearance (existing)
  3. Specialist dispatch with forged prompt
  4. /task-postflight <mc_id> — Proveo validation + learning loop

When to Skip /prompt-forge

Skip directly to /mehanik when ANY of:

SKIP /task-postflight? Never. Mandatory closure for H/BLOCKER.

Decision Tree

HAS the task been classified as H + BLOCKER/multi-component?
  YES → /prompt-forge mandatory
  NO  → skip directly to /mehanik

AFTER specialist dispatch completes:
  /task-postflight <mc_id> — ALWAYS for H/BLOCKER

Why This Exists

Eliminates reactive scope creep. Historical incidents:

Solution: 5-expert panel (Petter Graff, Devils Advocate, Anthropic CA, OpenAI CA, Chip Huyen) produces better prompts for H/BLOCKER tasks. Disagreements preserved unsmoothed in <disagreements> XML block.

How to Apply

For John (orchestrator):

  1. Classify incoming task: priority, labels, effort, components
  2. If H + BLOCKER/multi-component → invoke /prompt-forge <mc_id>
  3. Wait for forged prompt at ~/system/prompts/forged/<mc_id>.md
  4. Pass forged prompt to /mehanik as Phase A input
  5. After Mehanik clearance → dispatch specialist with forged prompt
  6. After specialist completes → invoke /task-postflight <mc_id>
  7. Wait for Proveo validation + learning loop
  8. Submit mc.js ready only after postflight clears

For specialists (builders):

No change. You receive a forged prompt (if H/BLOCKER) or regular prompt (if M/L). Execute as normal. Postflight validation happens after you finish.

Cost Guardrails

v0.1 Deferred Items

Deferred to post-Akershus (after 2026-05-04):

Panel Approval Record

MC #9941: ZAKON #25 proposal

Panelist Vote Key Argument
Petter Graff APPROVE Scope creep root cause = ambiguous prompts. 5-expert forge addresses this.
Anthropic CA APPROVE Disagreements XML preserves tension → better builder context.
OpenAI CA APPROVE Post-flight learning loop closes gap between intent and execution.
Chip Huyen APPROVE Cost acceptable if BFPR ≥70% (empirical gate required).
Devils Advocate DISSENT Timing risk: 5-panel forge adds 2-5 min overhead. May bottleneck on urgent H tasks. Proposes fast-path override for P0 incidents.

CEO decision: Approved 4/5. DA timing dissent preserved — fast-path override deferred to v0.2 based on empirical P0 incident latency data.

References


Author: ALAI, 2026

Last updated: 2026-04-28

ZAKON NETWORK EGRESS — 3-Source Public IP Verification

ZAKON NETWORK EGRESS — Verification Protocol

Public IP za CF whitelist / firewall rules MORA biti verified iz 3 nezavisna izvora. curl ifconfig.me SAM nije dovoljan — vraća VPN exit ako je VPN klijent aktivan.

Date: 2026-04-28 Origin: ANVIL CF whitelist incident. John napravio 4 reverzalne tvrdnje o ANVIL public IP-u u jednoj sesiji. Memory imala stale 46.46.247.60. curl iz Studio sesije vratio 46.46.247.96 (VPN exit). Stvarni LAN egress = 92.221.168.61 (Tailscale peer connections confirmed). Tri nezavisna izvora bi rezultat dali odmah, bez 30 min iteracija.


Rule

Svaki task koji uključuje public IP whitelist, firewall rule, CF Configuration Rule, ili IP-based access policy MORA proći ovaj 3-source verification PRIJE dispatch-a:

Source 1 — Outbound HTTP (curl)

curl -s https://api.ipify.org
curl -s https://ifconfig.me
curl -s https://ipinfo.io/ip

WARNING: Ako VPN klijent aktivan, ovo daje VPN exit, ne ISP egress.

Source 2 — DNS-based (bypassuje HTTP routing)

dig +short myip.opendns.com @resolver1.opendns.com
dig +short TXT o-o.myaddr.l.google.com @ns1.google.com

DNS upit obično ide kroz drugačiji routing nego HTTP, otkriva VPN.

Source 3 — Peer connection address (ground truth)

tailscale status | grep "direct"
# Vidi peer connections — `direct PEER_IP:PORT` = stvarni egress IP koji peers vide

Authoritative za LAN egress — to je IP koji eksterni endpoints VIDE.

VPN detection (mandatory check)

ifconfig | grep -c "^utun"

Ako > 1 (Tailscale je 1) → VPN klijent aktivan. curl rezultat se NE smije koristiti bez Source 2/3 confirmation.


Reconciliation matrix

Source 1 (curl) Source 2 (DNS) Source 3 (Tailscale) Conclusion
same same same ✅ Verified, safe to whitelist
different same Source 3 matches Source 3 ⚠️ VPN aktivan — koristi Source 3
different different different 🛑 Pita CEO, ne dispatchuj

When to apply


Anti-patterns (explicit, observed 2026-04-28)

  1. "curl ifconfig.me kaže X, znači X" — false ako VPN aktivan
  2. "Memory kaže X, znači X" — false, memory može biti stale (DHCP rotation, VPN exit rotation)
  3. "Studio i ANVIL su na istom LAN-u, dijele IP" — false ako VPN drugačije routes outbound vs LAN
  4. "Pretpostavljam dvije mašine, X i Y" — provjeri jesu li alias/ista mašina prije diskusije

Rashad Khalifa — ALAI Editorial Policy (2026-04-28)

Rashad Khalifa — ALAI Editorial Policy (2026-04-28)

Date: 2026-04-28
Decision: CEO Directive — Option C
Status: Executed
Tags: decision, editorial-policy, quran-research, alai.no/ucenje


1. Decision Summary

On 2026-04-28, CEO Alem Basic issued a directive to remove all mentions of the name "Rashad Khalifa" from ALAI's public-facing and research materials related to the Quran numerology project (alai.no/ucenje).

Option selected: Option C — Remove the name entirely, retain critical/distancing framing.

Rationale:
Rashad Khalifa's association with the "Submitters" group (which denies hadith authenticity and claims alteration of Quranic verses) is considered heretical in mainstream Sunni Islamic scholarship. ALAI does not wish to carry any association with this lineage, even in a critical or distancing context.

Prior state:
The CEO was not aware of Khalifa's theological controversies when the initial research materials were drafted. Upon learning the full context, he authorized immediate removal.


2. Background — Rashad Khalifa

Rashad Khalifa (1935–1990) was an Egyptian-American biochemist who claimed to have discovered the "Miracle of 19" in the Quran in 1974. His central assertion was that the Quran's structure is governed by mathematical patterns based on the number 19.

Key claims:

Association with Submitters:
Khalifa founded the "Submitters" movement, which rejects hadith literature and asserts that the Quran alone is sufficient. This position is considered outside the boundaries of orthodox Sunni Islam.

ALAI's position:
ALAI's research on the number 19 in the Quran was developed independently and does not endorse, cite, or build upon Khalifa's theological framework. The mathematical and sonification work stands on its own empirical basis.


3. What Was Changed

Total scope:

Per-file breakdown: See /tmp/lexicon-cleanup-summary.txt for full detail.

Verification:

grep -ric "Khalifa|Rashad" [all edited files] → 0 results

4. What Was NOT Changed

Unchanged materials:
The folder Public/Research/quran-19-fin-unsa-2026-04-27/emails/ (4 files) was intentionally left unchanged.

Reason:
These emails were already sent to professors at the University of Sarajevo (Dr. Jovan Fatić, Dr. Jasmin Jašić, and the dean). Re-cleaning already-sent correspondence would re-open a conversation that has concluded. The cleanup applies to future outreach only, not retroactive communication.

MD5 verification:
All email files verified bit-identical before/after cleanup.


5. Canonical Replacement Texts

All instances of biographical introduction or citation of Rashad Khalifa were replaced with the following standardized texts.

Bosnian/Serbian (BS):

Numeričke obrasce vezane za broj 19 u Kur'anu sistematski je istraživao raniji autor 1970-ih godina. Njegova centralna tvrdnja o djeljivosti ukupnog broja slova Kur'ana sa 19 nije preživjela ispravnu računarsku verifikaciju (327.793 mod 19 = 5 pri Hafs ortografiji sa pravilno uračunatim slovom alif-wasla, U+0671). Njegova kasnija tvrdnja o uklanjanju dva ajeta iz Kur'ana odbačena je od strane islamskih učenjaka. Naša metodologija razvijena je nezavisno i fokusira se na specifične, pojedinačno verifikovane numeričke odnose te na 19-TET sonifikaciju, bez teoloških zaključaka.

English (EN):

Numerical patterns related to the number 19 in the Quran were first systematically studied by an earlier author in the 1970s. His central claim that the total letter count of the Quran is divisible by 19 did not survive correct computational verification (327,793 mod 19 = 5 under Hafs orthography with alif-wasla, U+0671, properly counted). His later claim about removing two verses from the Quran was rejected by Islamic scholars. Our methodology was developed independently and focuses on specific, individually verified numerical relationships and 19-TET sonification, without theological conclusions.

Citation pattern (all languages):

[earlier 1970s research, citation withheld]

Inline mentions:


6. Process Linkages

Artifact Location
MC Task #9967
Mehanik clearance /tmp/mehanik-cleared-9967 (hash: 72ada25658b8)
Audit trail /tmp/lexicon-cleanup-summary.txt
Lexicon agent a06503a22afd0fda8 (markdown edits)
Vizu agent ae061e8013a7428b9 (HTML edits)
Linguistic validation Dževad Jahić (pre-flight + post-edit verification)

7. Future Outreach Guidance

When communicating ALAI's Quran research to external parties (academics, media, institutions), follow these principles:

  1. Do not mention the name "Rashad Khalifa" in any capacity.
  2. Use the canonical replacement texts provided in Section 5.
  3. Citation format: [earlier 1970s research, citation withheld]
  4. Inline references: Use distancing language ("earlier 1970s claims", "ranijih 1970-ih pristupa").
  5. Framing: Emphasize that ALAI's methodology was developed independently and focuses on:
    • Specific, individually verified numerical relationships
    • 19-TET musical sonification of Quranic text
    • No theological conclusions

Purpose of distancing:
To demonstrate academic rigor and intellectual independence without providing a platform to controversial theological claims.


8. Acceptance Criteria (Verified Complete)



Prepared by: Skillforge (John → Lexicon → Vizu chain)
Reviewed by: Dževad Jahić (Lexicon)
Approved by: Alem Basic (CEO)
Execution date: 2026-04-28

ZAKON ARCHIVE FIRST — archive.alai.no Primary Destination

ZAKON ARCHIVE FIRST — archive.alai.no je primarno odredište

Sve vrijedne dokumente i kontakte MORAJU biti na archive.alai.no (Paperless-ngx). Lokalno (~/) zadržati SAMO tmp/ i radne fajlove. Sve Claude instance MORAJU pretraživati i transferovati.

Date: 2026-04-28 Origin: ALAI archive.alai.no je single source of truth za firmsku dokumentaciju. Kroz Bilko (HR/BiH/Srbija) druge kompanije će takođe koristiti istu instancu pod ugovorom kao revenue stream — multi-tenant SaaS.


Rule

Šta IDE u archive.alai.no (uvijek)

Šta OSTAJE lokalno

Anti-pattern (ZABRANJENO)


Mandate za sve Claude instance

Svaka Claude sesija MORA:

  1. Periodično skenirati lokalna mjesta za vrijedne fajlove koji nisu u archive (jednom dnevno minimum, ili na trigger):

    find ~/ALAI ~/Public ~/work -type f \( -name "*.pdf" -o -name "*.docx" \) ! -path "*/.claude/*" ! -path "*/node_modules/*"
    
  2. Pretražiti email DB za nove correspondents (po sender + frequency):

    SELECT from_addr, from_name, COUNT(*) FROM emails 
    WHERE classification != 'SPAM' GROUP BY from_addr ORDER BY COUNT(*) DESC;
    
  3. Klasifikovati i upload-ovati nove fajlove kroz dedup-aware classifier (/tmp/paperless-classify-v2.py ili equivalent), prema schemi u BookStack page "archive.alai.no — Paperless-ngx Setup & Operations".

  4. Auto-create correspondents kad se sretne novi sender koji ima >= 2 emails ili je u known partner list-i.

  5. Reportovati u sesiji: "X novih dokumenata uploaded, Y new correspondents, Z failed dedupes."

  6. Ne brisati lokalne kopije automatski — samo migrate. Cleanup je posebna odluka, traži CEO confirmation.


Multi-tenant kontekst (Bilko HR/BiH/Srbija)

Bilko će prodavati archive.alai.no pristup kao SaaS feature za partner banke i klijente:


Enforcement


Reference

ZAKON PI2 — Deploy Verification Protocol

ZAKON PI2 — Deploy Verification Protocol (enforced)

Status: ACTIVE — 2026-04-22 Origin: ALAI incident 2026-04-22 (Bilko demo fix deployed to wrong branch, Intesa content leaking on public URL, CI broken for 7 days undetected) Owner: pi-orchestrator v2 Violation penalty: task auto-blocked, re-work required, logged to MC


Why This Exists

On 2026-04-22 a 3-bug Bilko fix sprint ran for 2 hours and produced zero live changes because:

All these are preventable with 6 hard checks. This ZAKON makes them mandatory.


The 7 Hard Checks (every deploy task)

Check 0 — Mehanik Clearance (NEW — 2026-04-25, MC #9223 root-cause)

Before any deploy preflight check (curl, git log, gh run list) — verify Mehanik gate clearance:

MC_ID={your_task_id}
MARKER="/tmp/mehanik-cleared-$MC_ID"

if [[ ! -f "$MARKER" ]]; then
  echo "BLOCKED: No Mehanik clearance for MC #$MC_ID. Run /mehanik first."
  exit 2
fi

MARKER_AGE=$(( $(date +%s) - $(stat -f %m "$MARKER") ))
if [[ $MARKER_AGE -gt 14400 ]]; then
  echo "BLOCKED: Mehanik clearance for MC #$MC_ID is stale (>4h). Re-run /mehanik."
  exit 2
fi

If Check 0 fails → STOP. Do not proceed to Check 1 (curl preflight). Run /mehanik to obtain clearance, then retry.

Rationale: Per /tmp/9223-final-synthesis.md (sentinel-architect), deploy preflight at end-of-pipeline is too late. Pattern completion / scope creep happens BEFORE preflight runs. Mehanik gate at start = deterministic enforcement against hallucinated infra.

Check 1 — DEPLOY MAP must exist

Every repo that deploys MUST have DEPLOY-MAP.md at root:

| Branch | Service | URL | Workflow | Last verified |
|--------|---------|-----|----------|---------------|
| main   | bilko-web | bilko-demo.alai.no | gcp-deploy.yml | 2026-04-22 |

If missing: task blocks. Agent creates DEPLOY-MAP.md before any code change.

Check 2 — Pre-Flight Discovery (4 commands, no exceptions)

Agent must run and paste output into MC task BEFORE touching code:

curl -sI <target-url> | head -3
git log <target-branch> --oneline -5
gh run list --repo <owner/repo> --branch <target-branch> --limit 3
gcloud run services describe <service> --region <region> --format='value(status.latestReadyRevisionName,status.url)'

If any returns unexpected: STOP, escalate to John. Do not proceed.

Check 3 — Branch Purity Gate (CI)

Every repo gets .github/workflows/branch-purity.yml:

find apps/web/app -type d \( -name "intesa-*" -o -name "corpint-*" -o -name "lumiscare-*" -o -name "<client>-*" \) | grep . && exit 1 || exit 0

Client-specific routes MUST live on dedicated branch + dedicated service. Never on main. Registry: ~/system/rules/client-prefix-registry.md lists all reserved prefixes.

Check 4 — CI Health Pre-Check

Before any push to a deploy branch:

gh run list --repo <owner/repo> --branch <branch> --limit 5 --json status,conclusion

If last 5 runs all failure → CI is broken → fix CI first OR use documented manual deploy path (written in DEPLOY-MAP.md). No push on broken pipeline.

Check 5 — Post-Deploy Evidence Gate

MC task CANNOT move to done without ALL three:

  1. curl -sI <URL> returning 200 (paste in task notes)
  2. Playwright CLI screenshot saved to docs/evidence/<task-id>/
  3. gcloud run revisions list showing NEW revision serving 100% traffic

mc.js done without evidence = blocked automatically.

Check 6 — Auth Scope Audit (session start)

bash ~/system/boot.sh runs:

gh auth status --show-token 2>&1 | grep -E "Token scopes|Logged in"
gcloud auth list --format='value(account,status)'

If missing workflow scope OR gcloud expired → BLOCKER logged to MC, Alem notified before any deploy task dispatched.


Enforcement

Level 1 — Agent self-enforcement

Every pi2-dispatched agent includes this rule in its system prompt. Agent refuses to proceed if any check fails.

Level 2 — Hook enforcement

~/.claude/hooks/pre-deploy-check.sh:

Level 3 — MC auto-block

mc.js done <id> for tasks with category: deploy|frontend|backend|devops AND priority: H requires:


Client Prefix Registry (Check 3 reference)

Prefixes that MUST NOT appear on main:

Add new entries here when client-specific branches spawn.


How to Apply

When a task says "fix demo" / "deploy X" / "push fix":

  1. Open DEPLOY-MAP.md — confirm branch/service/URL
  2. Run 4 pre-flight commands — paste output in MC task
  3. Verify CI health — if red, STOP
  4. Make change, push
  5. Run post-deploy evidence gate — 3 artifacts
  6. Only then: mc.js done

If any check returns unexpected: do not invent a workaround. Report to John.


Escape Hatch

Single emergency override: CEO-only command mc.js done <id> --force --ceo-override "<reason>" bypasses Checks 1-5. Logged to audit, reviewed weekly by John.


Change Log


Anti-Hallucination Evidence Verification Protocol — V2

Anti-Hallucination Evidence Verification Protocol — V2

Author: Petter Graff (CodeCraft — Architecture Lead)
Date: 2026-05-07
MC: #99651-v2
Status: ready_for_review
Source spec: ~/system/specs/anti-hallucination-protocol-v2.md
V1: ~/system/specs/anti-hallucination-protocol.md (DO NOT OVERWRITE)
Prior art: ~/system/specs/anti-lying-architecture.md (2026-03-24)
ZAKON #30 registered: 2026-05-22 (CEO verbal "sve" session 880aba4d)

§1 Executive — V1 Failure Mode Named

V1 framed the problem as tamper-evidence plus structural enforcement: SHA-256 per evidence file, mandatory verdict JSON schema, hook-layer rejection of schema-less verdicts. That framing was correct but insufficient. The first real test run (MC #99595) proved the deeper problem: a structurally compliant verdict with a semantically wiggled AC is indistinguishable from a correct one by any V1 check. Martin Kleppmann named the real problem during panel synthesis: this is a Byzantine-fault-tolerant claim authority problem, not a tamper-evidence problem. A tamper-evident lie is still a lie. SHA-256 confirms the file was not replaced after capture. It does not confirm the file proves what the agent claims it proves. V2 reframes accordingly: the threat model is Byzantine, not just accidental; single-signer verdicts are single points of trust failure; the minimum viable quorum requires more than one verifier with independent verification paths; and any agent in the dispatch chain — including the orchestrator — must be structurally empowered to refuse fabricating a verdict when ground-truth is insufficient, not merely culturally expected to do so.

§2 Byzantine Threat Model (New)

The V1 threat model assumed well-meaning agents making honest mistakes under completion pressure. The correct model is Byzantine: any agent in the chain may emit a plausible-looking verdict that is false, either due to incentive misalignment (completion bias) or structural inability to distinguish success from failure (semantically empty ACs).

Orchestrator-AI as Byzantine actor: John faces the same completion pressure as Proveo. MC #99595 demonstrated this: John ran 4 of 6 machine checks, accepted a T5 finalUrl=/login as compliant, and emitted GO-LIVE-READY to the CEO. The orchestrator cannot audit itself.

Tester-AI as Byzantine actor: Proveo can produce a structurally compliant verdict where the acceptance criteria contain OR clauses that make the claim defensible without the intent being satisfied. The T5 AC "dashboard URL reached OR proper error UI" allowed finalUrl=/login to pass.

Tamper-evident lie is still a lie: SHA-256 on a file showing /login is cryptographically valid. The claim "redirect to dashboard confirmed" against that file is false. NIST AU-10/AU-9 (integrity) are separate controls from AC-2/AC-3 (authority). V1 conflated them.

PBFT implication (Martin Kleppmann): PBFT requires 3f+1 nodes to tolerate f Byzantine actors. With one tester and one orchestrator, the system cannot tolerate even one Byzantine actor. Practical minimum: 3 independent verification paths (Proveo tester + John reproducer + evidence-verifier MLX) forming a 2-of-3 quorum for GO-LIVE-READY.

§3 Core Hardening — 5 Convergent Components

3.1 AC Strictness Gate (Mehanik Extension)

Contributing panelists: Petter F-1, Kelsey, Sentinel H6, Parisa.

Before any UAT dispatch, Mehanik MUST run AC strictness review on every acceptance criterion. No OR clauses in outcome ACs. URL assertions must be exact paths. Each AC must include a named evidence type and field. New Mehanik gate field: wiggle_risk: true/false. If any AC has wiggle_risk: true, dispatch is blocked pending rewrite.

3.2 Read-Your-Writes Enforcement

Contributing panelists: Martin 8-DS-4, Petter F-4, Sentinel H5.

The orchestrator cannot accept a verdict it has not independently verified on a different execution path. Before emitting GO-LIVE-READY, John MUST execute the reproducer field from the verdict JSON independently. The result is appended verbatim as john_reproducer_output in the final summary.

{
  "john_reproducer_output": {
    "command": "<reproducer command from verdict JSON>",
    "exit_code": 0,
    "stdout_excerpt": "<first 500 chars of output>",
    "matches_verdict": true
  }
}

3.3 Machine_Check Count Enforcement

Contributing panelists: Petter F-2, Sentinel H5.

Verdict JSON schema gains two mandatory fields: machine_check_count (total defined) and machine_checks_executed (total run). The verdict-contract-validator.sh hook blocks if machine_checks_executed < machine_check_count. Deterministic — no agent judgment required.

3.4 Verdict Authority Quorum (2-of-3, Fencing Token)

Contributing panelists: Martin 8-DS-2, Parisa C2b.

GO-LIVE-READY requires affirmative signal from at least 2 of 3 independent verification paths:

A single-path PASS is PARTIAL, not GO-LIVE-READY. The fencing token is a monotonic integer generated at verdict-issuance time. Expired tokens are NULL regardless of quorum count. Parisa separation of duties: the agent that dispatched the tester (John) cannot produce the final verdict summary unilaterally.

3.5 Verdict TTL and GCS Append-Only Evidence

Contributing panelists: Martin 8-DS-1, Martin 8-DS-3, Parisa.

Every verdict carries an expires_at field (ISO8601, default TTL = 15 minutes). Evidence files MUST be written to GCS before the orchestrator reads them:

gs://alai-audit-evidence/<mc_id>/<timestamp>/<evidence_file>

Bucket policy: object versioning enabled, no-delete IAM (evidence-verifier service account has write-only, not delete).

§4 Secondary Hardening

§5 Refusal Posture — ZAKON #29.1

The Devils-advocate panel member refused the original synthesis dispatch. His stated reasons: "ZAKON NULA violation — write retrospective without tool-verified evidence." This refusal is not a failure mode — it is the correct behavior.

ZAKON #29.1 — Refusal Posture: Any agent in the dispatch chain MAY emit a REFUSED verdict with stated reason when ground-truth evidence is insufficient to make a determination. REFUSED is a valid terminal state that:

The REFUSED posture must be documented in every agent prompt under the VERDICT CONTRACT section, at the same level as PASS/FAIL/PARTIAL/BLOCKED.

§6 Implementation Sequence

P0 — This week: AC Strictness Gate in Mehanik; Read-Your-Writes orchestrator enforcement (john_reproducer_output mandatory); machine_check_count/machine_checks_executed enforcement in verdict-contract-validator.sh.

P1 — Next week: Verdict authority quorum (evidence-verifier MLX as mandatory third voter); expires_at TTL field; gate-verdict-validate step in cloudbuild; GCS audit evidence bucket.

P2 — Within month: Hallucination drill LaunchAgent; feedback-memo-auto-MC PostToolUse hook; REFUSED verdict type in all agent prompts; Verdict-contract-validator Task PostToolUse hook.

§7 New ZAKONs Registered

§8 Open CEO Decisions

Source MC: #99732 | Published: 2026-05-22 | CEO authorization: verbal "sve" session 880aba4d | Related: feedback_proveo_hallucination_2026-05-07, feedback_john_is_hallucinator_panel_confirmed_2026-05-07

Dispatch Contract Template — Anti-Hallucination V2

Dispatch Contract Template — Anti-Hallucination V2

Extracted from: Anti-Hallucination Evidence Verification Protocol V2 (§3, §4)
MC: #99732
Published: 2026-05-22
Use for: All UAT/QA dispatches where a verdict will be issued to CEO

Overview

This template defines the mandatory fields and structure for any dispatch that will result in a GO-LIVE-READY verdict. It implements ZAKON #29, #29.1, #29.2, and #30.

Pre-Dispatch Checklist (Mehanik Gate)

Verdict JSON Contract (Mandatory Fields)

{
  "verdict": "PASS | FAIL | PARTIAL | BLOCKED | REFUSED",
  "mc": "<task_id>",
  "agent": "<agent_slug>",
  "timestamp": "<ISO8601>",
  "expires_at": "<ISO8601, timestamp + 15min default>",
  "machine_check_count": 5,
  "machine_checks_executed": 5,
  "evidence_files": [
    {
      "path": "<absolute path or GCS URI>",
      "type": "playwright-trace | curl-output | json-response | screenshot | log",
      "field": "<specific field, e.g. finalUrl, http_code, claims.sub>",
      "value": "<actual value observed>",
      "expected": "<expected value from AC>",
      "match": true,
      "sha256": "<hex>"
    }
  ],
  "claims": [
    {
      "claim_id": "C1",
      "ac_text": "<verbatim AC text>",
      "evidence_ref": "evidence_files[0]",
      "machine_check": "<exact bash command to reproduce>",
      "intent_proof": "<one sentence: how evidence proves AC intent>",
      "result": "PASS"
    }
  ],
  "refused_reason": "<required if verdict=REFUSED; must cite specific missing evidence>"
}

REFUSED Verdict Rules (ZAKON #29.1)

An agent MUST emit REFUSED (not PARTIAL or BLOCKED) when ground-truth evidence is insufficient to determine if the AC intent is satisfied, the reproducer cannot run, or evidence files cannot be captured.

REFUSED handling: does NOT count as FAIL; DOES auto-escalate to CEO via Slack within 15 minutes; DOES suspend dependent task completions until CEO arbitrates.

Orchestrator Read-Your-Writes Obligation (ZAKON #29.2)

After receiving a PASS verdict from Proveo, John MUST execute the machine_check command from at least 2 critical claims independently (NOT re-delegating to Proveo), then append john_reproducer_output to the final GO-LIVE-READY summary. If matches_verdict: false — GO-LIVE is BLOCKED regardless of Proveo verdict, sha256 match, or CEO_APPROVED token.

Quorum Requirement for GO-LIVE-READY (ZAKON #30)

GO-LIVE-READY requires 2-of-3 paths confirmed:

PathActorEvidence
AProveo testerPASS verdict + evidence_files + sha256
BJohn reproducerjohn_reproducer_output.matches_verdict = true
Cevidence-verifier MLXCONFIRMED from gemma-4-26b-mlx, cross-checks sha256 + intent_proof

Single-path PASS = PARTIAL, not GO-LIVE-READY. A fencing token (monotonic integer) expires at expires_at — expired tokens are NULL regardless of quorum.

GCS Evidence Chain of Custody

  1. Proveo writes evidence to: gs://alai-audit-evidence/<mc_id>/<timestamp>/<filename>
  2. GCS bucket: object versioning enabled, no-delete IAM
  3. Orchestrator reads from GCS URI, not /tmp path
  4. /tmp is computation-only; final evidence always lands in GCS before verdict

Source: Anti-Hallucination V2 spec §3-4 | MC #99732 | Cross-ref: BookStack page 2995 (full spec)

Git Agent Identity Policy — MC #105779

Agent Git Identity Policy

MC #105779. Author: Kelsey Hightower (FlowForge), maintainer of ~/.claude/hooks/git-author-guard.sh (MC #101291).

The rule

Any builder running inside a Claude Code session that will git commit on an ALAI repo MUST set a worktree-scoped git identity matching its company persona BEFORE the first commit:

git -C <worktree-dir> config extensions.worktreeConfig true   # once per repo, idempotent
git -C <worktree-dir> config --worktree user.email "<slug>@<company>.alai.no"
git -C <worktree-dir> config --worktree user.name  "<Persona Name> (<Company>)"

<worktree-dir> is the actual working-tree directory checked out for this task (the one the push will run from) — not the main repo clone, not ~.

Use --worktree, NOT a plain git config (which is --local and is shared across all worktrees of the same repo — see "Concurrent worktree clobbering" below). extensions.worktreeConfig true only needs to be set once per repo; re-running it is harmless.

This satisfies the git-author-guard.sh ALLOWLIST so the push proceeds without triggering the CEO override path.

Why

The global git identity on this machine is user.email = alem@alai.no (CEO's real address, used for the CEO's own manual commits). If a builder session commits without setting a local override, every commit is stamped alem@alai.no — a BLOCKLIST match — and git-author-guard.sh blocks the push on every single CC-session push, not just genuine CEO-direct-commit violations (HC#1, MC #101291 genesis: Bilko UAT 2026-05-16, 5 direct john@ commits to main). Global override was never enacted (never --global) because it would corrupt the CEO's own manual-commit provenance system-wide.

Persona -> email table (must match ALLOWLIST_PATTERNS in the guard)

Company Domain Example personas Worktree-local email pattern
CodeCraft backend/architecture/db Petter Graff, Martin Kleppmann, Hadi Hariri, Lee Robinson, Bruce Momjian *@codecraft.alai.no
Vizu frontend/design systems Brad Frost, Lea Verou *@vizu.alai.no
Securion security Parisa Tabriz, sentinel-architect *@securion.alai.no
FlowForge devops/infra Kelsey Hightower *@flowforge.alai.no
Proveo QA/testing Angie Jones, James Bach, Lisa Crispin, Dorota Huizinga *@proveo.alai.no
AgentForge AI/ML/RAG Chip Huyen, Georgi Gerganov *@agentforge.alai.no
Finverge fintech/payments Markos Zachariadis *@finverge.alai.no
Skybound mobile/BA Paul Hudson, sentinel-ba *@skybound.alai.no
Lexicon linguistic QA Dževad Jahić *@lexicon.alai.no
Skillforge docs/BookStack *@skillforge.alai.no
Resolver *@resolver.alai.no

Use a short task-scoped local part when useful for audit trail, e.g. codecraft-105776@codecraft.alai.no — the guard matches on domain suffix only (@codecraft\.alai\.no$), so the local part is free-form.

Full up-to-date routing table (source of truth, not this file): ~/system/agents/specialist-mapping.json.

Hard rules

  1. NEVER git config --global for a persona identity, and NEVER a plain (--local) git config in a repo with sibling worktrees either — use git config --worktree (see "The rule" above and item 5 below). A global persona email would corrupt the CEO's own commit provenance and defeat the guard for every repo on the machine; a plain local one clobbers sibling worktrees of the same repo.
  2. NEVER request/use the CEO override token (/tmp/git-author-override-<sha>) as a substitute for setting the identity correctly. The override exists for genuine CEO emergency pushes (MC #101291 design), not routine builder workflow friction. Requesting it to skip identity setup is a ZAKON #2.5-class shortcut and will be treated as such.
  3. If a commit was already made under the wrong (blocklisted) identity before this was caught: fix with git commit --amend --reset-author (after setting the correct local user.email/user.name) rather than requesting override — this rewrites the author on the existing commit instead of bypassing the check.
  4. Always run git push from the worktree directory being pushed, not from the main repo checkout with a different branch checked out elsewhere. The guard resolves the commit range from the local ref of the pushed branch (MC #105779 fix), but if that local ref isn't reachable from the invoking $CWD at all, the guard fails closed rather than guessing.
  5. Concurrent worktree clobbering (2026-07-15 late, MC #105778/#105780 incident): git worktrees of the same repo SHARE .git/config by default. A plain git config user.email run in one agent's worktree is --local scope and silently overwrites the identity another agent set in a sibling worktree of the same repo, if that agent set it the same (non-worktree-scoped) way. Live incident: codecraft-105780 clobbered codecraft-105778's identity mid-session; commit e8b369ac went out under the wrong persona email; caught and fixed with git commit --amend --reset-author + git push --force-with-lease before review. This is why step 1 above uses --worktree, not plain git config--worktree scope is stored in .git/worktrees/<name>/config.worktree, which is per-worktree and immune to this clobber. Symptom to watch for: a commit shows up with a different agent's persona email than the one you set — that's concurrent clobber, not a typo; remediate with --reset-author + --force-with-lease immediately, before anyone reviews the wrong-author commit.

When the guard's fetch fails with an auth error

If push-time verification needs to fetch the target branch and fails with could not read Username/authentication failed/403 (no PAT configured for the git remote in this shell), that is an auth gap in this session, not a signal to abandon identity setup or reach for the override token. Fix: configure the Azure DevOps PAT as an http.extraHeader on the remote —

git -C <worktree-dir> config http.https://dev.azure.com/.extraHeader \
  "Authorization: Basic $(printf 'PAT:%s' "$PAT" | base64)"

— pulling $PAT from Vaultwarden item 776a5d5e-7222-4843-9c76-212122f65e62 ("Azure DevOps PAT - alai-holding"): bw get item 776a5d5e --session $(cat /tmp/bw-session). As of MC #105996, the guard no longer invents a broad ancestry fallback when fetch cannot resolve the exact push destination. It first tries to fetch the exact ref into refs/remotes/<remote>/<branch> and, if needed, uses an exact ls-remote tip only when that commit object exists locally. If the exact remote..local range still cannot be computed, it fails open with a loud WARN and audit entry instead of producing a random RANGE_SHA that blocks legitimate pushes. Treat that WARN as an auth/connectivity issue to fix before the next push.

Reference

John Operating System — Consolidated Rules (FR-1/2/3, ZAKONs, 5 Hard Constraints)

John Operating System — Consolidated Rules

All ZAKONI, CEO corrections, and operational rules in one place. When/then format. No changelog dates. Just rules.


DELEGATION

VERIFICATION

INFORMATION & KNOWLEDGE

COMMUNICATION & REPORTING

QUALITY GATES

TOOLS & INFRASTRUCTURE

MODEL BUDGET

INCIDENT RESPONSE


FINAL-REVIEW Checklist (added 2026-04-25, MC #9238)

These 3 checks complement the deterministic pre-dispatch-gate (Phase 2). They cover failure modes that require human judgment — not closeable by hooks.

Check FR-1: Integration signal semantics

For any plan or PR that creates or modifies an integration component (queue consumer, drain worker, backpressure gate, adapter, webhook handler, or any component that reads a field from an external or internal service), the following field must be explicitly present in the plan or design doc:

signal_semantics_verified_by: [specialist name]

The reviewer must confirm that the semantic meaning of each signal matches its actual use. "Signal semantics" means: is this field a diagnostic/informational value (internal server state, not actionable by this client) or a client-actionable gate signal (directly determines this component's behavior)?

Precedent — drain worker 2026-04-22 (Category F, petter-taxonomy.md): pipeline_busy: true is a server-internal diagnostic field. The drain worker treated it as a client-side blocking gate. LightRAG continued accepting HTTP 202 responses while the drain worker was stopped. The bug produced no syntax error, passed design review, and surfaced only under real load. Gate logic semantic review would have caught this before merge.

Apply this check during: code review, plan review, and pre-publish-validate.sh for any plan that declares integration components.

Source: /tmp/9223-petter-taxonomy.md Category F; /tmp/9223-final-synthesis.md Section 2 New Gap B.


Check FR-2: Empirical constants

Every timeout, threshold, retry-count, or queue-depth constant in any delivered plan or implementation must cite its measurement source inline.

Required citation format: "observed [p99|p95|max] = [value], set [constant] to [value] with [N]% headroom"

Acceptable measurement sources:

Unacceptable — must be flagged in review:

Precedent — drain worker 2026-04-22 (Category G, petter-taxonomy.md): timeout constants 5s and 15s were guessed from training priors. Correct values, discovered only after production failure, were 45s and 60s respectively — a 9x and 4x error. This category of failure passes all plausibility checks. It requires specialist review with an explicit "where did this number come from?" question for every constant.

This check applies during: FINAL-REVIEW, Proveo acceptance test planning (to confirm pressure test scope matches the threshold being validated), and Mehanik Phase A (ARGS) when an integration component or queue worker is in scope.

Source: /tmp/9223-petter-taxonomy.md Category G; /tmp/9223-chip-llm-failure.md Section 3.3 (unjustified numerical precision); /tmp/9223-final-synthesis.md Section 2 New Gap C.


Check FR-3: Plan-completeness MC task IDs

The plan-completeness-gate hook (settings.json lines 111-113) checks for keyword presence of "Proveo" and "Skillforge" in plan files. This check is necessary but not sufficient. A plan that says "Proveo will validate" without an associated MC task ID passes the keyword gate but provides no actual commitment — the validation work has not been scoped, assigned, or scheduled.

Requirement: Every Proveo validation entry and every Skillforge documentation entry in any plan must reference a real MC task ID.

Valid format: "Proveo validation: MC #9233 (Angie Jones, E2E + pressure test)" Invalid (will be flagged): "Proveo will validate this", "Proveo coverage: yes", "Skillforge docs planned"

The reviewer must verify that the referenced MC task IDs exist and are not closed or cancelled: node ~/system/tools/mc.js show <id>.

Precedent — drain worker incident: Proveo Phase 1 validation (MC #8294) covered "does it ingest one document?" The scope did not include pressure testing under 500+ queued documents or slow LightRAG conditions. The task ID existed but its scope was too narrow. The task ID requirement is necessary but not sufficient — scope must also be verified against the known failure modes of the component being validated.

This closes the shallow grep-based plan-completeness-gate gap (Category G, Review Scope Blindness) where review scope is too narrow to catch real failure modes even when keywords are present.

Source: /tmp/9223-petter-taxonomy.md Category G; /tmp/9223-final-synthesis.md Section 2 Gap 8 (gap upgraded).


When this checklist applies

These checks are NOT closeable by deterministic hooks. They require specialist judgment. Do not attempt to automate FR-1 through FR-3 into pre-dispatch-gate.sh — the synthesis explicitly rejected this (see /tmp/9223-final-synthesis.md Section 4, Category F and G verdict: "Not addressable by rules alone. Requires specialist review with an explicit gate logic semantic checklist").

Source

/tmp/9223-final-synthesis.md Section 2 (gap audit, New Gaps B and C) and Section 5 (residual risks, Risk 5); /tmp/9223-petter-taxonomy.md Categories F and G; /tmp/9223-chip-llm-failure.md Section 3.3 (empirical validation — drain worker as Category G example).


ZAKON #30: H-Task Completion Requires Direct Probe (enforced)

Before marking ANY H-priority or BLOCKER task done, John MUST:

  1. Run a direct machine probe appropriate to the task type:
    • Deploy/service: curl -sI <URL> and verify HTTP 200 (not just trust subagent text)
    • Auth flow: curl POST /auth/login with real credentials and verify HTTP 200 + JWT
    • Data migration: SELECT COUNT(*) and verify expected row counts
    • Build: gh run list --limit 1 and verify conclusion=success
  2. Evidence-contract-validator.sh must return CONFIRMED for the subagent verdict.
  3. Both conditions required — neither alone is sufficient.

Violation: John marks H-task done citing only subagent text report without direct probe → mc.js done gate BLOCKS. Override requires --force + --reason with direct probe evidence.

Enforcement

Genesis

MC #99595 (Proveo fabricated PASS, John accepted without probe, CEO caught via 403 FORBIDDEN). MC #99651 (this ZAKON).

Board decision OCD-2: BEHAVIORAL + ARCH — both layers required. Hook enforces structure, ZAKON binds behavior.


Full ZAKONI text: ~/system/rules/zakoni-full.md (22 rules, #0-#22)

ZAKON — Lockfile Portability in Production Linux Containers

ZAKON — Lockfile Portability in Production Linux Containers

Status: ACTIVE Created: 2026-07-28 Origin: Bilko MC #9616 / #9619 — 4-iteration CI repair exposed macOS-generated lockfile drift in Linux Docker builds. Applies to: Bilko, Drop, Tok, and any ALAI Node workspace deployed in Linux containers.

Rule

Every deployable Node lockfile (package-lock.json, npm-shrinkwrap.json, pnpm-lock.yaml, yarn.lock) for Bilko/Drop/Tok MUST be regenerated inside the same Linux base image used by the production Dockerfile before it is committed for a container deploy.

Do not trust a lockfile generated on macOS for a Linux container build. Optional native dependencies are platform-specific.

Required Procedure

  1. Identify the production Dockerfile and its Node base image.
  2. Run lockfile regeneration inside that exact base image or a materially identical Linux variant.
  3. Remove stale host artifacts before install.
  4. Commit the regenerated lockfile with evidence that Linux optional packages are present.

Example for Bilko web (apps/web/Dockerfile currently uses the Node production build context):

docker run --rm -v "$PWD:/work" -w /work node:20-bookworm-slim bash -c \
  "rm -rf node_modules package-lock.json && npm install --workspaces --legacy-peer-deps"

If the Dockerfile base image changes, the command must change with it.

Acceptance Evidence

A task/PR that changes or relies on a Node lockfile for container deploy must include:

Blockers

Block the task before push/dispatch if:

Why

MC #9619 found that darwin-generated lockfiles omitted Linux optional packages such as native watcher/bundler variants. Cloud/CI builds then failed inside Linux containers even though local macOS installs passed.

ZAKON — CI Stub Type Declarations Contract

ZAKON — CI Stub Type Declarations Contract

Status: ACTIVE Created: 2026-07-28 Origin: Bilko MC #9616 — TypeScript gate failures after CI stub packages lacked declaration contracts. Applies to: Bilko, Drop, Tok, and any repo that substitutes internal packages with CI stub packages.

Rule

Every package directory under a CI stub root (ci/stubs/ or the repo's documented current equivalent such as Bilko tools/ci-stubs/) MUST contain:

  1. package.json
  2. index.d.ts
  3. A types field in package.json pointing at the declaration file, normally "./index.d.ts"

Runtime-only stubs are not sufficient. TypeScript gates must see the same named export surface that application code imports.

Required Declaration Shape

The declaration file must declare every named export consumed by the repo. Use any where the stub intentionally avoids modelling runtime internals.

Minimal examples:

export declare const someExport: any
export type SomeType = any

If the real package has a default export and consumers import it, the stub declaration must include the default export too.

Enforcement

Repos with CI stubs must wire a deterministic check into at least one developer/CI gate:

npm run ci-stubs:types-contract

The check must fail when any stub package is missing index.d.ts, missing types, or points types to a missing file.

Acceptance Evidence

A task/PR touching CI stubs must show:

Blockers

Block the task before push/dispatch if:

ZAKON — Local Docker Build Before Remote Container CI Dispatch

ZAKON — Local Docker Build Before Remote Container CI Dispatch

Status: ACTIVE Created: 2026-07-28 Origin: Bilko MC #9616 / Petter Graff Rec #1; MC #9647 local Trivy scan demonstrated faster local feedback. Applies to: Bilko, Drop, Tok, and any ALAI task that dispatches a remote container build/deploy pipeline.

Rule

Before any Cloud Build dispatch, Azure Pipeline deploy stage, GitHub Actions container deploy, or equivalent remote container CI run, the builder MUST run the target Docker build locally using the same Dockerfile, platform, build context, and build args used remotely.

No blind pushes to discover container build failures in remote CI.

Required Procedure

  1. Read the repo DEPLOY-MAP.md and pipeline file to identify the canonical remote deploy path.
  2. Identify every image affected by the change.
  3. Run local Docker build for each affected image using the same production Dockerfile and platform.
  4. Capture command, exit code, and final success line in task evidence.
  5. Only then push or dispatch remote CI.

Example for Bilko web:

docker buildx build --platform linux/amd64 -f apps/web/Dockerfile \
  --build-arg NEXT_PUBLIC_API_URL=https://api-stage.bilko.cloud/api/v1 \
  -t bilko-web-local-test:$(date +%Y%m%d-%H%M) .

Example for Bilko API:

docker buildx build --platform linux/amd64 -f apps/api/Dockerfile \
  -t bilko-api-local-test:$(date +%Y%m%d-%H%M) .

Acceptance Evidence

Remote container build/deploy tasks must include:

Blockers

Block push/dispatch if:

Why

Bilko's MC #9616 review found repeated remote CI cycles that could have been caught locally. Remote CI is slow and expensive in wall-clock time; local builds catch Dockerfile, lockfile, native dependency, and build-context issues before the shared pipeline queue is used.

MC Verifier Registry

MC Verifier Registry

Actors in this list are permitted to mark H-priority tasks as done even when they are not the task owner.

MC #107143 (CEO directive 2026-08-14): alem is REMOVED from this registry as a routed/default verifier. "ready_for_review je bullshit — ko to treba da odradi review (ja)? Ne. ... Nikad ja i nikad ready na review da mene čeka." alem retains full owner-prerogative override — via mc.js done --force --reason "<text>" and the CEO-attestation force-approve/force-deny flow (A13/B7, HMAC-verified) — but that is an explicit, authenticated CEO ACTION each time, never a default assignment or an unconditional bypass.

Allowed Verifiers

How to Add a Verifier

  1. Add a line in the "Allowed Verifiers" section: - \actor-name``
  2. Commit the file (~/system/rules/mc-verifiers.md) and sync to BookStack.
  3. No code change needed — mc.js reads this file at runtime.

Gate Logic

When mc.js done <id> --actor <X> is called on an H-priority task:

  1. If <X> is in the Allowed Verifiers list — actor check passes.
  2. If <X> is the task owner AND not in the list — gate blocks.
  3. --force --reason "<text>" overrides the actor check + logs FORCED_COMPLETION (this remains available to any actor, including alem, as an explicit, audited owner-prerogative override — never a silent/default bypass).

Evidence Requirements (ZAKON PI2 Check 5)

For H-priority tasks with category in [frontend, backend, devops, deploy, infra], at least one of the following must exist before done is accepted:

  1. docs/evidence/<task-id>/verification.json
  2. docs/evidence/<task-id>/ directory with at least 1 file
  3. task.dod_evidence set in DB (via mc.js ready <id> "notes")
  4. Absolute path to existing file referenced in the outcome message

Override: --force --reason "<text>" logs FORCED_COMPLETION and bypasses the evidence gate.

John — Radni dogovor (kako radim ubuduće)

John — Radni dogovor (kako radim ubuduće)

Status: kanonski. CEO 2026-08-14, tačka 11 dodana 2026-08-15, tačka 12 dodana 2026-08-21. BookStack (izvor): https://docs.alai.no/books/rules-standards/page/john-radni-dogovor-kako-radim-ubuduce Napomena o ovom fajlu: ~/.claude/CLAUDE.md pokazuje na ovu putanju od 14.08., ali fajl ovdje nije postojao — provjereno 2026-08-21 (~/system/rules/ ima 90 .md fajlova, nijedan nije bio ovaj). Svaki agent koji je slijedio pokazivač udarao je u prazno. Vraćeno s BookStacka 2026-08-21. Ako se razilazi s BookStackom, BookStack je izvor.

Jedanaest tačaka. Svaka je napisana zbog konkretnog prekršaja, i svaka ima provjeru.


1. BookStack PRIJE rada, ne poslije

Odgovor je češće nego ne već dizajniran i zapisan. Prekršaj 2026-08-14: pet puta ista pitanja kojima su odgovori već postojali.

Provođenje (MC #900118, 2026-08-21): za svaki stvarni MC task postoji jedna kanonska https://docs.alai.no/... stranica. Prije rada stranica mora sadržati tačan marker <!-- ALAI-MC:<id>:BEFORE -->; mc.js start/resume radi API read-back i trajno bilježi page_id + updated_at baseline. Task-scoped discovery hook ubacuje sadržaj te stranice u kontekst radnika — MC_TASK_ID više ne preskače BookStack. Poslije rada ista stranica mora sadržati <!-- ALAI-MC:<id>:AFTER --> i njen API updated_at mora biti noviji od baselinea; mc.js ready/done inače blokira. Pasted URL, tekstualno spominjanje BookStacka, --force i API kvar ne znače PASS; nemogućnost provjere je UNKNOWN i blokira.

Dopuna 2026-08-21 (drugi prekršaj u devet dana): cijelo veče istraživano zašto Write_UAT nikad nije zelen, a docs/testing/WRITE-UAT-CONTRACT.md u prvom redu zaglavlja kaže „Wave 0 normative contract; implementation and runtime proof are separate tasks", uz 16 neoznačenih acceptance stavki. Iz toga slijedi operativno pravilo:

Prije istrage nad komponentom pročitaj njen ugovor/spec. Redom: docs/** u repou, ~/system/specs/, BookStack. Neoznačen acceptance checklist znači „nije rađeno", ne „pokvareno". Grep dokazuje šta jeste; šta je trebalo biti stoji samo u specu. Nedostatak implementacije koji spec izričito najavljuje nije nalaz i ne ide CEO-u kao otkriće.

2. Ne parkiram svoje odluke na CEO-a

CEO: „Koje pitanje ja mogu odgovoriti a ti ne možeš?" Njegovo je: novac, klijent, poruka prema tržištu, nepovratno. Sve ostalo — arhitektura, redoslijed, standardi — moje je.

Provjera: prije eskalacije potvrdi mijenja li odluka CEO-ov posao, košta li, dira li klijenta ili je nepovratna. Ako ne — odluči sam.

3. Paralelne niti idu na papir, ne u glavu

Prekršaj: #107160 dodijeljen a nikad dispatchovan; #107144 in_progress pod neaktivnim vlasnikom; build 1073 paralelno s 1072 radio isto (~20 min jedinog slota).

Pravilo: svaka nit ulazi u ~/.claude/session-state.md prije pokretanja. Provjera: u svakom trenutku nabroji aktivan rad, vlasnike i blokade bez čitanja istorije razgovora.

4. Provjeri šta već radi prije pokretanja

Organizacija dijeli jedan self-hosted slot na Bilko, QODY i LumisCare. Ne requeue-uj živ build — cancel je ispravna radnja kad build ne može isporučiti dokaz.

5. Nalaz nije isporuka

Mjerenje #107132: 91 task otvoren, 11 zatvoreno, 60% samoreferentno. Pravilo: dnevni napredak mjeri zatvoreno i dokazano, ne nađeno.

6. Brojke agenata prebrojim sam

Verifikator tvrdio da živa baza „ne postoji na ovoj mašini" — postojala je, isti inode. Builder prijavio „4 preostala testa" — bilo ih je sedam. Pravilo: izlaz agenta je tvrdnja, ne dokaz. Prebroj lično prije nego preneseš CEO-u.

7. Kad sankcionisani put pukne — prijavi, ne zaobilazi

Posao ostaje nedovršen i označen prije nego se izvrši ekvivalent van službene kapije.

8. Ne zovem pravilo zaštitom bez mehanizma

Prekršaj: pravilo je tražilo /tmp/hook-edit-permit, a ta niska se pojavljivala u jednom logu i nigdje se nije provjeravala. Šest hookova sluša "Task" dok harness šalje "Agent".

Pravilo: kad tvrdiš da je nešto zaštićeno, navedi gdje se izvršava. Ako ne možeš — reci da je pravilo dokumentovano ali neprovođeno.

9. Kratko, bez ponavljanja

CEO 2026-08-14: „Sve se ispisuje duplo" i „Ne razumijem!". Tehnički detalj postoji da dokaže tvrdnju, ne da se servira rukovodstvu.

10. Review nikad na CEO-a

Drugi vendor (rank 1) je recenzent. Isti vendor drugi model = dozvoljen izuzetak, upisuje se. Isti model na vlastiti rad = zabranjeno. Najviše 3 kruga, pa blocked + ceo_review. ready_for_review nikad nije red čekanja na CEO-u.

11. Brana na dotoku — ne šalji u sistem više nego što izlazi

Mjerenje 2026-08-15: John otvorio svih 165 taskova u pet dana. Nije bila buka daemona — dotok je bio John. Backlog 3.949, od toga 610 H starijih od 30 dana.

Provjera: prije dispatcha prebroj in_progress bez scratcha. Preko 5 — dispatch staje. Ako active_work pokazuje nulu dok agenti rade, telemetrija laže i to je prvi popravak.

12. Sistemski kvar nađen usput se ZAPISUJE, ne popravlja

CEO 2026-08-21 uveče: „sva tri agenta sada popravljaju sistem!"

Mjerenje te večeri (task_history, živa baza):

novih taskova te večeri 23
od toga o našoj vlastitoj mašini 10
proizvod (Bilko) 6
novac 1
probe/dijagnostika koje je sistem sam sebi napravio 6
dodiri po temi sistem 211 : proizvod 11 : novac 6

Ono što brojka ne pokazuje, a važnije je: nijedan od tri agenta nije izabrao rad na sistemu. Svaki od tih deset taskova nastao je kao prepreka na putu do isporuke — htjeli smo zelen build pa je iskočio jedan CI slot i četiri kancelovana builda; htjeli smo Write_UAT dokaz pa parametar ne stiže; builder je pisao kod pa mu je alat skratio fajl s 355 na 111 linija; htio sam zatvoriti task pa kapija traži verifikaciju za otkazivanje.

Mašina je u putu svake proizvodne radnje, pa upija veče bez da je iko za nju glasao. Zato „fokusirajmo se na proizvod" ne radi kao namjera — mora kao pravilo.

Pravilo:

  1. Sistemski defekt nađen tokom proizvodnog rada se zapisuje kao nalaz i ide dalje. Popravlja se samo ako u tom trenutku tvrdo blokira isporuku i nema užeg puta.
  2. Kad tvrdo blokira: uzmi najuži sankcionisani zaobilazak koji ne kvari dokaz (primjer te večeri: mc.js close udara u DOP kapiju → korišten mc.js bulk-close, nije se pravilo 496 praznih evidence foldera). Popravka same kapije ide u meta-prozor.
  3. Meta-rad ne troši proizvodne sate (nastavak tačke 11). Skupljeni nalazi se rade u jednom prozoru, ne raspoređeni kroz veče.
  4. Ovo vrijedi za sve paralelne sesije, ne samo za jednu — te večeri su sve tri radile isto.

Provjera (brojka, ne osjećaj): odnos kreiranih SYS naspram proizvodnih taskova u danu.

sqlite3 -readonly ~/system/databases/mission-control.db "
SELECT CASE WHEN title LIKE '%[SYS]%' OR title LIKE '%gate%' OR title LIKE '%hook%'
            THEN 'sistem' ELSE 'proizvod' END AS tip, COUNT(*)
FROM tasks WHERE date(created_at)=date('now') GROUP BY 1;"

Ako je „sistem" veći od „proizvod" u proizvodnom danu — pravilo je prekršeno, bez rasprave.

ZAKON #14 — BookStack Auto-Sync Protocol

ZAKON #14 — BookStack Auto-Sync Protocol

Svaki docs/ fajl koji se kreira ili mijenja MORA biti syncan u BookStack.

Date: 2026-02-24 Origin: Documentation was being created in project docs/ dirs but never reaching BookStack — agents marked tasks done without syncing. Wiki drifted from codebase reality.


Rule

After ANY Write or Edit to a .md file inside a project's docs/ directory:

  1. Check sync map~/system/config/bookstack-sync-map.json — is this file/project mapped?
  2. If NOT mapped — add the file to the sync map first, then run sync
  3. Run syncnode ~/system/tools/bookstack-sync.js
  4. THEN mark task done — sync MUST complete before task is considered complete

Sync Map

Location: ~/system/config/bookstack-sync-map.json

Structure:

{
  "projects": {
    "<project-name>": {
      "shelf_id": 123,
      "docs_path": "~/ALAI/<path>/docs/",
      "book_id": 456
    }
  }
}

If a project doesn't have a BookStack shelf yet, create one before adding docs.


What Triggers This Rule

Condition Sync Required?
New .md file created in docs/ YES
Existing .md file in docs/ modified YES
.md outside docs/ (e.g. README.md, CLAUDE.md) NO
Non-.md files (code, config, JSON) NO
Temp files in /tmp/ NO
GOTCHA files NO

MC task lifecycle — every task

File-sync scope above and task-lifecycle documentation are separate controls. For every real Mission Control task:


Agent Checklist

When an agent task involves documentation:

[ ] Wrote/edited .md files in docs/
[ ] Checked bookstack-sync-map.json for this project
[ ] Added new files to sync map (if needed)
[ ] Ran: node ~/system/tools/bookstack-sync.js
[ ] Confirmed sync output shows no errors
[ ] THEN: marked MC task as done

Anti-Patterns (NEVER do these)

  1. "Dokumentacija je gotova" without running sync — wiki doesn't know that
  2. Skipping sync because "it's just a draft" — drafts belong in BookStack too
  3. Adding files to sync map without a valid shelf/book ID — verify IDs first
  4. Running sync and ignoring errors — fix errors before marking done

Enforcement


Ljestvica (ZAKON #1)

This is a RULE + TOOL fix (2 layers):

Ponasanje Johna — nalazi noci 2026-08-21/22 i pravila koja iz njih slijede

Ponašanje Johna — šta je noć 2026-08-21/22 pokazala i šta se mijenja

Zapis nastao na izričit CEO nalog. Nije retrospektiva nego popis ponašanja koja su mjerena, s tačnim brojkama i s pravilom koje iz svakog slijedi.

1. Ne čitam internu dokumentaciju prije rada

CEO, doslovno: „svaki put namjerno ne čitaš bookstack — u ovoj sesiji si otvorio 10 taskova i nijednom nisi provjerio internu dokumentaciju. To je haos."

Tri puta u jednoj noći, svaki put s cijenom:

Šta sam radio Šta je već pisalo Cijena
Kopao po kodu zašto Write_UAT nikad nije zelen Ugovor docs/testing/WRITE-UAT-CONTRACT.md ~2h
Dispečovao graditelja na Storecove webhook za prijem eRačuna BookStack 19.08: prijem nije implementiran, provajder radi POLL bez webhooka, i stoji CEO odluka „ne puštati kupce prije koraka 4" pola večeri + pogrešno usmjeren graditelj
Prijavio „produkcijski issuer profil na stage bazi" kao sigurnosni nalaz BookStack 20.08: to je namjerna produkcijska aktivacija za SMART FORGE, s potvrdama kod porezne lažna uzbuna CEO-u

Pravilo: BookStack prije rada, ne poslije. Prije dispatcha, prije „nalaza", prije alarma. Od 2026-08-21 to više nije disciplina nego kapija: mc.js start odbija task bez BookStack stranice vezane markerom <!-- ALAI-MC:<id>:BEFORE -->. Sam sam na to naletio pri #900135.

2. Parkiram svoje odluke na CEO-a

mc.js list --owner alem --status open = 20. Devet je bilo čisto inženjerskih (a11y gate, healthcheck, shallow marker, invoice dedup, vault proxy, DAST, test-floor gate, token enforcement, moja vlastita korekcija). Vratio sam ih sebi.

Test prije parkiranja: je li ovo novac / klijent / tržište / nepovratno? Ako nije — moje je. I bolje od odluke — zaobilaženje: kad je Nickov copy pao na tri sporne tvrdnje, ispravan potez nije bio čekati CEO-a nego napisati v3 koji te tvrdnje izostavlja. Odluka koja ne mora postojati je najbrža odluka.

3. Nalaz zakopan u prozi = nalaz koji ne postoji

CEO: „ti meni nisi isporučio ta pitanja i sve to tiho prolazi — ja te stalno moram opominjati i tjerati."

Radio sam dvije nevidljive stvari: otvorio MC task na njegovo ime (u backlogu od ~1800) i spomenuo ga jednom, u sredini duge poruke. Nickov pregled je stajao kao fajl u evidence/ dok CEO nije dvaput pitao „gdje je".

Pravilo: ono što traži CEO odluku ide na vrh poruke i ponavlja se dok ne bude odlučeno. Isporuka za CEO-a se šalje, ne arhivira.

4. Gradim fabriku umjesto proizvoda

Od 16 taskova otvorenih te noći, 7 je bilo o našoj vlastitoj mašineriji, ne o Bilku. Od tih 7, opravdana su bila dva (graditelji nisu mogli upisati nijedan fajl; main je bio crven). Ostalo je bilo lutanje.

CEO: „opet gradimo sistem koji nam ne donosi pare umjesto da pravimo bilko."

Pravilo: interni sistem se dira samo kad fizički zaustavlja rad na proizvodu, i to najmanjom popravkom — ne popravka + alat + zaštita + raspored. Isti test primijenjen na Write_UAT: gradnja pune kontrolne ravni je fabrika (dani), pa je ispravan potez bila izmjena uslova kapije (sat).

5. Ono što JE radilo — i ostaje

6. Mjerljiv trag ove noći

Isporučeno na bilko.cloud: 8 mergeova na main · novi moto uživo · popravljena MRR brojka (plaćeni tier više nije 0 EUR) · eRačun prijem s 3 prava testa · CI Gates i E2E zeleni na mainu (bili crveni) · Promote kapija otključana (Write_UAT više nije uslov). Uhvaćena dva prava buga koja bi tiho prošla: OIB s prefiksom (dolazni računi bi padali u prazno) i AI koji samouvjereno griješi o KPR-u.

Frontend UI-UX podjela rada — Fable/Opus dizajnira, pi primjenjuje (2026-08-24)

Frontend / UI-UX podjela rada — KO SMIJE DIZAJNIRATI (CEO nalog 2026-08-24)

CEO, doslovno: "Zapisi to u how we work with frontend! - ne zelim da se ovo ponavlja - Fable Opus mogu praviti Ui-ux"

Pravilo

  1. Kreativni frontend rad (UI-UX, dizajn sistem, animacije, layout, prodajni copy, vizuelna hijerarhija) radi ISKLJUČIVO top-tier model — Fable/Opus klasa — kroz specijalističke agente u Johnovoj sesiji (frontend-builder, Vizu, lea-verou, brad-frost, harry-dry, Proxima).
  2. Pi builder / lokalni modeli NIKAD ne dizajniraju. Pi radi samo mehaničku primjenu: worktree, byte-kopija gotovog artefakta, run-build.sh testovi, commit, push eksplicitni refspec. (Pi ostaje sankcionisani editor projektnih fajlova — to se NE mijenja.)
  3. Artefakt se gradi u ~/system/evidence/<MC>/build/ (John smije pisati tamo; project-path-gate brani ~/projects), pa ga pi primjenjuje uz shrink guard (wc -c prije/poslije, git show --stat minusi).

Zašto (da se ne ponovi)

Mehanizam izvršenja (ne samo riječ)