Plan Review Archive
Human-review HTML for design plans and specs. Markdown in
docs/superpowers/specs remains the source of truth.
- Approved 中文版
Partner API — Test Mode Foundation (Sub-project 1)
Partner API keys gain a fixed test or live mode on the same host, Stripe-style, so partners can build and verify their supply-side integration against isolated, partner-scoped test data before switching to a live key. Synthetic test landlords, simulated claim, consent and listing review, and a full reset replace the old 'integrate against UAT' rule without changing live-key or landlord grm_ key behaviour.
- Run test mode inside each deployment on the same host, with the key deciding the environment instead of a separate sandbox deployment or UAT-as-Testing.
- Give every partner key a fixed, immutable mode shown in its grp_test_ or grp_live_ prefix; Bun verify fails closed on a missing mode or mismatched prefix and PartnerKeyAuth sets key_mode on every partner route.
- Reverse the hard-coded 'partner means live' rule in every writer and reader so partner rows take is_test from the key mode and cross-mode IDs return the usual concealed 404.
- Approved 中文版
Partner API — Enquiry and Offer Webhooks
Authorised partners receive signed, minimal notifications for viewing requests, thread messages and offers, then fetch current details through the existing Partner API. Transactional capture, frozen consent and enrollment references, fresh key authority and bounded HTTPS delivery preserve privacy and prevent delayed work from following newly granted access.
- Notify five enquiry and offer event types with minimal versioned resource identifiers, covering every actor including the subscribing partner and automated changes.
- Use one admin-managed callback per partner on the existing panel detail page, with disabled-first setup and no self-service, event filters or multiple endpoints.
- Capture each business occurrence and its candidate audience in the same Go PostgreSQL transaction, preserving exact payload bytes and never waiting for network calls inside the mutation.
- Approved 中文版
Partner Portal — Developer Integration Experience
Add public, guided integration documentation to the partner portal so developers can make their first authenticated UAT request and implement landlord and listing workflows correctly. Generate the read-only API reference from the shipped Partner OpenAPI contract, with explicit consent, permission, visibility, retry, and test-data guidance.
- Publish guided documentation inside the dedicated partner portal while keeping account, profile, and key management authenticated.
- Generate the read-only API reference at build time from the checked-in Partner OpenAPI contract rather than maintain a second endpoint catalogue.
- Use existing UAT for integration testing; do not add a sandbox, test/live partner keys, or an environment switch.
- Approved 中文版
Partner API — Self-Service Signup and Key Management
Verified human accounts can create an active external partner and manage API keys without administrator involvement. A dedicated portal gives each account sole ownership of one partner while preserving separate service identities, landlord consent, and once-only secret disclosure.
- Open onboarding requires a verified human account but no invitation or administrative approval.
- Each account owns at most one partner through nullable, unique owner_user_id; creators receive no platform-wide admin role.
- A dedicated SolidStart partner portal reuses the existing authentication system and human-session proxy patterns.
- Approved 中文版
Partner API — Enquiries and Offers
Authorised partners can read and respond to tenant viewing requests, exchange thread messages, and read offers through the Partner API, limited to properties they created. Consent-only permissions, scoped SQL readers, existing landlord workflows, and audit attribution preserve privacy and access boundaries without granting offer negotiation or acceptance authority.
- The Partner API mirrors landlord v1 viewing reads and actions, thread reads and posts, and offer reads only.
- Partners can access only properties whose immutable origin_partner_id matches the calling partner, with no all-properties opt-in.
- Both enquiries:read and enquiries:write are consent-only permissions granted through landlord approval, never through landlord creation.
- Approved 中文版
Rental Tenant Profile — Design
Tenants get an optional profile (photo plus twelve fields such as age, race, nationality, occupation, occupants and pets) that landlords see on viewing requests, offers and message threads from that tenant. Every field is optional and clearable, only the request's own landlord can read it, and the tenant sees exactly what landlords see.
- Every profile field (photo, gender, birth year, race, nationality, occupation, employment type, occupants, move-in month, smoker, pets, languages, about) is optional, and booking a viewing never depends on the profile.
- Race is included as an optional field at the product owner's direction after the discrimination risk was raised; religion and monthly income are excluded.
- Profiles live in a new Go-owned table rental_tenant_profiles with typed nullable columns; the Better Auth users table is not changed.
- Approved 中文版
Property Archive and Delete — P2
Adds two ways to take a rental property off the platform: permanent delete for a property no tenant ever interacted with, and a reversible archive for every other property. Archive closes open enquiries and emails tenants, never touches a current or upcoming tenancy, and keeps tenant history readable; it ships on the rental app, v1 and the Partner API.
- Permanent delete is allowed only when no viewing request, offer, agreement or tenancy ever existed on the property's listings, counting soft-deleted rows; otherwise DELETE returns 409 property_has_history.
- Archive is refused only by a tenancy with ends_on >= today (Kuala Lumpur date) or an agreement awaiting signatures, returning 409 property_has_active_tenancy.
- Archive withdraws every non-terminal listing through a new state-machine event, declines or cancels open viewing requests and offers, and emails each affected tenant after commit.
- Approved 中文版
Landlord API — Contacts (v1, own phone only)
The last sub-project of the Money, agreements, tenants bundle lets a landlord's agent read the landlord's own phone, set it only when none is on file, and see a single party_details_complete boolean. No name, NRIC, or address ever leaves the server, test keys cannot write, and every set is audited without the number.
- Contacts over v1 cover only the key owner's own phone (read and set) and one party_details_complete boolean; no name, NRIC, or address value is returned or writable, and no other user's contact is reachable.
- PUT /me/contact/phone sets the phone only when none is on file; a different stored number returns 409 phone_already_set, so prompt injection through tenant messages cannot redirect tenants.
- The phone is returned in clear because it is the landlord's own number, already given to every confirmed tenant.
- Approved 中文版
Landlord API — Move-in Handover (v1, read + draft)
A landlord's AI agent can read the move-in Handover Report in every state, including the tenant's dispute threads, and build the draft's areas, entries, and photos through the Landlord Rental API v1. Submitting the Baseline, replying to the tenant, and AI consent stay the landlord's own acts in the portal, and a server-computed readiness block tells the agent when to send the landlord to submit.
- The agent reads the report in every state and builds the draft (areas, entries, photos); submit, responses, acceptance, the final PDF, AI consent, and AI analysis stay portal-only.
- Full dispute threads are returned, including tenant comments and reply photos, with actors as roles and no user ids, names, IPs, user agents, AI fields, or acceptance audit data.
- A nullable created_via = 'api' marks agent-made areas, entries, and media; the portal editor labels them 'Added by your assistant', and the Baseline, its hash, and the PDF are unchanged.
- Approved 中文版
Landlord API — Enquiries & Offers (v1)
A landlord's AI agent can read and reply to viewing requests, and read offers, through the Landlord Rental API v1 with the existing Enquiries & offers permission. The agent never sees tenant contact details and never takes a legally binding action; offers stay read-only in the portal.
- The agent can read viewing requests, threads and offers, send thread messages, and confirm, counter or decline viewing times; offers are read-only and every offer action stays in the portal.
- Every v1 response identifies the tenant by first name only, never full name, phone, email, NRIC, user ids or the exact address_line.
- A viewing request takes the test/live mode of its listing; owner or mode mismatch reads as 404, with no new is_test columns.
- Approved
Landlord API — Rent & Payments (v1)
Lets a landlord's AI agent read tenancies, the rent ledger, tenant payment claims, landlord receipts, and proof files through the Landlord Rental API v1, and confirm or reject tenant claims. A strict confirm gate, one locked review transaction with audit fields, and transition-only tenant email keep agent actions safe and traceable.
- The agent reads tenancies, the rent ledger, all non-draft payment records, and the proof file, and may only confirm or reject tenant claims; reversal, landlord receipts, charge cancel/reopen, late notices, and the pay-to name stay in the portal.
- A claim is clean only when ai_verdict is agrees, payee_check is match, and there are no duplicate signals; a flagged claim needs override_checks true plus a non-empty review_note, otherwise 409 payment_checks_not_clean.
- payee_check has four API values: match, mismatch, unknown, and not_set, where not_set means no pay-to-name check result was stored when the proof was evaluated; setting a pay-to name later never rechecks a submitted claim.
- Approved
Partner API — P1: Foundation and Supply Side
A separate Partner API (/api/partner/v1) lets white-label sites, and later external portals and CRMs, create landlord accounts and manage their properties and listings under per-landlord grants. P1 covers partner identity and keys, account creation with an email-only Claim, consent for existing accounts, the fourteen v1 supply-side operations mirrored per landlord, and admin tooling.
- The Partner API is a separate surface at /api/partner/v1 in the Go rental module; Bun owns partner keys (configId partner) and every Better Auth account write.
- Claim secrets travel only in platform email: partners never receive a claim URL, token or expiry, see only claimed true/false, and may request a rate-limited resend.
- POST /landlords may recover only the account its own provisioning attempt created, proven by a stamp on the user; every other existing account needs the landlord's consent through a partner-delivered connect link.
- Approved 中文版
TypeSafe Jev — Handover Dispute Sorting and Escalation
Jev helps with move-in handover disputes without grading damage: it matches a tenant's missing-item report to an existing report item for the landlord, and checks every thread comment for four fixed escalation reasons that only admins see. The original severity score is replaced because slice 5 bans AI severity grading toward the parties.
- No severity score: four fixed yes/no escalation reasons (safety_hazard, not_livable, health_risk, threat_or_abuse) are shown to admins only, keeping the slice 5 ban on AI severity grading.
- The thread type chip comes from plain code: the target item's EntryType, or 'Missing from report' for report_omission.
- Jev only matches an opening report_omission event to an existing report item, and answers the four escalation reasons on every event with a comment from either side.
- Approved 中文版
TypeSafe Jev — Payment Proof Double-Check
Extends receipt checking with a payee check against a new per-tenancy pay-to account name (plain-code exact match, Jev for non-exact) and a period check of the receipt date against the chosen charges' due dates. The verdict stays one value, and a new ai_differs_fields list tells the landlord which fields differ.
- The payee is compared against a new per-tenancy pay-to account name (tenancies.payee_name), not the landlord's display name, to avoid false alarms from display names and spouse or company accounts.
- The period check is a plain-code date rule: differs when receipt date is earlier than the earliest chosen charge DueOn minus one month (PeriodEarlyLimitMonths = 1, calendar-month clamping); late payment is never flagged.
- The verdict stays a single value (differs > fields_unreadable > agrees, not_applicable when no extraction); a new ai_differs_fields list names every differing field and is empty unless the verdict is differs.
- Approved 中文版
Decision Model Providers — Per-Feature Switch and Local Replay
Lets each rental AI feature (listing, chat, duplicate) choose its own System One decision model, TypeSafe Jev or the self-hosted open-weight Kev, through one Provider interface, a registry and per-provider threshold tables. Before any switch, real production calls are replayed against Kev on the developer's own machine through a loopback-only client, and a per-unit report compares the two models. Updated after the duplicate check shipped (#146) to adapt its judge, sweep gate, threshold and eval tool.
- A shared Provider interface (same Judge signature as rental's current Client) is the only abstraction; Jev and Kev both use the existing *Client with a new WithModel option, and a second adapter waits for a provider with a different API.
- Each feature picks its provider by env var (TYPESAFE_LISTING_PROVIDER, TYPESAFE_CHAT_PROVIDER, TYPESAFE_DUPLICATE_PROVIDER), default jev; the registry list and threshold tables live in code, keyed by provider name.
- When a feature switch is on and its provider is not registered (including a missing Jev key) or has no threshold entry, the server refuses to start; today a missing key silently turns the feature off.
- Approved 中文版
TypeSafe Jev — Rental Duplicate Property Check
Adds TypeSafe Jev as a judge for rental duplicate properties that the exact address fingerprint misses. Code narrows candidates by trimmed postcode and a shared word, Jev scores each cross-landlord pair, and a strong yes becomes a Duplicate Hint that an admin must confirm, choosing the suspect side, before it becomes a normal Duplicate Flag.
- A Jev yes (p >= 0.7) saves a Duplicate Hint in a new rental_duplicate_hints table; only an admin confirm turns it into a Duplicate Flag, so Jev never flags or holds publication by itself.
- Candidates are other landlords' properties with the same trimmed postcode and one shared significant word, ranked by unit tokens, top 10; the SQL fetches 501 rows and an overflow is logged, pushed +24h and never treated as checked.
- On confirm the admin must pick the suspect property with nothing preselected; it is saved as property_id, the flagged side that Upheld suspends or rejects.
- Approved
TypeSafe Jev — Rental Chat Message Check
Every person-typed rental chat message is judged by TypeSafe Jev for scam signs and early off-platform contact while it is sent, with a 2s limit. The message is always delivered; only the receiver sees a warning, and admins get a Chat findings page with review, ban and suspend actions.
- Jev judges each person-typed message synchronously before the insert with a 2s total deadline; on error or timeout the message is saved as not_checked and still delivered, so the receiver never sees a message before its check attempt ends (M3).
- One Jev call asks three Noul questions — money before viewing, remote landlord, off-platform contact — and the contact question is asked only while viewing_stage is not_confirmed (M4, M12).
- Findings warn the receiver only, until an admin marks false_alarm; the sender never sees them and messages are never held or hidden (M2, M11).
- Approved 中文版
Landlord API — Slice 3: Media Sync
A declarative PUT keeps a property's photo gallery in step with a listing site: each Source owns only its own photos, fetches run outside the database lock behind a public-IP-only SSRF guard, and every URL gets its own result. API keys can also upload and list ownership proofs, but never download them.
- D37: ship fetch-by-URL for photos now; presigned upload waits for Slice 5 and its CLI caller.
- D38/ADR-0065: a gallery PUT owns only photos with source = its Source, any origin channel; source NULL photos are unowned and never touched by sync.
- D39/Q1: a Source's block is appended after unowned photos; owned photos are read-only in the panel, enforced by the server, with an explanatory read-only message.
- Approved
TypeSafe Jev — Shared Client and Rental Listing Check
Adds a shared Go client for TypeSafe Jev, a small typed AI judge, plus a typesafe_calls call log, and uses it to check rental listing addresses and text. Landlords see form warnings and admins see check findings, but Jev never blocks a save or rejects a listing — a person always decides.
- Jev lives in a new vendor-named shared package internal/shared/infrastructure/typesafe/, not the chat/vision AI module; rental depends only on its vendor-neutral ListingJudge port (J1, J10).
- Every Jev call writes one typesafe_calls row (input, output, tokens, model, latency), deleted after 90 days; a failed log write never fails the call (J3).
- One Jev call per check covers address quality and listing text; findings are stored as code + field + probability and rendered from static Paraglide messages keyed by code (J4, J14).
- Approved 中文版
Landlord API — Slice 2: Idempotent Sync
Slice 1 made a landlord's API key a valid identity; nothing yet stopped a nightly sync writing the same flat twice. Slice 2 makes every write repeatable through per-source external refs, an address fingerprint that refuses to guess, a single-transaction idempotency claim, and a test-mode sandbox that never touches the public marketplace. Twenty-five decisions (D12–D36), each with its rejected alternatives recorded.
- External refs live in a side table, one per source per mode, so two sync feeds never overwrite each other's name for one flat (D14).
- The address fingerprint is unique per landlord per mode in the database, so a duplicate cannot be created by any path — API, panel or a bad PUT (D33).
- A high-rise with no unit number produces no fingerprint at all; guessing is worse than missing, so an ambiguous or unit-less match returns 409 rather than adopting (D18, D27, D29).
- Approved
Landlord API — Slice 1: Foundation
Slice 1 makes a Better Auth API key a valid identity for the rental API, decides per-key what it may do, and freezes a public /api/v1/rental contract over the ten handlers that already exist. It adds no new business endpoints, no new tables, and keeps Bun authoritative for key identity while Go enforces a true hourly allowance in Redis.
- A key may submit a listing for admin review in the landlord's name (D1); it never publishes directly to live, because the admin review queue still stands between submit and live.
- Key auth mounts in a separate APIKeyAuthMiddleware on an explicit v1 route allowlist (D12); AuthMiddleware is untouched, so a key can never reach a legacy rental route or another module's routes.
- v1 is key-only (D13): a cookie or Authorization header is ignored there, and a raw key presented as a Bearer token or cookie does not authenticate legacy Go routes either.
- Approved
DIY Rental Platform — Slice 6: Conversation Inbox, Tenant Overview, Tenant Offers
Slice 6 adds the two screens a rental user opens when they do not already know which record they want: a conversation inbox for both parties and a tenant Overview that answers "where am I, and what next?". It adds no tables, and it repairs two inherited defects — a settled-in tenant who cannot message anyone, and a landlord Offers page 404-ing in production.
- A thread is a viewing request, not a new entity — the inbox is a projection over rental_viewing_requests and rental_messages, with no rental_threads table and no dual-write.
- Thread writability resolves ONE chain stage (none / offer / agreement / tenancy) rather than combining three independent booleans, because entity.AgreementStatus never leaves 'completed' and an OR would make HasLiveAgreement true forever.
- The grace period is 30 days past ends_on, compared as Asia/Kuala_Lumpur calendar dates with an exclusive cutoff at local midnight of ends_on + 31 days; the stored DATE's Y/M/D are used as-is and never timezone-converted first.
- Approved
Rental Portal App Split — Design
Moves the authenticated rental portal (landlord + tenant) out of the Panel SolidStart app into its own independently deployed app, so the two products can ship on separate schedules. Ten reviewed decisions cover error-handler decoupling, the host/cookie constraint, Vitest project enumeration, sign-in and landing behaviour, a usage-derived translation split, two-app E2E and deploy pipelines, and a scoped rename inventory.
- D1 — error-handlers.ts keeps its existing signatures and drops the redundant routeAIError call; installAIAPIErrorHandler moves to a Panel-owned AI module, so PR2 copies the post-PR1 file to the portal unchanged.
- D2 — the portal is hosted on a sibling host under the same registrable domain as the Better Auth session cookie (landlord.kokweng.net as a working assumption); the gremlin.my migration is deferred and the cross-host spike is an open risk, not a confirmation.
- D3a — Vitest projects are enumerated explicitly (shared-packages and panel in PR1, rental in PR2), with acceptance comparing collected test file identities rather than a fixed count.
- Approved
Rental Frontend — Slices 3, 4, and 5 (Panel)
Design for three sequential OpenSpec changes (rental-slice3-panel, rental-slice4-panel, rental-slice5-panel) that build the offers/agreements, ledger/payments, and move-in handover screens in the SolidStart panel at frontend/solidstart/apps/panel. It resolves demo-versus-backend conflicts, keeps all slice 1 routes untouched, and records four missing backend capabilities plus three blocking backend defects. Release is blocked until rental-slice2-panel is built, PR #109 lands, and the backend prerequisites merge.
- The tenant surface lives at /tenant/* in the SolidStart panel as mobile-first responsive pages rather than in Flutter or Astro.
- Screens use the panel's existing glass design system and @monorepo/solid-pkg-ui, taking only information architecture, flow, and wording from the HTML demo.
- Slice 1 routes are preserved: /owner stays the listing grid and the landlord dashboard gets a new /owner/dashboard route.
- Approved
DIY Rental Platform — Slice 4: Tenancy Establishment, Rent Ledger, and AI Payment Proof Matching
Slice 4 turns a completed tenancy agreement into an operational tenancy with a fixed-term rent ledger, human-controlled payment confirmation, durable reminders, and immutable late notices. Optional platform-funded vision AI extracts receipt details under explicit consent, while deterministic checks and landlord decisions remain authoritative.
- A completed agreement creates exactly one operational Tenancy and the entire fixed-term charge schedule in the same database transaction.
- Charge lateness is derived from Malaysian calendar dates, while payment decisions, reversals, reminders, cancellations, and notices are stored as auditable facts.
- Tenant payments are claims requiring landlord confirmation; landlord-recorded receipts are born confirmed, but both paths pay charges only through active allocations.
- Approved
DIY Rental Platform — Slice 5: Move-in Handover and AI-Assisted Condition Report
Slice 5 creates one immutable, party-authorized move-in condition report per tenancy: the landlord submits a structured baseline, the tenant records disputes and omissions, and the platform freezes both positions into canonical evidence and a deterministic PDF. AI may draft neutral photo descriptions only after uploader-specific consent, but the complete manual workflow ships first and remains fully functional without AI.
- Each tenancy has at most one landlord-led move-in report, backed by structured records that freeze into canonical baseline and final snapshots with SHA-256 hashes.
- Report creation and submission use the tenancy start date in Asia/Kuala_Lumpur, with a hard window from seven calendar days before through three calendar days after and no retrospective or admin override.
- The tenant review window is a platform-set seven calendar days; silence finalizes as no tenant response and never as implicit acceptance.
- Approved 中文版
DIY Rental Platform — Slice 3: Offers, Tenancy Agreements, and E-Signature
Slice 3 is where the Malaysian rental platform stops being a noticeboard and becomes the place the deal closes: a tenant with a confirmed viewing offers terms, the landlord counters or accepts, and the platform issues a lawyer-reviewed tenancy agreement that both parties sign inside the app. A grilling session on 2026-08-26 settled 23 open questions and produced three ADRs — documents frozen and content-addressed at issue, click-to-sign under the Electronic Commerce Act 2006, and one blank-filling template under the Legal Profession Act 1976 s.37.
- The tenancy agreement PDF is frozen at issue rather than rendered on demand: rendered once, hashed, and stored under a content-addressed key that is its own SHA-256, so both parties provably sign the same bytes even if the template later changes (ADR-0058).
- Rendering and upload happen before the database transaction opens, not inside it: a rollback would leave the uploaded object behind anyway, and content-addressing makes a retry overwrite the same key so the orphan heals itself instead of needing a cleanup sweep.
- Signing is click-to-sign under the Electronic Commerce Act 2006 — typed full name and NRIC plus an evidence row carrying user id, timestamp, IP, user-agent, and the document hash — rejecting drawn signatures, DSA 1997 certified signatures, and third-party providers like DocuSign (ADR-0059).
- Approved 中文版
DIY Rental Platform — Public Marketplace (Astro)
The anonymous, SEO-critical public face of the Malaysian rental marketplace: a new Astro 7 app at rent.gremlin.my that server-renders search and listing pages, reads Go directly for anonymous public data, and ships no island framework at all. A 22-question grilling session on 2026-08-26 settled the domain, the indexing rules, image handling, and the Seeker-to-Tenant handoff into the panel — and uncovered three gaps in slice 1's schema that must be fixed before its public API contract freezes.
- The public marketplace is a new independently deployed Astro 7 app at frontend/astro/apps/rental served from rent.gremlin.my, a second exception to the one-platform-app rule after the quiz app (ADR-0056).
- SSR calls Go directly at /api/public/rental/… rather than proxying through Bun, because cookie forwarding and CORS handling do not apply to an anonymous server-to-server read, and a public marketing site should not depend on Bun's uptime.
- RENTAL_API_URL holds an origin only and deliberately carries no PUBLIC_ prefix, which makes 'the browser never calls the API' a mechanical guarantee in Astro rather than a convention.
- Approved 中文版
DIY Rental Platform — Slice 1: Listings and Owner Onboarding
Slice 1 of a Malaysian rental marketplace: landlord signup, property listings, manual admin approval, and public browse — built inside the existing monorepo rather than greenfield. A 2026-08-24 design-review grilling session settled the architecture on the platform's shared Postgres database and Better Auth deployment, resolved a role-token naming collision with the existing org-owner role, and tightened the data model, storage, and state-machine details before implementation starts.
- Rental runs in the shared platform Postgres database and shared Better Auth deployment rather than a separate database, isolated only by the rental_ table prefix (ADR-0055).
- Landlord accounts use a distinct global role token landlord, not owner, to avoid colliding with the existing org-scoped owner role already merged into claims.Roles.
- A property has at most one non-terminal listing (draft/pending_review/live) at a time; a new listing can only be created once the previous one reaches withdrawn, and admins can restore a suspended listing directly back to live.
- Approved 中文版
DIY Rental Platform — Slice 2: Viewings, Messaging, and Reminders
Slice 2 of the Malaysian rental marketplace: tenants propose viewing times, owners confirm or counter inside a per-request message thread, contact details reveal only on confirmation, and a 24-hour reminder fires by email. A same-day grilling session resolved 17 design gaps — a terminology collision with the platform's multi-tenancy vocabulary, the fact that slice 1 is still unbuilt, state-machine reachability, a missing terminal status for lapsed viewings, and per-transition email and reveal rules — before implementation starts.
- Viewing requests use request-then-confirm negotiation, not published availability slots: the tenant proposes up to 3 times, the owner confirms, counters, or declines, with no calendar table or booking lock.
- The viewing request row is the message thread — there is no separate chat feature — and counter/re-propose transitions also insert a rental_messages row so the negotiation history survives even though proposed_times only ever holds the current offer.
- No new tenant role: any signed-in user may book, authorization is row-level against tenant_user_id, and users.role stays single-valued exactly as slice 1 established for landlord.
- Approved
Quiz app — favourites, statistics, exam flags, community stats
Adds four server-rendered extensions to the shipped quiz app: saved questions, idempotent exam flags, newest-answer statistics, and an always-visible community evidence block. The design preserves the v1 security and no-JavaScript constraints while adding only one table and one column.
- Favourites use a composite (user_id, question_id) primary key and explicit idempotent favourite and unfavourite actions keyed by question slug.
- Exam flags live on attempt rows, are restricted to exam attempts by a database constraint, and mutate under the same owned exam-row lock as answer submission and finalisation.
- Statistics count only each user's newest answered attempt per non-retired question across practice and exams, with deterministic tie-breakers.
- Approved 中文版
Quiz App — Design
A standalone, mobile-first Astro app for cloud-certification exam simulation and clue-assisted practice. Server-owned attempts and deadlines make sessions resumable and tamper-resistant, while a git-backed CSV question bank with per-row content hashing gives idempotent imports and immutable attempt history from day one.
- The quiz is an independently deployed Astro server app with its own Postgres database and Better Auth domain, with no calls to the Bun or Go backends.
- Exam answers and the immutable deadline are server-owned; forms use POST/Redirect/GET while the client countdown is presentational only.
- Questions are spreadsheet-authored CSV files in git, one per exam type, with the filename stem supplying exam_type and a hand-written Slug column supplying stable identity.
- Approved 中文版
DW Semantic History Search — Design
Adds local, pgvector-based semantic search over Digital Worker chat history. The current Postgres FTS ('simple' config) cannot segment Chinese or code-switched rojak, leaving 40% Malay + 10-20% Chinese chat effectively unsearchable; local bge-m3 embeddings fix this with no API cost and enable cross-lingual retrieval. Approved after the 2026-07-22 grill session resolved all open questions.
- Run per-domain embedding models; DW stays isolated from the ai/crm stacks with its own dw_message_embeddings table using halfvec(1024) + halfvec_cosine_ops.
- Use local bge-m3 (1024-dim) via Ollama, embedding raw code-switched messages with no LLM/translation normalization; store the model identity and always filter queries by it.
- Produce embeddings from one periodic watermark sweep over CLOSED conversation windows — a single code path that yields async, retry, backfill (empty watermark), and model-swap rebuild; ingest is completely unchanged.
- Approved 中文版
FieldForce Mobile App Design
FieldForce is the first Flutter app in the Gremlin mobile workspace: an offline-first field-worker client that syncs directly with the existing Go/Postgres/NATS backend via PowerSync — no separate mobile backend. The MVP proves offline-first work cycles, realtime updates when connected, and feature-flagged shift-scoped background location, inside a melos monorepo built for multiple apps from day one.
- Flutter + PowerSync in a melos monorepo with Clean Architecture is selected over React Native, Capacitor, and native Kotlin/Swift; ecosystem cohesion and PowerSync collapsing offline+realtime+migration outweigh losing TS type-sharing (ADR-0037, ADR-0038, ADR-0039).
- PowerSync keeps a local SQLite DB in sync with the existing Postgres; the Go backend stays the single source of truth and write authority, so there is no separate mobile backend and no hand-built WebSocket realtime (ADR-0040).
- Heterogeneous data paths: interactive entities flow through PowerSync buckets, but high-volume append-only background location telemetry routes around PowerSync to a dedicated Go endpoint via the engine's own queue.
- Draft
FieldForce Mobile App Design
FieldForce becomes a real offline-first Flutter mobile app backed by PowerSync, with the Go backend retaining all identity, write authority, conflict resolution, feature flags, and business rules. The grill pass tightened the design around Task as the canonical sync entity, mobile JWT/session source, Phase 1 Shift backend work, PowerSync Cloud Free for development, explicit uploadData endpoint mapping, rejected Task upload UX, and Crashlytics debug context.
- Build FieldForce as a Flutter app with a Melos monorepo and layered core packages matching the backend's hexagonal boundaries.
- Use PowerSync for interactive offline entities; route background location telemetry through flutter_background_geolocation's own queue to a dedicated Go endpoint.
- Keep Go as the write authority: uploadData() is a Flutter-side bridge to existing or entity-specific Go API endpoints, not a generic backend write endpoint.
- Approved 中文版
Digital Worker Phase 1.5 — Self-Service Identity Verification Design
A Phase 1.5 self-service identity verification flow: a verified Gremlin user binds their own external chat identity by DMing a short-lived, single-use code to the worker on Telegram or WhatsApp, and the inbound webhook supplies the authoritative external_user_id so no one copies an opaque platform ID. It replaces admin-by-hand ID sourcing while producing the same verified dw_external_identities row, leaving the Phase 1 security gate unchanged.
- Self-service DM-code challenge replaces admin ID-sourcing; the webhook envelope's external_user_id is the authoritative binding key (ADR-0035).
- v1 self-service is Telegram + WhatsApp only (shared webhook path); Discord self-service is deferred (Gateway-only ingest) and stays admin-assert.
- Codes persist a single code_lookup = HMAC-SHA256(token, server pepper); the raw token is never stored or logged (the second hash column was dropped).
- Approved
Digital Worker Phase 3 — Progress & Risk Digest Design
Phase 3 turns what the Digital Worker already observes into a scheduled Progress & Risk Digest: a per-channel-binding summary of progress, blockers, stale commitments, and follow-ups, delivered via the in-app notifications module and read in the SolidStart panel. It is the lowest-risk next step, composed almost entirely of Phase 1/2 primitives, with no new external-posting surface.
- Phase 3 ships a per-channel-binding Progress & Risk Digest delivered on a configurable schedule plus on-demand, via the in-app notifications module and the SolidStart panel — no posting to external chat channels.
- The digest is computed hybrid: Commitment health (overdue + unclear ownership) comes from structured extracted data with no AI, while Progress, Blockers, and Suggested follow-ups come from one bounded, gated LLM pass.
- Generation mirrors the Fieldforce briefings engine — a system_cron loop plus a new dw_digests store, with one GenerateChannelDigest use case shared by the scheduled and on-demand triggers.
- Approved
Morning Routine Dashboard — Design
Persists the agent-generated daily Morning Routine briefing to Postgres and renders it on a frosted-glass dashboard in the SolidStart panel, with a service-token ingest API, per-user card preferences, a browsable date rail, and a 2-tier feature flag. Telegram is reduced to a 3-line teaser deep-linking to the dashboard.
- The agent keeps generating the report and POSTs structured JSON to a service-token ingest endpoint; a new Go morningroutine module stores and serves it per user.
- One mr_reports row per (user_id, report_date) with JSONB section arrays; re-POSTing the same date is a full replace, never a partial merge.
- Card preferences are a pure display filter — the report always carries full top_stats and the UI shows the enabled subset, with unknown keys appended at the end for discoverability.
- Approved
Digital Worker Phase 2 — Role-Agent Memory And Skill Learning Design
Phase 2 gives each Digital Worker role-agent durable, cross-channel memory and approved, versioned skills, governed by a Learning Inbox and per-agent approval. A 2026-06-06 grilling session trimmed scope to memory + skills + a tone-only Agent Soul, deferring Constructive-Critic critique and KPI signals to Phase 3, and reconciled the design with the shipped Phase-1 schema.
- Phase 2 ships memory + approved skills + Learning Inbox + Agent Soul as a tone/posture knob only; Constructive-Critic critique, process-improvement proposals, and KPI-signal capture move to a Phase 3 spec.
- Memory is owned by the role-agent keyed on (org_id, role_agent_id), shared cross-channel, with policy-over-learning precedence: admin-authored org memory outranks machine-learned role-agent memory (ADR-0032).
- dw_role_agents is an ALTER not a CREATE: keep the shipped name/persona columns and status CHECK('active','disabled'); add soul_id (FK ON DELETE SET NULL), auto_memory_enabled, auto_memory_require_verified, skill_learning_enabled.
- Approved
Digital Worker Team Chat Observer Design
Phase 1 of the Digital Worker product: a Team Chat Observer that integrates directly with WhatsApp, Telegram, and Discord to answer @-mentions in-channel and draft follow-up tasks from observed commitments into a review inbox. It enforces verified identity, per-channel capability policy, a two-tier LLM (local triage then gated remote), and human approval only for consequential actions — with Fieldforce as the sole task-promotion target.
- Direct integration with the WhatsApp, Telegram, and Discord bot APIs — no OpenClaw/Hermes middleware and no Bun bridge; the Go core owns one adapter per provider (ADR-0031).
- Mention-response is a direct, ungated, in-channel reply; only consequential actions (creating/assigning Fieldforce tasks, posting unsolicited messages, scheduling) are human-gated — a safe-executable vs consequential action model (ADR-0029).
- Proactive extraction is two-tier: a local Ollama triage model is an unbilled pre-gate filter, and only a positive hit calls the frontier model through AccessGate (digital_worker:chat_task_extract) — ADR-0028.
- Approved
Fieldforce Phase 5 — AI Risk Intervention Inbox Design
Phase 5 ships a manager-facing AI Risk Intervention Inbox that turns risk detection into actionable draft interventions — assignee nudges, supervisor escalations, or reassignment recommendations. A daily cron pipeline deterministically scores open tasks, persists ranked recommendation rows, and calls the LLM once per org to draft text; page loads serve stored rows only and never trigger LLM calls.
- Risk Intervention Inbox selected over briefing follow-up drafts and task-detail copilot — a proactive, filterable command-center surface backed by persisted ff_risk_interventions rows, not dependent on the Phase 4 morning briefing.
- Deterministic risk scoring (7 rule keys with additive weights: overdue 40, escalated_no_progress 30, repeated_rejection 25, approaching_due 20, no_activity 20, high_priority_idle 15, stalled_checklist 10) ranks candidates; the LLM drafts text only and never re-ranks.
- generation_mode follows ADR-0023 lease-then-LLM: INSERT starts as pending, finalizes to llm or heuristic_only; all reads must filter WHERE generation_mode <> 'pending'.
- Approved
Plan HTML Review App Design
Defines a manual workflow that converts canonical markdown specs into clean HTML review pages via an agentic LLM CLI, served by a dedicated Astro app at apps/plans. The generated HTML is a fast-comprehension layer over the source markdown — not a second source of truth.
- Generation is LLM-driven via a pluggable agentic CLI (claude|codex|gemini); the agent writes JSON + HTML files directly into a temp dir which the script validates and atomically promotes.
- Output shape is a metadata JSON file plus a sibling HTML body fragment; the Astro shell wraps the fragment with chrome (hero, TOC, footer).
- Component vocabulary is closed: body_html may only use classes declared in COMPONENT_CATALOG.md; undeclared classes trigger a suggestion entry in JSON, not a lint pass.
- Approved
Fieldforce Phase 4 — Daily AI Briefings + At-Risk Delays Design
Phase 4 ships a daily AI-generated briefing per org, persisted as ff_briefings records and surfaced as a panel dashboard widget for managers and supervisors. A hybrid pipeline (deterministic heuristics shortlist → single LLM call ranks and reasons) keeps costs at one call per org per day, with full heuristic-only fallback when the AI gate denies or the LLM fails. A new ai_prompt_templates table lets platform admins tune LLM prompts in the DB without code PRs.
- Approach A selected: one org-scope LLM briefing per day with supervisor team-filtered at-risk view — 1 LLM call per org per day, avoiding cost-scaling per-team calls.
- ff_briefings UNIQUE(org_id, briefing_date) provides lease-based idempotency — the losing replica on a UNIQUE conflict skips the org with no LLM spend.
- team_ids denormalized onto ff_briefing_at_risk at generation time for cheap supervisor read filtering with correct snapshot semantics (team membership at generation time).
- Approved
Phase 2 Grill Session — Decisions & Clarifications
Grill session between Wayne and Claude resolving eight open design questions for Fieldforce Phase 2 across Go backend, Astro mobile, and SolidStart panel. Decisions lock in atomic attachment linking, immutable ticked checklist items, upload-on-select for both platforms, and role-only approval access control.
- Activity creation and attachment linking are atomic: if any attachment ID is invalid or already-used, the entire transaction rolls back with 422.
- Ticked checklist items (done: true) are immutable — Go returns 422 if client attempts to modify done/ticked_at/ticked_by.
- Client sends full checklist item objects including existing ticked_at/ticked_by; Go stores as-is with no server-side matching.
- Approved
Fieldforce Phase 3 — Task Creation AI + BYOK Foundation
Phase 3 delivers the first user-facing AI feature in Fieldforce — natural-language task creation on the SolidStart Panel — plus the platform-wide AccessGate that all future AI calls must pass through, covering trial/platform/BYOK/disabled modes, plan caps, AES-GCM encrypted BYOK key management, and a global AI kill-switch. Three deferred Phase 2 AI features (NL task parsing, auto-categorization, AI checklist generation) are delivered as one user action via a single combined-schema LLM call.
- Single combined-schema LLM call per parse-task request replaces two sequential calls, halving latency and aligning token debit with user-visible Generate actions.
- AccessGate.Authorize must run before any prompt construction; every AI call routes through the gate before provider interaction.
- Trial rows are lazy-provisioned on first AI call via INSERT ON CONFLICT DO NOTHING; no org-creation hook couples core org creation to AI module availability.
- Approved +1 variant
Fieldforce Management — Design Spec
Fieldforce Management is a multi-tenant SaaS module for dispatching tasks to field teams, tracking execution, and verifying completion with AI — supporting service, sales, and logistics verticals. Two surfaces (Panel desktop + Mobile Web) share one org-scoped backend, with ClawUI routing all AI calls across Anthropic, OpenAI, Google, and Azure providers with per-org cost tracking and audit logging.
- Two surfaces (Panel desktop + Mobile Web) share one backend; role controls WHAT you see, surface controls HOW you see it — both route through /api/organizations/:org_id/fieldforce/*.
- All AI calls route through ClawUI middleware for cost tracking, audit logging, and multi-provider failover — Anthropic, OpenAI, Google, and Azure OpenAI supported.
- Storage abstraction layer (FieldforceStorageAdapter interface) is defined in Phase 1 so components never call IndexedDB directly — Electric SQL swap in Phase 4 is a single implementation change with zero component changes.
- Approved +1 variant
grm CLI — Auth MVP Design
Design for the grm CLI's authentication commands (login, logout, whoami) using OAuth 2.0 Device Authorization Flow with Better Auth's deviceAuthorization and apiKey plugins. The CLI stores a long-lived API key locally after browser-based sign-in.
- OAuth 2.0 Device Authorization Flow chosen for login — enables both human and AI agent authentication without exposing credentials in the terminal
- Long-lived API key stored locally after device flow completes — agents authenticate once and reuse the key for all subsequent operations
- Thin Cobra abstraction layer (CommandDef/FlagDef/Context/Build) eliminates framework boilerplate while preserving completions and man pages